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

x = np.arange(0.0, 100.0, 2.0)
y = x ** 1.3 + np.random.rand(*x.shape) * 30.0
s = np.random.rand(*x.shape) * 800 + 500

markers = ['\\alpha', '\\beta', '\gamma', '\sigma','\infty', \
            '\spadesuit', '\heartsuit', '\diamondsuit', '\clubsuit', \
            '\\bigodot', '\\bigotimes', '\\bigoplus', '\imath', '\\bowtie', \
            '\\bigtriangleup', '\\bigtriangledown', '\oslash' \
           '\ast', '\\times', '\circ', '\\bullet', '\star', '+', \
            '\Theta', '\Xi', '\Phi', \
            '\$', '\#', '\%', '\S']

def getRandomMarker():
    return "$"+markers[randint(0,len(markers),1)]+"$"

def getMarker(i):
    # Use modulus in order not to have the index exceeding the lenght of the list (markers)
    return "$"+markers[i % len(markers)]+"$"

for i, mi in enumerate(markers):
    plt.plot(x[i], y[i], "b", alpha=0.5, marker=getRandomMarker(), markersize=randint(16,26,1))
    plt.plot(x[i], y[i]+50, "m", alpha=0.5, marker=getMarker(i), markersize=randint(16,26,1))
    # Let's see if their "center" is located where we expect them to be...
    plt.plot(x[i], y[i]+100, "y", alpha=0.5, marker=getMarker(i), markersize=24)
    plt.plot(x[i], y[i]+100, "k+", markersize=12, markeredgewidth=2)

plt.xlabel("x-axis")
plt.ylabel("y-axis")
plt.xlim( -5, plt.xlim()[1]+5 )
plt.ylim( 0, plt.ylim()[1]*1.1 )
gcf().set_size_inches(12,6)
plt.show()

rawDescription: Matplotlib custom marker/symbol

description: Matplotlib custom marker/symbol


code:
if formset.is_valid():
    formset.save()
    return HttpResponseRedirect('/')

rawDescription: Model formset refresh extra field disappears


code:
# env is the environment handed to you by the WSGI server.
# I am removing the query string from the env before passing it to the
# FieldStorage so we only have POST data in there.
post_env = env.copy()
post_env['QUERY_STRING'] = ''
post = cgi.FieldStorage(
    fp=env['wsgi.input'],
    environ=post_env,
    keep_blank_values=True
)

rawDescription: Accessing POST Data from WSGI

description: Accessing POST Data from WSGI


code:
import time
import requests
import re
from bs4 import BeautifulSoup

Aniday = time.strftime("%B %d")
r = requests.get("http://www.animefansftw.com")
r.content
soup = BeautifulSoup(r.content, "html.parser")
print("Today's Animu Crack:\n")

for div in soup.find_all("div", {"class": "date"}):
    get_date = div.text
    clean_date = " ".join(get_date.split())
    if clean_date == Aniday:
        post_div = div.parent.parent
        title = post_div.h1.text.encode('ascii','ignore')
        print("{title}\n{date}\n".format(title=title,date=clean_date))

rawDescription: python 3, BeautifulSoup 4, scrape and print text of specific parse tree

description: Python 3, BeautifulSoup 4, scrape and print text of specific parse tree


code:
lst = ['ab','cd','f']
from itertools import product
list(product(*lst))

rawDescription: Programmatically generate list of combinations other lists


code:
list = ["simon", "tom", "sarah", "peter", "jane"]
word = input()
if word.lower() in list:
    print('Ok')
    #continue with rest of program
else:
     print('No, sorry')

rawDescription: Python How to accept only certain words with user input


code:
import itertools
list1
[k for k, g in itertools.groupby(list1)]

rawDescription: Python Remove SOME duplicates from a list while maintaining order?


code:
from django.db import models
from django.contrib.sites.models import Site

class BlogEntry(models.Model):
    headline = models.CharField(max_length=200)
    text = models.TextField()
    # ...
    sites = models.ManyToManyField(Site)

rawDescription: how to show content depending on domain/subdomain

description: Show content depending on domain/subdomain


code:
def func():
    a = 2
    otherFunc()

rawDescription: Can a decorated function access variables of the decorator


code:
# Demean
demeaned = np_arr_2d - np_arr_2d.mean(axis=1)[:, None]

# Dot product of each row with index
res = np.ma.dot(demeaned, demeaned[index])

# Norm of each row
row_norms = np.ma.sqrt((demeaned ** 2).sum(axis=1))

# Normalize
res = res / row_norms / row_norms[index]

rawDescription: How to improve very inefficient numpy code for calculating correlation

description: Improve very inefficient numpy code for calculating correlation


rawDescription: Finding local maxima/minima with Numpy in a 1D numpy array


code:
'foo' == True  # -> False
'' == True     # -> False
'' == False    # -> False

rawDescription: Mysterious Cases of Booleans, Equivalencies, and Object Identifiers


code:
import tkinter.messagebox
tkinter.Tk().withdraw()
a=tkinter.messagebox.askquestion('','hi')

rawDescription: Python - What is tkinter's default window reference?


code:
a = raw_input('type a word')
a[::-1]

rawDescription: Is there a better way to write my python code


code: value, _ = myfunction(param)

rawDescription: How to elegantly ignore some return values of a Python function?

description: Elegantly ignore some return values of a Python function


code:
def make_class(modeladmin, request, queryset):
    new_class = Class()
    new_class.save()
    for student in queryset:
        new_class.students.add(student.id)
    return redirect(reverse('admin:mgmt_class_change', args=(new_class.id,)))

rawDescription: Django Admin Actions: Add "Students" to "Academic Class"


code:
from numpy import *
from matplotlib.pyplot import *
from math import *

t=arange(0,4*pi/2,0.0001)
print(t)
#first set of parameters
A=1
B=1
a1=1
b1=2
d=pi/2
#second set of parameters
a2=2
b2=3
X1=[]
Y1=[]
Y2=[]
X2=[]
for i in range(len(t)):
    x1=A*sin(a1*t[i]+d)
    y1=B*sin(b1*t[i])
    x2=A*sin(a2*t[i]+d)
    y2=B*sin(b2*t[i])
    X1=append(X1,x1)
    Y1=append(Y1,y1)
    X2=append(X2,x2)
    Y2=append(Y2,y2)
figure()
plot(t,X1, color='blue')
plot(t,Y1, color='pink')
plot(t,X2, color='purple')
plot(t,Y2, color='green')
show()

rawDescription: (Python) Trouble displaying a graph of a Lissajous curve


code:
from win32con import PAGE_READWRITE, MEM_COMMIT, MEM_RESERVE, MEM_RELEASE,\
    PROCESS_ALL_ACCESS
from commctrl import LVM_GETITEMTEXT, LVM_GETITEMCOUNT

import struct
import ctypes
import win32api
import win32gui

GetWindowThreadProcessId = ctypes.windll.user32.GetWindowThreadProcessId
VirtualAllocEx = ctypes.windll.kernel32.VirtualAllocEx
VirtualFreeEx = ctypes.windll.kernel32.VirtualFreeEx
OpenProcess = ctypes.windll.kernel32.OpenProcess
WriteProcessMemory = ctypes.windll.kernel32.WriteProcessMemory
ReadProcessMemory = ctypes.windll.kernel32.ReadProcessMemory
memcpy = ctypes.cdll.msvcrt.memcpy

def readListViewItems(hwnd, column_index=0):

    # Allocate virtual memory inside target process
    pid = ctypes.create_string_buffer(4)
    p_pid = ctypes.addressof(pid)
    GetWindowThreadProcessId(hwnd, p_pid) # process owning the given hwnd
    hProcHnd = OpenProcess(PROCESS_ALL_ACCESS, False, struct.unpack("i",pid)[0])
    pLVI = VirtualAllocEx(hProcHnd, 0, 4096, MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE)
    pBuffer = VirtualAllocEx(hProcHnd, 0, 4096, MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE)

    # Prepare an LVITEM record and write it to target process memory
    lvitem_str = struct.pack('iiiiiiiii', *[0,0,column_index,0,0,pBuffer,4096,0,0])
    lvitem_buffer = ctypes.create_string_buffer(lvitem_str)
    copied = ctypes.create_string_buffer(4)
    p_copied = ctypes.addressof(copied)
    WriteProcessMemory(hProcHnd, pLVI, ctypes.addressof(lvitem_buffer), ctypes.sizeof(lvitem_buffer), p_copied)

    # iterate items in the SysListView32 control
    num_items = win32gui.SendMessage(hwnd, LVM_GETITEMCOUNT)
    item_texts = []
    for item_index in range(num_items):
        win32gui.SendMessage(hwnd, LVM_GETITEMTEXT, item_index, pLVI)
        target_buff = ctypes.create_string_buffer(4096)
        ReadProcessMemory(hProcHnd, pBuffer, ctypes.addressof(target_buff), 4096, p_copied)
        item_texts.append(target_buff.value)

    VirtualFreeEx(hProcHnd, pBuffer, 0, MEM_RELEASE)
    VirtualFreeEx(hProcHnd, pLVI, 0, MEM_RELEASE)
    win32api.CloseHandle(hProcHnd)
    return item_texts

rawDescription: Use Python to extract ListView items from another application


code:
for i in range(50):
    for j in range(50):
        color = int(2.56 * (i + j))
        pyglet.graphics.draw(1, pyglet.gl.GL_POINTS,
            ('v2i', (i, j)),
            ('c3B', (color, color, color))
        )

rawDescription: pixelwise drawing in pyglet (python)

description: Pixelwise drawing in pyglet (python)


code:
from selenium import selenium

sel = selenium("localhost", 4444, "*firefox", "http://www.google.com/webhp")
sel.start()

sel.open("http://www.google.com/webhp")
sel.type("q", "hello world")
sel.click("btnG")
sel.wait_for_page_to_load(5000)
assert "hello world - Google Search" == sel.get_title()
sel.stop()

rawDescription: Is there some module for Python that works with Firefox?


rawDescription: Serializing a class into json for python/gae


code:
import datetime
import matplotlib.pyplot as plt
from matplotlib.dates import AutoDateLocator, AutoDateFormatter, date2num

#make my own data:
date = '2016-02-23'
low = 10

#how to format dates:
date_datetime = datetime.datetime.strptime(date, '%Y-%m-%d')
int_date = date2num( date_datetime)

#create plots:
fig, ax = plt.subplots()

#plot data:
ax.bar(int_date,low, label="Minimum number of players", color="red")

#format date strings on xaxis:
locator = AutoDateLocator()
ax.xaxis.set_major_locator(locator)
ax.xaxis.set_major_formatter( AutoDateFormatter(locator) )

#adjust x limits and apply autoformatter fordisplay of dates
min_date = date2num( datetime.datetime.strptime('2016-02-16', '%Y-%m-%d') )
max_date = date2num( datetime.datetime.strptime('2016-02-28', '%Y-%m-%d') )
ax.set_xlim([min_date, max_date])
fig.autofmt_xdate()

#show plot:
plt.show()

rawDescription: Date into matplotlib graph

description: Date into matplotlib graph


code:
import matplotlib.pyplot as plt

plt.gca().set_color_cycle(['red', 'green', 'blue', 'yellow'])

rawDescription: python plotting using matplotlib

description: Python plotting using matplotlib


code:
import lxml.html
t = lxml.html.fromstring("...")
t.text_content()

rawDescription: Filter out HTML tags and resolve entities in python


code:
db.bidding.aggregate([
    {
        "$group": {
            "_id": "$bid_item",
            "number_of_objects": { "$sum": 1 },
            "total_price": {
                "$sum": {
                    "$cond": [ { "$ne": [ "$price", "null" ] }, "$price", 0 ]
                }
            },
            "total_users": {
                "$sum": {
                    "$cond": [ { "$ne": [ "$users", "null" ] }, "$users", 0 ]
                }
            },
            "total_number_of_users_after_bid": {
                "$sum": {
                    "$cond": [
                        {
                            "$and": [
                                { "$ne": [ "$highestBid", "null" ] },
                                { "$ne": [ "$users", "null" ] }
                            ]
                        },
                        "$highestBid", 0
                    ]
                }
            }
        }
    }
])

rawDescription: Combine three different Aggregate into a single one


code:
idx = random.randint(0, len(list1)-3)
list1[idx:idx+3]

rawDescription: Selecting a random list element of length n in Python


code:
import json
import urllib2
r = urllib2.urlopen('https://github.com/timeline.json')

