code:
from body_parser import Extractor
import re

class FEOProcessor(object):

    CHECKS = [
        ('Standard JavaScript Inlining Optimization', ('EMBED_JAVASCRIPT',), 'check_js_inlining'),
        ('HTML5 Advanced Cache', ('JAVASCRIPT_HTML5_CACHE', 'CSS_HTML5_CACHE'), 'check_html5_advanced_cache'),
        ('Cookieless Resource Domain', ('RENAME_JAVASCRIPT', 'RENAME_CSS'), 'check_cookieless_resource_domain'),
        ('Minificatiopn of JS', ('MINIFY_JAVASCRIPT',), 'check_js_minifaction'),
        ('File Versioning', ('RENAME_JAVASCRIPT', 'RENAME_IMAGE', 'RENAME_CSS'), 'check_file_versioning'),
        ('Small Image Embedding', ('EMBED_IMAGE',), 'check_small_image_embedding'),
        ('Responsive Image Loading', ('RESPONSIVE_IMAGES',), 'check_responsive_image_loading'),
        ('Asynchronous JS and CSS Loading', ('ASYNC_JAVASCRIPT',), 'check_async_js_and_css_loading'),
        ('JS Pre-Execution', ('PRE_EXECUTE_JAVASCRIPT',), 'check_js_pre_execution'),
        ('EDGESTART', ('EDGESTART',), 'check_edgestart'),
        ('Invoke Click OnTouch', ('BlzFastClick',), 'check_click'),
        ('Cellular Connection Keep-Alive', ('blzEnableMobileHeartbeat',), 'check_cell'),
    ]

    def __init__(self):
        self.parser = Extractor()
        self.result = dict((k, 'Not Applied') for k,_,_ in self.CHECKS)

    for _, keys, name in CHECKS:
        locals()[name] = lambda self, result, _keys=keys: all(result.get(k, 0)>0 for k in _keys)

    def process_feo_debug_output(self, analysis_id, url):
        feed = self.parser.start_parser(analysis_id, url, True)
        result = self.get_feo_tags(feed)
        for name, _, func in self.CHECKS:
            self.result[name] = ('Not Applied','Applied')[getattr(self,func)(result)]
        return self.result

    def get_feo_tags(self, feed):
        result = {}
        tag_list = re.findall(r'(?:TextTransApplied):\s*((?:(?:[A-Z]+(?:_[A-Z\d]+)+)?\(\d+\)\s*(?:,\s*|;))*)', str(feed))
        for tag in tag_list:
            for element in tag.split(","):
                index = element.index('(')
                if element[:index].strip():
                    result[element[:index].strip()] = (element.split("(")[1].rstrip(");"))
        return result
    def check_edgestart(self, result):
        return 1 if 'EDGESTART' in result.keys() else 0
    def check_click(self, result):
        return 1 if 'BlzFastClick' in result.keys() else 0
    def check_cell(self, result):
        return 1 if 'blzEnableMobileHeartbeat' in result.keys() else 0

rawDescription: How to incorporate this additional use case in the following python code

description: Incorporate this additional use case in the following python code


code:
import sys
import subprocess

subprocess.call([sys.executable, 'testprint.py'])

rawDescription: Python subprocess is running a different version of Python


code:
today = datetime.datetime.now()
print (today.strftime("%m/%d/%Y-%H:%M:%S"))

rawDescription: Datetime python script not outputting correct hour, minute, and second


code:
import pytest

class AppImpl:
    def __init__(self, app_name):
        self.name = app_name

    def get_name(self):
        return self.name

@pytest.fixture(params=['App1', 'App2'])
def app(request):
    return AppImpl(request.param)

def test_1(app):
    assert app.get_name()

def test_2(app):
    assert 'App' in app.get_name()

if __name__ == '__main__':
    pytest.main(args=[__file__, '-v'])

rawDescription: Python unittest loading test data on the fly


code:
class ClassMeta(metaclass=M):
  pass

rawDescription: Shouldn't __metaclass__ force the use of a metaclass in Python?


code:
import urllib2
# Create an OpenerDirector with support for Basic HTTP Authentication...
auth_handler = urllib2.HTTPBasicAuthHandler()
auth_handler.add_password(realm='PDQ Application',
                          uri='https://mahler:8092/site-updates.py',
                          user='klem',
                          passwd='kadidd!ehopper')
opener = urllib2.build_opener(auth_handler)
# ...and install it globally so it can be used with urlopen.
urllib2.install_opener(opener)
urllib2.urlopen('http://www.example.com/login.html')

rawDescription: Python code to find if x is following y on twitter. More Pythonic way please


code:
r = np.arange(6).reshape(2, 3)
r[:, None] - r

rawDescription: Use numpy to get the positions of all objects in 3D space relative to one another


code:
from unittest.runner import TextTestResult
TextTestResult.getDescription = lambda _, test: test.shortDescription()

rawDescription: how to change the test description of python (2.7) untitest

description: Change the test description of python (2.7) untitest


rawDescription: how to put a valid filepath as a function parameter in python

description: Put a valid filepath as a function parameter in python


rawDescription: Split by \b when your regex engine doesn't support it


code:
class CompanyAdmin(admin.ModelAdmin):
    def render_change_form(self, request, context, *args, **kwargs):
         context['adminform'].form.fields['theme'].queryset = Theme.objects.filter(name__iexact='company')
         return super(CompanyAdmin, self).render_change_form(request, context, args, kwargs)

rawDescription: filter foreignkey field in django admin

description: Filter foreignkey field in django admin


code:
def pairwise_deque(iterator, n=2):
    it = chain(iterator, repeat(None, n - 1))
    d = collections.deque(islice(it, n - 1), maxlen=n)
    for a in it:
      d.append(a)
      yield tuple(d)

rawDescription: Which pairwise() implementation?

description: Which pairwise() implementation


code:
def loop(self):                                                         #SCENE LOOP
        while True:
            for event in pg.event.get():
                if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
                    pg.quit()
                    sys.exit()
                for k, v in self.buttons.items():
                    if 'click' in k.handleEvent(event):
                        self.goto(v)
            pg.display.update()

rawDescription: Getting dict value from for loop in Python


code: return redirect(item.get_absolute_url() + '#hash')

rawDescription: How to redirect to the absolute URL of a model instance while appending a hash?

description: Redirect to the absolute URL of a model instance while appending a hash


code:
class MyClass(models.Model):
    ...

    def save(self):
        super(Myclass,self).save()
        if not self.code:
            self.code = str(self.id) + str(self.type_id)
            self.save()

rawDescription: Django charfield compose default value

description: Django charfield compose default value


code:
def debug_trace():
  '''Set a tracepoint in the Python debugger that works with Qt'''
  from PyQt4.QtCore import pyqtRemoveInputHook

  # Or for Qt5
  #from PyQt5.QtCore import pyqtRemoveInputHook

  from pdb import set_trace
  pyqtRemoveInputHook()
  set_trace()

rawDescription: Debugging a pyQT4 app?

description: Debugging a pyQT4 app


code:
driver.maximize_window()
driver.get('https://www.woolworths.com.au/Shop/Browse/back-to-school/free-school-labels')
driver.implicitly_wait(15)
centerPanel = driver.find_element_by_css_selector("#center-panel > div[class*='hideScroll-wrapper']")
jsScript = """
        function move_up(element) {
            element.scrollTop = element.scrollTop - 1000;
        }

        function move_down(element) {
            element.scrollTop = element.scrollTop + 1000;
        }

        move_down(arguments[0]);
        move_down(arguments[0]);
        """
driver.execute_script(jsScript, centerPanel)

time.sleep(3)

jsScript = """
        function move_up(element) {
            element.scrollTop = element.scrollTop - 1000;
        }

        function move_down(element) {
            console.log('Position before: ' + element.scrollTop);
            element.scrollTop = element.scrollTop + 1000;
            console.log('Position after: ' + element.scrollTop);
        }

        move_up(arguments[0]);
        """
driver.execute_script(jsScript, centerPanel)

rawDescription: Selenium python unable to scroll down

description: Selenium python unable to scroll down


code:
from PyQt4.QtGui import *
import sys

class MainWindow(QMainWindow):
  def __init__(self):
    super(MainWindow, self).__init__()

    self.tray = QSystemTrayIcon(QApplication.style().standardIcon(QStyle.SP_DriveDVDIcon), self)
    m = QMenu()
    m.addAction('First')
    m.addAction('Second')
    self.tray.setContextMenu(m)
    self.tray.show()

    p = QPushButton("test", self)
    self.setCentralWidget(p)
    p.clicked.connect(self.onClick)

  def onClick(self):
    new_m = QMenu()
    new_m.addAction('First')
    new_m.addAction('Third')
    self.tray.setContextMenu(new_m)

app = QApplication(sys.argv)
w = MainWindow()
w.show();
sys.exit(app.exec_())

rawDescription: Qt QSystemTrayIcon change menu items

description: Qt QSystemTrayIcon change menu items


code: values = [v for k, v in config.items('main')]

rawDescription: How can I get the values of every item in a section?

description: Get the values of every item in a section


code: fname, url, records = next(readline_google_store(ngram_len=1,indices='a'))

rawDescription: Read google ngrams using google_ngram_downloader


code:
import json
data = {'x': x, 'y': y}
# To write to a file:
with open("output.json", "w") as f:
    json.dump(data, f)

# To print out the JSON string (which you could then hardcode into the JS)
json.dumps(data)

rawDescription: Transfer array from python to javascript


code:
producer.publish(
    msg, exchange=exchange,
    retry=retry, retry_policy=retry_policy,
    **dict({'routing_key': req.properties['reply_to'],
            'correlation_id': req.properties.get('correlation_id'),
            'serializer': serializers.type_to_name[req.content_type],
            'content_encoding': req.content_encoding}, **props)
)

rawDescription: How do I specify an AMQP correlationId with Kombu?

description: Specify an AMQP correlationId with Kombu


code:
from pyramid.renderers import render

from pyramid_mailer import get_mailer
from pyramid_mailer.message import Message

import premailer

def send_templated_mail(request, recipients, template, context, sender=None):
    """Send out templatized HTML and plain text emails.

    Each HTML email should have a plain text fallback. Premailer package is used to convert any CSS styles in HTML email messages to inline, so that email clients display them.

    The email is assembled from three different templates:

    * Read subject from a subject specific template $template.subject.txt

    * Generate HTML email from HTML template, $template.body.html

    * Generate plain text email from HTML template, $template.body.txt

    Make sure you have configured your template engine (Jinja 2) to read TXT templates beside HTML.

    :param request: HTTP request, passed to the template engine. Request configuration is used to get hold of the configured mailer.

    :param recipients: List of recipient emails

    :param template: Template filename base string for template tripled (subject, HTML body, plain text body). For example ``email/my_message`` would map to templates ``email/my_message.subject.txt``, ``email/my_message.body.txt``, ``email/my_message.body.html``

    :param context: Template context variables as a dict

    :param sender: Override the sender email - if not specific use the default set in the config as ``mail.default_sender``
    """

    assert recipients
    assert len(recipients) > 0
    assert type(recipients) != str, "Please give a list of recipients, not a string"

    subject = render(template + ".subject.txt", context, request=request)
    subject = subject.strip()

    html_body = render(template + ".body.html", context, request=request)
    text_body = render(template + ".body.txt", context, request=request)

    if not sender:
        sender = request.registry.settings["mail.default_sender"]

    # Inline CSS styles
    html_body = premailer.transform(html_body)

    message = Message(subject=subject, sender=sender, recipients=recipients, body=text_body, html=html_body)

    mailer = get_mailer(request)
    mailer.send(message)

rawDescription: What would be the right way to render jinja2 template in the pyramid view for an e-mail message?


code:
from behave import given, when, then

@given('a user')
def step_impl(context):
    from django.contrib.auth.models import User
    u = User(username='foo', email='foo@example.com')
    u.set_password('bar')

@when('I log in')
def step_impl(context):
    br = context.browser
    br.open(context.browser_url('/account/login/'))
    br.select_form(nr=0)
    br.form['username'] = 'foo'
    br.form['password'] = 'bar'
    br.submit()

@then('I see my account summary')
def step_impl(context):
    br = context.browser
    response = br.response()
    assert response.code == 200
    assert br.geturl().endswith('/account/')