with open("a.txt", "w") as f:
    for item in json.load(r) or []:
        try:
            f.write(item['repository']['name'] + "\n")
        except KeyError:
            pass

rawDescription: Getting JSON objects from website using standard json and urllib2


code:
from mock import Mock, patch

class MyClass(object):
    def __init__(self, a, b, c):
        pass

def method_to_test():
    m = MyClass(1, 'test', {'key' : 'value'})

@patch('__main__.MyClass')
def test_my_method(mock_class):
    method_to_test()
    mock_class.assert_called_with(1, 'test', {'key': 'value'})

test_my_method()

rawDescription: Init params with patch and Mock with urllib2


code:
import scipy.io as sio
import gzip

f_out = gzip.open(filepath_dot_gz, 'wb')
sio.savemat(f_out, do_compression = True)

rawDescription: Data compression in python/numpy

description: Data compression in python/numpy


code:
#!/usr/bin/python

import sys

d = {}
line_list=[]
alist=[]
f = open(sys.argv[3], 'r') # Persisted Dictionary File

for line in f:
    line = line.strip()
    if line =="":
        continue
    alist = line.split()
    key = alist[0]
    value = alist[1]
    d[str(key)] = str(value)
    alist=[]
f.close()

fr = open(sys.argv[1], 'r') # source file
fw = open(sys.argv[2]+"/masked_"+sys.argv[1], 'w') # Target Directory Location

for line in fr:
    line = line.strip()
    if line == "":
        continue
    columns = line.strip().split('|')
    if columns[0].find("@") > 1:
        looking_for = columns[0] # this is what we need to search
    else:
        looking_for = "Dummy@dummy.com"
    if looking_for in d:
        # by default, iterating over a dictionary will return keys
            new_line = d[looking_for]+'|'+'|'.join(columns[1:])
            line_list.append(new_line)
    else:
        new_idx = str(len(d)+1)
        d[looking_for] = new_idx
        kv = open(sys.argv[3], 'a')
        kv.write(looking_for+" "+new_idx+'\n')
        kv.close()
        new_line = d[looking_for]+'|'+'|'.join(columns[1:])
        line_list.append(new_line)
fw.writelines(line_list)

rawDescription: Python Noob issue with populating dictionary from file. Then updating dict and writing back to file


code:
info = u"Hello, Welcome\nPlease follow the instructions \u2191"
tkMessageBox.showinfo("Welcome", info)

rawDescription: How to display the arrow symbol in Python tkMessageBox?

description: Display the arrow symbol in Python tkMessageBox


code:
import requests

def find_broken_links(root, driver):
    visited = set()
    broken = set()
    # Use queue for BFS, list / stack for DFS.
    elements = [root]
    session = requests.session()

    while len(elements):
        el = elements.pop()
        if el in visited:
            continue

        visited.add(el)

        resp = session.get(el)
        if resp.status_code in [500, 404]:
            broken.add(el)
            continue

        driver.get(el)
        links = driver.find_element_by_tag_name("a")
        for link in links:
            elements.append(link.get_attribute('href'))

    return broken

rawDescription: Using selenium webdriver, how to click on multiple random links in webpage one after another continuously to detect broken links?


code:
@staticmethod
def fit_func(x, a, b):
    return a * x + b

rawDescription: Python lmfit: Model object trys to use "self" as free variable


code:
import pymongo
client = pymongo.MongoClient('servername')

rawDescription: Does pymongo require mongodb to be installed locally?


rawDescription: Zip with list output instead of tuple

description: Zip with list output instead of tuple


code:
while Gtk.events_pending():
    Gtk.main_iteration()

rawDescription: Python + Gtk: File dialog when closed, how to check?


rawDescription: python equivalent of MATLAB statement A(B==1)= C

description: Python equivalent of MATLAB statement A(B==1)= C


code:
class ListPrefixer:
    def __init__(self, typ):
        self.typ = typ

    def __getitem__(self, args):
        return self.typ(args)

class MyList(list):
    def each(self, func):
        return MyList(func(x) for x in self)

e = ListPrefixer(MyList)

e[1, 2, 3, 4].each(lambda x: x**2)
#>>> [1, 4, 9, 16]

rawDescription: Can literals in Python be overridden?

description: Can literals in Python be overridden


code:
p1 = subprocess.Popen("ssh igp@" + str(comp1[0]) + " blender -b "+ str(path) +" -s " + str(comp1[1]) + " -e " + str(comp1[2]) + " -a", shell=True)
p2 = subprocess.Popen("ssh igp@" + str(comp2[0]) + " blender -b "+ str(path) +" -s " + str(comp2[1]) + " -e " + str(comp2[2]) + " -a", shell=True)
p3 = subprocess.Popen("ssh igp@" + str(comp3[0]) + " blender -b "+ str(path) +" -s " + str(comp3[1]) + " -e " + str(comp3[2]) + " -a", shell=True)
p1.wait()
p2.wait()
p3.wait()

rawDescription: Using python to start parallel ssh rendering jobs


code: output = ["\t".join(a) for a in the_list]

rawDescription: Most 'pythonic' way to write list to .xls file?


code: print (int(hexlify(corr),16))&0x01

rawDescription: apply a bit mask in python

description: Apply a bit mask in python


code:
small_cities = df.groupby(["City", "State"]).filter(lambda x: x.count() < 3)
small_cities

rawDescription: How to limit by column repetitions in Python Pandas

description: Limit by column repetitions in Python Pandas


code:
import re
import panda as pd

raw_data = open('your_file.csv', 'rb').read()
rows  = re.split('\n', raw_data)

for idx, row in enumerate(rows):
    cells = row.split(',')
    if 'Velocity' in cells:
        header_names = cells    # this will be something like ['Velocity', ' CO', ' RC', ...]
        header_row   = idx
        break

# Now you have the header line as well as the custom header names.
# You can start using pandas.read_csv
pd.read_csv('your_file.csv', header=header_row)

# ...

# and use `header_names` for your plots.

rawDescription: Analyzing a CSV file using Django Pandas and Pyplot


rawDescription: How can I smooth out these signal traces using python?

description: Smooth out these signal traces using python


code:
try:
    from local_settings import *
except ImportError:
    # if you require a local_settings to be present,
    # you could let this exception rise, or raise a
    # more specific exception here
    pass

rawDescription: Creating an in memory constant when django starts


code:
def heaviside(x, epis):
    return np.piecewise(x, (x>=epis, x<-epis),
             (1, 0, lambda x: 0.5 + x/(2*epis) + np.sin(np.pi*x/epis)/(2*np.pi) ) )

rawDescription: Why is the output of my function in binary?


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

# Generate data...
nx, nsteps = 100, 20
x = np.linspace(0, 1, nx)
data = np.random.random((nx, nsteps)) - 0.5
data = data.cumsum(axis=0)
data = data.cumsum(axis=1)

# Plot
cmap = mpl.cm.autumn
for i, y in enumerate(data.T):
    plt.plot(x, y, color=cmap(i / float(nsteps)))

plt.show()

rawDescription: Can i put a color changer in a loop?

description: Put a color changer in a loop


code:
plt.subplots_adjust(hspace=0.5)
plt.subplot(121)
plt.imshow(U2[40,:,:],cmap=cm.hot);plt.colorbar()

plt.subplot(122)
plt.imshow(V2[60,:,:],cmap=cm.hot);plt.colorbar()

plt.pause(0.0001)
plt.savefig('./U2V2.{0:07d}.png'.format(step))

rawDescription: Python - Loop with figure to save matplotlib


code:
tmpl = template.Template(template_string)
tmpl.render(template.Context(context))

rawDescription: Google App Engine - Python and render from bigtable


code:
from subprocess import Popen

# start program
p = Popen(["program.exe", "arg1"])
# do other stuff here
# ...
# at the end wait for the program to exit
returncode = p.wait()
# run final step here

rawDescription: python subprocess use

description: Python subprocess use


code:
from wsgiref.simple_server import make_server
from pyramid.config import Configurator
from pyramid.response import Response

def hello_world(request):
    if request.subpath:
        name = request.subpath[0]
    else:
        name = 'Incognito'
    return Response('Hello %s!' % name)

if __name__ == '__main__':
    config = Configurator()
    config.add_route('hello', '/*subpath')
    config.add_view(hello_world, route_name='hello')
    app = config.make_wsgi_app()
    server = make_server('0.0.0.0', 8081, app)
    server.serve_forever()

rawDescription: All addresses to go to a single page (catch-all route to a single view) in Python Pyramid


code:
import datetime
import dateutil

def parse(date_string):
    result = dateutil.parser.parse(date_string, default=datetime.datetime(1581, 1, 1))
    if result.year == 1581:
        now = datetime.datetime.now()
        result = result.replace(year=now.year)
        if result < now:
            result = result.replace(year=now.year + 1)
    return result

parse('8th April')

rawDescription: Default "future" year when effecting date conversion with dateutil


code:
def bigrams_per_line(doc):
    for ln in doc.split('\n'):
        terms = re.findall(r'\w{2,}', ln)
        for bigram in zip(terms, terms[1:]):
            yield '%s %s' % bigram

cv = CountVectorizer(analyzer=bigrams_per_line)
cv.fit(['This is a\nmultiline string'])
print(cv.get_feature_names())
# ['This is', 'multiline string']

rawDescription: Create ngrams only for words on the same line (disregarding line breaks) with Scikit-learn CountVectorizer


code:
class MySpider(scrapy.Spider):
    name = "myspider"
    start_urls = (
        'https://example.com/login', #login page
    )

    def __init__(self, *args, **kwargs):
        self.url_list = [] #your url lists
        return super(MySpider, self).__init__(*args, **kwargs)

    def parse(self, response):
        data = {}

        return scrapy.FormRequest.from_response(
            response,
            formdata=data,
            callback=self.my_start_requests
        )

    def my_start_requests(self, response):
        # ignore the login callback response
        for url in self.url_list:
            # scrapy will take care the cookies
            yield scrapy.Request(url, callback=self.parse_item, dont_filter=True)

    def parse_item(self, response):
        # your code here
        pass

rawDescription: Scrapy fixed URLs

description: Scrapy fixed URLs


code:
bcolors = {"BLUE": '\033[94m',
           "HIGH": '\033[93m',
           "OKAY": '\033[92m',
           "FAIL": '\033[91m',
           "BOLD": '\033[1m',
           "LINE": '\033[4m',
           "ENDC": '\033[0m'
           }

def _genF(color):
    return lambda s: bcolors[color] + s + bcolors["ENDC"]

globals().update({k.lower():_genF(k) for k,v in bcolors.items()})

In[10]: blue("Foo")
Out[10]: '\x1b[94mFoo\x1b[0m'
In[11]: blue(bold(okay("Foo")))
Out[11]: '\x1b[94m\x1b[1m\x1b[92mFoo\x1b[0m\x1b[0m\x1b[0m'

rawDescription: Use a generic function to do stuff based on the caller?


code:
import urllib
rawdata = urllib.urlopen('http://yahoo.co.jp/').read()
import chardet
chardet.detect(rawdata)

rawDescription: how to check in python if a string contains characters only form specific code page?

description: Check in python if a string contains characters only form specific code page


code:
import pandas as pd
df = pd.read_csv('Full_List.csv')
df = df.sort('red label')
df.to_csv('Full_List_sorted.csv', index=False)

rawDescription: Sorting by Specific Column data using .csv in python


code:
from django.conf import settings

settings.MY_CUSTOM_SETTING

rawDescription: What is the Django HOST_DOMAIN setting for?


code: [item for item in my_list if not item.startswith(whitelist)]

rawDescription: Compare beginning of strings of a list with a whitelist


code:
import requests

url = 'http://.....'
r = requests.get(url, headers={'User-Agent': 'Mozilla/5.0'})
assert 'Delivered' in r.content

rawDescription: How to fetch Redirected URL or it's content via Requests Library?

description: Fetch Redirected URL or it's content via Requests Library


rawDescription: How to average column data for multiple columns in text files?

description: Average column data for multiple columns in text files


code: proteinseq[0][:20] # Get up to the 20 characters from the 1st item in the list

rawDescription: Split a list into individual characters in python


code:
import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [1, 2, 2, 3, 10]
b = plt.bar(x, y)
b[0].set_color('r')
plt.show()

rawDescription: Working with bar charts in python

description: Working with bar charts in python


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

fig = gcf()
ax = gca()
x = np.linspace(0, 2*np.pi, 256)
line, ( bottoms, tops), verts =  ax.errorbar(x, np.sin(x), yerr=1)

verts[0].remove() # remove the vertical lines

yerr = 1
def animate(i=0):
    #    ax.errorbar(x, np.array(x), yerr=1, color='green')
    y = np.sin(x+i/10.0)
    line.set_ydata(y)  # update the data
    bottoms.set_ydata(y - yerr)
    tops.set_ydata(y + yerr)
    return line, bottoms, tops

def init():
    # make an empty frame
    line.set_ydata(np.nan * np.ones(len(line.get_xdata())))
    bottoms.set_ydata(np.nan * np.ones(len(line.get_xdata())))
    tops.set_ydata(np.nan * np.ones(len(line.get_xdata())))
    return line, bottoms, tops

ani = animation.FuncAnimation(fig, animate, np.arange(1, 200), init_func=init,
    interval=25, blit=True)
plt.show()

rawDescription: Animation by using matplotlib + errorbar


code:
import win32com.client

wbk = 'C:\\Path\\To\\Workbook.xlsx'

xlApp = win32com.client.Dispatch("Excel.Application")
xlApp.Workbooks.Open(wbk)

xlAscending = 1
xlSortColumns = 1
xlApp.Sheets(1).Columns("A:B").Sort(Key1=xlApp.Sheets(1).Range("B1"),
                                    Order1=xlAscending, Orientation=xlSortColumns)

xlApp.Quit
xlApp = None

rawDescription: Sort a Range of Cells, win32com.client

description: Sort a Range of Cells, win32com.client


code:
import numpy as np

fig = figure()
ax = fig.add_subplot(111)
dx_in_points = np.diff(ax.transData.transform(zip([0]*len(dx), dx)))
scatter(x,y,c=z,s=dx_in_points**2,marker='s', edgecolors='none')

rawDescription: Python scatter plot. Size and style of the marker


code:
def del_component_with_uid(cal,uid):
    cal_str=cal.to_ical()
    component_find=find_component_with_uid(cal,uid)
    if component_find is not False:
        firstfind = unicode(cal_str, encoding="latin1").find(unicode(component_find, encoding="latin1"))
        export_cal(cal_str[:firstfind]+cal_str[firstfind+len(component_find):])

def find_component_with_uid(cal,uid):
    propert = uid
    for component in cal.subcomponents:
        for prop in component.property_items():
            if prop[0] == 'UID' and prop[1] == uid:
                return component.to_ical()
    return False

def export_cal(calendar_str):
    f = open('./Calendars/example.ics', 'w')
    f.write(calendar_str)
    f.close()

rawDescription: Ical in python - removing events

description: Ical in python - removing events


rawDescription: How to logging with timed rotate file handler in Tornado?

description: Logging with timed rotate file handler in Tornado


code:
from subprocess import call
var = "Hello world!"
cmd = 'echo "%s" | pbcopy' % var
call([cmd], shell=True)

rawDescription: python , mac - Storing a string inside "command v"

description: Python , mac - Storing a string inside "command v"


code:
def printLog(*inp):
    print(*inp, file=self.file)

rawDescription: Python pass print statement including non strings to function


code:
def sum(a,b):
    if a>0 and b>0:
        return str(a*b) + "\n" + str(sum(a,b-1))
    else:
        return ""

rawDescription: Python: Adding new line after return in recursive function


code:
def get_boundaries2(segments, i):
    x, y = np.where(segments == i) # where i is
    right = x + 1
    rightMask = right < segments.shape[0] # keep in bounds
    down = y + 1
    downMask = down < segments.shape[1]
    rightNeighbors = segments[right[rightMask], y[rightMask]]
    downNeighbors = segments[x[downMask], down[downMask]]
    neighbors = np.union1d(rightNeighbors, downNeighbors)
    return neighbors

rawDescription: Can I vectorise this python code?

description: Vectorise this python code


code:
from IPython.utils.io import stdout;
stdout.write('Matches:'+'\033[0;33m'+str(123)+'\033[0;0m')

rawDescription: How to enable output text highlighting in IPython on Windows?

description: Enable output text highlighting in IPython on Windows


code:
def run_process(record):
    result = ping(record)

pool = Pool(processes=10)
results = pool.map_async(run_process, [records])
for r in results.get():
    write_to_database(r)

rawDescription: Best way of parallelizing functions from django task


code:
import psycopg2 as db
conn = db.connect('dbname=billings user=steve password=xxxxx port=5432')
curs = conn.cursor()
curs.execute("""select table_name from information_schema.tables WHERE table_schema='public' AND table_type='BASETABLE'""")
curs.fetchall()

rawDescription: How do I extract table metadata from a database using python

description: Extract table metadata from a database using python


code:
service_start = datetime.date(2012, 5, 6)
service_end = datetime.date(2015, 7, 24)
first_days = (service_end.year - service_start.year) + (1 if service_start.month == 1 and service_start.day == 1 else 0)

rawDescription: Number of times each day occurs between two dates


code:
with patch('random.choice', return_value=3) as mock_random:
    choice = my_code_that_uses_random()
    assert choice == 3

rawDescription: Can I patch 'random' using unittest.mock.patch?

description: Patch 'random' using unittest.mock.patch


code: my_args = [my_args]

rawDescription: How can I convert a string to a list in python?

description: Convert a string to a list in python


code:
df
df = df.unstack().fillna(0).stack()
df

rawDescription: Enter Missing Year Amounts with Zeros After GroupBy in Pandas


code:
if (np.iscomplexobj(b)):
    a = a + 0j
a[0:2] *= b

rawDescription: Numpy arrays, fancy indexing, complex numbers


code:
from dateutil.relativedelta import relativedelta
import datetime
delta = relativedelta(months=6)
six_month_away = datetime.date.today() - delta
abs((six_month_away - datetime.date.today()).days)

rawDescription: Calculate number of days for last 6months from today in python


code:
from bs4 import BeautifulSoup
soup = BeautifulSoup(html)  # Or some xml-like structure
# This will select all link tags which have a rel attribute with value dns-prefetch.
if len(soup.select('link[rel=dns-prefetch]')) > 0:
    self.pre_resolve_dns_enabled = True
if len(soup.select('link[rel=prefetch]')) > 0:
    self.prefetch_enabled = True

rawDescription: How to make this code generic

description: Make this code generic


code:
import decimal, numpy
d = decimal.Decimal('1.1')
a = numpy.array([d,d,d],dtype=numpy.dtype(decimal.Decimal))
type(a[1])

rawDescription: numpy array with dtype Decimal?

description: Numpy array with dtype Decimal


code:
def switchvals(arr, val1, val2):
    mask1 = arr == val1
    mask2 = arr == val2
    arr[mask1] = val2
    arr[mask2] = val1

rawDescription: Simultaneously flipping two values in a Numpy Array


code:
def reset(percent=50):
    return random.randrange(100) < percent

rawDescription: random boolean by percentage

description: Random boolean by percentage


rawDescription: use a list of values to select rows from a pandas dataframe

description: Use a list of values to select rows from a pandas dataframe


code:
import code

def readfunc(prompt):
    raw = input(prompt)
    if raw.count(',')!=1:
        print('Bad expression: {}'.format(raw))
        return ''
    s, x = raw.split(',')
    return '''x={}; {}'''.format(x, s)

code.interact('Calc 0.1', readfunc)

rawDescription: Force function argument to be a string

description: Force function argument to be a string


code:
# say you have a photo that the user wants to remove from album.
album = Album.objects.latest('id')
photo = Photo.objects.album_contents.latest('id')

# to remove that m2m relationship...
# delete the through table row which matches said relationship
MyThroughTable.objects.filter(album=album, photo=photo).delete()

rawDescription: Django: ManyToMany with ability to order AND to add/remove relationships?


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

array_list = [np.random.random_integers(0, i, (5,5)).astype(bool) for i in range(10)]

count = 0
fig, axes = plt.subplots(nrows=2, ncols=5)
for i in range(2):
    for j in range(5):
        axes[i, j].imshow(array_list[count], interpolation='nearest')
        count += 1
        axes[i, j].axis('off')
plt.show()

rawDescription: How to remove matplotlib axis from multiple plots?

description: Remove matplotlib axis from multiple plots


code: return any(childName == c.name for c in self.children)

rawDescription: Python List operations

description: Python List operations


code:
def get_content(filename):
    lookup = (
        (r'.*key1.*', 'blahblah',),
        (r'.*key2.*', 'thing',),
    )
    for pattern, content in lookup:
        if re.match(pattern, filename):
            return content

rawDescription: How to use regex as dictionary's key?

description: Use regex as dictionary's key


code:
import networkx as nx
G=nx.path_graph(4)
pos=nx.spring_layout(G)
nx.set_node_attributes(G,'pos',pos)
G.node

rawDescription: Exporting Layout Positions for a Graph Using NetworkX


code:
yticks = plt.gca().get_yticks().tolist() # get list of ticks
yticks[-1] = ''                          # set last tick to empty string
ax.set_yticklabels(yticks)

rawDescription: How to customize individual numbers on an axis in matplotlib?

description: Customize individual numbers on an axis in matplotlib


rawDescription: django dropdownlist onchange submission

description: Django dropdownlist onchange submission


code:
import gi
gi.require_version('Gst', '1.0')
from gi.repository import GObject, Gst
import numpy as np
import cv2

GObject.threads_init()
Gst.init(None)

def YUV_stream2RGB_frame(data):

    w=640
    h=368
    size=w*h

    stream=np.fromstring(data,np.uint8) #convert data form string to numpy array

    #Y bytes  will start form 0 and end in size-1
    y=stream[0:size].reshape(h,w) # create the y channel same size as the image

    #U bytes will start from size and end at size+size/4 as its size = framesize/4
    u=stream[size:(size+(size/4))].reshape((h/2),(w/2))# create the u channel  itssize=framesize/4

    #up-sample the u channel to be the same size as the y channel and frame using pyrUp func in opencv2
    u_upsize=cv2.pyrUp(u)

    #do the same for v channel
    v=stream[(size+(size/4)):].reshape((h/2),(w/2))
    v_upsize=cv2.pyrUp(v)

    #create the 3-channel frame using cv2.merge func watch for the order
    yuv=cv2.merge((y,u_upsize,v_upsize))

    #Convert TO RGB format
    rgb=cv2.cvtColor(yuv,cv2.cv.CV_YCrCb2RGB)

    #show frame
    cv2.imshow("show",rgb)
    cv2.waitKey(5)

def on_new_buffer(appsink):

   sample = appsink.emit('pull-sample')
   #get the buffer
   buf=sample.get_buffer()
   #extract data stream as string
   data=buf.extract_dup(0,buf.get_size())
   YUV_stream2RGB_frame(data)
   return False

def Init():

   CLI="rtspsrc name=src location=rtsp://192.168.1.20:554/live/ch01_0 latency=10   !decodebin ! appsink name=sink"

   #simplest way to create a pipline
   pipline=Gst.parse_launch(CLI)

   #getting the sink by its name set in CLI
   appsink=pipline.get_by_name("sink")

   #setting some important properties of appsnik
   appsink.set_property("max-buffers",20) # prevent the app to consume huge part of memory
   appsink.set_property('emit-signals',True) #tell sink to emit signals
   appsink.set_property('sync',False) #no sync to make decoding as fast as possible

   appsink.connect('new-sample', on_new_buffer) #connect signal to callable func

def run():
    pipline.set_state(Gst.State.PLAYING)
    GObject.MainLoop.run()

Init()
run()

rawDescription: reading a h264 RTSP stream into python and opencv

description: Reading a h264 RTSP stream into python and opencv


code:
Available_axis = [x for x in Available_axis
                  if x != max(axes.iteritems(), key = operator.itemgetter(1))[0]]

rawDescription: Delete array item based on dictionary value in python


code:
names = set()
for proc in psutil.process_iter():
   names.add(proc.name())

if SomeProcess not in names:
   subprocess.call("%s"%SomeProcess, shell=True)

rawDescription: Python test if an element is in a dictionary


rawDescription: How do I get the name of a key in PyWin32 giving its keycode?

description: Get the name of a key in PyWin32 giving its keycode


code:
from matplotlib.patches import Rectangle
someX, someY = 2, 3
currentAxis = plt.gca()
currentAxis.add_patch(Rectangle((someX - .5, someY - .5), 1, 1, facecolor="grey"))

rawDescription: How to draw a rectangle over a specific region in a matplotlib graph

description: Draw a rectangle over a specific region in a matplotlib graph