@then('I see a warm and welcoming message')
def step_impl(context):
    # Remember, context.parse_soup() parses the current response in
    # the mechanize browser.
    soup = context.parse_soup()
    msg = str(soup.findAll('h2', attrs={'class': 'welcome'})[0])
    assert "Welcome, foo!" in msg

rawDescription: Generate Django behave code

description: Generate Django behave code


code:
for key in data:
  exec("{0} = '{1}'".format(key,data[key]))

rawDescription: how to: convert dictionary to strings in Python?

description: How to: convert dictionary to strings in Python


code:
from io import BytesIO
from PIL import Image
from django.core.files.uploadedfile import InMemoryUploadedFile

# Where image is your ImageFieldFile
pil_image = Image.open(image)
pil_image.resize((20, 20))

image_bytes = BytesIO()
pil_image.save(image_bytes)

new_image = InMemoryUploadedFile(
    image_bytes, None, image.name, image.type, None, None, None
)
image_bytes.close()

rawDescription: Changing image type in Django

description: Changing image type in Django


code: ['abc' + str(i) for i in range(10)]

rawDescription: Add string to list

description: Add string to list


code:
def attach_file(self, path, mimetype=None):
    """Attaches a file from the filesystem."""
    filename = os.path.basename(path)
    content = open(path, 'rb').read()
    self.attach(filename, content, mimetype)

rawDescription: Send bulk emails in Django with the same attachment


code: print((base64.b64encode(hmac.new(bytearray("SECRET".upper(), "ASCII") , bytearray("TEST","ASCII") , hashlib.sha512).digest())).decode("ASCII").replace("\n", ""))

rawDescription: Python 3 sign a message with key sha512

description: Python 3 sign a message with key sha512


code:
width = 200
height = 300
lllon, lllat, urlon, urlat = -144.99499512, -59.95500183, -65.03500366, 60.00500107
dlon = (urlon-lllon) / width
dLat = (urlat-lllat) / height
baseArray = np.fromfunction(lambda y,x: (1000.0 / (width + height)) * (y+x), (height, width), dtype = float)
lons = np.arange(lllon, urlon, dlon)
lats = np.arange(lllat, urlat, dLat)
lons, lats = np.meshgrid(lons, lats)

fig = plt.figure()
plt.title("The Plot")
m = Basemap(projection='cyl',
          resolution = 'c',
          llcrnrlon = lllon, llcrnrlat = lllat,
          urcrnrlon =urlon, urcrnrlat = urlat
)

m.pcolormesh(lons, lats, baseArray, shading='flat', latlon=True)
plt.show()

rawDescription: Basemap and numpy 2d array

description: Basemap and numpy 2d array


code:
topandlow = [(k, 100 * v / sum(som.values())) for k, v in som.most_common()[:3] + som.most_common()[-3:]]
for k, v in topandlow:
    print(k, "Procentaantal: ", v)

rawDescription: how to get the items from the dictionary python

description: Get the items from the dictionary python


code:
nums = [1, 2]
f = open("file", "r")
source = f.read()
f.close()
out = open("file", "w")
for line in source.splitlines():
    found = False
    for n in nums:
        if line.find(str(n)) > -1:
            found = True
            break
    if found:
        continue
    out.write(line+"\n")
out.close()

rawDescription: How to delete line from the file in python

description: Delete line from the file in python


code:
import subprocess
import datetime
import time

now = datetime.datetime.now()
stopat = now.replace(hour=7, minute=0, second=0, microsecond=0)
delta = stopat.timestamp() - now.timestamp()
if delta > 0:
    proc = subprocess.Popen("wget name", shell=True)
    try:
        proc.wait(delta)
    except subprocess.TimeoutExpired:
        proc.terminate()
        try:
            proc.wait(2)
        except subprocess.TimeoutExpired:
            proc.kill()

rawDescription: Stopping a thread without loop (a function that takes a long time)


code:
from fabric.context_managers import settings
with settings(host_string='remote_server'):
    run('ls -lart')

rawDescription: How to target a different host inside a Fabric command

description: Target a different host inside a Fabric command


rawDescription: How to prevent plotly from plotting automatically

description: Prevent plotly from plotting automatically


code:
with open('dirlist', 'r') as f, open('status', 'w') as status:
    for line in f.readlines():
        exists = os.path.exists(line)
        status.write(str(exists).upper())

rawDescription: Reading through a file list and checking directory for file's existence using Python


code:
stats = hotshot.stats.load("stones.prof")
stats.strip_dirs()
stats.sort_stats('time', 'calls')
readable_str = xprint_stats(stats, 20)

import pstats
def xprint_stats(self, *amount):
    x = ""
    for filename in self.files:
        x += " " + filename
    #if self.files: print >> self.stream
    # ?
    indent = ' ' * 8
    for func in self.top_level:
        #print >> self.stream, indent, xfunc_get_function_name(func)
        x += indent + pstats.func_get_function_name(func)

    #print >> self.stream, indent, self.total_calls, "function calls",
    x +=  indent + str(self.total_calls) + " function calls" + " "
    if self.total_calls != self.prim_calls:
        #print >> self.stream, "(%d primitive calls)" % self.prim_calls,
        x += "(%d primitive calls)" % self.prim_calls + " "
    #print >> self.stream, "in %.3f seconds" % self.total_tt
    #print >> self.stream
    x +=  "in %.3f seconds" % self.total_tt + "\n"
    #width, list = stats.get_print_list(amount)
    msg, width, list = xget_print_list(stats, amount)
    x += msg

    if list:
        #self.print_title()
        x += "\n" + '   ncalls  tottime  percall  cumtime  percall filename:lineno(function)'
        x += "\n"
        for func in list:
            #self.print_line(func)
            x +=  xprint_line(self, func) + "\n"
#        print >> self.stream
#        print >> self.stream
    #return self
    return x

def xprint_line(self, func):
    x = ""
    cc, nc, tt, ct, callers = self.stats[func]
    c = str(nc)
    if nc != cc:
        c = c + '/' + str(cc)
#    print >> self.stream, c.rjust(9),
#    print >> self.stream, f8(tt),
    x +=  c.rjust(9) + " "
    x +=  pstats.f8(tt) + " "
    if nc == 0:
        #print >> self.stream, ' '*8,
       x +=  ' '*8
    else:
        #print >> self.stream, f8(float(tt)/nc),
        x +=  pstats.f8(float(tt)/nc) + " "
    #print >> self.stream, f8(ct),
    x +=  pstats.f8(ct) + " "
    if cc == 0:
        #print >> self.stream, ' '*8,
        x +=  ' '*8
    else:
        #print >> self.stream, f8(float(ct)/cc),
        x +=   pstats.f8(float(ct)/cc) + " "
    #print >> self.stream, func_std_string(func)
    x +=  pstats.func_std_string(func) + " "
    return x

def xget_print_list(self, sel_list):
    width = self.max_name_len
    if self.fcn_list:
        stat_list = self.fcn_list[:]
        msg = "   Ordered by: " + self.sort_type + '\n'
    else:
        stat_list = self.stats.keys()
        msg = "   Random listing order was used\n"

    for selection in sel_list:
        stat_list, msg = self.eval_print_amount(selection, stat_list, msg)

    count = len(stat_list)

    if not stat_list:
        return 0, stat_list
    #print >> self.stream, msg
    if count < len(self.stats):
        width = 0
        for func in stat_list:
            if  len(pstats.func_std_string(func)) > width:
                width = len(pstats.func_std_string(func))
    #return width+2, stat_list
    return msg, width+2, stat_list

rawDescription: Python stats: how do I write it to a (human readable) file


code: minus_seven = today - datetime.timedelta(days = 7)

rawDescription: Datetime problem at start of month in Python


code:
from django.template.defaultfilters import slugify

class Migration(DataMigration):

    def forwards(self, orm):
        for obj in orm.MyModel.objects.filter(slug__isnull=True):
            slug = slugify(obj.name)
            obj.slug = slug
            suffix = 2
            while orm.MyModel.objects.filter(slug=obj.slug).exists():
                obj.slug = "%s-%d" % (slug, suffix)
                suffix = suffix + 1
            obj.save()

    def backwards(self, orm):
        pass # no need to change anything

rawDescription: Generate slug field data for existing entries in database


code:
keepgoing = True
while keepgoing:
    userInput = input("Please enter an integer: ")  # Get the input.
    try:
        userInput = int(userInput)  # Try to convert it into an integer.
    except ValueError:
        if userInput:  # See if input is non-empty.
            print("Sorry, that is not an integer.")
        else: # If we get here, there was no input.
            print("Empty input")
    else:
        keepgoing = False

rawDescription: Specific Try and Except

description: Specific Try and Except


code:
rank = [1, 2, 3]
suit = ['clubs', 'hearts', 'spades']
card = [(a, b) for a in rank for b in suit]

rawDescription: make a list of int and a list of string into a list of tuple (int,string)

description: Make a list of int and a list of string into a list of tuple (int,string)


code:
f = open(filename, 'w')
f.write("hello\talex")

rawDescription: How do I write a "tab" in Python?

description: Write a "tab" in Python


code:
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
import itertools as IT
import numpy as np
import matplotlib.cbook as cbook

def text_to_pixels(text, path='arialbd.ttf', fontsize=14):
    """
    http://stackoverflow.com/a/27753869/190597 (jsheperd)
    http://stackoverflow.com/a/36386628/190597 (unutbu)
    """
    font = ImageFont.truetype(path, fontsize)
    w, h = font.getsize(text)
    h *= 2
    image = Image.new('L', (w, h), 1)
    draw = ImageDraw.Draw(image)
    draw.text((0, 0), text, font=font)
    arr = np.asarray(image)
    arr = np.where(arr, 0, 1)
    arr = arr[(arr != 0).any(axis=1)]
    return arr

def get_image():
    fn = cbook.get_sample_data("ada.png")
    face_img = Image.open(fn).convert('RGBA')
    face_img = face_img.resize((30, 40), Image.ANTIALIAS)
    # give image a white background
    img = Image.new('RGBA', size=(36, 46), color=(255, 255, 255))
    img.paste(face_img, (3, 3))
    return img

def sqdist(a, b):
    return ((a -b)**2).sum()

def pics_in_text(text, faces, img_width=600, img_height=250, path='arialbd.ttf',
                 fontsize=20, minsep=1000):
    arr = text_to_pixels(text, path=path, fontsize=fontsize)
    yx = np.column_stack(np.where(arr)).astype(float)
    yx /= arr.shape
    yx *= (0.75, 0.90)
    yx += 0.05
    yx *= (img_height, img_width)
    yx = yx.astype('int')
    np.random.shuffle(yx)
    keep = []
    for coord in yx:
        if all(sqdist(item, coord) > minsep for item in keep):
            keep.append(coord)
    yx = IT.cycle(keep)

    img = Image.new('RGBA', size=(img_width, img_height), color=(255, 255, 255, 255))
    seen = list()
    for face, coord in zip(faces, yx):
        deg = np.random.uniform(-45, 45)
        face = face.rotate(deg, resample=Image.BICUBIC, expand=False)
        img.paste(face, tuple(coord[::-1]), mask=face)
    return img

def get_image():
    import matplotlib.cbook as cbook
    fn = cbook.get_sample_data("ada.png")
    face_img = Image.open(fn).convert('RGBA')
    face_img = face_img.resize((30, 40), Image.ANTIALIAS)
    # give image a white background
    img = Image.new('RGBA', size=(36, 46), color=(255, 255, 255))
    img.paste(face_img, (3, 3))
    return img

num_faces = 650
faces = IT.islice(IT.cycle([get_image()]), num_faces)
img = pics_in_text('800', faces, img_width=1200, img_height=500,
             path='/usr/share/fonts/truetype/msttcorefonts/Comic_Sans_MS.ttf',
             fontsize=40, minsep=375)
img.save('/tmp/out.png', 'PNG')

rawDescription: Layout images in form of a number

description: Layout images in form of a number


code:
import sys

if __name__ == "__main__":
    if '-s' in sys.argv:
        sort_files()

rawDescription: call python module functions from command line

description: Call python module functions from command line


code:
df = publishers.reset_index()
df.columns = ['Publisher', 'Frequency']
df.to_excel('publisher.xlsx',
            sheet_name='publisher frequencies',
            index=False)

rawDescription: how to add columns names to a DataFrame and save it to Excel

description: Add columns names to a DataFrame and save it to Excel


rawDescription: Remove rows in 3D numpy array

description: Remove rows in 3D numpy array


rawDescription: Assign value to missing data that isn't already in the array