code:
class USpider(BaseSpider):
    """my spider. """

    start_urls = ['http://www.amazon.com/s/?url=search-alias%3Dapparel&sort=relevance-fs-browse-rank']
    allowed_domains = ['amazon.com']

    def parse(self, response):
        '''Parse main category search page and extract subcategory search link.'''
        self.log('Downloaded category search page.', log.DEBUG)
        if response.meta['depth'] > 5:
            self.log('Categories depth limit reached (recursive links?). Stopping further following.', log.WARNING)

        hxs = HtmlXPathSelector(response)
        subcategories = hxs.select("//div[@id='refinements']/*[starts-with(.,'Department')]/following-sibling::ul[1]/li/a[span[@class='refinementLink']]/@href").extract()
        for subcategory in subcategories:
            subcategorySearchLink = urlparse.urljoin(response.url, subcategorySearchLink)
            yield Request(subcategorySearchLink, callback = self.parseSubcategory)

    def parseSubcategory(self, response):
        '''Parse subcategory search page and extract item links.'''
        hxs = HtmlXPathSelector(response)

        for itemLink in hxs.select('//a[@class="title"]/@href').extract():
            itemLink = urlparse.urljoin(response.url, itemLink)
            self.log('Requesting item page: ' + itemLink, log.DEBUG)
            yield Request(itemLink, callback = self.parseItem)

        try:
            nextPageLink = hxs.select("//a[@id='pagnNextLink']/@href").extract()[0]
            nextPageLink = urlparse.urljoin(response.url, nextPageLink)
            self.log('\nGoing to next search page: ' + nextPageLink + '\n', log.DEBUG)
            yield Request(nextPageLink, callback = self.parseSubcategory)
        except:
            self.log('Whole category parsed: ' + categoryPath, log.DEBUG)

    def parseItem(self, response):
        '''Parse item page and extract product info.'''

        hxs = HtmlXPathSelector(response)
        item = UItem()

        item['brand'] = self.extractText("//div[@class='buying']/span[1]/a[1]", hxs)
        item['title'] = self.extractText("//span[@id='btAsinTitle']", hxs)
        ...

rawDescription: Following links, Scrapy web crawler framework


code:
from twisted.internet.protocol import Factory, Protocol
from twisted.internet.endpoints import TCP4ServerEndpoint
from twisted.internet import reactor

class QOTD(Protocol):

    def connectionMade(self):
        # self.factory was set by the factory's default buildProtocol:
        self.transport.write(self.factory.quote + '\r\n')
        self.transport.loseConnection()

class QOTDFactory(Factory):

    # This will be used by the default buildProtocol to create new protocols:
    protocol = QOTD

    def __init__(self, quote=None):
        self.quote = quote or 'An apple a day keeps the doctor away'

endpoint = TCP4ServerEndpoint(reactor, 8007)
endpoint.listen(QOTDFactory("configurable quote"))
reactor.run()

rawDescription: Passing parameters to twisted factory to be passed to session


code:
import os
import cv2
import numpy as np

# Construct the input matrix
in_matrix = None
for f in os.listdir('dirpath'):
    # Read the image in as a gray level image. Some modifications
    # of the codes are needed if you want to read it in as a color
    # image. For simplicity, let's use gray level images for now.
    im = cv2.imread(os.path.join('dirpath', f), cv2.IMREAD_GRAYSCALE)

    # Assume your images are all the same size, width w, and height h.
    # If not, let's resize them to w * h first with cv2.resize(..)
    vec = im.reshape(w * h)

    # stack them up to form the matrix
    try:
        in_matrix = np.vstack((in_matrix, vec))
    except:
        in_matrix = vec

# PCA
if in_matrix is not None:
    mean, eigenvectors = cv2.PCACompute(in_matrix, np.mean(in_matrix, axis=0).reshape(1,-1))

rawDescription: how to find the pca of an image using python and opencv?

description: Find the pca of an image using python and opencv


code:
from tensorflow.models.embedding.word2vec_optimized import FLAGS
from tensorflow.models.embedding.word2vec_optimized import main
main(_)
FLAGS.train_data = "this"
FLAGS.eval_data = "that"
FLAGS.save_path = "some_path"
main(_)

rawDescription: How to call a Python function that is designed to work with command line arguments?

description: Call a Python function that is designed to work with command line arguments


code:
import re
str = 'linux windows mac'
a = re.compile('...u.',re.IGNORECASE)
a.match(str).group(0) # returns 'linux'

regex = '...u.'
b = re.compile(regex,re.IGNORECASE)
b.match(str).group(0) # returns 'linux'

rawDescription: How to include a variable in REGEX in python?

description: Include a variable in REGEX in python


code:
# run your simulation like usual
runSimulation()

#create a ordered grid of axes, not one in top of the others
axcolor = 'lightgoldenrodyellow'
fig = p.figure()
axdata = p.subplot2grid((7,4),(0,0),colspan=4,rowspan=4)
axpos = p.subplot2grid((7,4),(-2,0),colspan=4, axisbg=axcolor)
axvel = p.subplot2grid((7,4),(-1,0),colspan=4, axisbg=axcolor)

# create your plots in the global space.
# you are going to reference these lines, so you need to make them visible
# to the update functione, instead of creating them inside a function
# (and thus losing them at the end of the function)
x = range(width)
lpos, = axdata.plot(x,yPosition,'r')
lvel, = axdata.plot(x,yVelocity,'g')
ltarget, = axdata.plot(x,yTarget,'k')
lforce, = axdata.plot(x,yForce,'b')

# same as usual
spos = Slider(axpos, 'Position Gain', 1.0, 20.0, valinit=1.5)
svel = Slider(axvel, 'Velocity Gain', 5.0, 500.0, valinit=60.0)

def update(val):
    # you don't need to declare the variables global, as if you don't
    # assign a value to them python will recognize them as global
    # without problem
    runSimulation(round(spos.val,2),round(svel.val,2))
    lpos.set_ydata(yPosition)
    lvel.set_ydata(yVelocity)
    ltarget.set_ydata(yTarget)
    lforce.set_ydata(yForce)
    # you need to update only the canvas of the figure
    fig.canvas.draw()

spos.on_changed(update)
svel.on_changed(update)
p.show()

rawDescription: Using Matplotlib sliders with multiple plots on the same axes


rawDescription: I have a problem with pprint in python

description: I have a problem with pprint in python


code:
context = zmq.Context()

def sender():
    sock = context.socket(zmq.PUB)
    sock.connect("tcp://localhost:44444")
    time.sleep(1)
    sock.send("status good")

sender()

rawDescription: PyZMQ socket's fail to send when created in function


code:
binary = "\x22"  # <- this is what binary should look like
[m.start() for m in re.finditer(binary, data_file._file_contents)]

rawDescription: Find Binary Value Within ASCII String

description: Find Binary Value Within ASCII String


code:
import datetime

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    Form = QtWidgets.QWidget()
    ui = Ui_Form()
    ui.setupUi(Form)
    Form.show()

    def update_label():
        current_time = str(datetime.datetime.now().time())
        ui.label.setText(current_time)

    timer = QtCore.QTimer()
    timer.timeout.connect(update_label)
    timer.start(10000)  # every 10,000 milliseconds

    sys.exit(app.exec_())

rawDescription: pyQt: How do I update a label?

description: PyQt: How do I update a label


code:
def Max(list):
    if len(list) == 1:
        return list[0]
    else:
        m = Max(list[1:])
        return m if m > list[0] else list[0]

def main():
    list = eval(raw_input(" please enter a list of numbers: "))
    print("the largest number is: ", Max(list))

main()

rawDescription: Python: Recursive function to find the largest number in the list


code:
import new

def copyfunc(func):
    return new.function(func.func_code, func.func_globals, func.func_name,
                        func.func_defaults, func.func_closure)

class Metaclass(type):
    def __new__(meta, name, bases, attrs):
        for key in attrs.keys():
            if key[0] == '_':
                skey = key[1:]
                for base in bases:
                    original = getattr(base, skey, None)
                    if original is not None:
                        copy = copyfunc(original)
                        copy.__doc__ = attrs[key].__doc__
                        attrs[skey] = copy
                        break
        return type.__new__(meta, name, bases, attrs)

class Class(object):
    __metaclass__ = Metaclass
    def execute(self):
        '''original doc-string'''
        return self._execute()

class Subclass(Class):
    def _execute(self):
        '''sub-class doc-string'''
        pass

rawDescription: Using the docstring from one method to automatically overwrite that of another method


code:
class FootnoteNumbers(object):
    def __init__(self, start=1):
        self.count = start - 1

    def __call__(self, match):
        self.count += 1
        return "<sup>{}</sup>".format(self.count)

new_body_text = re.sub(pattern, FootnoteNumbers(), text)

rawDescription: How to properly iterate with re.sub() in Python

description: Properly iterate with re.sub() in Python


code:
target_feature_names = ['x'.join(['{}^{}'.format(pair[0],pair[1]) for pair in tuple if pair[1]!=0]) for tuple in [zip(input_df.columns,p) for p in poly.powers_]]
output_df = pd.DataFrame(output_nparray, columns = target_feature_names)

rawDescription: Sklearn preprocessing - PolynomialFeatures - How to keep column names/headers of the output array / dataframe


code:
from docutils.core import publish_string
import jinja2

html = publish_string(source=text, writer_name='html')
node = jinja2.Markup(html)

rawDescription: jinja2 + reStructured Markup

description: Jinja2 + reStructured Markup


code:
@app.route('/github-auth-start', methods=["GET"])
def github_auth_start():
    next_url = request.args.get('next') or url_for('main_page')
    if current_user.is_authenticated():
        return flask_github.authorize(
            redirect_uri = url_for(
                    'github_auth_finished',
                    _external=True,
                    next=next_url))
    return abort(403)

rawDescription: How to set "next" url recieved by flask_github.authorized_handler?

description: Set "next" url recieved by flask_github.authorized_handler


code:
from __future__ import print_function
import random

name = raw_input("Hi, I'm PyVa.  What is your name: ")
print('Hi',name, end='.')

yesorno = raw_input('  Would you like to play Rock, Paper, Scissors?: ')

while(1):

    yesorno = str(yesorno)

    if yesorno == str('Yes'):
        choices = ['Rock', 'Paper', 'Scissors']
        print('Ok')
        your_choice = raw_input('Choose Rock, Paper or Scissors: ')
        print('My turn...')

        my_choice = random.choice(choices)
        print('I choose,', my_choice)
        if your_choice == my_choice:
            print('We both choose the same, it is a draw.')
        elif your_choice == 'Rock' and my_choice == 'Paper':
            print('I win!')
        elif your_choice == 'Scissors' and my_choice == 'Paper':
            print('You win!')
        elif your_choice == 'Paper' and my_choice == 'Rock':
            print('You win!')
        elif your_choice == 'Paper' and my_choice == 'Scissors':
            print('I win!')
        elif your_choice == 'Rock' and my_choice == 'Scissors':
            print('You win!')
        elif your_choice == 'Scissors' and my_choice == 'Rock':
            print('I win!')

        again = raw_input('Would you like to play again? [y/n]:')

        if again is "y":
            next
        else:
            print('Thanks for playing!\n')
            exit()

    else:
        print('Ok, maybe we can play later, bye.')

rawDescription: How to loop in a simple Python Game?

description: Loop in a simple Python Game


code:
import pyximport
pyximport.install()

rawDescription: How do I import function from .pyx file in python?

description: Import function from .pyx file in python


code:
import sys

def int_overflow(val):
  if not -sys.maxint-1 <= val <= sys.maxint:
    val = (val + (sys.maxint + 1)) % (2 * (sys.maxint + 1)) - sys.maxint - 1
  return val

rawDescription: Simulating integer overflow in Python

description: Simulating integer overflow in Python


code:
for domain in dDomainSeqSum.keys():# CHANGE TO COMPRESS FILE
    dDomainSeqSumSWS[domain]={}
    for pdb in dDomainSeqSum[domain]:#add sws of a pdb in a variable and later add that variable to the domain thing
        pdb2 = pdb[:4] #you do not need to convert to list for indexing and you can slice the first four characters off.
        dDomainSeqSumSWS[domain][pdb2]=[]
        for i in range(len(PDBSum)): #make pdb3 search and then compare to the pdb stored
            if pdb in PDBSum[i]:
                if "SWS_ID" in PDBSum[i]:
                    line = PDBSum[i].split()
                    dDomainSeqSumSWS[domain].setdefault(pdb2,[]).append(line[2])

rawDescription: How Do you prevent overwriting of data in a Dictionary through a for loop


code:
train_y = train_y[..., np.newaxis]
# or
train_y = train_y.reshape(train_y.shape + (1,))

rawDescription: Numpy reshape sub-list

description: Numpy reshape sub-list


code:
df1 = DataFrame(list('ABCDE'), columns=['x'])
df1
df2 = DataFrame(list('CDEF'), columns=['y'])
df2
set(df1.x).symmetric_difference(df2.y)

rawDescription: How do I do a SQL style disjoint or set difference on two Pandas DataFrame objects?

description: Do a SQL style disjoint or set difference on two Pandas DataFrame objects


code:
filename = request.GET[ 'yourfilename' ]

from django.core.files.uploadedfile import SimpleUploadedFile
file_contents = SimpleUploadedFile("%s" %(filename), request.raw_post_data)

modelinstance.picture.save(filename, file_contents, True)

rawDescription: Saving file uploaded via ajax to Django model ImageField


code:
from scrapy.utils.markup import remove_tags, remove_tags_with_content

input = hxs.select('//div[@id="content"]').extract()
output = remove_tags(remove_tags_with_content(input, ('script', )))

rawDescription: Scraping text without javascript code using scrapy


code:
qClock = time.clock if qDuration > 0 else lambda: 0
qDuration = (qClock() + qDuration) if qDuration > 0 else 1

rawDescription: Python's syntactical sugar gone wrong

description: Python's syntactical sugar gone wrong


rawDescription: Regex for replacing certain string in python


code:
import numpy as np
a = np.arange(9).reshape(3,3)
a
b = np.repeat(a, 3, axis=1) # array, times, axis
b

rawDescription: python: How do I expand a numpy array with adjacent duplicate columns?

description: Python: How do I expand a numpy array with adjacent duplicate columns


rawDescription: Click on a link under td/td section selenium python


code:
import sys
from PySide.QtGui import *
from PySide.QtCore import *
from PySide.QtWebKit import *
from Browser_AutoPilot import BrowserAutoPilot

class Main_Gui(QDialog):
    def __init__(self):
        QDialog.__init__(self)
        layout = QVBoxLayout()
        self.bt_new = QPushButton('New')
        self.tabwidget = QTabWidget()
        layout.addWidget(self.tabwidget)
        layout.addWidget(self.bt_new)
        self.setLayout(layout)
        self.bt_new.clicked.connect(self.add_new)

    def add_new(self):
        br = browser()
        self.tabwidget.addTab(br, 'browser')

class browser(QWidget):
    load_finished = Signal()

    def __init__(self):
        QWidget.__init__(self)
        layout = QVBoxLayout()
        self.br = BrowserAutoPilot()
        self.bt_Start = QPushButton('Start')
        layout.addWidget(self.br)
        layout.addWidget(self.bt_Start)
        self.setLayout(layout)
        self.th = TimerThread()
        self.bt_Start.clicked.connect(self.start_load)

    def start_load(self):
        self.stop_thread(self.th)

        self.th.nextURL.connect(self.load_url_slot)
        self.br.loadFinished.connect(self.wait_loading)
        self.th.start()

    def load_url_slot(self, url):
        self.br.load(QUrl(url))

    def wait_loading(self):
        self.th.loaded = True

    def stop_thread(self, thread):
        thread.terminate()
        if thread.isRunning():
            QCoreApplication.processEvents()

    def sleep(self, seconds):
        end = QTime.addSecs(QTime.currentTime(), seconds)
        while end > QTime.currentTime():
            QCoreApplication.processEvents()

class TimerThread(QThread):
    nextURL = Signal(str)

    def __init__(self, loaded=False):
        QThread.__init__(self)
        self.loaded = loaded

    def run(self):
        sites = ['https://mayaposch.wordpress.com/2011/11/01/how-to-really-truly-use-qthreads-the-full-explanation/',
                 'http://www.codecademy.com/tracks/python', 'http://www.google.com']

        for url in sites:
            print(self.thread(), url)
            self.nextURL.emit(url)
            self.loaded = False
            while not self.loaded:
                self.sleep(1)

app = QApplication(sys.argv)
win = Main_Gui()
win.resize(800, 600)
win.show()
sys.exit(app.exec_())

rawDescription: how to run many instances of an object simultaneously in pyqt pyside

description: Run many instances of an object simultaneously in pyqt pyside


code:
questions_fname = "Test.txt"

with open(questions_fname) as f:
    for line in f:
        line = line.rstrip().replace('\\n', '\n')
        print(line)

rawDescription: python 3.2.3 ignore escape sequence in string

description: Python 3.2.3 ignore escape sequence in string


code:
ones = []
pos = 0
while val:
   if val & 1:
      ones.append(pos)
   pos += 1
   val >>= 1

rawDescription: Python - direct a functions output to a set


code: stuff_name = self.path_args[0]

rawDescription: Get URL parameter inside prepare() function, instead of get() / post()


code: value = float(somelist[0])

rawDescription: Importing data from a file as a float in python


code:
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

import jsonpickle

class Pizza:
    pass

class Example(webapp.RequestHandler):
    def get(self):
        jsonpickle.load_backend('django.utils.simplejson',
                                'dumps','loads',ValueError)
        encoded = jsonpickle.encode(Pizza())
        self.response.out.write( jsonpickle.decode(encoded).__class__ )

run_wsgi_app(webapp.WSGIApplication([('/', Example),],debug=True))

rawDescription: google app engine jsonpickle

description: Google app engine jsonpickle


code: print("Your income tax is ${:,}".format(income))

rawDescription: How to add commas to digits in Python 3?

description: Add commas to digits in Python 3


code:
def add_property(mock_object, property_name, property_value) :
    prop = mock.PropertyMock(return_value=property_value)
    setattr(type(mock_object), property_name, prop)

    # this catches sdk changes if spec_set is used with the MagicMock as
    # it will fail if you assign the property to an non-existant attribute
    mock_object.attach_mock(prop, property_name)

mock_item = mock.MagicMock(spec_set=sdk.MyItemClass)
add_property(mock_item, 'name', "Item title")

rawDescription: How do I catch sdk changes in my unittests when mocking properties

description: Catch sdk changes in my unittests when mocking properties


code: y = ([(dft[nn].real)*np.cos(np.pi*x*nn) + (dft[nn].imag)*np.cos(np.pi*x*nn) for nn in range(0,n)])

rawDescription: Fourier Series from Discrete Fourier Transform


code: tgtPorts = [s.strip() for s in str(options.tgtPort).split(',')]

rawDescription: Splitting string on comma, remove the comma


code:
current_hour = datetime.now().hour

while 1:
    if(datetime.now().hour != current_hour):
        run_Method()
        current_hour = datetime.now().hour

rawDescription: python, while loop, at the start of each hour call method

description: Python, while loop, at the start of each hour call method


rawDescription: Python: equivalent to Ruby's a = [0..200]


code:
import urllib2
from BeautifulSoup import BeautifulSoup

html = urllib2.urlopen("http://www.google.com").read()
soup = BeautifulSoup(html)
all_links = soup.findAll("a")

rawDescription: Regex for links in html text

description: Regex for links in html text


code:
with open(filename, 'r') as input_f:
    prevline = ''
    line_num = 0

    for line in input_f:
        line_num += 1
        if line.strip() != prevline.strip():     # use strip()
            print('%3d - %s' % (line_num, line))

        prevline = line

rawDescription: Printing non-matching (unique) lines in a file


code:
import Tkinter as tk

class ExampleApp(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        t = SimpleTable(self, 10,2)
        t.pack(side="top", fill="x")
        t.set(0,0,"Hello, world")

class SimpleTable(tk.Frame):
    def __init__(self, parent, rows=10, columns=2):
        # use black background so it "peeks through" to
        # form grid lines
        tk.Frame.__init__(self, parent, background="black")
        self._widgets = []
        for row in range(rows):
            current_row = []
            for column in range(columns):
                label = tk.Label(self, text="%s/%s" % (row, column),
                                 borderwidth=0, width=10)
                label.grid(row=row, column=column, sticky="nsew", padx=1, pady=1)
                current_row.append(label)
            self._widgets.append(current_row)

        for column in range(columns):
            self.grid_columnconfigure(column, weight=1)

    def set(self, row, column, value):
        widget = self._widgets[row][column]
        widget.configure(text=value)

if __name__ == "__main__":
    app = ExampleApp()
    app.mainloop()

rawDescription: Creating a table look-a-like Tkinter

description: Creating a table look-a-like Tkinter


code: handle = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, "your_sub_key", 0, _winreg.KEY_READ | _winreg.KEY_WOW64_64KEY)

rawDescription: Change 64bit Registry from 32bit Python

description: Change 64bit Registry from 32bit Python


code: ar[np.where([i in another_ar for i in ar[:,0]])]

rawDescription: NumPy: filter rows by np.array

description: NumPy: filter rows by np.array


code:
import bottle
from wsgiproxy.app import WSGIProxyApp

root = bottle.Bottle()
proxy_app = WSGIProxyApp("http://localhost/")
root.mount(proxy_app,"/proxytest")

rawDescription: Routes in bottle which proxy to another server


code: L = [{k: d[k](v) for (k, v) in l.iteritems()} for l in L]

rawDescription: Apply functions to values of dictionaries


code:
from fabric.api import env
from fabric.operations import run, put

env.hosts = ['frodo@middleearth.com']

def copy():
    # make sure the directory is there!
    run('mkdir -p /home/frodo/tmp')

    # our local 'testdirectory' - it may contain files or subdirectories ...
    put('testdirectory', '/home/frodo/tmp')

# [frodo@middleearth.com] Executing task 'copy'
# [frodo@middleearth.com] run: mkdir -p /home/frodo/tmp
# [frodo@middleearth.com] put: testdirectory/HELLO -> \
#     /home/frodo/tmp/testdirectory/HELLO
# [frodo@middleearth.com] put: testdirectory/WORLD -> \
#     /home/frodo/tmp/testdirectory/WORLD
# ...

rawDescription: How do I copy a directory to a remote machine using Fabric?

description: Copy a directory to a remote machine using Fabric


rawDescription: Django: select all A objects that are involved in m2m relationships with any B objects (via B.m2mfield)


code:
pattern = "(<td>)?\n\s+(</td>)?"
filename1 =  '[<td>\n                  myfile.doc\n                </td>]'
filename2 = r'[<td>\n                  myfile.doc\n                </td>]'
re.sub(pattern, '', filename1)
re.sub(pattern, '', filename2)

rawDescription: re.sub isn't matching when it seems it should

description: Re.sub isn't matching when it seems it should


code:
a = [
['first_name', 'last_name', 'email'],
['Danny', 'Lastnme', 'name@email.com'],
['Sally', 'Surname', 'name@email.com'],
['Sally', 'Surname', 'name@email.com'],
['Sally', 'Surname', 'name@email.com'],
['Chris', 'Lastnam', 'name@email.com'],
['Larry', 'Seconds', 'name@email.com'],
['Barry', 'Barrins', 'name@email.com'],
['Glenn', 'Melting', 'name@email.com'],
['Glenn', 'Melting', 'name@email.com'],
]

result = {}

b = [tuple(x) for x in a[1:]]
all_uniques = set(b)
result['unique'] = [list(x) for x in list(all_uniques)]

# To show which ones have duplicates use Mr Es solution:

from collections import Counter

t = Counter(b)
dupes = []

for k, v in t.iteritems():
    if v > 1:
        dupes.append(list(k)*(v-1))

result['dupes'] = dupes

print(result)

rawDescription: Django - De-dupe a List and Keep the Dupes


rawDescription: Can I split an input that doesnt have spaces?

description: Split an input that doesnt have spaces


code:
def nonZero(var):
   if isinstance(var,collection):
     if len(collection) == 0 : return False
     else: return True
   if isinstance(var, number):
     if number == 0 : return False
     else: return True
   if isinstance(var, boolean): return var
   if isinstance(var, NoneType): return False
   if hasattr(var,'__nonzero__'): return var.__nonzero__()

nodeIds = Framework.getDataAsList(key)
if not nonZero(nodeIds) : nodeIds = []

rawDescription: Python assignment with or

description: Python assignment with or


code:
import re

mystring = [
'FOO_LG_06.ip',
'FOO_LV_06.ip',
'FOO_SP_06.ip',
'FOO_LN_06.id',
'FOO_LV_06.id',
'FOO_SP_06.id']