code:
with db.transaction():
    with db.savepoint():
        do_stuff()
    with db.savepoint():
        do_more_stuff()

rawDescription: Is it possible to nest transactions in peewee + sqlite?


code: [w for w in words if all([w[i] in chars[i] for i in range(len(w))])]

rawDescription: Advanced Python list comprehension

description: Advanced Python list comprehension


code:
import os
os.system("start python perf_test.py 5")

rawDescription: how to launch a command window from Python

description: Launch a command window from Python


code:
def node_recurse_generator(node):
    yield node.value
    for n in node.ChildElements:
        for rn in node_recurse_generator(n):
            yield rn

rawDescription: Python generators: correct code recursing a tree


code:
import json
import sqlite3

def get_my_jsonified_data(key):
    with sqlite3.connect('test.db') as conn:
        cursor = conn.cursor()
        cursor.execute("SELECT * FROM mytable WHERE column=?;", [key])
        data = cursor.fetchall()
        return json.dumps(data)

rawDescription: Send JSON response from Sqlite queries in Python


code:
import os
basedir = os.environ.get('OPENSHIFT_DATA_DIR')

import sqlite3
conn = sqlite3.connect(os.path.join(basedir,'example.db'))

rawDescription: My sqllite database gets reset every time I push changes, hosted on Openshift


code:
import copy

class Crazy(object):
  def __init__(self, body, weird=copy.copy):
    self.gomez = body
    self.cousinitt = weird
  def __mul__(self, n):
    return [self.cousinitt(x) for x in (self.gomez * n)]

a = Crazy([[]]) * 3

rawDescription: Python - Using the Multiply Operator to Create Copies of Objects in Lists


code: hash(l)

rawDescription: How to hash lists?

description: Hash lists


code:
p = urlparse.urlparse(my_url, 'http')
netloc = p.netloc or p.path
path = p.path if p.netloc else ''
if not netloc.startswith('www.'):
    netloc = 'www.' + netloc

p = urlparse.ParseResult('http', netloc, path, *p[3:])
print(p.geturl())

rawDescription: How to prepend http if the url doesn't have http in it?

description: Prepend http if the url doesn't have http in it


rawDescription: Replace some string part with another Django


code:
import xml.etree.ElementTree as ET

str = "<sec>John</sec> said hi to a woman (named <sec>Mary</sec>)"

doc = ET.fromstring("<root>" + str + "</root>")
result = [x.text for x in doc.findall(".//sec")]

# >>> ['John', 'Mary']

rawDescription: Match everything inside multiple instances of a tag in a string in python


code:
user_fields = {"name", "pwd"}
jsondict= {"name":"value","pwd":"pwdvalue","email":"email@gmail.com"}
userdict = {key: value for (key, value) in jsondict.items() if key in user_fields}
u = users(**userdict)

rawDescription: python,django - can i call save directly in views ? i hav array,from which only some keys need to be saved,so automation or manual?

description: Python,django - can i call save directly in views ? i hav array,from which only some keys need to be saved,so automation or manual


code:
n = 10

ax = locks.plot(kind='bar', y='SUM')
ticks = ax.xaxis.get_ticklocs()
ticklabels = [l.get_text() for l in ax.xaxis.get_ticklabels()]
ax.xaxis.set_ticks(ticks[::n])
ax.xaxis.set_ticklabels(ticklabels[::n])

ax.figure.show()

rawDescription: Pandas: bar plot xtick frequency

description: Pandas: bar plot xtick frequency


code:
from sqlalchemy.orm import aliased

Visit1 = aliased(Visit)
Visit2 = aliased(Visit)
session.query(User)\
    .join(Visit1, (Visit1.user_id==User.id) & (Visit1.visit_number==1))\
    .join(Visit2, (Visit2.user_id==User.id) & (Visit2.visit_number==2))\
    .values(User.id, Visit1.Score-Visit2.Score)

rawDescription: Comparing two database entries with sqlalchemy


code:
np.add.at(X,tuple(coords.T),1)
X

rawDescription: Accumulate constant value in Numpy Array


code:
def periodically_continued(a, b):
    interval = b - a
    return lambda f: lambda x: f((x - a) % interval + a)

@periodically_continued(-1, 1)
def f(x):
    return x

g = periodically_continued(0, 1)(lambda x: -x)

assert f(2.5) == 0.5
assert g(2.5) == -0.5

rawDescription: How to define periodic function in python?

description: Define periodic function in python


code:
import re
NAMES_AND_VALUES = re.compile(r'\w+')
OPERATORS = re.compile(r'(?:\+|\*|\-|\/)+')
string = '((a * 5) // ((10 - y) + z))'
NAMES_AND_VALUES.findall(string)
OPERATORS.findall(string)

rawDescription: Parse math expression elements from string to list


code:
import csv

with open('1.csv', 'r') as f:
    csv_f = csv.reader(f)

new_content = []
old_content = []

for row in csv_f:
    if 'yepme' in row[2]:
        new_content.append(row)
    else:
        old_content.append(row)

with open('output.csv', 'wb') as f:
    wr = csv.writer(f, dialect='excel')
    wr.writerows(new_content)

with open('1.csv', 'wb') as f:
    wr = csv.writer(f, dialect='excel')
    f.writerows(old_content)

rawDescription: Cut data from one sheet into another in csv in python


code:
grid = {}
points = []

def addPoint(x, y):
    # returns True if the point was accepted

    # compute the cell of the point
    ix = int(math.floor(x / dist))
    iy = int(math.floor(y / dist))

    # check cell and all neighbors
    for nhcell in ((ix-1, iy-1), (ix, iy-1), (ix+1, iy-1),
                   (ix-1,  iy ), (ix,  iy ), (ix+1,  iy ),
                   (ix-1, iy+1), (ix, iy+1), (ix+1, iy+1)):
        if nhcell in grid:
            for xx, yy in grid[nhcell]:
                if (x - xx)**2 + (y - yy)**2 < dist2:
                    # anoter existing point is too close
                    return False

    # the new point is fine
    points.add((x, y))

    # we should also add it to the grid for future checks
    if (ix, iy) in grid:
        grid[(ix, iy)].append((x, y))
    else:
        grid[(ix, iy)] = [(x, y)]

    return True

rawDescription: Most efficient way to remove x,y coordinates in a specified area


code:
#=====================================================
# purpose: logistic regression
import numpy as np
import scipy as sp
import scipy.optimize

import matplotlib as mpl
import os

# prepare the data
data = np.loadtxt('data.csv', delimiter=',', skiprows=1)
vY = data[:, 0]
mX = data[:, 1:]
# mX = (mX - np.mean(mX))/np.std(mX)  # standardize the data; if required

intercept = np.ones(mX.shape[0]).reshape(mX.shape[0], 1)
mX = np.concatenate((intercept, mX), axis = 1)
iK = mX.shape[1]
iN = mX.shape[0]

# logistic transformation
def logit(mX, vBeta):
    return((np.exp(np.dot(mX, vBeta))/(1.0 + np.exp(np.dot(mX, vBeta)))))

# test function call
vBeta0 = np.array([-.10296645, -.0332327, -.01209484, .44626211, .92554137, .53973828,
    1.7993371, .7148045  ])
logit(mX, vBeta0)

# cost function
def logLikelihoodLogit(vBeta, mX, vY):
    return(-(np.sum(vY*np.log(logit(mX, vBeta)) + (1-vY)*(np.log(1-logit(mX, vBeta))))))
logLikelihoodLogit(vBeta0, mX, vY) # test function call

# different parametrization of the cost function
def logLikelihoodLogitVerbose(vBeta, mX, vY):
    return(-(np.sum(vY*(np.dot(mX, vBeta) - np.log((1.0 + np.exp(np.dot(mX, vBeta))))) +
                    (1-vY)*(-np.log((1.0 + np.exp(np.dot(mX, vBeta))))))))
logLikelihoodLogitVerbose(vBeta0, mX, vY)  # test function call

# gradient function
def likelihoodScore(vBeta, mX, vY):
    return(np.dot(mX.T,
                  (logit(mX, vBeta) - vY)))
likelihoodScore(vBeta0, mX, vY).shape # test function call
sp.optimize.check_grad(logLikelihoodLogitVerbose, likelihoodScore,
                       vBeta0, mX, vY)  # check that the analytical gradient is close to
                                                # numerical gradient

# optimize the function (without gradient)
optimLogit = scipy.optimize.fmin_bfgs(logLikelihoodLogitVerbose,
                                  x0 = np.array([-.1, -.03, -.01, .44, .92, .53,
                                            1.8, .71]),
                                  args = (mX, vY), gtol = 1e-3)

# optimize the function (with gradient)
optimLogit = scipy.optimize.fmin_bfgs(logLikelihoodLogitVerbose,
                                  x0 = np.array([-.1, -.03, -.01, .44, .92, .53,
                                            1.8, .71]), fprime = likelihoodScore,
                                  args = (mX, vY), gtol = 1e-3)
#=====================================================

rawDescription: Logistic regression using SciPy

description: Logistic regression using SciPy


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

testData = np.random.rand(100,2)-[0.5, 0.5]

fig, ax = plt.subplots()
circle1=plt.Circle(testData[20,:],0,color='r',fill=False, clip_on = False)
ax.add_artist(circle1)
# i is the radius
def animate(i):
    #init()
    #you don't want to redraw the same dots over and over again, do you?
    circle1.set_radius(i)

def init():
    sctPlot, = ax.plot(testData[:,0], testData[:,1], ".")
    return sctPlot,

ani = animation.FuncAnimation(fig, animate, np.arange(0.4, 2, 0.1), init_func=init,
    interval=25, blit=False)
plt.show()

rawDescription: matplotlib circle, animation, how to remove old circle in animation

description: Matplotlib circle, animation, how to remove old circle in animation


code:
from ctypes import cast, pointer, c_int32, c_byte, POINTER
cast(pointer(c_int32(arg1)), POINTER(c_byte)).contents.value

rawDescription: Simulating C#'s sbyte (8 bit signed integer) casting in Python


code:
from settings_shared import DATABASES_SHARED
DATABASES = DATABASES_SHARED.copy()
DATABASES.update({ ... })

rawDescription: Single installation, multiple domains and apps?


code: env.hosts = env.hosts or ['host1', 'host2', 'host3']

rawDescription: Fabric : ignore env.hosts when using -H option


code:
import curses
import time
import threading

def show_progress(win,X_line,sleeping_time):

    # This is to move the progress bar per iteration.
    pos = 10
    # Random number I chose for demonstration.
    for i in range(15):
        # Add '.' for each iteration.
        win.addstr(X_line,pos,".")
        # Refresh or we'll never see it.
        win.refresh()
        # Here is where you can customize for data/percentage.
        time.sleep(sleeping_time)
        # Need to move up or we'll just redraw the same cell!
        pos += 1
    # Current text: Progress ............... Done!
    win.addstr(X_line,26,"Done!")
    # Gotta show our changes.
    win.refresh()
    # Without this the bar fades too quickly for this example.
    time.sleep(0.5)

def show_progress_A(win):
    show_progress( win, 1, 0.1)

def show_progress_B(win):
    show_progress( win, 4 , 0.5)

if __name__ == '__main__':
    curses.initscr()

    win = curses.newwin(6,32,14,10)
    win.border(0)
    win.addstr(1,1,"Progress ")
    win.addstr(4,1,"Progress ")
    win.refresh()

    threading.Thread( target = show_progress_B, args = (win,) ).start()
    time.sleep(2.0)
    threading.Thread( target = show_progress_A, args = (win,)).start()

rawDescription: Print 2 lines in the console concurrently in Python


rawDescription: Unit Test warning when migrating from 1.5 to 1.7


code:
# 0123456789012345678901234567890123456789012345678901234567890
# 1       firm A         Manhattan (company name)     25,000
#                        SK Ventures                  25,000
#                        AEA investors                10,000
# 2       firm B         Tencent collaboration        16,000
#                        id TechVentures              4,000
# 3       firm C         xxx                          625
# Field #1 is 8 wide (0 -> 7)
# Field #2 is 15 wide (8 -> 22)
# Field #3 is 19 wide (23 -> 41)
# Field #4 is arbitrarily wide (42 -> end of line)
field_lengths = [ 8, 15, 19, ]
data = []
with open('/path/to/file', 'r') as f:
    row = f.readline()
    row = row.strip()
    pieces = []
    for x in field_lengths:
        piece = row[:x].strip()
        pieces.append(piece)
        row = row[x:]
    pieces.append(row)
    data.append(pieces)