for soth in mystring:
    matches = re.search(r'FOO_(\w+)_06(\.\w{2})', soth)
    print(matches.group(1) + matches.group(2))

rawDescription: Extracting part of string through regex in Python


code:
blah="ajsdlk akajl <ajksd@ajksldf.com>"
blah.split('<')[1].split('>')[0]

rawDescription: Python - Execute command set results as variable


rawDescription: How to locate text input by name using Selenium WebDriver?

description: Locate text input by name using Selenium WebDriver


code:
from multiprocessing import Process, Pipe

def read_frames(connection_obj):
  #initilize the video capture object
  cam  = cv2.VideoCapture(0)
  while True:
    ret, frame = cam.read()
    connection_obj.send(frame) # is this what you want to send?

    if exit_condition is True:
        connection_obj.close()
        break

def launch_read_frames(connection_obj):
    """
    Starts the read_frames function in a separate process.
    param connection_obj: pipe to send frames into.
    Returns a pipe object
    """
    read_frames_process = Process(target=read_frames, args=(connection_obj,)) # this trailing comma is intentional
    read_frames_process.start()
    read_frames_process.join()

    return parent_conn

def act_on_frames(connection_obj):
    while True:
        frame = connection_obj.recv()
        # Do some stuff with each frame here

if __name__ == '__main__':
    parent_conn, child_conn = Pipe()
    launch_read_frames(child_conn)

    # You could also call this function as a separate process, though in
    # this instance I see no performance benefit.
    act_on_frames(parent_conn)

rawDescription: How to keep a real-time data read-in loop separate from more processing intensive operations in Python?

description: Keep a real-time data read-in loop separate from more processing intensive operations in Python


code:
import numpy as np
import matplotlib as mpl
import matplotlib.colorbar as cb
import matplotlib.pyplot as plt
from datetime import datetime
from matplotlib import dates

y = np.reshape(np.random.rand(100), (10, 10))
f1 = plt.figure()
ax1 = f1.add_axes([0.15, 0.15, 0.76, 0.80])
mindate = mpl.dates.date2num(datetime(2010, 1, 10))
maxdate = mpl.dates.date2num(datetime(2010, 1, 20))
im1 = ax1.imshow(
    y, cmap='binary', aspect='auto',
    origin='upper', interpolation='nearest',
    extent=(0, 1, mindate, maxdate))

ax1.yaxis_date()

ax1.invert_yaxis()
hfmt = dates.DateFormatter('%b %d %Y')
ax1.yaxis.set_major_locator(dates.DayLocator(interval=1))
ax1.yaxis.set_major_formatter(hfmt)

plt.show()

rawDescription: Displaying an inverted vertical date axis


code:
class WorkResource( BaseModelResource ):
    links = fields.ToManyField('musiclibrary.api.LinkResource', attribute=lambda bundle: Link.objects.filter(entity0_content_type=ContentType.objects.get_for_model(bundle.obj), entity0_object_id=bundle.obj.id))

rawDescription: Django Tastypie Generic Relation

description: Django Tastypie Generic Relation


code: set((np.convolve(v, longtuple, 'valid') >> k & 1).tostring() for v in itertools.product([0,1], repeat = m))

rawDescription: Fast way to apply function elementwise to a numpy array


rawDescription: Parse date and time from string with time zone using Arrow


code:
import re
linere = re.compile(r"^(?P<value>[0-9a-fA-F]+)h; ParIsa\.(?P<name>[a-zA-Z.]+)\[(?P<index>\d+)\]\.(?P<attribute>[0-9a-zA-Z_]+) \(BYTE\)$")

rawDescription: Python text to tree structure creation

description: Python text to tree structure creation


code:
import win32gui
win = win32gui
while True:
    print(win.GetWindowText(win.GetActiveWindow()))

rawDescription: How to get python to recognise what window I am using?

description: Get python to recognise what window I am using


code: names = set([name.rpartition('_')[0] for name in glob('*_*.dat')])

rawDescription: Automatically find files that start with similar strings (and find these strings) using Python


code:
import argparse
import sys
from StringIO import StringIO

old_stderr = sys.stderr
sys.stderr = cap = StringIO()
old_argv = sys.argv
sys.argv = ['--help']
TheClass().parse_args()
sys.stderr = old_stderr
sys.argv = old_argv

parser = argparse.ArgumentParser(description=cap.read())
parser.add_argument('--foo', type=float)

my_args, remainder = parser.parse_known_args()
sys.argv = remainder

TheClass(foo=my_args.foo).parse_args()

rawDescription: How can I add additional arguments to a python code?

description: Add additional arguments to a python code


rawDescription: Convert two character string to its hex value in Python


code: user = models.ForeignKey(User, null=True)

rawDescription: What is the default type for a user in Django?


code:
rgb = [ v for v in image_buffer for _ in range( 3 ) ]
rgb_ba = bytearray( rgb )
bitmap.FromBuffer( height, width, rgb_ba )

rawDescription: Convert Mono8 image buffer to displayable format for wx.Bitmap in wxPython Phoenix in Python


code:
class HouseForm(forms.ModelForm):
    address = forms.CharField(widget=forms.Textarea)

    class Meta:
        model = House

rawDescription: How to cutomize a modelform widget in Django 1.1?

description: Cutomize a modelform widget in Django 1.1


code:
class BoxAdminForm(forms.ModelForm):
    box_item_quantity = forms.IntegerField()

    def __init__(self, *args, **kwargs):
        """ populate box_item_quantity initial value """
        super(BoxAdminForm, self).__init__(*args, **kwargs)
        if self.instance:
            self.initial['box_item_quantity'] = self.instance.item.quantity

    class Meta:
        model = Box

class BoxAdmin(admin.ModelAdmin):
    form = BoxAdminForm

    def save_model(self, request, obj, form, change):
        super(BoxAdmin, self).save_model(request, obj, form, change)
        obj.item.quantity = form.cleaned_data.get('box_item_quantity')
        obj.item.save()

admin.site.register(Box, BoxAdmin)

rawDescription: Edit field from ForeignKey in Admin

description: Edit field from ForeignKey in Admin


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

data = [tuple(pair)
        for pair in np.random.uniform(5, size=(20,2))
        for c in range(np.random.random_integers(50))]
count = collections.Counter(data)

points = count.keys()
x, y = zip(*points)
sizes = np.array(count.values())**2
plt.scatter(x, y, s=sizes, marker='o', c=sizes)
plt.show()

rawDescription: Python:Plotting a bubble chart of location data


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

N = 20
size = 4
x_data = y_data = range(N)

fig = plt.figure()

prev = None
for n in range(0, N, size):
    # clear figure
    plt.clf()

    # set axes background transparent for plots n > 0
    if n:
        fig.patch.set_alpha(0.0)
        axes = plt.axes()
        axes.patch.set_alpha(0.0)

    plt.axis([0, N, 0, N])

    # here you'd read the next x/y values from disk into memory and plot
    # them.  simulated by grabbing batches from the arrays.
    x = x_data[n:n+size]
    y = y_data[n:n+size]
    ax = plt.plot(x, y, 'ro')
    del x, y

    # render the points
    plt.draw()

    # now composite the current image over the previous image
    w, h = fig.canvas.get_width_height()
    buf = numpy.fromstring(fig.canvas.tostring_argb(), dtype=numpy.uint8)
    buf.shape = (w, h, 4)
    # roll alpha channel to create RGBA
    buf = numpy.roll(buf, 3, axis=2)
    w, h, _ = buf.shape
    img = Image.fromstring("RGBA", (w, h), buf.tostring())
    if prev:
        # overlay current plot on previous one
        prev.paste(img)
        del prev
    prev = img

# save the final image
prev.save('plot.png')

rawDescription: Large PyPlot - avoid memory allocation

description: Large PyPlot - avoid memory allocation


code:
from collections import Counter
special_chars = '''!"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~ '''
found_chars = [c for c in open(yourfile).read() if c in special_chars]
counted_chars = Counter(found_chars)

rawDescription: Python: Counting a specific set of character occurrences in lines of a file


code:
class A(object):
    _instances = weakref.WeakValueDictionary()
    _next_id = functools.partial(next, itertools.count())

    def __init__(self):
        self._instances[self._next_id()] = self

rawDescription: Python: How to implement a static list in a class referencing all created items and an easy way to delete the items?


code:
a = get_exif('photo2.jpg')
lat = [float(x)/float(y) for x, y in a['GPSInfo'][2]]
latref = a['GPSInfo'][1]
lon = [float(x)/float(y) for x, y in a['GPSInfo'][4]]
lonref = a['GPSInfo'][3]

lat = lat[0] + lat[1]/60 + lat[2]/3600
lon = lon[0] + lon[1]/60 + lon[2]/3600
if latref == 'S':
    lat = -lat
if lonref == 'W':
    lon = -lon

rawDescription: Translate Exif DMS to DD Geolocation with Python


code:
from matplotlib import pyplot as plt
plt.plot(x)
plt.legend(['x', 'y', 'z'])

rawDescription: plot components of a vector separately in matplotlib

description: Plot components of a vector separately in matplotlib


code:
def sortStudents(a):
    return sorted(key=lambda b: (b[1], b[0]), reverse=True)

rawDescription: Sorting names in tuple using lambda expression not working


code: min(allowedList, key=sortedList.index)

rawDescription: Finding first instance of one list in a second list


code: cv2.getPerspectiveTransform(src, dst)

rawDescription: undistorting/ dewarping a picture with 4 points on a plane

description: Undistorting/ dewarping a picture with 4 points on a plane


code:
import xml.etree.ElementTree as ET

html = '''

Some reasonably well-formed HTML content.

    <form action="login">
    <input name="foo" value="bar"/>
    <input name="username"/><input name="password"/>

It is not unusual to see   in an HTML page.

    </form>'''

magic = '''<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
            "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" [
            <!ENTITY nbsp ' '>
            ]>'''  # You can define more entities here, if needed

et = ET.fromstring(magic + html)

rawDescription: Parsing XHTML using xml.etree.ElementTree


code:
def CreateCircleArray(radius=1):
    theta = np.linspace(0, 2*np.pi, 50)
    x = radius * np.cos(theta)
    y = radius * np.sin(theta)
    return np.array([x, y]).T

def PlotArray(array):
    ax = plt.subplot(111, aspect="equal")
    ax.scatter(array[:, 0], array[:, 1], color="k")
    plt.show()

PlotArray(CreateCircleArray())

rawDescription: Scatter plot (2D), which shows a dotted circle and other 2D-shapes made by geometrical functions with ipython, numpy and matplotlib


rawDescription: Python resolve a host name with IPv6 address


code:
target_cols = ['MedDescription', 'Min', 'Max', 'Days Unused']
df1.merge(df2[target_cols], on='MedDescription', how='left')

rawDescription: Fill DataFrame row values based on another dataframe row's values pandas


code:
from PIL import Image
import numpy as np

w, h = 512, 512
data = np.zeros((h, w, 3), dtype=np.uint8)
data[256, 256] = [255, 0, 0]
img = Image.fromarray(data, 'RGB')
img.save('my.png')

rawDescription: How do I convert a numpy array to (and display) an image?

description: Convert a numpy array to (and display) an image


code:
import os
os.environ['HUDSON_HOME'] = 'http://localhost:8080'

rawDescription: os.environ() giving errors while setting for Hudson

description: Os.environ() giving errors while setting for Hudson


code:
search = (
    SearchQuerySet().filter(content=term)
)

search_list = search[:]
unpublished_Mymodels = Mymodel.objects.filter(published=False)

for match in search_list:
    try:
        if match.model_name == 'Mymodel':
            if match._get_object() in unpublished_Mymodels:
                search_list.remove(match)
    except:
        pass

search = search_list

rawDescription: Exclude objects on Haystack search without the need of update_index


code:
# Lognormal distribution of P's
Pmean0 = 0.
P_0 = Lognormal('P_0', mu=Pmean0, tau=isigma2, trace=False, value=P_inits[0])
P = [P_0]

# Recursive step
for i in range(1,nyears):
    Pmean = Lambda("Pmean", lambda P=P[i-1], k=k, r=r: log(max(P+r*P*(1-P)-k*catch[i-1],0.01)))
    Pi = Lognormal('P_%i'%i, mu=Pmean, tau=isigma2, value=P_inits[i], trace=False)
    P.append(Pi)

rawDescription: PyMC: Parameter estimation in a Markov system


code:
from kivy.app import App
from kivy.uix.tabbedpanel import TabbedPanel
from kivy.lang import Builder