rawDescription: Python: parsing texts in a .txt file

description: Python: parsing texts in a .txt file


code:
class one(gtk.VBox):

  def __init__(self):
    gtk.VBox.__init__(self)
    self.builder = gtk.Builder()
    self.builder.add_from_file("ui_for_one.glade")
    some_widget = self.builder.get_object("some_widget")
    self.add(some_widget)
    self.builder.connect_signals(self)
    # No reason to call self.show() here, that should be done manually.

  #Your callback functions here

class two(object):  # This is the page in a notebook.

  def __init__(self):
    self.builder = gtk.Builder()
    self.builder.add_from_file("ui_for_two.glade")
    self.some_container = self.builder.get_object("some_container")
    self.one = one()
    self.some_container.pack_start(self.one, False, False)
    self.some_container.show_all() #recursively show some_container and all its child widgets

    self.builder.connect_signals(self)

rawDescription: gtk.Builder() and multiple glade files breaks

description: Gtk.Builder() and multiple glade files breaks


code:
def sorting(seq):
    prev = seq[0]
    conf = True
    for itr in seq:
        if itr < prev:
            conf = False
            break
        prev = itr
    if conf: return seq
    for i in range(len(seq)):
        j = i
        while j>0 and seq[j]<seq[j-1]:
            seq[j],seq[j-1]=seq[j-1],seq[j]
            j = j-1
    return seq

rawDescription: Finding the best case and worst case performance time for the code


code:
import numpy_indexed as npi
samples_mask = npi.multiplicity(train_y) >= n_min
filtered_train_y = train_y[samples_mask]

rawDescription: Remove rows from numpy array when its repeated less than n times


code:
def set_proxy(self,  proxy):

    proxy_url = QUrl(proxy)

    if unicode(proxy_url.scheme()).startswith('http'):
        protocol = QNetworkProxy.HttpProxy
    else:
        protocol = QNetworkProxy.Socks5Proxy
    QNetworkProxy.setApplicationProxy(
        QNetworkProxy(
            protocol,
            proxy_url.host(),
            proxy_url.port(),
            proxy_url.userName(),
            proxy_url.password()))

rawDescription: PyQt: how to use QWebPage with an anonimous proxy


code:
from selenium import webdriver
driver = webdriver.Chrome()
driver.get('https://in.finance.yahoo.com/q?s=RELIANCE.NS&ql=0')
for element in driver.find_elements_by_class_name('yfi-price-change-green'):
    print(element.text)

rawDescription: inconsitent behaviour of beautifulSoup

description: Inconsitent behaviour of beautifulSoup


code:
def getInput():
    while True:
        yield raw_input("enter input: ")

for input in getInput():
    if input == 'exit':
        break
    result = useInput(input)

rawDescription: How to break a Python while loop from a function within the loop

description: Break a Python while loop from a function within the loop


code:
def isHappy(x):
    while True:
        if x == 1:
            return True
        if x == 4:
            return False
        x = nextNumberInSequence(x)

rawDescription: when to stop when number is not a happy number

description: When to stop when number is not a happy number


code: from math import *

rawDescription: Python calculator - Implicit math module


code:
try:
    while True:
        ...
        ...
except KeyboardInterrupt:
    exit

rawDescription: Interrupt Python infinite while loop with key press


code:
import re
test = "hI MY NAME iS FoO bar"
re.split("foo", test, flags=re.IGNORECASE)

rawDescription: Split by a word (case insensitive)

description: Split by a word (case insensitive)


code:
def move():
    global x1, y1, dx, dy, flag, n

    x1, y1 = x1 + dx, y1 + dy

    if x1 > 360:
        n = 1
        x1, dx, dy = 360, 0, 15
        can1.itemconfig(1, fill=color[n])

    if y1 > 360:
        n = n + 2
        y1, dx, dy = 360, -15, 0
        can1.itemconfig(1, fill=color[n])

    if x1 < 10:
        n = 2
        x1, dx, dy = 10, 0, -15
        can1.itemconfig(1, fill=color[n])

    if y1 < 10:
        n = 3
        y1, dx, dy = 10, 15, 0
        can1.itemconfig(1, fill=color[n])

    can1.coords(oval1, x1, y1, x1 + 30, y1 + 30)

    if flag > 0:
        abl1.after(50, move)

rawDescription: How to change color in Python?

description: Change color in Python


code:
import datetime as dt
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

def drange(start, end, interval=dt.timedelta(days=1)):
    output = []
    while start <= end:
        output.append(start)
        start += interval
    return output

# Generate a series of dates for plotting...
edate = drange(dt.datetime(2012, 2, 1), dt.datetime(2012, 6, 15),
                      dt.timedelta(days=5))
bdate = drange(dt.datetime(2012, 1, 1), dt.datetime(2012, 5, 15),
                      dt.timedelta(days=5))

# Now convert them to matplotlib's internal format...
edate, bdate = [mdates.date2num(item) for item in (edate, bdate)]

ypos = range(len(edate))
fig, ax = plt.subplots()

# Plot the data
ax.barh(ypos, edate - bdate, left=bdate, height=0.8, align='center')
ax.axis('tight')

# We need to tell matplotlib that these are dates...
ax.xaxis_date()

plt.show()

rawDescription: How can i use xaxis_date() with barh()?

description: Use xaxis_date() with barh()


code:
for person in persons:
    for k, v in person.items():
        if isinstance(v, dict) and 'years' in v:
            person[k] = v['years']

rawDescription: How to perform quick upleveling in python?

description: Perform quick upleveling in python


rawDescription: Python - sort a list of lists that are uneven in length


code:
if re.match(".*AuditFeesExpenses", item['name']):
    print(file.split(os.path.sep)[-1], end="| ")
    print(item['name'], end="| ")
    print(item.get_text())
    break

rawDescription: How to proceed to next file after first match - Python 3.x

description: Proceed to next file after first match - Python 3.x


code:
path=[1,2,3,4,5]
return str(path)

rawDescription: How to retrieve values of list in browser using web2py?

description: Retrieve values of list in browser using web2py


code:
from wsgiref import simple_server
from SocketServer import ThreadingMixIn

class ThreadingWSGIServer (ThreadingMixIn, simple_server.WSGIServer): pass

server = ThreadingWSGIServer(...)
server.set_app(app)
server.serve_forever()

rawDescription: wsgi in multijob mode

description: Wsgi in multijob mode


code:
p = df["input"].pct_change()
p
p.loc[(df["input"].shift() < 0) & (df["input"] > 0)] *= -1
p

rawDescription: How to make pandas/core/generic/pct_change to return a positive value when changing from a negative to a positive value

description: Make pandas/core/generic/pct_change to return a positive value when changing from a negative to a positive value


rawDescription: return regex variable without knowing variable names

description: Return regex variable without knowing variable names


code:
import cgi
form = cgi.FieldStorage()
form.value

rawDescription: receive xml content of http post request from apache cgi python

description: Receive xml content of http post request from apache cgi python


code:
#!/usr/bin/env python
from subprocess import call, check_call

try:
   rc = call(['omxplayer', 'first file'])
except KeyboardInterrupt:
   check_call(['omxplayer', 'second file'])
else:
   if rc != 0:
      raise RuntimeError('omxplayer failed to play the first file, '
                         'return code: %d' % rc)

rawDescription: Popen.kill() failing

description: Popen.kill() failing


code:
import re
myString = "HI there. You should higher that person for the job. Hi hi."
keyword = "hi"
search = re.compile(r'\b(%s)\b' % keyword, re.I)
search.sub('<b>\\1</b>', myString)

rawDescription: Python: Replace string with prefixStringSuffix keeping original case, but ignoring case when searching for match


code:
qp = QPixmap()
qp.loadFromData(my_bytes)

rawDescription: Displaying Image (in bytes) in PyQt

description: Displaying Image (in bytes) in PyQt


code:
app = webapp2.WSGIApplication([
    webapp2.Route('/', handler='handlers.HomeHandler', name='home'),
    webapp2.Route('/wiki', handler=WikiHandler, name='wiki'),
    webapp2.Route('/wiki/<page>', handler=WikiHandler, name='wiki-page'),
])

# /
uri = uri_for('home')
# http://localhost:8080/
uri = uri_for('home', _full=True)
# /wiki
uri = uri_for('wiki')
# http://localhost:8080/wiki
uri = uri_for('wiki', _full=True)
# http://localhost:8080/wiki#my-heading
uri = uri_for('wiki', _full=True, _fragment='my-heading')
# /wiki/my-first-page
uri = uri_for('wiki-page', page='my-first-page')
# /wiki/my-first-page?format=atom
uri = uri_for('wiki-page', page='my-first-page', format='atom')

rawDescription: webapp2 - How to reverse URL in templates?

description: Webapp2 - How to reverse URL in templates


code:
import urllib2

CHUNKSIZE = 4096

r = urllib2.urlopen('http://www.python.org')

buffer = b''

while True:
    chunk = r.read(CHUNKSIZE)
    if not chunk:
        break
    if bad_thing_happened:
        break

    buffer += chunk

rawDescription: How to "break" out of urllib read

description: "break" out of urllib read


rawDescription: How to implement a timeout control for urlllib2.urlopen

description: Implement a timeout control for urlllib2.urlopen


code: re.findall(r'\d+%', text)

rawDescription: Extracts all the number before percentage in Python?


code:
import subprocess
from time import sleep
filename="file.foo"
finished = False
while not finished:
    handlesactive=subprocess.check_output("handle.exe")
    activehandles=str(handlesactive).count(filename)
    if activehandles == 0: finished = True
    print("still busy")
    sleep(2)

rawDescription: os.stat doesn't update when large file is being copied

description: Os.stat doesn't update when large file is being copied


code:
raw = subprocess.check_output(['iwconfig'],stderr=subprocess.STDOUT)
data = raw.decode(sys.stdin.encoding)

rawDescription: Using python to measure Wi-Fi

description: Using python to measure Wi-Fi


code:
class ConversationManager(models.Manager):
    def has_all(self, participants):
        # Start with all conversations
        reducedQs = self.get_query_set()
        for p in participants:
            # Reduce to conversations that have a participant "p"
            reducedQs = reducedQs.filter(participants__id=p.id)
        return reducedQs

rawDescription: Django M2M QuerySet filtering on multiple foreign keys


code: {apple:red, banana:yellow}.get(value)

rawDescription: How to avoid if/elif/else when one value corresponds with another?

description: Avoid if/elif/else when one value corresponds with another


code:
for x in range(1,20): #loop to create 19 subdirectories
    path = os.path.join(dir_Name, str(x))
    os.makedirs(path, exist_ok=True) #create directories 1/ 2/ 3/ etc..
    shutil.copy(filename, os.path.join(path, filename))
    shutil.copy(filename1, os.path.join(path, filename1))
    with open(os.path.join(path, "fragments_procs.in"), 'w') as frag:
        frag.write(str(x) + "\n" + str(20-x)) #file will read 1, 19, since it is on first loop and must be in 1/, second file will read 2 18 must be in 2/ etc...

rawDescription: Loop control when creating directories

description: Loop control when creating directories


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

x,y,temp = np.loadtxt('data.txt').T #Transposed for easier unpacking
nrows, ncols = 100, 100
grid = temp.reshape((nrows, ncols))

plt.imshow(grid, extent=(x.min(), x.max(), y.max(), y.min()),
           interpolation='nearest', cmap=cm.gist_rainbow)
plt.show()

rawDescription: Make a 2D pixel plot with matplotlib

description: Make a 2D pixel plot with matplotlib


code:
def _Kbhit():
    fd = sys.stdin.fileno()
    fl = fcntl.fcntl(fd, fcntl.F_GETFL)
    fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)
    try:
        chars = sys.stdin.read(10)
    except TypeError:
        chars = ""
    finally:
        fcntl.fcntl(fd, fcntl.F_SETFL, fl)
        return chars

rawDescription: How can I tell how much to read from nonblocking stdin?

description: Tell how much to read from nonblocking stdin


code:
class BoatList(generics.ListCreateAPIView):
    permission_classes = (IsOwnerOrReadOnly,)
    serializer_class = BoatSerializer
    filter_backends = (filters.DjangoFilterBackend,)
    filter_fields = ('id', 'home_port',)

    def get_queryset(self):
        id_list = self.request.GET.getlist("id")
        if not id_list:
            return []
        return Boat.objects.filter(id__in=id_list)

rawDescription: Django-Filter and query with an array

description: Django-Filter and query with an array


code:
x = linspace(0,10)
y1 = randn(50)
y2 = randn(50)+10

scatter(x, y1, color='red')
scatter(x, y2, color='blue')

rawDescription: Color on a scatter graph Python Matplotlib


code:
xml_data = '''<?xml version='1.0' encoding='ASCII' ?>
<root>
<foo>

<c></c>
</foo>
<bars>
<bar>
<one>interesting</one>
<two>interesting</two>
<three>interesting</three>
</bar>
<bar>
<one>interesting</one>
<two>interesting</two>
<three>interesting</three>
</bar>
<bar>
<one>interesting</one>
<two>interesting</two>
<three>interesting</three>
</bar>
</bars>
</root>
'''

from lxml import etree

root = etree.fromstring(xml_data)
for bars in root.findall('.//bars'):
    print(etree.tostring(bars, method='text'))

rawDescription: Python lxml and parsing a subtree

description: Python lxml and parsing a subtree


code:
list1 = ['paste', 'text', 'text', 'here', 'here', 'here', 'my', 'i', 'i', 'me', 'me']
list2 = ["i","me"]
list3 = [item for item in list1 if item not in list2]
list3

rawDescription: remove elements in one list present in another list

description: Remove elements in one list present in another list


code:
import sqlite3
conn = sqlite3.connect('example.db')
c = conn.cursor()
c.execute('''CREATE TABLE table_name {}'''.format(tuple(column_list)))

rawDescription: column names as variables while creating table

description: Column names as variables while creating table


code:
U = np.random.rand(3,24,5)
R = np.eye(3,3)
result = np.einsum( "ijk,il", U,R )

rawDescription: numpy: broadcast matrix multiply accross array

description: Numpy: broadcast matrix multiply accross array


code:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import ImageGrid

# Generate some random data
data_top = np.random.random((3,10,10)) * 5
data_bot = np.random.random((3,20,20)) * 10

fig  = plt.figure()

grid_top = ImageGrid(fig, 211, nrows_ncols = (1, 3),
                     cbar_location = "right",
                     cbar_mode="single",
                     cbar_pad=.2)
grid_bot = ImageGrid(fig, 212, nrows_ncols = (1, 3),
                     cbar_location = "right",
                     cbar_mode="single",
                     cbar_pad=.2)

for n in xrange(3):
    im1 = grid_top[n].imshow(data_top[n],
                            interpolation='nearest', vmin=0, vmax=5)

    im2 = grid_bot[n].imshow(data_bot[n], cmap=plt.get_cmap('bone'),
                             interpolation='nearest', vmin=0, vmax=10)

grid_top.cbar_axes[0].colorbar(im1)
grid_bot.cbar_axes[0].colorbar(im2)

plt.show()

rawDescription: How do I add two colorbars on the same plot in pyplot (matplotlib)?

description: Add two colorbars on the same plot in pyplot (matplotlib)


code:
from collections import defaultdict
import json

d = defaultdict(dict)
for date in dates:
    d[date.year][date.month] = info_for_date(date)
json.dumps(d)

rawDescription: How do I create a data structure that will be serialized this JSON format in python?

description: Create a data structure that will be serialized this JSON format in python


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

pos = np.arange(4)
freq = [0, 1, 3, 0]
width = 1.0

plt.bar(pos, freq, width, color='b',)
plt.xlim(pos.min(), pos.max()+width)
plt.show()

rawDescription: How to force PyPlot to show empty bins in a bar plot

description: Force PyPlot to show empty bins in a bar plot


code:
from math import ceil

def week_of_month(dt):
    """ Returns the week of the month for the specified date.
    """

    first_day = dt.replace(day=1)

    dom = dt.day
    adjusted_dom = dom + first_day.weekday()

    return int(ceil(adjusted_dom/7.0))

rawDescription: python - Week number of the month

description: Python - Week number of the month


code: bar_2 = None # type: Foo

rawDescription: Define an object of a certain class as None


code:
def process_sublist(i, sublist):
    """Deliver this i-th sublist to the external system."""
    pass

def process_list(main_list, sublist_size):
    """Split main_list into sublists and call process_sublist."""
    for i in range(0, len(main_list), sublist_size):
        index = i / sublist_size
        sublist = main_list[i:i+sublist_size]
        process_sublist(index, sublist)

# Use the function process_list.
main_list = ['1029', '2314', '466754', '6345', '3456', ...]
process_list(main_list, 300)

rawDescription: Dynamically split lists in python

description: Dynamically split lists in python


code:
import os
from django.conf import settings

file_name = os.path.join(settings.BASE_DIR, 'file1.json')
details_raw = open(file_name, 'r')

rawDescription: Django on Ubuntu VPS [Errno 2] No such file or directory: 'file1.json'


code:
import pwd
pw = pwd.getpwnam("nobody")
uid = pw.pw_uid

rawDescription: How do I find userid by login (Python under *NIX)

description: Find userid by login (Python under *NIX)


rawDescription: comparison between the elements of list with keys of dictionary

description: Comparison between the elements of list with keys of dictionary


code:
def get_context_data(self, **kwargs):
    context = super(ProjectView , self).get_context_data(**kwargs)
    context['projects'] = Project.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')
    return context

rawDescription: How to add ListView to generic DetailView ? Django

description: Add ListView to generic DetailView ? Django


code:
from functools import reduce # if Python 3

reduce(lambda x, y: x.intersection(y), (set(x.split(',')) for x in aDict.values()))

rawDescription: python intersect of dict items

description: Python intersect of dict items


code:
from datetime import datetime, timedelta

# initial_date = datetime.today()
initial_date = datetime(2000, 3, 2)
interval = timedelta(days = 6)
increment = timedelta(days = 1)

i = initial_date - interval
while i <= initial_date:
    print(i)
    i += increment

rawDescription: "Month" issue in loop using ISODate

description: "Month" issue in loop using ISODate


code:
import string

{s: i for i, s in enumerate(string.ascii_uppercase, 1)}

rawDescription: Python predefined dictionaries or sets

description: Python predefined dictionaries or sets


code: typ, data = imap_conn.fetch(uid, '(BODY.PEEK[TEXT])')

rawDescription: Python IMAP call

description: Python IMAP call


code:
import numpy as np
a = np.random.rand(10,1)
b = np.random.rand(10,1)
c = b > 0.5
d = a * b # Note that * in NumPy is always elementwise (use .dot for matrix multiplication)
e = a + b
f = a.mean() # Can also use np.mean(a)
g = b.sum() # Can also use np.sum(b)

rawDescription: What is the preferred way to handle basic arrays in Python?


code:
from django import forms

class TeamForm(forms.ModelForm):
    manager = forms.ModelChoiceField(queryset=User.objects.order_by('username'))

    class Meta:
        model = Team

class TeamAdmin(admin.ModelAdmin):
    list_display = ('name', 'manager')
    form = TeamForm

rawDescription: Django Admin: Ordering of ForeignKey and ManyToManyField relations referencing User


code:
ax = [plt.subplot(gs[0]),]
ax.append(plt.subplot(gs[1], sharey=ax[0]))
ax.append(plt.subplot(gs[2], sharex=ax[0]))

rawDescription: How to create Matplotlib figure with image and profile plots that fit together?

description: Create Matplotlib figure with image and profile plots that fit together


code:
foo = set(range(0, 4))
foo
foo.update(range(2, 6))
foo

rawDescription: Python: how to add the contents of an iterable to a set?


code:
class PasswordLoggingFilter(logging.Filter):
    def filter(self, record):
        # Modify record, especially record.msg and/or record.args.
        if want_to_keep_record:
            return True
        else:
            return False

logger.addFilter(PasswordLoggingFilter())

rawDescription: selectively log requests using logging module

description: Selectively log requests using logging module


code:
import sys
...
if sys.argv[0].endswith('.exe'):
   ...

rawDescription: Is there a way for a python script to know what type of file it is?


code:
@user_required
def post(self, **kwargs):
    email = self.request.POST.get('email')
    auser = self.auth.get_user_by_session()
    userid = auser['user_id']
    user = auth_models.User.get_by_id(auser['user_id'])
    existing_user = auth_models.User.get_by_auth_id(email)

    if existing_user is not None:
        # You need to handle duplicates.
        # Maybe you merge the users? Maybe you return an error?
        pass

    # Test the uniqueness of the auth_id. We must do this to
    # be consistent with User.user_create()
    unique = '{0}.auth_id:{1}'.format(auth_models.__class__.__name__, email)

    if auth_models.User.unique_model.create(unique):
        # Append email to the auth_ids list
        user.auth_ids.append(email)
        user.put()
        return "Email updated"
    else:
        return 'some error'

rawDescription: How to add an auth_id with webapp2?

description: Add an auth_id with webapp2


code:
import math
userDecimals = 6
'{:.{}f}'.format(math.sqrt(1 - .1 **2), userDecimals)
userDecimals = 10
'{:.{}f}'.format(math.sqrt(1 - .1 **2), userDecimals)

rawDescription: user input value to use as decimal value python

description: User input value to use as decimal value python


code:
#!python3

"""
Per WikiPedia (https://en.wikipedia.org/wiki/Centre_points_of_Australia)

Median point
============

The median point was calculated as the midpoint between the extremes of
latitude and longitude of the continent.

    24 degrees 15 minutes south latitude, 133 degrees 25 minutes east
    longitude (24°15′S 133°25′E); position on SG53-01 Henbury 1:250 000
    and 5549 James 1:100 000 scale maps.

"""
MEDIAN_LAT = -(24.00 + 15.00/60.00)
MEDIAN_LON = (133 + 25.00/60.00)

"""
From the OP:

The starting grid has the overall shape of a rectangle, made up of
squares with width of 0.11 and length 0.11. The entire rectange is about
50x30. Lastly I have a shapefile which outlines the 'forecast zones' in
Australia, and if any point in the grid is outside this zone then we
omit it. So all the leftover points (insideoceanlist) are the ones in
Australia.
"""

DELTA_LAT = 0.11
DELTA_LON = 0.11

GRID_WIDTH = 50.0 # degrees
GRID_HEIGHT = 30.0 # degrees

GRID_ROWS = int(GRID_HEIGHT / DELTA_LAT) + 1
GRID_COLS = int(GRID_WIDTH / DELTA_LON) + 1

LAT_SIGN = 1.0 if MEDIAN_LAT >= 0 else -1.0
LON_SIGN = 1.0 if MEDIAN_LON >= 0 else -1.0

GRID_LOW_LAT = MEDIAN_LAT - (LAT_SIGN * GRID_HEIGHT / 2.0)
GRID_HIGH_LAT = MEDIAN_LAT + (LAT_SIGN * GRID_HEIGHT / 2.0)
GRID_MIN_LAT = min(GRID_LOW_LAT, GRID_HIGH_LAT)
GRID_MAX_LAT = max(GRID_LOW_LAT, GRID_HIGH_LAT)

GRID_LOW_LON = MEDIAN_LON - (LON_SIGN * GRID_WIDTH / 2.0)
GRID_HIGH_LON = MEDIAN_LON + (LON_SIGN * GRID_WIDTH / 2.0)
GRID_MIN_LON = min(GRID_LOW_LON, GRID_HIGH_LON)
GRID_MAX_LON = max(GRID_LOW_LON, GRID_HIGH_LON)

GRID_PROXIMITY_KM = 40.0

"""https://en.wikipedia.org/wiki/Longitude#Length_of_a_degree_of_longitude"""
_Degree_sizes_km = (
    (0,  110.574, 111.320),
    (15, 110.649, 107.551),
    (30, 110.852, 96.486),
    (45, 111.132, 78.847),
    (60, 111.412, 55.800),
    (75, 111.618, 28.902),
    (90, 111.694, 0.000),
)

# For the Australia situation, +/- 15 degrees means that our worst
# case scenario is about 40 degrees south. At that point, a single
# degree of longitude is smallest, with a size about 80 km. That
# in turn means a 40 km distance window will span half a degree or so.
# Since grid squares a 0.11 degree across, we have to check +/- 5
# cols.

GRID_SEARCH_COLS = 5

# Latitude degrees are nice and constant-like at about 110km. That means
# a .11 degree grid square is 12km or so, making our search range +/- 4
# rows.