Builder.load_string("""

<Test>:
    do_default_tab: False
    tab_width: self.size[0]/len(self.tab_list)
    TabbedPanelItem:
        text: 'tab 1'
    TabbedPanelItem:
        text: 'tab2'

    TabbedPanelItem:
        text: 'tab3'
""")

class Test(TabbedPanel):
    pass

class TabbedPanelApp(App):
    def build(self):
        return Test()

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

rawDescription: How to make TabbedPannel's tabs fill all horizontal space?

description: Make TabbedPannel's tabs fill all horizontal space


code:
docRelCounts = docCounts/docLengths

goodDocRelCounts = docRelCounts[i,:][np.invert(np.isnan(docRelCounts[i,:]))]
relCountMeans = goodDocRelCounts.mean()
relCountDeviations = goodDocRelCounts.std()

rawDescription: how do I remove columns from a collection of ndarrays that correspond to zero elements of one of the arrays?

description: Remove columns from a collection of ndarrays that correspond to zero elements of one of the arrays


code:
dct = {}
with open('input', 'r') as f:
    for line in f:
        name, value = line.split()
        key, name = name.split('_')
        lst = dct.get(key ,[])
        lst.extend([name, value])
        dct[key] = lst

with open('result', 'w') as f:
    for k, v in dct.items():
        f.write(k+" " + (" ".join(v))+"\n")

rawDescription: Python) parsing data from correlation matrix file


code:
def validate_user(surname, username, passwd, password, errors):
    for n in [surname, username]:
        n = n.strip()
        # Append the following printed strings to a list if you want to return them..
        if not n:
            print("{} is not valid, enter a valid name..".format(n))
        if len(n) > 20:
            print("{} is too long, please shorten.".format(n))

rawDescription: Iterating through function arguments python


code:
import sys, os
os.isatty(sys.stdout.fileno())

rawDescription: How to know if the output is going to a terminal or not?

description: Know if the output is going to a terminal or not


code:
import re
p = re.compile(r'(?:\w+\s+){1,2}layout')
p.findall(" 25/4 16th june road ,watertank layout ,blr")
p.findall(" jacob circle 16th rusthumbagh layout , 5th cross")
p.findall(" oberoi splendor garden blossoms layout , 5th main road")
p.findall(" belvedia heights , 15th layout near Jaffrey gym")

rawDescription: Matching multiple words Regex , python

description: Matching multiple words Regex , python


code:
pid = Popen(["internals/applog.sh",])

while True:
    answer = raw_input("Press Y when you are done: ")
    if answer == 'Y':
        pid.kill()
        break

rawDescription: How to call a shell script from python in multiprocess?

description: Call a shell script from python in multiprocess


code: pd.pivot_table(df, values=['D', 'E'], rows=['B'], aggfunc=[np.mean, np.sum])

rawDescription: Multiple AggFun in Pandas

description: Multiple AggFun in Pandas


code:
if isinstance( arg, collections.Sequence ):
    self._some_var = list(arg)
else:
    self._some_var.append( arg )

rawDescription: len(object) or hasattr(object, __iter__)?

description: Len(object) or hasattr(object, __iter__)


code:
horizontalSobelMtx = [[-1,0,1],[-2,0,2],[-1,0,1]]
horizontalSobelMtx = numpy.asanyarray(horizontalSobelMtx, np.float32)

rawDescription: In OpenCV, what data types does cv2.filter2D() expect?


code:
class MyGObjectClass(gobject.GObject):
    __gsignals__ = {
      "some-signal": (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (object, )),
    }

rawDescription: How do I create a new signal in pygtk

description: Create a new signal in pygtk


code:
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

me = 5.974 * 10 ** (24)  #  mass of the earth
mm = 7.348 * 10 ** (22)  #  mass of the moon
G = 6.67259 * 10 ** (-20)  #  gravitational parameter
re = 6378.0  #  radius of the earth in km
rm = 1737.0  #  radius of the moon in km
r12 = 384400.0  #  distance between the CoM of the earth and moon
M = me + mm

pi1 = me / M
pi2 = mm / M
mue = 398600.0  #  gravitational parameter of earth km^3/sec^2
mum = G * mm  #  grav param of the moon
mu = mue + mum
omega = np.sqrt(mu / r12 ** 3)
nu = -129.21 * np.pi / 180  #  true anomaly angle in radian

x = 327156.0 - 4671
#  x location where the moon's SOI effects the spacecraft with the offset of the
#  Earth not being at (0,0) in the Earth-Moon system
y = 33050.0   #  y location

vbo = 10.85  #  velocity at burnout

gamma = 0 * np.pi / 180  #  angle in radians of the flight path

vx = vbo * (np.sin(gamma) * np.cos(nu) - np.cos(gamma) * np.sin(nu))
#  velocity of the bo in the x direction
vy = vbo * (np.sin(gamma) * np.sin(nu) + np.cos(gamma) * np.cos(nu))
#  velocity of the bo in the y direction

xrel = (re + 300.0) * np.cos(nu) - pi2 * r12
#  spacecraft x location relative to the earth
yrel = (re + 300.0) * np.sin(nu)

#  r0 = [xrel, yrel, 0]
#  v0 = [vx, vy, 0]
u0 = [xrel, yrel, 0, vx, vy, 0]

def deriv(u, dt):
    n1 = -((mue * (u[0] + pi2 * r12) / np.sqrt((u[0] + pi2 * r12) ** 2
                                               + u[1] ** 2) ** 3)
        - (mum * (u[0] - pi1 * r12) / np.sqrt((u[0] - pi1 * r12) ** 2
                                              + u[1] ** 2) ** 3))
    n2 = -((mue * u[1] / np.sqrt((u[0] + pi2 * r12) ** 2 + u[1] ** 2) ** 3)
        - (mum * u[1] / np.sqrt((u[0] - pi1 * r12) ** 2 + u[1] ** 2) ** 3))
    return [u[3],  #  dotu[0] = u[3]
            u[4],  #  dotu[1] = u[4]
            u[5],  #  dotu[2] = u[5]
            2 * omega * u[4] + omega ** 2 * u[0] + n1,  #  dotu[3] = that
            omega ** 2 * u[1] - 2 * omega * u[3] + n2,  #  dotu[4] = that
            0]  #  dotu[5] = 0

dt = np.arange(0.0, 320000.0, 1)  #  200000 secs to run the simulation
u = odeint(deriv, u0, dt)
x, y, z, x2, y2, z2 = u.T

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot(x, y, z)
plt.show()

my_x, my_y, my_z = (384400,0,0)

delta_x = x - my_x
delta_y = y - my_y
delta_z = z - my_z
distance = np.array([np.sqrt(delta_x ** 2 + delta_y ** 2 +
           delta_z ** 2)])

print(distance.min())

rawDescription: minimum distance from an array

description: Minimum distance from an array


code:
import sys
from PyQt4 import QtGui