GRID_SEARCH_ROWS = 4

def make_grid(rows, cols):
    return [[0 for col in range(cols)] for row in range(rows)]

Grid = make_grid(GRID_ROWS, GRID_COLS)

def _col_to_lon(col):
    return GRID_LOW_LON + (LON_SIGN * DELTA_LON * col)

Col_to_lon = [_col_to_lon(c) for c in range(GRID_COLS)]

def _row_to_lat(row):
    return GRID_LOW_LAT + (LAT_SIGN * DELTA_LAT * row)

Row_to_lat = [_row_to_lat(r) for r in range(GRID_ROWS)]

def pos_to_grid(pos):
    lat, lon = pos

    if lat < GRID_MIN_LAT or lat >= GRID_MAX_LAT:
        print("Lat limits:", GRID_MIN_LAT, GRID_MAX_LAT)
        print("Position {} is outside grid.".format(pos))
        return None

    if lon < GRID_MIN_LON or lon >= GRID_MAX_LON:
        print("Lon limits:", GRID_MIN_LON, GRID_MAX_LON)
        print("Position {} is outside grid.".format(pos))
        return None

    row = int((lat - GRID_LOW_LAT) / DELTA_LAT)
    col = int((lon - GRID_LOW_LON) / DELTA_LON)

    return (row, col)

def visit_nearby_grid_points(pos, dist_km):
    row, col = pos_to_grid(pos)

    # +0, +0 is not symmetric - don't increment twice
    Grid[row][col] += 1

    for dr in range(1, GRID_SEARCH_ROWS):
        for dc in range(1, GRID_SEARCH_COLS):
            misses = 0
            gridpos = Row_to_lat[row+dr], Col_to_lon[col+dc]
            if great_circle(pos, gridpos).meters <= dist_km:
                Grid[row+dr][col+dc] += 1
            else:
                misses += 1
            gridpos = Row_to_lat[row+dr], Col_to_lon[col-dc]
            if great_circle(pos, gridpos).meters <= dist_km:
                Grid[row+dr][col-dc] += 1
            else:
                misses += 1
            gridpos = Row_to_lat[row-dr], Col_to_lon[col+dc]
            if great_circle(pos, gridpos).meters <= dist_km:
                Grid[row-dr][col+dc] += 1
            else:
                misses += 1
            gridpos = Row_to_lat[row-dr], Col_to_lon[col-dc]
            if great_circle(pos, gridpos).meters <= dist_km:
                Grid[row-dr][col-dc] += 1
            else:
                misses += 1
            if misses == 4:
                break

def get_pos_from_line(line):
    """
    FIXME: Don't know the format of your data, just random numbers
    """
    import random
    return (random.uniform(GRID_LOW_LAT, GRID_HIGH_LAT),
            random.uniform(GRID_LOW_LON, GRID_HIGH_LON))

with open("strikes.data", "r") as strikes:
    for line in strikes:
        pos = get_pos_from_line(line)
        visit_nearby_grid_points(pos, GRID_PROXIMITY_KM)

rawDescription: Python creating density map efficiently

description: Python creating density map efficiently


code:
import urllib
import urllib2

username = 'foo'
password = 'bar'

passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, MY_APP_PATH, username, password)
authhandler = urllib2.HTTPBasicAuthHandler(passman)
opener = urllib2.build_opener(authhandler)
urllib2.install_opener(opener)

params= { "param1" : param1,
          "param2" : param2,
          "param3" : param3 }

xmlResults = urllib2.urlopen(MY_APP_PATH, urllib.urlencode(params)).read()
results = MyResponseParser.parse(xmlResults)

rawDescription: How do I add basic authentication to a Python REST request?

description: Add basic authentication to a Python REST request


code:
import alsaaudio
import random
import struct

BUFFER_SIZE = 1024

def noise_callback():
    return [random.randint(-20000, 20000) for i in range(BUFFER_SIZE)]

def openaudio(card_name, freq, buffer_size, callback):
    device = alsaaudio.PCM(card=card_name)

    device.setchannels(1)
    device.setrate(freq)
    device.setformat(alsaaudio.PCM_FORMAT_S16_LE)

    device.setperiodsize(buffer_size)

    while True:
        samples = callback()
        data = struct.pack("h" * len(samples), *samples)
        device.write(data)

openaudio(card_name="default", freq=44100, buffer_size=BUFFER_SIZE, callback=noise_callback)

rawDescription: Open audio with callback using ALSA

description: Open audio with callback using ALSA


code: [(field.name, getattr(obj,field.name)) for field in obj._meta.fields]

rawDescription: String Dictionary Representation of a Model/Object instance in Python/Django?


code:
import tkinter as tk

class Application(tk.Frame):
    def __init__(self, master=None):
        self.setLounge = 21.0
        tk.Frame.__init__(self, master)
        master.columnconfigure(0, weight=1)
        master.rowconfigure(0, weight=1)
        self.grid(sticky="news")
        self.createWidgets()

    def createWidgets(self):
        self.lou_dec = tk.Button(self)
        self.lou_dec["text"] = "<"
        self.lou_dec["command"] = self.louDec
        self.lou_dec.grid(row=1, column=1, sticky=("N", "S", "E", "W"))

        self.lblLouTemp = tk.Label(self)
        self.lblLouTemp["text"] = self.setLounge
        self.lblLouTemp.grid(row=1, column=2, sticky=(tk.N + tk.S + tk.E + tk.W))

        self.lou_inc = tk.Button(self)
        self.lou_inc["text"] = ">"
        self.lou_inc["command"] = self.louInc
        self.lou_inc.grid(row=1, column=3, sticky=(tk.N, tk.S, tk.E, tk.W))

        for i in range(1,4):
            self.columnconfigure(i, weight=1)
        self.rowconfigure(1, weight=1)

    def louDec(self):
        self.setLounge -= 0.5
        print ("%s" % self.setLounge)
        fo = open("/home/tony/Code/tempreg.txt", "w")
        fo.write("%s" % self.setLounge)
        fo.close()

    def louInc(self):
        self.setLounge += 0.5
        print ("%s" % self.setLounge)
        fo = open("/home/tony/Code/tempreg.txt", "w")
        fo.write("%s" % self.setLounge)
        fo.close()

root = tk.Tk()
root.title("Heating Controller")
root.geometry("320x240")
app = Application(master=root)
app.mainloop()

rawDescription: Tkinter widget not filling grid

description: Tkinter widget not filling grid


rawDescription: Upcounting output

description: Upcounting output


code:
class MyFraction:
    def __init__(self, numerator=1, denominator=1):
        self.numerator = numerator
        self.denominator = denominator

    def get_fraction(self):
        from fractions import Fraction
        return Fraction(numerator=self.numerator, denominator=self.denominator)

    def __repr__(self):
        return '{}/{}'.format(self.numerator, self.denominator)

f = MyFraction(numerator=7, denominator=14)
print(f)  # prints 7/14
print(f.get_fraction())  # prints 1/2

rawDescription: how to get fraction as it is ( without getting itssimplest fraction )? i vainly tried using this:

description: Get fraction as it is ( without getting itssimplest fraction )? i vainly tried using this:


code:
class DB_TempTestModel(db.Model):
    data = db.BlobProperty()

class MyHandler(webapp.RequestHandler):
    def get(self):
        starttime = datetime.datetime.now()
        lots_of_data = ' '*500000
        if self.request.get('a') == '1':
            db.put(DB_TempTestModel(data=lots_of_data))
            db.put(DB_TempTestModel(data=lots_of_data))
            db.put(DB_TempTestModel(data=lots_of_data))
            db.put(DB_TempTestModel(data=lots_of_data))
        if self.request.get('a') == '2':
            db.put_async(DB_TempTestModel(data=lots_of_data))
            db.put_async(DB_TempTestModel(data=lots_of_data))
            db.put_async(DB_TempTestModel(data=lots_of_data))
            db.put_async(DB_TempTestModel(data=lots_of_data))
        self.response.out.write(str(datetime.datetime.now()-starttime))

rawDescription: Is get_result() a required call for put_async() in Google App Engine


code:
response = HttpResponseRedirect(next)
# Do whatever else you need to do here with the response object
return response

rawDescription: How do I redirect an user back to the page they were trying to access once they log in? (Django)

description: Redirect an user back to the page they were trying to access once they log in? (Django)


code:
cls = object.__class__
object.__class__ = cls.__class__(cls.__name__ + "WithExtraBase", (cls, ExtraBase), {})

rawDescription: Adding base class to existing object in python


code:
from concurrent.futures import ThreadPoolExecutor
import sys

def some_action(line):
    pass # TODO: the actual task

with ThreadPoolExecutor() as executor:
    for line in sys.stdin:
        future = executor.submit(some_action, line)

rawDescription: Split tasks among threads in python

description: Split tasks among threads in python


code:
import pandas as pd
df = pd.read_stata('my_data_in.dta')
df.to_stata('my_data_out.dta')

rawDescription: Save .dta files in python

description: Save .dta files in python


code:
from inspect import getcallargs
def f1(a,b):
   """a==b"""
   pass

def f2(f, *f_args, **f_kwargs):
    f_callargs = getcallargs(f, *f_args, **f_kwargs)
    return eval(f.__doc__, None, f_callargs)

f2(f1, 2, 2)

rawDescription: How to get a functions arguments and values from outside the function?

description: Get a functions arguments and values from outside the function


code:
import functools

@functools.total_ordering
class Property():
    ...

rawDescription: reflected greater than magic methods

description: Reflected greater than magic methods


code:
test_str = "<1>dadad<2>gfdgf<3>"
import re
re.findall(r'(?=<).*?(?<=>)', test_str)

rawDescription: Split array between 2 symbols

description: Split array between 2 symbols


code: np.size(a) - np.count_nonzero(a)

rawDescription: Most efficient (and pythonic) way to count False values in 2D numpy arrays?


code:
class mymat(np.ndarray):
    def __new__(cls, n):
        ret = np.eye(n)
        return ret.view(cls)

rawDescription: Subclassing numpy.ndarray

description: Subclassing numpy.ndarray


code:
def setVal(new):
    global value
    value = new

rawDescription: Python module manipulation with other modules


code:
parser = OptionParser(usage='usage: %prog [options] arguments')
parser.add_option('-f', '--file',
                        dest='filename',
                        help='foo help')
(options, args) = parser.parse_args()
if options.filename is None:   # if filename is not given
    parser.error('Filename not given')

rawDescription: Is it possible to make an option in optparse a mandatory?


code:
connector = reactor.connectTCP(
            host=IP,
            port=PORT,
            factory=DemoFactory,
            timeout=30,
            bindAddress=(LOCAL_IP, 0))

connector.transport.getHandle().setsockopt(socket.IPPROTO_TCP, TCP_MD5SIG, md5sig)
reactor.run()

rawDescription: how to call setsockopt before reactor.connectTCP

description: Call setsockopt before reactor.connectTCP


code:
from tkinter import *
from shutil import disk_usage

class Sizer(Frame):

    @classmethod
    def main(cls):
        NoDefaultRoot()
        root = Tk()
        root.geometry('{}x{}'.format(200, 100))
        root.resizable(False, False)
        root.title('Drive Information')
        widget = cls(root)
        widget.grid(row=0, column=0, sticky=NSEW)
        root.mainloop()

    def __init__(self, master=None, cnf={}, **kw):
        super().__init__(master, cnf, **kw)
        self.selection = StringVar(self)
        self.menu = OptionMenu(self, self.selection, 'A:\\', 'B:\\', 'C:\\')
        self.menu.grid(row=0, column=0, sticky=NSEW)
        self.button = Button(self, text='Scan the drive', command=self.scan)
        self.button.grid(row=1, column=0, sticky=NSEW)
        self.display = Label(self)
        self.display.grid(row=2, column=0, sticky=NSEW)

    def scan(self):
        disk = self.selection.get()
        try:
            information = disk_usage(disk)
        except FileNotFoundError:
            self.display['text'] = 'Disk {!r} cound not be found'.format(disk)
        else:
            self.display['text'] = 'Used: {}\nFree: {}'.format(
                information.used, information.free)

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

rawDescription: accessing a USB drive in python for a beginner

description: Accessing a USB drive in python for a beginner


code:
from gurobipy import Model, GRB, LinExpr, quicksum