class Window(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        layout = QtGui.QVBoxLayout(self)
        self.button = QtGui.QPushButton('Test')
        self.edit = QtGui.QTextEdit()
        layout.addWidget(self.edit)
        layout.addWidget(self.button)
        self.button.clicked.connect(self.handleTest)

    def handleTest(self):
        self.edit.append('spam: spam spam spam spam')

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

rawDescription: Add more than one line to a QTextEdit PyQt


code: df.loc[:, df.dtypes == np.float64]

rawDescription: Selecting Pandas Columns by dtype

description: Selecting Pandas Columns by dtype


code:
import re
blockOfText = 'two thousand may be represented as 2000 2000.00 2,000 and 2k'
' '.join([ ''.join(x[0]) for x in re.findall(r'(\$?\d+([,\.]\d+)?k?)', blockOfText) ])

rawDescription: Python regex for dollar amounts including commas and decimals


code:
from dulwich.repo import Repo
from dulwich.client import HttpGitClient
local = Repo.init("local", mkdir=True)
client = HttpGitClient('http://github.com/adammorris/')
remote_refs = client.fetch("history.js.git",local)
local["HEAD"] = remote_refs["refs/heads/master"]

rawDescription: How to pull from the remote using dulwich?

description: Pull from the remote using dulwich


code:
def func(a, b=None):
    if b is None:
        b = 100
    return a + b

rawDescription: Is there a way to tell a python function received a default value or keyword parameter?


code:
file_path = os.path.join(os.path.dirname(os.path.realpath(__name__)), 'EvalofSelf1.xlsx')
response = HttpResponse(open(file_path, 'rb').read())
response['Content-Type'] = 'mimetype/submimetype'
response['Content-Disposition'] = 'attachment; filename=DownloadedEval.xlsx'

rawDescription: Django Serve .XLSX File and force download


code:
class User(object):
    def __init__(self, username):
        self.username = username
def object_hook(name, d):
    cls = {'WP_User': User}[name]
    # The following was added by me -Antti
    d = convert_member_dict(d)
    return cls(**d)
user = loads(data, object_hook=object_hook)
user.username

rawDescription: Object_hook not given phpserialize

description: Object_hook not given phpserialize


code:
def collecList(collection):
    liste, keys, value = [], [], []
    for row in collection.find().sort("index"):
        keys.append(row.keys())
        value.append(row.values())
    zipped = zip(keys, value)
    for x, y in zipped:
         liste.append(dict(zip(x, y)))
    return liste

rawDescription: MongoDB Flask and pymongo

description: MongoDB Flask and pymongo


code:
import matplotlib.ticker as ticker
g.ax_joint.xaxis.set_major_locator(ticker.MultipleLocator(90))
g.ax_joint.yaxis.set_major_locator(ticker.MultipleLocator(45))

rawDescription: Setting the axes tick values of a seaborn jointplot


code: help(str)

rawDescription: what's the difference between string method and str method in Python?

description: What's the difference between string method and str method in Python


code:
User.objects.filter(
    Q(profile__category__name__icontains=search_string) |
    Q(profile__Tags__name__icontains=search_string)
).distinct()

rawDescription: Django : Searching from different tables in django


code:
xpath_output = 'background-image: url(\"/uploads/images/teams/test.jpeg\")'

path = xpath_output.split('"')[1]

rawDescription: Retrieve url from background-image

description: Retrieve url from background-image


code:
import signal

class TimeoutException(Exception):   # Custom exception class
    pass

def timeout_handler(signum, frame):   # Custom signal handler
    raise TimeoutException

# Change the behavior of SIGALRM
signal.signal(signal.SIGALRM, timeout_handler)

for i in range(3):
    # Start the timer. Once 5 seconds are over, a SIGALRM signal is sent.
    signal.alarm(5)
    # This try/except loop ensures that
    #   you'll catch TimeoutException when it's sent.
    try:
        A(i) # Whatever your function that might hang
    except TimeoutException:
        continue # continue the for loop if function A takes more than 5 second
    else:
        # Reset the alarm
        signal.alarm(0)

rawDescription: break the function after certain time

description: Break the function after certain time


code:
def get_adjlist_with_names(graph):
    names = graph.vs["name"]
    result = {}
    for index, neighbors in enumerate(graph.get_adjlist()):
        result[names[index]] = [names[nei] for nei in neighbors]
    return result

rawDescription: python igraph - get_adjlist() not returning vertex names, only ids

description: Python igraph - get_adjlist() not returning vertex names, only ids


code:
if key not in urls:
  connection = urllib.request.urlopen(url)
  urls[key] = url
  return connection.getcode()

rawDescription: Does urllib.request.urlopen(url) use cache?


code:
l = np.array([-3, -2, -1, 0, 1, 2, 3, 4, 3, 2, 1, 0, -1, -2, -3, 4, -3, -2, -1, 0, 1, 2])
epsilon = 1
inds = np.argwhere(np.abs(l) < epsilon) # indices of “almost zero” items
left = inds[0] # index of the first “almost zero” value
right = inds[-1] # -//- last
l[:left + 1] = 0 # zero out everything to the left and including the first “almost zero”
l[right:] = 0 # -//- last
l

rawDescription: Finding the index values where a certain value occurs in an array in Python


code:
urls = mongo_models.URL.objects.filter(name=name)
bytes = mongo_models.BytesForURL.objects.filter(
            timestamp__gte=from_time,
            timestamp__lte=to_time, url__in=urls)

rawDescription: How to fetch foreign key relationships in mongoengine

description: Fetch foreign key relationships in mongoengine


code:
import subprocess
import sys

outfile = i + ".txt"

cmd = sys.path[0] + "/htmltotext " + i + ".html"

with open(outfile, "w") as output_f:
    p = subprocess.Popen(cmd, stdout=output_f, shell=True)

rawDescription: Calling html2text iteratively on a set of htmls not working


code:
def handle_refund_and_credit(total, card_total, user):
    total = 600
    card_total = 400
    user_credit_refund = total - card_total
    handle_refund(total)
    user.print_credit += user_credit_refund

def handle_refund(amount):
    __refund(amount)

rawDescription: Clarifying responsibility with named parameters


code:
def print_blackjack(pHands):
    for i in range(len(pHands)):
        print('Player', i, ':', pHands[i])

rawDescription: Print List with Number of Players (Blackjack)


code:
from django.template.response import TemplateResponse

def decorator(view):
    def wrapper(request, *args, **kwargs):
        r = view(request, *args, **kwargs)
        r.context_data = {'foo': 'bar'}
        return r.render()
    return wrapper

@decorator
def index(request):
    return TemplateResponse(request, 'index.html')

rawDescription: Django: add context to response using decorator


code:
from PyQt5.QtCore import QDate, QDateTime
QDate.currentDate().toPyDate()
QDateTime.currentDateTime().toPyDateTime()

rawDescription: How can you convert QDate in PyQt5 to a datetime.date?

description: Convert QDate in PyQt5 to a datetime.date


code:
# create some masked data
a=cumsum(random.random((20,200)), axis=0)
X,Y=meshgrid(arange(a.shape[1]),arange(a.shape[0]))
a[Y<15*sin(X/50.)]=nan
a[Y>10+15*sin(X/50.)]=nan

# draw the image along with some curves
imshow(a,interpolation='nearest',origin='lower',extent=[-2,2,0,3])
xd = linspace(-2, 2, 200)
yd = 1 + .1 * cumsum(random.random(200)-.5)
plot(xd, yd,'w',linewidth=3)
plot(xd, yd,'k',linewidth=1)
axis('normal')

rawDescription: Heatmap with varying y axis

description: Heatmap with varying y axis


code:
class Queue:
    """Create a queue object with a given maximum size.

    If maxsize is <= 0, the queue size is infinite.
    """
    def __init__(self, maxsize=0):
        self.maxsize = maxsize
        self._init(maxsize)
        self.mutex = _threading.Lock()
        self.not_empty = _threading.Condition(self.mutex)
        ... # Stuff we don't care about

    def get(self, block=True, timeout=None):
        self.not_empty.acquire() # Only on thread can hold this at a time
        try:
            if not block:
                if not self._qsize(): # If there's nothing in the Queue
                    raise Empty
            ... # Other stuff we don't care about, since you use block=False
            item = self._get()
            self.not_full.notify()
            return item
        finally:
            self.not_empty.release()

    def _init(self, maxsize):
        self.queue = deque()

    def _qsize(self, len=len):
        return len(self.queue)

rawDescription: Python Queue.get(block=False) with non-empty Queue. Can it raise Queue.empty?


code:
import cherrypy
import os.path
import struct
import time
import subprocess
import commands

class Server(object):
    led_on=1
    led_off=1
    def index(self):
        html = """

                """
        return html
    index.exposed = True

    def Process(self,  on='0'):
        if on == '1':
            self.led_on = int(on)
            subprocess.call(['guvcview &'], shell=True)
            time.sleep(2)
            output = commands.getoutput('ps -A')
            if 'guvcview' in output:
                return "guvcview is running"

        if on == '0':
            self.led_off = int(on)
            subprocess.call(['sudo pkill guvcview'], shell=True)
            time.sleep(2)
            output = commands.getoutput('ps -A')
            if 'guvcview' in output:
                return "Please wait ....."
            else:
                return "guvcview closed"

        return "Please wait ....."
    Process.exposed = True

conf = {
        'global' : {
            'server.socket_host': '0.0.0.0',
            'server.socket_port': 8085
        },

        '/images': {
            'tools.staticdir.on': True,
            'tools.staticdir.dir': os.path.abspath('images')
        }
    }
cherrypy.quickstart(Server(), config=conf)

rawDescription: How to display "Please wait...." on the web page when click on a button using Python&HTML

description: Display "Please wait...." on the web page when click on a button using Python&HTML


code: dtwithoutseconds = dt.replace(second=0, microsecond=0)

rawDescription: Stripping off the seconds in datetime python


code:
def get_pvs(service, profile_id, start_date, end_date, type, data):
    if type == 'url':
        kwargs = {
            'dimensions': 'ga:pagePath',
            'filters': 'ga:pageviews!=0',
            'maxresults': 100
        }
    elif type == 'author':
        kwargs = {
            'dimensions': 'ga:dimension2',
            'max_results': '100'
        }
    return service.data().ga().get(
        ids = 'ga:' + profile_id,
        start_date = start_date,
        end_date = end_date,
        metrics = 'ga:pageviews',
        sort = '-ga:pageviews',
        **kwargs).execute()

rawDescription: How can I refactor this code to be more concise?

description: Refactor this code to be more concise


code:
input_types = ['Foreign Country', 'Adverb', 'Adjective', 'Animal', 'Verb (ing)']
input_types.append('Verb')
input_types.append('Verb (ing)')
input_types.append('Adverb')
input_types.append('Adjective')
input_types.append('A Place')
input_types.append('Type of Liquid')
input_types.append('Part of the Body')
input_types.append('Verb')

story = '''If you are traveling in {} and find yourself having to cross
a piranha-filled river, here's how to do it {}.
Piranhas are more {} during the day, so cross the river at night.
Avoid areas with netted {} traps - piranhas may be {} there looking to {} them!
When {} the river, swim {}. You don't want to wake them up and make them {}!
Whatever you do, if you have an open wound,
try to find another way to get back to the {}.
Piranhas are attracted to fresh {} and will most likely take a bite out
of your {} if you {} in the water!'''

print('WELCOME TO MADLIBS! PY V1.2.1\n')
print('To see the story type all thirteen parts of speech below')

results = []

for number, value in enumerate(input_types):
    user_input = raw_input('#{} - {}: '.format(number+1, value))
    results.append(user_input)

print('Here is your story: ')
print(story.format(*results))

rawDescription: raw_input while loop not working

description: Raw_input while loop not working


code: x['C'] = x['B'].replace(to_replace=r'\b'+x['A']+r'\b', value='',regex=True)

rawDescription: Remove words that appear in other column, Pandas


code:
def get_monotonic_subsequences(data, min_length):
    direction = data[1] - data[0] #determine direction of initial subsequence
    subsequences = []
    cur_seq = []
    for i in range(0, len(data) - 1):
        if direction > 0:
            if (data[i] >= data[i-1]):
                cur_seq.append(data[i])
            else:
                subsequences.append(cur_seq)
                cur_seq = [data[i]]
                direction = data[i+1] - data[i]
        else:
            if (data[i] <= data[i-1]):
                cur_seq.append(data[i])
            else:
                subsequences.append(cur_seq)
                cur_seq = [data[i]]
                direction = data[i+1] - data[i]

    if  (data[-1] - data[-2])*direction > 0:
        cur_seq.append(data[-1])
        subsequences.append(cur_seq)
    else:
        subsequences.append(cur_seq)
        subsequences.append([data[-1]])
    return [x for x in subsequences if len(x) >= min_length]

rawDescription: Determining where in a list ascending or descending stops


code:
import os
import cgi

class MyFieldStorage(cgi.FieldStorage):
    def make_file(self, binary=None):
        return open(os.path.join('/tmp', self.filename), 'wb')

rawDescription: python upload - where are tmp/FILES?

description: Python upload - where are tmp/FILES


rawDescription: Generating a simple mathematical sequence in Python


code:
from ctypes import *
f = c_float()
f_pointer = pointer(f) # full pointer functionality
f_byref = byref(f) # minimalistic pointer just for passing by reference

rawDescription: Using Python to access DLL functions with Pointers


code:
TIMEOUT = 1.0
INT = 3.0        # interval in seconds

# create udp_socket
last = time.time() - INT
udp_socket.settimeout(TIMEOUT)
while True:
    try:
        packet = udp_socket.recv(MAXSIZE)
    except socket.timeout:
        # handle recv timeout
        continue    # or break, or return
    except OSError:
        # handle recv error (Python 3.3+)
        break       # or continue, or return
    now = time.time()
    if now - last >= INT:
        # process the packet
        last = now

rawDescription: Drop Incoming 'packets' for Datagram Socket


code:
import itertools
sets = [{1,2,3}, {3,4,5}, {5,6,7}]
for s1,s2 in itertools.combinations(sets,2):
    print(s1, s2, s1 & s2)

rawDescription: Finding pairs of intersecting sets in a list of arbitrary sets


code:
next_objs = Media.objects.filter(id__gt=image.id).order_by('id')[:2]
prev_objs = Media.objects.filter(id__lt=image.id).order_by('-id')[:2]

rawDescription: optimize this query that selects rows before and after a pk

description: Optimize this query that selects rows before and after a pk


code:
def clean_data(data):
    data_iter = iter(data)
    for item in data_iter:
        if item in {'+', '-'}:
            yield item + next(data_iter)
        else:
            yield item

data = ['5', '+', '4X1', '-', '9.3X2']
new_data = clean_data(data)

print(list(new_data))  # ['5', '+4X1', '-9.3X2']

rawDescription: Python regex [group separator[

description: Python regex [group separator[


code:
import scrapy
from scrapy import signals
from scrapy.http import TextResponse
from scrapy.xlib.pydispatch import dispatcher

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

class EexSpider(scrapy.Spider):
    name = "eex"
    allowed_domain = ["google.com"]
    start_urls = ["http://google.com"]

    def __init__(self):
        self.driver = webdriver.Chrome()
        dispatcher.connect(self.spider_closed, signals.spider_closed)

    def spider_closed(self, spider):
        self.driver.close()

    def parse(self, response):
        self.driver.get(response.url)

    text_response = TextResponse(url=response.url, body=self.driver.page_source, encoding='utf-8')

rawDescription: Response not defined in Scrapy parse function


code:
myDict = {'Sun': {'Object': 'Sun', 'Satellites': 'Mercury,Venus,Earth,Mars,Jupiter,Saturn,Uranus,Neptune,Ceres,Pluto,Haumea,Makemake,Eris', 'Orbital Radius': '0', 'RootObject': 'Sun', 'Radius': '20890260'}, 'Moon': {'Object': 'Moon', 'Orbital Radius': '18128500', 'Period': '27.321582', 'Radius': '1737000.10'}, 'Earth': {'Object': 'Earth', 'Satellites': 'Moon', 'Orbital Radius': '77098290', 'Period': '365.256363004', 'Radius': '6371000.0'}}
for body in myDict:
     myDict[body]['Radius'] = float(myDict[body]['Radius'])
     myDict[body]['Orbital Radius'] = float(myDict[body]['Orbital Radius'])
myDict

rawDescription: Converting the value from string to integer in a nested dictionary


code:
from django.db.models import Q

date_filter = Q(start_date__range = [str(daterangestart), str(datereangeend)] )
date_filter |= Q(end_date__range = [str(daterangestart), str(datereangeend)] )
reportDetails = productreport.objects.filter(date_filter)

rawDescription: How to convert Mysql query for date range into Django query

description: Convert Mysql query for date range into Django query


code:
# If more than 1 second difference
if os.stat(src).st_mtime - os.stat(dest).st_mtime > 1:
    shutil.copy2 (src, dst)

rawDescription: Can we do a smart-copy in Python?

description: Can we do a smart-copy in Python


code: as_list = a.tolist()

rawDescription: What is this object called?

description: What is this object called


code: strchr.restype = c_char_p

rawDescription: Python and C coupling

description: Python and C coupling


code:
import sys
from PyQt4 import QtCore, QtGui

class StartQT4(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(StartQT4, self).__init__(parent)
        self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
        self.b = QtGui.QPushButton("exit", self, clicked=self.close)

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    myapp = StartQT4()
    myapp.show()
    sys.exit(app.exec_())

rawDescription: Python - How do i remove the window border? I have imported UI from Qt into Python and applied setWindowFlags


code:
def show_multiples(low, high, multi):
    #make empty list
    multi_list = []
    #make the list
    for i in range(high, low, -1):
        if i % multi == 0:
            multi_list.append(i)
            print('List was created')
    return multi_list # <-- this should be out of the loop

rawDescription: Transferring a list from function to function in python


code:
df_base = df_base.set_index("name")
df_upd = df_upd.set_index("name")
df_base.update(df_upd)
df_base

rawDescription: A clean and efficient way to update cells in pandas DataFrames