dual_subproblem = Model('dual_subproblem_(0,0)')
dual_subproblem.setParam('OutputFlag', 0)  # Also dual_subproblem.params.outputflag = 0
dual_subproblem.params.threads = 1
dual_subproblem.modelSense = GRB.MAXIMIZE
dual_subproblem.update()

rawDescription: Gurobi on Python: Muting the optimize function


code:
import signal, subprocess

old_action = signal.signal(signal.SIGINT, signal.SIG_IGN)
subprocess.call(['less', '/etc/passwd'])
signal.signal(signal.SIGINT, old_action)         # restore original signal handler

rawDescription: Delegate signal handling to a child process in python


code:
import dateutil
from dateutil import parser
datestrs = ['Monday 17th of September 2012 08:20:32 AM CDT', 'Fri, 01 Feb 2013 12:55:59 GMT', '2015-04-07 13:39:21', 'Fri Sep 11 15:58:57 +0000 2015']
datetime_objs = []
for datestr in datestrs:
  datetime_objs.append(parser.parse(datestr))

datetime_objs

rawDescription: Normalizing Timestamps in Different formats to a common format


code:
#--- Load a csv file and set CRS
#---1 Reference library
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from qgis.core import *
from qgis.utils import iface

#---  2 Turn of the CRS dialog box
s = QSettings()
oldValidation = s.value( "/Projections/defaultBehaviour")
s.setValue( "/Projections/defaultBehaviour", "useGlobal" )

#--- 3 Set file name here
InFlnm='Test.csv'

#--- 4  Set pathname here
InDrPth='C:/_Work/PyQGIS/Test/'

#--- 5 Build file name an path for uri
InFlPth="file:///"+InDrPth+InFlnm

#---  6 Set import Sting here note only need to set x and y other come for free
uri = InFlPth+"?delimiter=%s&xField=%s&yField=%s" % (",","x","y")

#--- 7 Load point layer
bh = QgsVectorLayer(uri, InFlnm, "delimitedtext")

#--- 8 Confirm something is loaded and valid
bh.isValid()

#--- 9 Set CRS
bh.setCrs(QgsCoordinateReferenceSystem(32365, QgsCoordinateReferenceSystem.EpsgCrsId))

#--- 10 Display the layer into QGIS (but it asks for CRS before displaying_
QgsMapLayerRegistry.instance().addMapLayer(bh)

#--- 11 turn CRS dialog box back on again
s.setValue( "/Projections/defaultBehaviour", oldValidation )

rawDescription: Import csv into QGIS using Python

description: Import csv into QGIS using Python


code:
import functools
...

# note that these are the 'new style' slot connections (not necessarily needed)
self.menu_entry_x.triggered.connect(functools.partial(myfunc, x))
self.menu_entry_y.triggered.connect(functools.partial(myfunc, y))

rawDescription: PyQt and QSignalMapper/lambdas - multiple signals, single slot


code:
counter = 0
while True:
    if os.path.isfile(name + str(counter) + suffix):
        counter += 1
    else:
        filepath = name + str(counter) + suffix
        break

rawDescription: Python Append to filename

description: Python Append to filename


code:
import wx

class MyFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None)

        self.panel = wx.Panel(self)

        # create controls
        self.cntrlPanel = wx.Panel(self.panel)
        stc1 = wx.StaticText(self.cntrlPanel, label="wow it works")
        stc2 = wx.StaticText(self.cntrlPanel, label="yes it works")
        btn = wx.Button(self.cntrlPanel, label="help?")
        btn.Bind(wx.EVT_BUTTON, self._onShowHelp)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(stc1)
        sizer.Add(stc2)
        sizer.Add(btn)
        self.cntrlPanel.SetSizer(sizer)

        # create help panel
        self.helpPanel = wx.Panel(self.panel)
        self.stcHelp = wx.StaticText(self.helpPanel, label="help help help\n"*8)
        btn = wx.Button(self.helpPanel, label="close[x]")
        btn.Bind(wx.EVT_BUTTON, self._onShowCntrls)
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.stcHelp)
        sizer.Add(btn)
        self.helpPanel.SetSizer(sizer)
        self.helpPanel.Hide()
        self.helpPanel.Raise()
        self.helpPanel.SetBackgroundColour((240,250,240))
        self.Bind(wx.EVT_SIZE, self._onSize)

        self._onShowCntrls(None)

    def _onShowHelp(self, event):
        self.helpPanel.SetPosition((0,0))
        self.helpPanel.Show()
        self.cntrlPanel.Hide()

    def _onShowCntrls(self, event):
        self.cntrlPanel.SetPosition((0,0))
        self.helpPanel.Hide()
        self.cntrlPanel.Show()

    def _onSize(self, event):
        event.Skip()
        self.helpPanel.SetSize(self.GetClientSizeTuple())
        self.cntrlPanel.SetSize(self.GetClientSizeTuple())

app = wx.PySimpleApp()
frame = MyFrame()
frame.Show()
app.SetTopWindow(frame)
app.MainLoop()

rawDescription: wxPython: Good way to overlay a wx.Panel on an existing wx.Panel

description: WxPython: Good way to overlay a wx.Panel on an existing wx.Panel


code:
import socket
import threading

class Client(threading.Thread):

    def __init__(self):
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.socket.connect(('127.0.0.1', 1234))
        print('Client connected to server')

        t = threading.Thread(target = self.read)
        t.daemon = True # helpful if you want it to die automatically
        t.start()

        t2 = threading.thread(target = self.write)
        t2.daemon = True
        t2.start()

    def read(self):
        while True:
            data = self.socket.recv(1024)
            if data:
                print('Received:', data)

    def write(self):
        while True:
            message = input()
            self.socket.send(bytes(message, 'utf-8'))

client = Client()

rawDescription: Python Multithreading, run two functions at the same time


code:
import re

def convert_vb_to_c(vb_code_lines):
    c_code = []
    current_with = ""
    for line in vb_code_lines:
        if re.search(r'^\s*With', line) is not None:
            current_with = line[5:] + "."
            continue
        elif re.search(r'^\s*End With', line) is not None:
            current_with = "{error_outside_with_replacement}"
            continue
        line = re.sub(r'(?<=[\s[({])\.', current_with, line)
        c_code.append(line)
    return "\n".join(c_code)

example = """
With Npclist[NpcIndex]
    .goTo(245)
End With
With hatla
    .matla.tatla[.matla.other] = .matla.other2
    dont.mind.me(.do.mind.me)
    .next()
End With
"""
# use file_object.readlines() in real life
print(convert_vb_to_c(example.split("\n")))

rawDescription: Python complex regex replace

description: Python complex regex replace


code:
from django.db import models

class MyField(models.CharField):

     def to_python(self, value):
         if value in ('Y', '1'):
             return True
         if value in ('N', '0'):
             return False
         raise ValueError

rawDescription: Django ORM: can I have a BooleanField associated to a char column in the database?


rawDescription: /bin/sh - non interactive usage from Python


code:
try:
    (element,) = tree.xpath('//xpath/selector')
except ValueError:
    raise InvalidSelector()
    # happened because the list was either empty or contained multiple elements

rawDescription: Getting exactly one element or raising exception with lxml xpath


code:
values = os.listdir("c:\\windows")

qlist = QtCore.QStringList(map(QtCore.QString, values))
qlistwidget.addItems(qlist)

rawDescription: Python Qlistview output dir

description: Python Qlistview output dir


rawDescription: is it possible to Only pull related users through foreign key relationship, once in django

description: Is it possible to Only pull related users through foreign key relationship, once in django


code: df.to_excel(writer, sheet_name='Sheet1', header=False, index=False)

rawDescription: Pandas groupby output to Excel using xlsxwriter


rawDescription: Restoring the default display context in Pandas


code:
while True:
    event=wait_for_event()
    event.process()
    if main_window_has_been_destroyed():
        break

rawDescription: When do I need to call mainloop in a Tkinter application?


code:
from sqlalchemy import *

metadata = MetaData()
engine = create_engine('mysql+mysqldb://scott:tiger@localhost/foo')
person_table = Table('person', metadata, autoload=True, autoload_with_engine=engine)
q = person_table.insert().values(name='John', age=20)
connection = engine.connect()
connection.execute(q)

rawDescription: How to use SQL databases in python without writing SQL?

description: Use SQL databases in python without writing SQL


code:
from random import randint

class Maze(object):
    """Class that generates maze"""

    def __init__(self, columns, rows):
        """Constructor takes columns and rows in input"""
        self.columns = columns
        self.rows = rows
        self.reset()

    def reset(self):
        # Building maze.
        self.__maze_cell_mapping = []
        for i in xrange(self.columns):
            for j in xrange(self.rows):
                self.__maze_cell_mapping.append((i, j))

        # Defining entrance.
        self.__entrance = None
        self.__define_entrance()

    def __define_entrance(self):
        """Random entrance defined at game start"""
        while self.__entrance is None:
            cell_id = randint(0, len(self.__maze_cell_mapping))
            if self.__is_boundary(cell_id):
                self.__entrance = self.__maze_cell_mapping[cell_id]

    def __is_boundary(self, cell_id):
        """
        :param int cell_id:
            ID of the cell to check.

        :rtype: bool
        :returns:
            ``True`` if given ``cell_id`` is at maze boundary.
        """
        column, row = self.__maze_cell_mapping[cell_id]
        if column == 0 or column == self.columns - 1:
            return True
        elif row == 0 or row == self.rows - 1:
            return True
        else:
            return False

    def print_maze(self):
        """Function that prints Wumpus World Maze"""
        result = [
            ['.'] * self.columns
            for _i in xrange(self.rows)
        ]

        column, row = self.__entrance
        result[column][row] = 'E'

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

rawDescription: Instantiation fails in a python object

description: Instantiation fails in a python object


code:
from django.contrib.gis.utils import GeoIP
from logger.models import Log # your simple Log model

def get_ip(request):
   xff = request.META.get('HTTP_X_FORWARDED_FOR')
   if xff:
      return xff.split(',')[0]
   return request.META.get('REMOTE_ADDR')

class UserLocationLoggerMiddleware(object):

    def process_request(self, request):
        if request.user and request.user.is_superuser:
            # Only log requests for superusers,
            # you can control this by adding a setting
            # to track other user types
            ip = get_ip(request)
            g = GeoIP()
            lat,long = g.lat_lon(ip)
            Log.objects.create(request.user, ip, lat, long)

rawDescription: How to track login locations of admin/staff in django website

description: Track login locations of admin/staff in django website


code: sum(len(x) for x in multilist)

rawDescription: How to find length of a multi-dimensional list?

description: Find length of a multi-dimensional list


code:
from pymongo import MongoClient
import xml.etree.ElementTree as ET
from urllib2 import urlopen

cl = MongoClient()
coll = cl["dbname"]["collectionname"]

tree = ET.parse("https://www.eventbrite.com/xml/event_search?app_key=USO53E2ZHT6LM4D5RA&country=DE&max=100&date=Future&page=1")
root = tree.getroot()

for event in root.findall("./event"):
    doc = {}
    for c in event.getchildren():
        if c.tag in ("start_date", "end_date", "title"):
            doc[c.tag] = c.text
        elif c.tag == "venue":
            doc[c.tag] = {}
            for v in c.getchildren():
                if v.tag in ("address", "address_2", "city", "latitude", "longitude", "name", "postal_code"):
                    doc[c.tag][v.tag] = v.text

    coll.insert(doc)

rawDescription: Parse XML file to fetch required data and store it in mongodb database in Python


code:
for index, item in enumerate(my_list):
    if index >= 5:
        item_5_indexes_ago = my_list[index-5]

rawDescription: How can I check a previous index when iterating through a for loop python

description: Check a previous index when iterating through a for loop python


code:
import numpy as np

def f(x):
    return np.exp(-x ** 2)
def fprime(x):
    return -2 * x * f(x)

a = np.linspace(-10, 10, 100)
a1 = f(a)
a2 = fprime(a)

b1 = np.fft.fft(a1)
b2 = np.fft.fft(a2)
omega = 2 * np.pi * np.fft.fftfreq(len(a), a[1] - a[0])

np.allclose(b1 * 1j * omega, b2)
# True

rawDescription: How does numpy.fft.fft work?

description: How does numpy.fft.fft work


code:
import ast

# which syntax elements are allowed at module level?
whitelist = [
  # docstring
  lambda x: isinstance(x, ast.Expr) \
             and isinstance(x.value, ast.Str),
  # import
  lambda x: isinstance(x, ast.Import),
  # class
  lambda x: isinstance(x, ast.ClassDef),
  # function
  lambda x: isinstance(x, ast.FunctionDef),
]

def validate(source, required_functions):
  tree = ast.parse(source)

  functions = set()
  required_functions = set(required_functions)

  for item in tree.body:
    if isinstance(item, ast.FunctionDef):
      functions.add(item.name)
      continue

    if all(not checker(item) for checker in whitelist):
      return False

  # at least the required functions must be there
  return len(required_functions - functions) == 0

if __name__ == "__main__":
  required_funcs = [ "init", "execute", "cleanup" ]
  with open("/tmp/test.py", "rb") as f:
    print("yay!" if validate(f.read(), required_funcs) else "d'oh!")

rawDescription: Importing a python module without actually executing it


rawDescription: Regular expressions in SQLalchemy queries?


code:
class Record(object):
    def __init__(self, x, y, z):
        pass # code goes here
    def get_record(id):
        pass # code goes here

rawDescription: For a simulation system, which data structure is most suitable?


code:
from functools import wraps

def has_role_decorator(role):
    def request_decorator(dispatch):
        @wraps(dispatch)
        def wrapper(request, *args, **kwargs):
            user = request.user
            if user.is_authenticated():
                if has_role(user, role):
                    return dispatch(request, *args, **kwargs)

            raise PermissionDenied
        return wrapper
    return request_decorator

rawDescription: Applying decorator to view - url not being found by reverse


code:
class EditBitmapButton(ManagedBase):

    events = ['EVT_BUTTON']

rawDescription: wxPython dictionary of classes to events they call

description: WxPython dictionary of classes to events they call


code:
import subprocess, sys

subprocess.call(sys.argv[1:])

rawDescription: Running a script that calls another script as an argument that in turn has arguments


code:
def singleNumber(nums):
    unique = 0
    for num in nums:
        unique ^= num
    return unique

rawDescription: Why is my python code so slow (leetcode)?


code:
with open ('C:/Users/***/Desktop/***/output.log', mode='w', encoding='utf-8') as a_file:
    a_file.write("test")  # <---

rawDescription: python 3.4.3 unable to write to a file in a desktop folder

description: Python 3.4.3 unable to write to a file in a desktop folder


code:
from os import path
path.dirname("C:\\a\\b\\c\\d\\")

rawDescription: How to get upper paths from a single path?

description: Get upper paths from a single path


code:
import os
import tables

direc = '/Users/cg/' # the working directory (where your files are stored)
dirs = os.listdir(direc)

for idir in dirs: # this will iterate over the files in your working directory

    if idir.endswith('.he5'): # only for HDF5 files...
        hdf5 = tables.openFile(os.path.join(direc,idir))

        #### DO WHAT YOU WANT WITH EACH FILE!

        hdf5.close()

rawDescription: Processing (iterate through) several (HDF5) files and several nodes in each HDF file


code:
model = QtSql.QSqlTableModel(self, db)
model.setTable("YourTable")
model.select()

tableview = QtGui.QTableView()
tableview.setModel(model)
tableview.show()

rawDescription: Database view in pyqt

description: Database view in pyqt


code:
def VowelOne():
    var = (Word.count('a')*5)
    return var

def VowelTwo():
    var = (Word.count('e')*4)
    return var

Word = input("Please enter a word (from the english dictionary) if you please ")
var = VowelOne()
VarTwo = VowelTwo()

print (Word)
print(VowelOne()+VowelTwo())

rawDescription: How do I find a variable within a string, and then give that variable a value

description: Find a variable within a string, and then give that variable a value


code:
from numpy.random import random
import matplotlib.pyplot as plt

def print_fractures():
    plt.subplot(212)
    plt.plot([1,2,3,4])

def histogram():
    plt.subplot(211)
    plt.hist(random(1000), 100)
    plt.xlabel('Spacing (m)', fontsize=15)
    plt.ylabel('Frequency (count)', fontsize=15)

histogram()
print_fractures()
plt.axis('equal')
plt.show()

rawDescription: matplotlib: multiple plots on one figure

description: Matplotlib: multiple plots on one figure


code:
mylist = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
old_index = 5
new_index = 1

mylist.insert(new_index, mylist.pop(old_index))
mylist

rawDescription: Create a function that rearranges item in list and shifts the other items (Python)


code:
mask = np.column_stack([df[col].str.contains(r"\^", na=False) for col in df])
df.loc[mask.any(axis=1)]

rawDescription: Search for String in all Pandas DataFrame columns and filter


code:
for src in inputready:
    if src == server_socket:
        ...

rawDescription: Python: check if it socket or file

description: Python: check if it socket or file


code: import pdb; pdb.set_trace()

rawDescription: Python process will not exit

description: Python process will not exit


code: changed_list = [int(f) if f.isdigit() else f for f in original_list]

rawDescription: How to convert strings numbers to integers in a list?

description: Convert strings numbers to integers in a list


code:
import turtle
def tree(f_length, spray=90., branches=2, f_scale=0.5, f_scale_friction=1.4, min_length=10):
    """
    Draws a tree with 2 branches using recursion
    """
    step = float(spray / (branches - 1))
    f_scale /= f_scale_friction
    turtle.forward(f_length)
    if f_length > min_length:
        turtle.left(spray / 2)
        tree(f_scale * f_length, spray, branches, f_scale, f_scale_friction, min_length)
        for counter in range(branches - 1):
            turtle.right(step)
            tree(f_scale * f_length, spray, branches, f_scale, f_scale_friction, min_length)
        turtle.left(spray / 2)
    turtle.back(f_length)

turtle.left(90)
tree(80, spray=120, branches=4)
turtle.exitonclick()

rawDescription: Drawing a fractal tree in Python

description: Drawing a fractal tree in Python


rawDescription: python convert RSA key (in PEM format) to hex string

description: Python convert RSA key (in PEM format) to hex string


code:
@mock.patch.object(models.KangaUser, 'save')
@mock.patch('django.contrib.auth.models.User')
def test_create(self, user_class_mock, kangauser_save_mock):
    # Mocking configuration
    # User
    user_class_mock.objects = mock.MagicMock()
    user_class_mock.objects.create_user = mock.MagicMock()
    user_class_mock.objects.create_user.return_value = User(id=1)

    # Test
    kangauser_manager = models.KangaUserManager()
    kanga_user = kangauser_manager.create(self.username, self.email, self.password, self.last_name, self.first_name, self.request, self.registered, self.send_confirmation)

    # Checks
    # create_user called with good parameters
    user_class_mock.objects.create_user.assert_called_with(username=self.username, email=self.email, password=self.password, first_name=self.first_name, last_name=self.last_name)
    # KangaUser
    self.assertTrue(kangauser_save_mock.called)

rawDescription: Django - Mocking the save method on a model


code:
def list_search(slist):
     for count, item in enumerate(slist):
         if(item.__class__ is list):
             list_search(item)
         else:
             if(count == 0 and item == 'bb'):
                 print(slist)

rawDescription: Python Search Nested Lists

description: Python Search Nested Lists


rawDescription: Python regular expression: treat apostrophe as text


code:
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot(range(1,6), range(5))
plt.xticks(range(1,6), ['a','b','c','d','e'])

labels = ['(%s)' % l.get_text() for l in ax.xaxis.get_ticklabels()]
ax.xaxis.set_ticklabels(labels)

rawDescription: Formatting string ticklabels matplotlib

description: Formatting string ticklabels matplotlib


code:
import pylab
counts = [0,0,0,125,56,0,0,0,34,77,123,0,0,0]
artists = pylab.bar(*zip(*enumerate(counts)), align='center')

lefts = [item.get_x() for item in artists]
rights = [item.get_x() + item.get_width() for item in artists]
pylab.xlim([min(lefts), max(rights)])

pylab.show()

rawDescription: Force bins with zero-height in matplotlib bar plot


code:
volumes = ["Volume:vol-XXXXXXXX", "Volume:vol-YYYYYYYY"]

json.dumps({
  "volumes": volumes
})

rawDescription: Convert Python List to JSON Separate Objects


code: output = sorted([1] * k + [0] * (n - k), key=lambda k: random.random())

rawDescription: Pythonic random list of booleans of length n with exactly k Trues


code:
import re, itertools

car = ['skoda', 'audi', 'benz']

text = """
I have a car="mycar"
My friend has a vehicle="myvehicle"
My uncle have a car="mycar"

Second verse same as the first

I have a car="mycar"
My friend has a vehicle="myvehicle"
My uncle have a car="mycar"
"""

it = itertools.cycle(car)
newtext = re.sub(r'mycar|myvehicle', lambda _: next(it), text)

rawDescription: python replace words one by one from a list

description: Python replace words one by one from a list


code:
col = db.gridfstest.files.findOne()
col.find_one()

rawDescription: Retrieve file metadata using python GridFS


code: sock.setsockopt(263, 20, 0);

rawDescription: QDISC_BYPASS in Python (Raw Sockets)

description: QDISC_BYPASS in Python (Raw Sockets)


code:
from dateutil.parser import parse
datetimeObj = parse(strDate)
# str date is a date string

rawDescription: Python module for date manipulation

description: Python module for date manipulation


code:
import re, collections

paragraph = "how are you now? Are you better now?"

splitter = re.compile('\W')
counts = collections.Counter(word.lower()
                             for word in splitter.split(paragraph)
                             if word)
for word, count in counts.most_common():
    print(count, word)

rawDescription: How can I use "uniq -c" command of unix in python code?

description: Use "uniq -c" command of unix in python code


code:
my_book = Book.objects.get(pk=1)
all_ingredients = Ingredient.objects.filter(recipe__book=my_book)

rawDescription: Flattening one-to-many relationship in Django


code:
logfile = open('.../yourfile.txt', 'a')
print>>logfile, lda.show_topics(topics=-1, topn=10)

rawDescription: Gensim: How to save LDA model's produced topics to a readable format (csv,txt,etc)?


code:
units = [20, 10, 5, 1, 0.5]
def change (number):
    counts = {}
    for unit in units:
        count, number = divmod(number, unit)
        counts[unit] = count
    return counts

rawDescription: List's and while loops - Python

description: List's and while loops - Python


code: mydict.setdefault(upperkey, {})[index+1] = value

rawDescription: data structure in python: best way or how to add or assign a new dictionary?

description: Data structure in python: best way or how to add or assign a new dictionary


code:
def stop_server(self):
    self.server.shutdown()
    self.server.server_close()

rawDescription: HTTPServer.shutdown returns but the socket is still open


code:
import urllib2
import re

print("Calibre is Updating")
url = urllib2.urlopen ( "http://sourceforge.net/projects/calibre/files" ).read()

result = re.search('title="/[0-9.]*/([a-zA-Z\-]*-[0-9\.]*)', url).groups()[0][:-1]
print(result)

rawDescription: Selecting specific text from a webpage using Python


code:
import numpy as np
import Tkinter as tk

import matplotlib
matplotlib.use('TkAgg')

from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import matplotlib.pyplot as plt

root = tk.Tk()

fig = plt.figure(1)
plt.ion()
t = np.arange(0.0,3.0,0.01)
s = np.sin(np.pi*t)
plt.plot(t,s)

canvas = FigureCanvasTkAgg(fig, master=root)
plot_widget = canvas.get_tk_widget()

def update():
    s = np.cos(np.pi*t)
    plt.plot(t,s)
    #d[0].set_ydata(s)
    fig.canvas.draw()

plot_widget.grid(row=0, column=0)
tk.Button(root,text="Update",command=update).grid(row=1, column=0)
root.mainloop()

rawDescription: Embed a pyplot in a tkinter window and update it


rawDescription: How to turn a boolean array into index array in numpy

description: Turn a boolean array into index array in numpy


code:
import collections
def flattish(l):
    for el in l:
        if isinstance(el, collections.Iterable) and not isinstance(el, str):
            if any(isinstance(e, collections.Iterable) for e in el):
                for sub in flattish(el):
                    yield sub
            else:
                    yield el
        else:
            yield [el]

rawDescription: How to unpack a nested list in python to sublists?

description: Unpack a nested list in python to sublists


code: __import__('%s.handlers' % x.__name__)

rawDescription: Importing a submodule given a module object


code:
mask = np.ones(a.shape,dtype=bool) #np.ones_like(a,dtype=bool)
mask[indices] = False
a[~mask] = 999
a[mask] = 888

rawDescription: NumPy array, change the values that are NOT in a list of indices