code:
x = os.statvfs('/')
x.f_favail

rawDescription: Replacement for python statvfs?

description: Replacement for python statvfs


code:
import wx
from wx.lib.mixins.listctrl import TextEditMixin

class EditableTextListCtrl(wx.ListCtrl, TextEditMixin):
    def __init__(self, parent, ID, pos=wx.DefaultPosition,
                size=wx.DefaultSize, style=0):
        wx.ListCtrl.__init__(self, parent, ID, pos, size, style)
        TextEditMixin.__init__(self)

class MyDialog(wx.Dialog):
    def __init__(self, parent, id, title):
        wx.Dialog.__init__(self, parent, id)
        listCtrl = EditableTextListCtrl(self, -1, style=wx.LC_REPORT|wx.LC_VRULES|wx.LC_HRULES, size=(300, 200))
        listCtrl.InsertColumn(0, 'State')
        listCtrl.InsertColumn(1, 'Capital')
        listCtrl.SetColumnWidth(0, 140)
        listCtrl.SetColumnWidth(1, 153)
        states = ['Slovakia', 'Poland', 'Hungary']
        capitals = ['Brastislava', 'Warsaw', 'Budapest']
        for i in range(3):
            listCtrl.InsertStringItem(0, states[i])
            listCtrl.SetStringItem(0, 1, capitals[i])

class MyApp(wx.App):
    def OnInit(self):
        dia = MyDialog(None, -1, 'capitals.py')
        dia.ShowModal()
        dia.Destroy()
        return True

app = MyApp(0)
app.MainLoop()

rawDescription: problem with editing labels in wx list control

description: Problem with editing labels in wx list control


code:
def myFunction(self, a, b):
    '''

    @param a:
    @type a:
    @param b:
    @type b:
    '''
    return 'Hello, world'

rawDescription: Autogenerate dummy documentation in the source code for Python in eclipse


code:
fbdata = request.facebook.users.getInfo(request.facebook.uid,
                                        ['name', 'pic', 'interests'])

rawDescription: How do I get the "Interests" of a facebook user uing Facebook Connect? (I'm using Django/python and pyFacebook middleware)

description: Get the "Interests" of a facebook user uing Facebook Connect? (I'm using Django/python and pyFacebook middleware)


code:
import Tkinter as tk
import Xlib.display as display

def mousepos(screenroot=display.Display().screen().root):
    pointer = screenroot.query_pointer()
    data = pointer._data
    return data["root_x"], data["root_y"]

def update():
    strl.set("mouse at {0}".format(mousepos()))
    root.after(100, update)

root = tk.Tk()
strl = tk.StringVar()
lab = tk.Label(root,textvariable=strl)
lab.pack()
root.after(100, update)
root.title("Mouseposition")
root.mainloop()

rawDescription: Showing Mouseposition with python

description: Showing Mouseposition with python


code:
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.canvas, 1, wx.EXPAND)
self.SetSizer(sizer)

rawDescription: wxPython: Making something expand

description: WxPython: Making something expand


code:
user = User()
user.username = request.json['username']
user.first_name = request.json['first_name']
user.last_name = request.json['last_name']
user.email = request.json['email']
user.password = user_manager.hash_password(request.json['password'])

db.session.add(user)
db.session.commit()

rawDescription: How to create a user 'programmatically' with Flask-user extension?

description: Create a user 'programmatically' with Flask-user extension


code:
import subprocess

mdbOutput = subprocess.check_output([ 'mdb', 'hostname' ])

rawDescription: what is the equivalent perl and python code for unix command "mdb hostname"

description: What is the equivalent perl and python code for unix command "mdb hostname"


rawDescription: Mechanize: submitting form but not loading new page to see results


code:
def load_miniatures(self, *args):
    proxy = Loader.image('http://10.0.13.206:9000/?action=snapshot')
    proxy.bind(on_load=self.receive_miniatures)

def receive_miniatures(self, proxy):
    if proxy.image.texture:
        self.image.texture = proxy.image.texture
    Clock.schedule_once(self.load_miniatures, 0.1)

def build(self):
    self.image = Image()
    self.load_miniatures()
    return self.image

rawDescription: How to refresh Image.texture from CoreImage.texture?

description: Refresh Image.texture from CoreImage.texture


code:
import calendar
df['Month'] = df['Month'].apply(lambda x: calendar.month_abbr[x])

rawDescription: python/pandas: convert month int to month name

description: Python/pandas: convert month int to month name


code:
import bisect
def func(times, start, end):
    bucket = [start, end]
    out = [x for x in times if bisect.bisect(bucket, x) is 1 or x in bucket]
    return out, (times.index(out[0]), times.index(out[-1]))

rawDescription: index estimation for a list of datetimes in python

description: Index estimation for a list of datetimes in python


rawDescription: Why is re.split() returning an extra blank at the end of my resulting List?


rawDescription: Append a plus sign before positive numbers?


code:
def main():
    num=int(input("Enter number of players: "))
    tmplist=[]
    for _ in range(num):
        pl=input("Enter name: " )
        tmplist.append(pl)

    print(tmplist)

rawDescription: How can I add values in the list using for loop in python?

description: Add values in the list using for loop in python


code:
import datetime
from dateutil.relativedelta import relativedelta
today = datetime.date.today()
two_m_ago = today - relativedelta(months=2)
# print two_m_ago ~> datetime.date(2015, 2, 25)
monday = two_m_ago - datetime.timedelta(days=two_m_ago.weekday())
# print monday ~> datetime.date(2015, 2, 23)

rawDescription: Python: Find date beginning two months prior to today AND start on a Monday


code:
cap = webdriver.DesiredCapabilities.PHANTOMJS
cap["phantomjs.page.settings.javascriptEnabled"] = False
driver = webdriver.PhantomJS(desired_capabilities=cap)

rawDescription: How to disable JavaScript in PhantomJS through Selenium WebDriver

description: Disable JavaScript in PhantomJS through Selenium WebDriver


code:
import string
replace_punctuation = string.maketrans(string.punctuation, ' '*len(string.punctuation))
text = text.translate(replace_punctuation)

rawDescription: how to replace punctuation in a string python?

description: Replace punctuation in a string python


code:
shouts = db.GqlQuery("""SELECT *
                          FROM Shout
                         WHERE when >= DATE('2010-11-05')
                           AND when < DATE('2010-11-06')""")

rawDescription: Why doesn't my GQL query return any results in my GAE App?


code:
from jarray import zeros
from java.io import BufferedInputStream, FileInputStream, FileOutputStream
from java.util.zip import ZipEntry, ZipOutputStream

def test(file):
    zos = ZipOutputStream(FileOutputStream(file + ".zip"))
    buf = zeros(1024, 'b')
    zipEntry = ZipEntry(file)
    fin = FileInputStream(file)
    bin = BufferedInputStream(fin)
    zos.putNextEntry(zipEntry)
    len = bin.read(buf)
    while len >= 0:
        zos.write(buf, 0, len)
        len = bin.read(buf)
    bin.close()
    zos.closeEntry()

rawDescription: help me translate Java code making use of bytes into jython code

description: Help me translate Java code making use of bytes into jython code


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

import random
import string
import sys

MAX_LENGTH = 20
MAX_SIZE = 11111

def get_random():
    return ''.join([
        random.choice(string.ascii_letters) for i in range(
            random.randrange(10, 1000))])

def get_random_list():
    return [get_random() for i in range(random.randrange(50, 1000))]

def get_str_length(rnd_list, item_idx):
    return len(''.join(rnd_list[:item_idx]))

rnd_list = get_random_list()

def calculate_ideal_amount(rnd_list):
    list_bounds = {
        'first': 1,
        'last': len(rnd_list)
    }
    print ('ORIG_SIZE: %s, ORIG_LEN: %s' % (
        get_str_length(rnd_list, len(rnd_list)), len(rnd_list)))
    if get_str_length(rnd_list, list_bounds['first']) > MAX_SIZE:
        return 0
    if get_str_length(rnd_list, list_bounds['last']) <= MAX_SIZE and \
            list_bounds['last'] <= MAX_LENGTH:
        return list_bounds['last']
    while True:
        difference = round((list_bounds['last'] - list_bounds['first']) / 2)
        middle_item_idx = list_bounds['first'] + difference
        str_len = get_str_length(
            rnd_list, middle_item_idx)
        print(
            'MAX_SIZE: %s, list_bounds: %s, '
            'middle_item_idx: %s, diff: %s, str_len: %s,' % (
                MAX_SIZE, list_bounds, middle_item_idx, difference, str_len))
        # sys.stdin.readline()
        if str_len > MAX_SIZE:
            list_bounds['last'] = middle_item_idx
            continue
        if middle_item_idx > MAX_LENGTH:
            return MAX_LENGTH
        list_bounds['first'] = middle_item_idx
        if difference == 0:
            if get_str_length(rnd_list, list_bounds['last']) <= MAX_SIZE:
                if list_bounds['last'] > MAX_LENGTH:
                    return MAX_LENGTH
                return list_bounds['last']
            return list_bounds['first']

ideal_idx = calculate_ideal_amount(rnd_list)

print (
    len(rnd_list), get_str_length(rnd_list, len(rnd_list)),
    get_str_length(rnd_list, ideal_idx), ideal_idx,
    get_str_length(rnd_list, ideal_idx + 1))

rawDescription: Python: Efficient way to split list of strings into smaller chunks by concatenated size


code: region = rec.seq[start:end]

rawDescription: Fetching genomic sequence efficiently in Python?


code:
from reportlab.lib.pagesizes import letter
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.platypus import BaseDocTemplate, Frame, PageTemplate, Paragraph

styles = getSampleStyleSheet()
styleN = styles['Normal']
styleH = styles['Heading1']

def footer(canvas, doc):
    canvas.saveState()
    P = Paragraph("This is a multi-line footer.  It goes on every page.  " * 5,
                  styleN)
    w, h = P.wrap(doc.width, doc.bottomMargin)
    P.drawOn(canvas, doc.leftMargin, h)
    canvas.restoreState()

doc = BaseDocTemplate('test.pdf', pagesize=letter)
frame = Frame(doc.leftMargin, doc.bottomMargin, doc.width, doc.height,
               id='normal')
template = PageTemplate(id='test', frames=frame, onPage=footer)
doc.addPageTemplates([template])

text = []
for i in range(111):
    text.append(Paragraph("This is line %d." % i,
                          styleN))
doc.build(text)

rawDescription: A multiline(paragraph) footer and header in reportlab


code:
import json
json.dumps(list)

rawDescription: Python: converting a list of dictionaries to json


code:
i = 0
while not lcd.is_pressed(LCD.SELECT):
    i = (i + 1) % 400
    if i == 0:
        lcd.message("Press Select")
    elif i == 200:
        lcd.clear()
    sleep(0.01)

rawDescription: Execute code after some time without using sleep in Python?


code:
import matplotlib.pyplot as plt
from cStringIO import StringIO
imgdata = StringIO()

fig, ax = plt.subplots()

# Make your plot here referencing ax created before
results.resid.hist(ax=ax)

fig.savefig(imgdata)

worksheet.insert_image(row, 0, imgdata)

rawDescription: Writing pandas/matplotlib image directly into XLSX file


rawDescription: combine list of lists in python (similar to string.join but as a list comprehension?)

description: Combine list of lists in python (similar to string.join but as a list comprehension?)


code:
lst = ['a', 'b', 'c', 'd', 'e',' f', 'g',' h', 'i']
n = 4  # Size of sublists
[lst[x:x+n] for x in xrange(0, len(lst), n)]

rawDescription: Convert normal list to specific nested list


code:
@patch("my_class.Comm", autospec=True)
def test_base(self, mock_comm_factory):
    mock_comm = mock_comm_factory.return_value
    MyClass()
    mock_comm.start.assert_called_with()

@patch("my_class.Comm", autospec=True)
def test_changeValue(self, mock_comm_factory):
    mock_comm = mock_comm_factory.return_value
    mock_comm.getval.return_value = 13
    MyClass().changeValue(33, 23)
    mock_comm.getval.assert_called_with(33)
    mock_comm.send.assert_called_with(33, 23)
    mock_comm.reset_mock()
    mock_comm.getval.return_value = 23
    MyClass().changeValue(33, 23)
    mock_comm.getval.assert_called_with(33)
    self.assertFalse(mock_comm.send.called)

rawDescription: Mocking Communications

description: Mocking Communications


code:
textfile=open('somefile.txt','r')
text_list=[line.split(' ') for line in textfile]
unique_words=[word for word in text_list if word not in unique_words]
print(len(unique_words))

rawDescription: how do I count unique words of text files in specific directory with Python?

description: Count unique words of text files in specific directory with Python


code:
import urllib2

manager = urllib2.HTTPPasswordMgrWithDefaultRealm()
manager.add_password(None, 'https://app.streamsend.com/emails', 'login', 'key')
handler = urllib2.HTTPBasicAuthHandler(manager)

director = urllib2.OpenerDirector()
director.add_handler(handler)

req = urllib2.Request('https://app.streamsend.com/emails', headers = {'Accept' : 'application/xml'})

result = director.open(req)
# result.read() will contain the data
# result.info() will contain the HTTP headers

# To get say the content-length header
length = result.info()['Content-Length']

rawDescription: CURL alternative in Python

description: CURL alternative in Python


rawDescription: how to replace via regex with group enclosed in python

description: Replace via regex with group enclosed in python


code:
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors import LxmlLinkExtractor
from myproject.items import someItem

class someSpider(CrawlSpider):
  name = 'crawltest'
  allowed_domains = ['someurl.com']
  start_urls = ['http://www.someurl.com/']

  rules = (Rule(LxmlLinkExtractor(allow=()), callback='parse_obj', follow=True),)

  def parse_obj(self,response):
    for link in LxmlLinkExtractor(allow=(),deny = self.allowed_domains).extract_links(response):
        item = someItem()
        item['url'] = link.url

rawDescription: Scrapy, only follow internal URLS but extract all links found


code:
from datetime import date

def get_image_path(self, filename):
     path = ''.join([date.today().strftime('static/article/%Y/%m/%d/'),
                     translit.slugify(filename)])
     return path

rawDescription: how to use curent date in image path django

description: Use curent date in image path django


code:
import time
from gi.repository import Gdk, Gtk, GObject

class MainWindow(Gtk.Window):
    """Example window."""

    def __init__(self):
        """Create new instance."""
        super(MainWindow, self).__init__()
        self.set_title('Test Windows')

        box = Gtk.VBox()
        label = Gtk.Label("Just a label....")
        box.pack_start(label, True, True, 0)
        button = Gtk.Button(" and a button")
        box.pack_start(button, True, True, 0)

        self.add(box)
        self.connect("destroy", Gtk.main_quit)
        self.show_all()

    def set_watch(self):
        """Set the mouse to be a watch."""
        watch = Gdk.Cursor(Gdk.CursorType.WATCH)
        gdk_window = self.get_root_window()
        gdk_window.set_cursor(watch)

    def long_call(self):
        """Perform a long call."""
        time.sleep(10)             # your time consuming operation here
        arrow = Gdk.Cursor(Gdk.CursorType.ARROW)
        gdk_window = self.get_root_window()
        gdk_window.set_cursor(arrow)

window = MainWindow()
window.set_watch()
GObject.idle_add(window.long_call)
Gtk.main()

rawDescription: Change the cursor to an hour glass using python in Gtk3


code:
import bs4
html_doc = """
<title>The Dormouse's story</title>

The Dormouse's story

Once upon a time there were three little sisters; and their names were
Elsie,
Lacie and
Tillie;
and they lived at the bottom of a well.

...

"""
soup = bs4.BeautifulSoup(html_doc, 'html.parser')
print(soup.text)
print(''.join(soup.find_all('p')[1].find_all_next(text=True)))

rawDescription: get text after h1 using beautiful soup in Python

description: Get text after h1 using beautiful soup in Python


rawDescription: How to write a regular expression to match a string literal where the escape is a doubling of the quote character?

description: Write a regular expression to match a string literal where the escape is a doubling of the quote character


code:
import os
import shutil

srcpath = "SOURCE"
destpath = "DESTINATION"

for root, subFolders, files in os.walk(srcpath):
    for file in files:
        subFolder = os.path.join(destpath, file[:5])
        if not os.path.isdir(subFolder):
            os.makedirs(subFolder)
        shutil.move(os.path.join(root, file), subFolder)

rawDescription: Python Move Files Based On Name

description: Python Move Files Based On Name


code:
class Type1:
   @classmethod
   def from_param(cls, obj):
       if obj is None:
           return c_void_p()
       else:
           return obj.c_ptr

rawDescription: Calling C function from ctypes: class instance can be None


code:
import re
import urllib
stream=urllib.urlopen("http://....")
result=re.search('<dcdIntegerValue>(\d*)</dcdIntegerValue>',stream.read(),re.IGNORECASE)
if result:
     value=result.group(1)

rawDescription: python, how to add variable value from xml response?

description: Python, how to add variable value from xml response


code:
from bulbs.rexster import Graph
g = Graph()                                 # create the Graph object
script = "g.V.range(start,end)"             # set a one line script
params = dict(start=0, end=9)               # put function params in dict
vertices = g.gremlin.query(script, params)  # execute the script in DB

rawDescription: Bulb Flow: How to get a range of vertices?


code:
arr = ["aa", "bb", "cc"]
{'item{}'.format(i): x for i,x in enumerate(arr)}

rawDescription: how to convert an array to a dict in python

description: Convert an array to a dict in python


code:
mData = _dm_Values
for i in range(0, iCount):
    if i == (iCount - 1):
        mData[key[i]] = value
    else:
        if key[i] not in mData.keys():
            mData[key[i]] = dict()
        mData = mData[key[i]]

rawDescription: Dynamically edit dict tree in Python

description: Dynamically edit dict tree in Python


code:
def skipNdCmp(f1, f2,skip1,skip2,bufsize = 8*1024):
    with open(f1, 'rb') as fp1, open(f2, 'rb') as fp2:
        for i in xrange(0,skip1): fp1.readline()
        for i in xrange(0,skip2): fp2.readline()
        while True:
                b1 = fp1.read(bufsize)
                b2 = fp2.read(bufsize)
                if b1 != b2:
                    return False
                if not b1:
                    return True

rawDescription: Does Python have any standard lib which can compare two files by omitting the first several lines?


code:
with open("myfile.txt") as f, open("output.txt", "w") as out:
    for line in f:
        out.write("bar" + line)

rawDescription: Appending a string in front of every item in the file using Python


code:
import requests

for i in range(101):
    payload = {'usn': i}
    response = requests.post("index.php", data=payload)
    # do something with response

rawDescription: Pass Python parameters to HTML

description: Pass Python parameters to HTML


code:
t = array([2,  0,  1,  4,  5,  3])
indices = np.argsort(t)
print(z[indices])

rawDescription: Python: sorting time series values

description: Python: sorting time series values


code:
# The type of completer to use. Valid values are:
#
# 'plain'   : Show the available completion as a text list
#             Below the editing area.
# 'droplist': Show the completion in a drop down list navigable
#             by the arrow keys, and from which you can select
#             completion by pressing Return.
# 'ncurses' : Show the completion as a text list which is navigable by
#             `tab` and arrow keys.
c.IPythonWidget.gui_completion = 'ncurses'

rawDescription: IPython full suggestionlist

description: IPython full suggestionlist


code: range(year, year - 6, -1)

rawDescription: Python get a list of years

description: Python get a list of years


code:
unpack('6f', packed)
unpack('6i', packed)
unpack('3d', packed)
unpack('dfid', packed)

rawDescription: Unpacking binary files

description: Unpacking binary files


code:
keys = set(data_changes.keys()) & set(modem_changes.keys())
data_changes = {k:data_changes[k] for k in keys}
modem_changes = {k:modem_changes[k] for k in keys}
data_changes
modem_changes

rawDescription: Control flow of for loops

description: Control flow of for loops


code:
document = webview.page().currentFrame().documentElement()
document.findAll("a")
...

rawDescription: PyQtWebkit and java script

description: PyQtWebkit and java script


code:
from datetime import datetime
from glob import glob
import os

for filename in glob(os.path.join(filepath, 'ETos*.asc')):
    try:
        dt = datetime.strptime(os.path.basename(filename), 'ETos%Y%m%d.asc')
    except ValueError as e:
        continue # rest of file name didn't have valid date - do the needful
    os.rename(filename, os.path.join(filepath, format(dt, 'ETos%Y%j.asc')))

rawDescription: Convert YYYYMMDD filename to YYYYJD

description: Convert YYYYMMDD filename to YYYYJD


code:
import sys
from collections import defaultdict
from PIL import Image, ImageDraw

from wu_ccl import scan, flatten_label

def borders(img):
    result = img.copy()
    res = result.load()
    im = img.load()
    width, height = img.size

    for x in xrange(1, width - 1):
        for y in xrange(1, height - 1):
            if not im[x, y]: continue
            if im[x, y-1] and im[x, y+1] and im[x-1, y] and im[x+1, y]:
                res[x, y] = 0
    return result

def do_wu_ccl(img):
    label, p = scan(img)
    ncc = flatten_label(p)
    # Relabel.
    l = label.load()
    for x in xrange(width):
        for y in xrange(height):
            if l[x, y]:
                l[x, y] = p[l[x, y]]
    return label, ncc

def calc_dist(a, b):
    dist = float('inf')
    for p1 in a:
        for p2 in b:
            p1p2_chessboard = max(abs(p1[0] - p2[0]), abs(p1[1] - p2[1]))
            if p1p2_chessboard < dist:
                dist = p1p2_chessboard
    return dist

img = Image.open(sys.argv[1]).convert('RGB')
width, height = img.size
# Pad image.
img_padded = Image.new('L', (width + 2, height + 2), 0)
width, height = img_padded.size
# "discard" jpeg artifacts.
img_padded.paste(img.convert('L').point(lambda x: 255 if x > 30 else 0), (1, 1))

# Label the connected components.
label, ncc = do_wu_ccl(img_padded)

# Count number of pixels in each component and discard those too small.
minsize = 200
cc_size = defaultdict(int)
l = label.load()
for x in xrange(width):
    for y in xrange(height):
        cc_size[l[x, y]] += 1
cc_filtered = dict((k, v) for k, v in cc_size.items() if k > 0 and v > minsize)

# Consider only the borders of the remaining components.
result = Image.new('L', img.size)
res = result.load()
im = img_padded.load()
l = label.load()
for x in xrange(1, width - 1):
    for y in xrange(1, height - 1):
        if im[x, y] and l[x, y] in cc_filtered:
            res[x-1, y-1] = l[x, y]
result = borders(result)
width, height = result.size
result.save(sys.argv[2])
# Collect the border points for each of the remainig components.
res = result.load()
cc_points = defaultdict(list)
for x in xrange(width):
    for y in xrange(height):
        if res[x, y]:
            cc_points[res[x, y]].append((x, y))
cc_points_l = list(cc_points.items())

# Perform a dummy O(n^2) method to determine whether two components are close.
grouped_cc = defaultdict(set)
dist_threshold = 100 # pixels
for i in xrange(len(cc_points_l)):
    ki = cc_points_l[i][0]
    grouped_cc[ki].add(ki)
    for j in xrange(i + 1, len(cc_points_l)):
        vi = cc_points_l[i][1]
        vj = cc_points_l[j][1]
        kj = cc_points_l[j][0]
        dist = calc_dist(vi, vj)
        if dist < dist_threshold:
            grouped_cc[ki].add(kj)
            grouped_cc[kj].add(ki)
# Flatten groups.
flat_groups = defaultdict(set)
used = set()
for group, v in grouped_cc.items():
    work = set(v)
    if group in used:
        continue
    while work:
        gi = work.pop()
        if gi in flat_groups[group] or gi in used:
            continue
        used.add(gi)
        flat_groups[group].add(gi)
        new = grouped_cc[gi]
        if not flat_groups[group].issuperset(new):
            work.update(new)

# Draw a bounding box around each group.
draw = ImageDraw.Draw(img)
bpad = 10
for cc in flat_groups.values():
    data = []
    for vi in cc:
        data.extend(cc_points[vi])
    xsort = sorted(data)
    ysort = sorted(data, key=lambda x: x[1])
    # Padded bounding box.
    bbox = (xsort[0][0] - bpad, ysort[0][1] - bpad,
            xsort[-1][0] + bpad, ysort[-1][1] + bpad)
    draw.rectangle(bbox, outline=(0, 255, 0))
img.save(sys.argv[2])

rawDescription: Using Python, is there a way to automatically detect a box of pixels in an image?


code:
import re
re.findall(r'(?<!\.\s)\b[A-Z][a-z]*\b', 'lookbehind. This is what I have')

rawDescription: Find words with capital letters not at start of a sentence with regex


code:
pool._taskqueue._maxsize = maxsize
pool._taskqueue._sem = BoundedSemaphore(maxsize)

rawDescription: Python multiprocessing: how to limit the number of waiting processes?


code:
html = """

"""

HTML(html)

rawDescription: How to Render Dygraph in iPython Notebook?

description: Render Dygraph in iPython Notebook


code:
import random

from traits.api import HasTraits, List, Str, Button
from traitsui.api import ListStrEditor, View, UItem

class Demo(HasTraits):

    my_list = List(Str)

    add = Button("ADD")
    clear = Button("CLEAR")

    traits_view = \
        View(
            UItem('my_list', editor=ListStrEditor(auto_add=False)),
            UItem('add'),
            UItem('clear'),
        )

    def _my_list_default(self):
        return ['Item1', 'Item2']

    def _add_fired(self):
        new_item = "Item%d" % random.randint(3, 999)
        self.my_list.append(new_item)

    def _clear_fired(self):
        self.my_list = []

if __name__ == "__main__":
    demo = Demo()
    demo.configure_traits()

rawDescription: How to update ListStrEditor in TraitsUI, or another way of displaying a list in a Python GUI?

description: Update ListStrEditor in TraitsUI, or another way of displaying a list in a Python GUI


code:
listings = soup.find_all('h6')
projecturls = [] # <-------------
for i in listings:
    url = i.find_all('a', href=True)[0]['href']
    projecturls.append(url) # <------

rawDescription: Python assign text to new variable

description: Python assign text to new variable


code:
d = [i for i in range(6)] + [50]
d

rawDescription: How to extend list comprehension with values outside the set builder?

description: Extend list comprehension with values outside the set builder


code: print(dir())

rawDescription: How to standard-print `dir()` and other calls in Ipython

description: Standard-print `dir()` and other calls in Ipython


code:
# Remove the data variable definition above the for loop
if (Est_no) in line:
    data = line.split(',')
    # Process data like a list like you are already doing

rawDescription: Splitting lines in a text file into separate entries in a list?


rawDescription: Django- get child attributes in parent object


rawDescription: Django filter against Multiple Item QuerySets


code:
df = pd.DataFrame([[23], [34], ['36/375'], ['NA'], [62]])
df
df.convert_objects(convert_numeric=True)

rawDescription: Set cell value to NaN under certain conditions using lamda map in Pandas


code:
imatrix = lambda n: [[1 if j == i else 0 for j in range(n)] for i in range(n)]
imatrix(3)

rawDescription: Python Lambda Identity Matrix

description: Python Lambda Identity Matrix


code:
class MyMainWindow(QWidget):
    def __init__(self):
        QWidget.__init__(self, None)

        vbox = QVBoxLayout(self)

        self.sone = QSlider(Qt.Horizontal)
        self.sone.setRange(0,99)
        self.sone.setValue(0)
        vbox.addWidget(self.sone)

        self.stwo = QSlider(Qt.Horizontal)
        self.stwo.setRange(0,99)
        self.stwo.setValue(99)
        vbox.addWidget(self.stwo)

        self.sone.valueChanged.connect(self.sliderChanged)

    def sliderChanged(self, val):
        self.stwo.setValue(self.stwo.maximum() - val)

rawDescription: PySide (or PyQt) signals and slots basics


code: [f for f in os.listdir('.') if os.path.isdir(f)]

rawDescription: how to get a list of all the folders in current directory

description: Get a list of all the folders in current directory


code:
df1 = df[df.Col2 == "A"].sample(1)
df2 = df[~df.index.isin(df1.index)]
df1
df2

rawDescription: How to sample on condition with pandas?

description: Sample on condition with pandas


code:
class MyUser(AbstractBaseUser, PermissionsMixin):

    def save(self, *args, **kwargs):
        if not self.email_from_work:
            self.email_from_work = self.get_email()
        super(MyUser, self).save(*args, **kwargs)

    def get_email(self):
        return self.email

    objects = UserManager()
    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['email']

    username = models.CharField(
        _('username'),
        max_length=30,
        unique=True,
        help_text=_('Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only.'),
        validators=[
            validators.RegexValidator(
                r'^[\w.@+-]+$',
                _('Enter a valid username. This value may contain only '
                  'letters, numbers ' 'and @/./+/-/_ characters.')
            ),
        ],
        error_messages={
            'unique': _("A user with that username already exists."),
        },
    )
    first_name = models.CharField(_('first name'), max_length=30, blank=True)
    last_name = models.CharField(_('last name'), max_length=30, blank=True)
    email = models.EmailField(_('email address'), blank=True)
    is_staff = models.BooleanField(
        _('staff status'),
        default=False,
        help_text=_('Designates whether the user can log into this admin site.'),
    )
    is_active = models.BooleanField(
        _('active'),
        default=True,
        help_text=_(
            'Designates whether this user should be treated as active. '
            'Unselect this instead of deleting accounts.'
        ),
    )
    date_joined = models.DateTimeField(_('date joined'), default=now)
    email_from_work = models.EmailField(max_length=255, unique=True)

rawDescription: Django Extend AbstractUser and use email Field as default in other field


code:
def add():
    cursor = g.db.cursor()
    cursor.execute("INSERT INTO users(username) VALUES(?)", [request.form['name']])
    g.db.execute("INSERT INTO posts(body, user_id) VALUES(?,?)",
                 [request.form['body'], cursor.lastrowid])
    g.db.commit()
    ...

rawDescription: sqlite3 foreign key not working at all

description: Sqlite3 foreign key not working at all


code: lists.sort(key = lambda x: (x[2], x[6] * -1, x[1]))

rawDescription: Python Sorting 2D List with custom Key

description: Python Sorting 2D List with custom Key


code:
class DB(object):

    db_string = "mysql://%s:%s@%s/%s" % (db_username, db_password, db_host, db_name)
    db_engine = create_engine(db_string, encoding="UTF-8", echo=False)

    table1 = Table("table1", MetaData(), autoload=True, autoload_with=db_engine)

    def connect():
        return self.db_engine.connect()

    def get_data(self, time_limit):
        connection = self.connect()
        stmt = select([self.table1]).where(self.table1.c.last_check < time_limit)
        return connection.execute(alexa_domains)

rawDescription: sqlalchemy always returning the same data

description: Sqlalchemy always returning the same data


code:
#!/usr/local/cpython-3.3/bin/python

# "A1","Address2"          "A1","Address2"
# 0138,"DEERFIELD AVE"     0138,"DEERFIELD"
# 0490,"REMMINGTON COURT"  0490,"REMMINGTON"
# 2039,"SANDHILL DR"       2039,"SANDHILL"

import re
import csv

with open('aa_street.txt', 'r') as infile, open('actual-output', 'w') as outfile:
    reader = csv.reader(infile)
    writer = csv.writer(outfile)
    for row in reader:
        row_zero = row[0]
        row_one = re.sub('\s+(DR|COURT|AVE|)\s*$', '', row[1])
        writer.writerow([row_zero, row_one])

rawDescription: CVS writerow() after expression

description: CVS writerow() after expression


code: d = dict(d.items()[:MAX_RESULTS])

rawDescription: Trimming dictionaries

description: Trimming dictionaries


code:
d = {}
for obj in object_list:
    d[obj.thing] = obj
desired_list = d.values()

rawDescription: List of objects with a unique attribute

description: List of objects with a unique attribute


code:
def neighbors(x, y):
   return np.array([(x-1, y), (x, y-1), (x+1, y), (x, y+1)])
ind = zip(*np.where(x > 10))
neighb = np.concatenate([neighbors(*i) for i in ind])

rawDescription: indexing numpy array neighbours efficiently

description: Indexing numpy array neighbours efficiently


code:
def generate_substrings(sequence):
    length = len(sequence)
    for i in range(len(sequence)- 19):
        currentSequence = sequence[i:i+20]
        recursiveReplaceLetter(currentSequence)

def recursiveReplaceLetter(s):
    isOk = True
    for i in range(len(s)):
        if (s[i] == "R"):
            isOk = False
            newSequence1 = s
            newSequence1 = newSequence1[:i+1].replace("R", "A") + newSequence1[i+1:]
            recursiveReplaceLetter(newSequence1)

            newSequence2 = s
            newSequence2 = newSequence2[:i+1].replace("R", "G") + newSequence2[i+1:]
            recursiveReplaceLetter(newSequence2)
            break

        elif(s[i] == "S"):
            isOk = False
            newSequence1 = s
            newSequence1 = newSequence1[:i+1].replace("S", "C") + newSequence1[i+1:]
            recursiveReplaceLetter(newSequence1)

            newSequence2 = s
            newSequence2 = newSequence2[:i+1].replace("S", "G") + newSequence2[i+1:]
            recursiveReplaceLetter(newSequence2)
            break

    if (isOk):
        print (s)

sequence="gRRcagagacgcaagcctaRgggSgggggttgggggggcgtgt"
generate_substrings(sequence)

rawDescription: Function to generate substrings from a string with some characters replaced


code:
def calcentries(fmt):
    return len(struct.unpack(fmt, '\0' * struct.calcsize(fmt)))

rawDescription: Identify the number of elements in a python struct/pack fmt string?


code:
from dbconnect import connection

def propertyCount():
    c, conn = connection()
    c.execute("SELECT COUNT(*) FROM properties")
    property_count = c.fetchone()[0]

    return property_count

rawDescription: How Can I count an SQL Row and store it in a variable using FLASK without always getting 1 as an answer?

description: Count an SQL Row and store it in a variable using FLASK without always getting 1 as an answer


code:
file = tkFileDialog.askopenfile(parent=root,mode='rb',filetypes=[('Subrip Subtitle File','*.srt')],title='Choose a subtitle file')
abs_path = os.path.abspath(file.name)

rawDescription: How to get the absolute path of a file using tkFileDialog?

description: Get the absolute path of a file using tkFileDialog


code:
import multiprocessing as mp

p = mp.Pool(5)

# first solution
for urls_chunk in urls: # urls = [(url1...url6),(url7...url12)...]
    res = p.map(get_social_stat, urls_chunk)
    for record in res:
        save_to_db(record)

# or, simple
res = p.map(get_social_stat, urls)

for record in res:
   save_to_db(record)

rawDescription: Improve Speed of Python Script: Multithreading or Multiple Instances?


code:
import requests
from bs4 import BeautifulSoup

s = requests.Session() # Add this line

page1 = s.get('https://www.ksl.com/auto/search/index?keyword=&make%5B%5D=Acura&yearFrom=&yearTo=&mileageFrom=&mileageTo=&priceFrom=&priceTo=&zip=&miles=25&newUsed%5B%5D=All&page=0&sellerType=&postedTime=&titleType=&body=&transmission=&cylinders=&liters=&fuel=&drive=&numberDoors=&exteriorCondition=&interiorCondition=&cx_navSource=hp_search&search.x=63&search.y=8&search=Search+raquo%3B').text
page2 = s.get('https://www.ksl.com/auto/search/index?page=1').text

rawDescription: Scraping second page in Python Yields Different Data Than Browsing to Second Page


code:
from pprint import pprint

colors = [
    ['red', 'green', 'green', 'red' , 'red'],
    ['red', 'red', 'green', 'red', 'red'],
    ['red', 'red', 'green', 'green', 'red'],
    ['red', 'red', 'red', 'red', 'red']
]

motions = [[0,0],[0,1],[1,0],[1,0],[0,1]]

p_move = 0.8

def move(lst, u):
    q = []
    if u[0] != 0:
        index = u[0]
        for i, elem in enumerate(lst):
            q.append([lst[j-index][i] * p_move] for j in range(len(elem)))
    elif u[1] != 0:
        index = u[1]
        for i, elem in enumerate(lst):
            q.append([lst[i][j-index] * p_move] for j in range(len(elem)))
    return q

def main():
    total = sum(len(c) for c in colors)
    p = [[1.0 / total] * len(c) for c in colors]
    a = [[0] * len(c) for c in colors]
    for m in motions:
        a = move(p, m)
    pprint(p)

main()

rawDescription: Code throws TypeError: unsupported operand type(s) for -: 'int' and 'list'


code:
from flask import request
@app.route('/', methods=['GET', 'POST'])
def home_page():
    if request.is_xhr:
        context = controllers.get_default_context()
        return render_template('home.html', **context)

rawDescription: How can I identify requests made via AJAX in Python's Flask?

description: Identify requests made via AJAX in Python's Flask


code:
my_pipe = os.pipe()
...
while True:
    ready_fds = select.select(my_read_fds + [my_pipe[0]],
                              my_write_fds, my_except_fds, timeout)
    if my_pipe[0] in ready_fds[0]:
        # Add another fd to my_read_fds, etc.
        os.read(my_pipe[0], 1)
    ...

# To interrupt the current select call and add a new fd, write to the pipe:
os.write(my_pipe[1], 'x')

rawDescription: Interrupting Select to add another socket to watch in Python


code:
# __init__.py
...
application = cherrypy.tree.mount(root, '/', app_conf)
...

# notarequest.py
import myapp
host = myapp.application.config['database']['host']

rawDescription: How do you access config outside of a request in CherryPy?

description: Access config outside of a request in CherryPy


code:
data = [['Amy', '2'],
    ['Amy', '2'],
    ['Amy', '1'],
    ['Yoyo', '1'],
    ['Yoyo', '2'],
    ['Yoyo', '2']]

import itertools

def extract_key(v):
    return v[0]

# itertools.groupby needs data to be sorted first
data = sorted(data, key=extract_key)

result = [
    [k,[x[1] for x in g]]
    for k, g in itertools.groupby(data, extract_key)
]

rawDescription: Python: How to merge the same elements in an array?


code:
#windows
import winsound
winsound.Beep(300,2000)
#where a is the frequency and b is the duration in miliseconds

#linux

import os
os.system('play --no-show-progress --null --channels 1 synth %s sine %f' % ( a, b))

rawDescription: How do I ring a bell sound within an ssh session?

description: Ring a bell sound within an ssh session


rawDescription: Selecting rows depending on conditions for multiple columns


code:
import numpy as np
import seaborn as sns
import matplotlib.ticker as tkr

formatter = tkr.ScalarFormatter(useMathText=True)
formatter.set_scientific(True)
formatter.set_powerlimits((-2, 2))

x = np.exp(np.random.uniform(size=(10, 10)) * 10)
sns.heatmap(x, cbar_kws={"format": formatter})

rawDescription: making colorbar with scientific notation in seaborn

description: Making colorbar with scientific notation in seaborn


code:
import pylab as pl
import numpy as np
from scipy import ndimage
img = pl.imread("Aet62.png")[:, :, 0].astype(np.uint8)
img2 = ndimage.binary_erosion(img, iterations=40)
img3 = ndimage.binary_dilation(img2, iterations=40)
labels, n = ndimage.label(img3)
counts = np.bincount(labels.ravel())
counts[0] = 0
img4 = labels==np.argmax(counts)
img5 = ndimage.binary_fill_holes(img4)
result = ~img & img5
result = ndimage.binary_erosion(result, iterations=3)
result = ndimage.binary_dilation(result, iterations=3)
pl.imshow(result, cmap="gray")

rawDescription: Numpy PIL Python : crop image on whitespace or crop text with histogram Thresholds


rawDescription: Join each line from two files as one line using python


code:
import function_defined_in_another_file

class SomeClass():
    method = function_defined_in_another_file.function

rawDescription: Defining a method for a class somewhere else


code:
width = max(coord[0] for coord in coordinates)
height = max(coord[1] for coord in coordinates)
zeros_and_ones = numpy.zeros([width, height])
for x, y in coordinates:
    zeros_and_ones[x, y] = 1

rawDescription: numpy array plot matrix matplotlib

description: Numpy array plot matrix matplotlib


code:
map_func = { 'ID' : lambda x : 'mig_farm_seq.nextval',
             'ENTERPRISE_NAME' : wrap_str,
             'TAX_NUMBER' : wrap_str,
             'FAMILY_NAME' : lambda x : wrap_str(x.split()[0]),
             'GIVEN_NAME' : lambda x : wrap_str(x.split()[1]),
             'ENTERPRISE_REGISTRATION_NUMBER' : wrap_str,
             'PREMISE_NAME' : wrap_str,
             'HOUSE_ID' : wrap_str,
             'POSTAL_CODE' : wrap_str,
             'PHONE_NUMBER_1' : lambda x : wrap_str(get_phone_number(x, True)),
             'PHONE_NUMBER_2' : lambda x : wrap_str(get_phone_number(x, False)),
             'FAX_NUMBER' : lambda x : wrap_str(x.replace(' ', '')),
             'BANK_IDENTIFIER' : lambda x : wrap_str(x.replace(' ', '').replace('-', '')[:3]),
             'BANK_ACCOUNT_NUMBER' : lambda x : wrap_str(x.replace(' ', '').replace('-', '')),
             'NUMBER_OF_EMPLOYEES' : wrap_null,
             'SETTLEMENT_NUMBER' : wrap_null,
             'REGISTRATION_NUMBER' : lambda x : insert_reg_number % x,
             'GENDER' : wrap_str,
             'ACTIVITY' : lambda x : '0',
             'REG_HOLDER_ACTIVITY' : lambda x : '0',
             'PROCESSED_BY_JOB' : lambda x : '0'
         }

rawDescription: Example where lambdas are very useful in Python


rawDescription: How to make PyQt window state to maximised in pyqt

description: Make PyQt window state to maximised in pyqt


code:
from django.db.models.signals import post_save
from django.contrib.auth.models import User

def create_statistic(sender, *args, **kwargs):
    if kwargs.get('created'):
        s = Statisics( comments=0, thanked=0, user=kwargs['instance'])

post_save.connect(create_statistics, sender=User)

rawDescription: Where should I place the code to be executed each time a new User is created with django-registration?


rawDescription: Finding that which sums to the smallest value


code:
import pylab as pl
x = [0,1]
xTicks = ['LONDON','PARIS']
y = [2.39, 3.41]
pl.xticks(x, xTicks)
pl.xticks(range(2), xTicks, rotation=45) #writes strings with 45 degree angle
pl.plot(x,y,'*')
pl.show()

rawDescription: how can I plot string vs float in python?

description: Plot string vs float in python


code:
class A(HasTraits):
    b = Instance(HasTraits)
    traits_view = View( Item('b', editor=InstanceEditor(), style='custom') )

class B(HasTraits):
    c = Int
    traits_view = View( Item('c') )

rawDescription: views on Nested HasTraits object

description: Views on Nested HasTraits object


code:
import pkg

sub_modules = (
    pkg.__dict__.get(a) for a in dir(pkg)
    if isinstance(
        pkg.__dict__.get(a), types.ModuleType
    )
)

for m in sub_modules:
    for c in (
        m.__dict__.get(a) for a in dir(m)
        if isinstance(m.__dict__.get(a), type(Base))
    ):
        """ c is what I needed """

rawDescription: python: list modules within the package

description: Python: list modules within the package


code:
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(8000)
tornado.ioloop.IOLoop.instance().start()

rawDescription: Tornado as normal server

description: Tornado as normal server


code:
conn, addr = server.accept()
request = conn.recv(9999) #get a CONNECT request
# Here, parse the CONNECT string and get the host and port (not sure if you were doing that already.

# Then, try to connect *before* you tell the client the connection was established (in case it fails)
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #plaintext client
client.connect((host, 443)) #connect to chosen host

conn.send(b'HTTP/1.1 200 Connection estabilished\n\n')

# Then loop until the connections are closed.
while True:
    # Read from the client, send the data to the server.
    enc_req = conn.recv(9999) #this gets an encrypted request
    client.send(enc_req)

    # Read from the server, send the data to the client.
    resp1 = client.recv(9999) #this gets something unreadable (encrypted?)
    #could it be the certificate?
    #now what?
    # The first time it's certainly the Client Hello message, not encrypted, but in a binary format indeed.
    # Just send everything you've just read to the server.
    conn.send(resp1)

rawDescription: got stuck programming https proxy - what to do next?

description: Got stuck programming https proxy - what to do next


code:
import multiprocessing, subprocess

def run(c):
    exe = os.path.join("<location>","folder",str(c),"program.exe")
    run = os.path.join("<location>","folder",str(c),"run.dat")
    subprocess.check_call([exe,run],cwd=os.path.join("<location>","folder"),creationflags = subprocess.CREATE_NEW_CONSOLE)

def main():
    pool = multiprocessing.Pool(3)
    for c in range(10):
        pool.apply_async(run,(str(c),))
    pool.close()
    pool.join()

if __name__ == '__main__':
    main()

rawDescription: asynchronous subprocess with Popen

description: Asynchronous subprocess with Popen


code:
from PyQt4 import QtGui, QtCore

class Window(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        layout = QtGui.QVBoxLayout(self)
        self.combo = QtGui.QComboBox()
        self.combo.setEditable(True)
        self.combo.lineEdit().setAlignment(QtCore.Qt.AlignCenter)
        self.combo.addItems('One Two Three Four Five'.split())
        layout.addWidget(self.combo)

if __name__ == '__main__':

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

rawDescription: How to center text in QComboBox?

description: Center text in QComboBox


code:
import numpy as NP
a = NP.empty( shape=(0, 0) )
a
a.shape
a.size

rawDescription: How to create 0x0 Numpy array?

description: Create 0x0 Numpy array


code:
words = ["apples", "bananas", "tofu", "cats"]

head = ", ".join(words[:-1])
result = ", and ".join( [head, words[-1]] )

print(result)

rawDescription: Trying to generate a list using python script


code:
import numpy as np
# -- setup --
shape = (10,10,10)
dim = len(shape)
data = np.random.random(shape)
flag = np.zeros(shape, dtype=bool)
t_ct = int(data.size/5)
flag.flat[np.random.randint(0, flag.size, t_ct)] = True
# True flags the data
# -- end setup --

slcs = [slice(None)]*dim

while np.any(~flag): # as long as there are any False's in flag
    for i in range(dim): # do each axis
        # make slices to shift view one element along the axis
        slcs1 = slcs[:]
        slcs2 = slcs[:]
        slcs1[i] = slice(0, -1)
        slcs2[i] = slice(1, None)

        # replace from the right
        repmask = np.logical_and(~flag[slcs1], flag[slcs2])
        data[slcs1][repmask] = data[slcs2][repmask]
        flag[slcs1][repmask] = True

        # replace from the left
        repmask = np.logical_and(~flag[slcs2], flag[slcs1])
        data[slcs2][repmask] = data[slcs1][repmask]
        flag[slcs2][repmask] = True

rawDescription: Filling gaps in a numpy array

description: Filling gaps in a numpy array


code:
def haversine_pairwise(phi, lam):

    dphi = phi[1:]-phi[:-1]
    dlam = lam[1:]-lam[:-1]

    # r is assumed to be a known constant
    return r*(0.5*(1-cos(dphi)) + cos(phi[1:])*cos(phi[:-1])*0.5*(1-cos(dlam)))

rawDescription: Calculate diff of a numpy array using custom function instead of subtraction


code:
from nltk.util import tokenwrap
def generate_no_stdout(self, length=100):
    if '_trigram_model' not in self.__dict__:
        estimator = lambda fdist, bins: LidstoneProbDist(fdist, 0.2)
        self._trigram_model = NgramModel(3, self, estimator=estimator)
    text = self._trigram_model.generate(length)
    return tokenwrap(text)

rawDescription: Save any output a function gives, into a variable


code: df['B'] = rolling_apply(df.A, 30, numpy.prod)

rawDescription: Easiest way to iterate through a dataframe and get the product of the last 30 days


rawDescription: Changing Fast CGI to run a different version of python


code:
import Tkinter as tk

root = tk.Tk()
canvas = tk.Canvas(root, background="white")
canvas.pack(fill="both", expand=True)

text_item = canvas.create_text(20, 20, anchor="w", text="Hello world!", fill="white")
bbox = canvas.bbox(text_item)
rect_item = canvas.create_rectangle(bbox, outline="red", fill="black")
canvas.tag_raise(text_item,rect_item)

root.mainloop()

rawDescription: How to put an outline on a canvas text on python -- tkinter?

description: Put an outline on a canvas text on python -- tkinter


code:
def just_transforms(self, X):
    """Applies all transforms to the data, without applying last
       estimator.

    Parameters
    ----------
    X : iterable
        Data to predict on. Must fulfill input requirements of first step of
        the pipeline.
    """
    Xt = X
    for name, transform in self.steps[:-1]:
        Xt = transform.transform(Xt)
    return Xt

rawDescription: How to transform items using sklearn Pipeline?

description: Transform items using sklearn Pipeline


code:
from django.template.defaultfilters import floatformat

return floatformat(float(price) / product_amount, 2)

rawDescription: Django template: localize number returned from simple tag


code:
import bs4
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'html.parser')

for e in soup:
    if isinstance(e, bs4.element.ProcessingInstruction):
        e.extract()
        break

rawDescription: How Do I Remove An XML Declaration Using BeautifulSoup4


code:
with open('test.txt') as input_data:
    for line in input_data:
       match = re.search(r' is (.*) test ', line)
       if match:
          print(line)
          print(match.group(1))

rawDescription: Python read certain text from a single line


code:
def __init__(self, *args, **kwargs):
    def new_label_from_instance(self, obj):
        try:
            #see if there is a parent or not
            p = obj.parent
        except:
            #no parent; use the location's default label
            rep = obj.description
            return rep
        #if we find a location's parent, p=parent label and d=location label
        d = obj.description
        rep = "%s (%s)" % (d, p)
        return rep

    super(PublisherCreateTSCForm, self).__init__(*args, **kwargs)
    funcType = type(self.fields['location'].label_from_instance)
    self.fields['location'].label_from_instance = funcType(new_label_from_instance, self.fields['location'], forms.models.ChoiceField)

rawDescription: Django making recursive calls on relationship


code: sorted(mylist, key=lambda d: (d["id"], -d["score"]))

rawDescription: two level sorting of a list of dictionaries in python

description: Two level sorting of a list of dictionaries in python


code:
def contains(small, big):
    for i in xrange(len(big)-len(small)+1):
        for j in xrange(len(small)):
            if big[i+j] != small[j]:
                break
        else:
            return i, i+len(small)
    return False

rawDescription: Testing if a list contains another list with Python


code:
import xml.etree.ElementTree as et

filehandler = open("file.xml","r")
raw_data = et.parse(filehandler)
data_root = raw_data.getroot()
filehandler.close()

for children in data_root:
    for child in children:
        print(child.tag, child.text, children.tag, children.text)

rawDescription: Parsing an arbitrary XML file with ElementTree


code:
import csv
with open('speechurls.csv', 'r') as f:
    for row in csv.reader(f):
        if 'remarks-president' in row[0]:
            with open('remarks-president_urls.csv','a') as f1: f1.write("{}\n".format(row[0]))
        elif 'remarks-first-lady' in row[0]:
            with open('remarks-first-lady_urls.csv', 'a') as f2: f2.write("{}\n".format(row[0]))
        else:
            pass

rawDescription: Filtering CSV file of URLS based on String Match


code:
from forbiddenfruit import curse
curse(object, "methods_grep", classmethod(methods_grep))

rawDescription: Helper function injected on all python objects?


code:
class User (models.Model):
    name = models.CharField(max_length=20, primary_key=True)

    def __unicode__(self):
        return self.name

rawDescription: Django check to see if User.name is in database already -- match via user.name rather than user.id


code:
import matplotlib.pyplot as plt

x = [1,2,3]
y = [4,5,6]

fig, ax = plt.subplots()

ax.plot(x, y)

ax.set_xlim(0, 10)

plt.show()

rawDescription: How to avoid negative numbers on axis in matplotlib scatterplot

description: Avoid negative numbers on axis in matplotlib scatterplot


code:
import psutil
import getpass

user = getpass.getuser()

total = sum(p.memory_info()[0] for p in psutil.process_iter()
                               if p.username == user)

print('Total memory usage in bytes: ', total)

rawDescription: How to measure total memory usage of all processes of a user in Python

description: Measure total memory usage of all processes of a user in Python


code:
with concurrent.futures.ThreadPoolExecutor(max_workers=THREAD_LIMIT) as executor:
    # fqdn_list is a list of Fqdn instances
    for fqdn in fqdn_list:
        executor.submit(fqdn.port_scan)

rawDescription: Python ThreadPoolExecutor on method of instance


code:
import re
sometext = 'blah blah 1 2 3abcd efg-123word word2 word3 blah blah'
result = re.findall(
      r'(((?:(?:^|\s)+\w+){3}\s*)'            # Match 3 words before
      r'([^<]*|<[^/]|</[^b]|])'  # Match ...
      r'(\s*(?:\w+(?:\s+|$)){3}))', sometext) # Match 3 words after

result == [(' 1 2 3abcd efg-123word word2 word3 ',
    ' 1 2 3',
    'abcd efg-123',
    'word word2 word3 ')]

rawDescription: Finding a strings in a text using regular expressions with Python


code:
def p2abs(point):
    return math.sqrt(point[0] ** 2 + point[1] ** 2)

def rotatePoint(point, angle):
    s, c = math.sin(angle), math.cos(angle)
    return (p[0] * c - p[1] * s, p[0] * s + p[1] * c)

def rotatePoints(points, angle):
    return [rotatePoint(point, angle) for point in points]

points = map(lambda x: tuple(x[0]), contour)
convexHull = map(lambda x: points[x], scipy.spatial.ConvexHull(numpy.array(points)).vertices)

minArea = float("inf")
minRect = None

for i in range(len(hull)):
    a, b = convexHull[i], convexHull[i - 1]
    ang = math.atan2(b[0] - a[0], b[1] - a[1])

    rotatedHull = rotatePoints(convexHull, ang)

    minX = min(map(lambda p: p[0], rotatedHull))
    maxX = max(map(lambda p: p[0], rotatedHull))
    minY = min(map(lambda p: p[1], rotatedHull))
    maxY = max(map(lambda p: p[1], rotatedHull))

    area = (maxX - minX) * (maxY - minY)

    if area < minArea:
        minArea = area

        rotatedRect = [(minX, minY), (minX, maxY), (maxX, maxY), (maxX, minY)]
        minRect = rotatePoints(rotatedRect, -ang)

_, topLeft = min([(p2abs(p), i) for p, i in zip(range(4), minRect)])
rect = minrect[topLeft:] + minrect[:topLeft]

rawDescription: Finding rotated rectangle from contour

description: Finding rotated rectangle from contour


rawDescription: How to find two different class names using find_elements_by_css_selector

description: Find two different class names using find_elements_by_css_selector


code:
def letter_runs(letters):
    prev = None
    results = []

    for index, letter in enumerate(letters):
        if letter != prev:
            prev = letter
            results.append((index, letter))

    if results[0][1] != "X":
        results[0] = (results[1][0]-1, results[0][1])
    else: # if first run is "X" second must be something else!
        results[1] = (results[2][0]-1, results[1][1])

    return [(index, letter) for index, letter in results if letter != "X"]

rawDescription: An algorithm to find transitions in Python


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

import numpy as np

# create a matrix of random numbers and desired dimension
a = np.random.rand(236, 97)

# write matrix to file
a.tofile('output.txt', sep = ' ')

rawDescription: make a full matrix output in python

description: Make a full matrix output in python


rawDescription: How to turn to 0 the specific bit of number in Python?

description: Turn to 0 the specific bit of number in Python


Convert ['2 1', '2 1'] to [['1 ', '2'], ['2 ', '1']] in python


code:
import re
value1 = 'MA[1,2],MA[1,3],der(x),x,y'
value2 = 'M[a,b],x1,M[1,2],der(x),y1,y2,der(a,b)'
pat = re.compile(r'(?<![[()][\d\w]),')
pat.split(value1)
pat.split(value2)

rawDescription: python split a string by comma not inside matrix expression

description: Python split a string by comma not inside matrix expression


code:
with open("transfer-out/" + file, "r") as f:
    for line in f:
        cleanedLine = line.strip()
        if cleanedLine: # is not empty
            print(cleanedLine)

rawDescription: Removing spaces and empty lines from a file Using Python


code:
def func(x): # here x is a local variable which refers to the object[1,2,3]
    y = [4, 5, 6]
    x = y  #now the local variable x refers to the object [4,5,6]

def funcsecond(x): # here x is a local variable which refers to the object[1,2,3]
    y = [4, 5, 6]
    x[1] = y[1]  # it means [1,2,3][1]=5 , means you changed the object x was pointing to

x = [1, 2, 3]

rawDescription: Python list reference in a function.

description: Python list reference in a function.


code: q = [line.split(",", 1)[0] for line in lines]

rawDescription: List comprehensions tip

description: List comprehensions tip


code:
import datetime
datetime.datetime.now() - datetime.timedelta(days=3*365)

rawDescription: Python: get datetime for '3 years ago today'?


code:
import itertools

# the keyfunc extracts the key from each input element
keyfunc = lambda row: row.day_hour.strftime("%Y/%m/%d")

data = []
for day, day_rows in itertools.groupby(hits, key=keyfunc):
    sum_hits = 0
    sum_returning = 0
    for row in day_rows:
        sum_hits += int(row.hits)
        sum_returning += int(row.returning)
    data.append([day, sum_hits, sum_returning, sum_hits + sum_returning])

# data now contains your desired output

rawDescription: group a list by date while counting the rows values

description: Group a list by date while counting the rows values


rawDescription: Is the golden ratio defined in Python?

description: Is the golden ratio defined in Python


code:
import urllib
url='http://stackoverflow.com/questions/5158168/python-regex-question/5158341'
f=urllib.urlopen(url)
for linenum,line in enumerate(f):
    print(line)
    locations=[pos for pos,char in enumerate(line) if char=='1']
    print('line {n}=(count:{c}, pos:{l})'.format(
        n=linenum,
        c=len(locations),
        l=locations
        ))

rawDescription: Python regex question

description: Python regex question


code:
currentValue = 0
inpFileName = fileList[0]  # ?
for currentValue in range(1000):
  inpFile = open( inpFileName, 'r' )
  outFile = open( 'BMx_%d_Token.txt' % currentValue, 'w' )
  for inpLine in inpFile:
    outLine = inpLine.replace( ' = 2;', ' = %d;' % currentValue )
    outFile.write( outLine )
  inpFile.close()
  outFile.close()

rawDescription: Python String replacement in file

description: Python String replacement in file


code:
for p, ds, fs in os.walk(directory):
    if 'wanted' in fs:
        print('found in %s' % p)
        break

rawDescription: file existence test: fast subtree search in python

description: File existence test: fast subtree search in python


code:
import pyqtgraph.opengl as gl
from PyQt4.Qt import QApplication

class MyGLView(gl.GLViewWidget):
    def __init__(self, text):
        super(MyGLView, self).__init__()
        self.text = text

    def setText(self, text):
        self.text = text
        self.update()

    def paintGL(self, *args, **kwds):
        gl.GLViewWidget.paintGL(self, *args, **kwds)
        self.renderText(0, 0, 0, self.text)

app = QApplication([])
w = MyGLView(text="O HAI World")
w.show()

rawDescription: How to avoid using global variable to set text in GLViewWidget?

description: Avoid using global variable to set text in GLViewWidget


code:
def itervalues(self):
    for value, timestamp in super(TimedCache, self).itervalues():
        if time.time() - timestamp <= self.ttl:
            yield value

rawDescription: Override itervalues of dict

description: Override itervalues of dict


code:
x = [[1,2,3], {1:2}]
s = yaml.dump(x)
s
yaml.load(s)
yaml.load(s, Loader=yaml.BaseLoader)

rawDescription: Disable PyYAML value conversion

description: Disable PyYAML value conversion


code: [img for img in soup.findAll("img") if "width" in img.attrs]

rawDescription: Tags in HTML Parsing

description: Tags in HTML Parsing


code:
rfecv = RFECV(estimator=LogisticRegression(), step=1, cv=KFold(len(y),n_folds=10),
scoring='accuracy')

rawDescription: How to do RFECV in scikit-learn with KFold, not StratifiedKFold?

description: Do RFECV in scikit-learn with KFold, not StratifiedKFold


code:
from graphics import *
win = GraphWin('', 600,500)
text_x, text_y = 200, 50
with open("input.txt","r") as file:
    for line in file:
        print(line)
        label = Text(Point(text_x, text_y), line)
        label.draw(win)
        text_y += 50 # distance between 2 lines

rawDescription: (Python 3.2) File Processing on Python?

description: (Python 3.2) File Processing on Python


code:
class Example(object):
    a = []
    def __init__(self):
        self.b = []

foo = Example()
bar = Example()
foo.a
bar.a
foo.b
bar.b
foo.a.append(1)
foo.b.append(2)
foo.a
foo.b
bar.a
bar.b

rawDescription: Why does python + pylons "remember" previously specified class variables?


code: finalresult = sorted(result, key=lambda word: (-word[1], len(word[0]), word[0]))

rawDescription: How to sort in python with multiple conditions?

description: Sort in python with multiple conditions


code:
b_channel, g_channel, r_channel = cv2.split(img)

alpha_channel = np.ones((185, 198)) * 50 #creating a dummy alpha channel image.

img_RGBA = cv2.merge((b_chennel, g_channel, r_channel, alpha_channel))

rawDescription: python opennlp - add alpha channel to RGB

description: Python opennlp - add alpha channel to RGB


code:
class CreateNewPost(generic.edit.CreateView):
    model = BlogPost
    form_class = NewPostForm
    success_url = '/entries/%(id)s'

    def form_valid(self, form):
        obj = form.save(commit=False)
        obj.user = self.request.user
        obj.pub_date = timezone.now()
        obj.save()

rawDescription: A better way of setting values in CreateView?


code:
from django.contrib.admin.options import ModelAdmin
from django.contrib.admin import widgets
class CustomModelAdmin:
    def formfield_for_manytomany(self, db_field, request=None, **kwargs):
        """
        Get a form Field for a ManyToManyField.
        """
        # If it uses an intermediary model that isn't auto created, don't show
        # a field in admin.
        if not db_field.rel.through._meta.auto_created:
            return None
        db = kwargs.get('using')

        if db_field.name in self.raw_id_fields:
            kwargs['widget'] = widgets.ManyToManyRawIdWidget(db_field.rel, using=db)
            kwargs['help_text'] = ''
        else:
            kwargs['widget'] = widgets.FilteredSelectMultiple(db_field.verbose_name, False) # change second argument to True for filter_vertical

        return db_field.formfield(**kwargs)

ModelAdmin.__bases__ = (CustomModelAdmin,) + ModelAdmin.__bases__

rawDescription: In django-admin, how can I set filter_horizontal as the default?


code:
import subprocess
subprocess.call("cls", shell=True)

rawDescription: Should i continue clearing the screen with the os module or use subprocess?


code: new_string = re.sub(r'"(\d+),(\d+)"', r'\1.\2', original_string)

rawDescription: Python Regex replace

description: Python Regex replace


code:
searches = ('aa90_273024', 'another_search', 'yet_another_search')
my_result = [item[1:] for item in data if item[0] in searches]

rawDescription: Using a sublist to retrieve data from a larger list


code:
with open("path to save the file + filename.txt", "w") as f:
  f.write(method)

rawDescription: Python suds file

description: Python suds file


code:
from PIL import Image
image = Image.new('RGB', (n, m))

rawDescription: How can I create an empty n*m PNG file in Python?

description: Create an empty n*m PNG file in Python


code: re.split(r'\|--|:', your_string)

rawDescription: Splitting a string with two different characters


code:
from sqlalchemy import func
Document.query.filter(func.char_length(Document.doc_number)==5).all()

rawDescription: Using sqlalchemy.sql.functions.char_length as a filter condition


code:
reader = csv.DictReader(f.open)
for line_dict in reader:
   line_dict['First Column']
   line_dict['Second Column']

rawDescription: DictReader fieldnames vs csv reader first row


code:
import pexpect
proc = pexpect.spawn('command', logfile=open('mylog.txt','w'),
    searchwindowsize=80, timeout=-1)
for line in proc:
    print(line.strip())

rawDescription: python subprocess output disappear when redirect stdout to pipe

description: Python subprocess output disappear when redirect stdout to pipe


code:
lst = [1.0, 2.0, 3.0]
[x for x in lst for i in range(3)]

rawDescription: Repeat elements of list python

description: Repeat elements of list python


code:
import PySide.QtCore as QtCore
import PySide.QtGui as QtGui
import sys

class MainWindow(QtGui.QDialog):
        def __init__(self):
                QtGui.QDialog.__init__(self)

                dial = QtGui.QDial()
                dial.setNotchesVisible(True)
                self.spinbox = QtGui.QSpinBox()

                layout = QtGui.QHBoxLayout()
                layout.addWidget(dial)
                layout.addWidget(self.spinbox)
                self.setLayout(layout)

                #connect this event to the given method.
                dial.valueChanged.connect(self.changeSpinbox)

        def changeSpinbox(self, value):
                #do some operation on this value. In this case half it.
                self.spinbox.setValue(value / 2)

app = QtGui.QApplication(sys.argv)
main_window = MainWindow()
main_window.show()
app.exec_()

rawDescription: Qt Designer with Python: Connecting control dial with slider


code:
with open('myfile', 'r') as f:
    data = [line.split() for line in f]

rawDescription: Python - from file to data structure?

description: Python - from file to data structure


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

x = np.arange(-2*np.pi, 2*np.pi, 0.1)
y = np.arange(-2*np.pi, 2*np.pi, 0.1)
X, Y = np.meshgrid(x, y)

Z = np.sin(X) - np.cos(Y)
Z = np.ma.masked_less(Z, 0) # you use mask_equal(yourData, yourMagicValue)

fig, ax = plt.subplots()
ax.contourf(Z, zorder=5, cmap=plt.cm.coolwarm)
ax.xaxis.grid(True, zorder=0)
ax.yaxis.grid(True, zorder=0)

rawDescription: Grid Lines below the contour in Matplotlib


code:
f=open('foo.csv','w')
f.write('\n'.join(",".join(seq) for seq in itertools.product("01", repeat=10)))
f.close()

rawDescription: Writing itertools results to csv output

description: Writing itertools results to csv output


code:
import arcpy
import csv

f = open(r'C:\\user\\Exports.txt', 'w')
w = csv.writer(f, lineterminator='\n')

arcpy.env.workspace = "C:\\user\\rainfiles"

shapefileList = arcpy.ListFeatureClasses("*.shp")
for table in shapefileList:
    f.write("Shapefile:\n")
    f.write(table + "\n")
    fieldList = arcpy.ListFields(table)
    field_names = [field.name for field in fieldList]
    w.writerow(field_names)
    for row in arcpy.SearchCursor(table):
        field_vals = []
        for field in fieldList:
            val = row.getValue(field.name)
            # See if it's a geometry field; if so, use WKT
            try:
                val = val.WKT
            except AttributeError:
                # It's not a geometry, and that's okay
                pass
            field_vals.append(val)
        w.writerow(field_vals)

rawDescription: Exporting attributes of multiple shapefiles to a text file


code:
import cssutils
css = 'width:150px;height:50px;float:right;'
s = cssutils.parseStyle(css)
s.width
s.height
s.keys()
s.cssText
del s['width']
s.cssText

rawDescription: Using Beautiful Soup to convert CSS attributes to individual HTML attributes?


code:
with open('outfile.txt', 'wb') as outfile, open('infile.txt', 'r') as infile:
    [outfile.write(i.replace('|', ' ') + '\n')  for i in infile.read().split()]

rawDescription: How to use regular expression parse text with symbol "| "

description: Use regular expression parse text with symbol "| "


code: joined_tables = [mapper.class_ for mapper in query._join_entities]

rawDescription: Can I inspect a sqlalchemy query object to find the already joined tables?

description: Inspect a sqlalchemy query object to find the already joined tables


code:
import multiprocessing as mp

queue = mp.Queue()

def adder(q):  # for the sake of this example, let's say we want to add squares of all numbers to the queue
    i = 0
    while i < 100:
        q.put(i**2)
        i += 1
    q.put(None)

def monitor(q):  # monitor the queue and do stuff with the data therein
    for e in iter(q.get, None):
        print(e)   # for now, let's just print the stuff

a = mp.Process(target=adder, args=(queue,))
b = mp.Process(target=monitor, args=(queue,))
a.start()
b.start()
a.join()  # wait for the process to finish
b.join()  # wait for the process to finish (both processes running simultaneously)
a.terminate()
b.terminate()

rawDescription: How can I create two objects that monitor each other?

description: Create two objects that monitor each other


code:
from PIL import Image, ImageDraw

im = Image.new("RGB", (640, 240))
dr = ImageDraw.Draw(im)

def circle(draw, center, radius, fill):
    dr.ellipse((center[0] - radius + 1, center[1] - radius + 1, center[0] + radius - 1, center[1] + radius - 1), fill=fill, outline=None)

W = 40
COLOR = (255, 255, 255)

coords = (40, 40, 600, 200)

dr.line(coords, width=W, fill=COLOR)
circle(dr, (coords[0], coords[1]), W / 2, COLOR)
circle(dr, (coords[2], coords[3]), W / 2, COLOR)

im.show()

rawDescription: Draw rounded corner line in ImageDraw python


code:
import json
jstr = '''{
   "EZMessage":{
      "action":"account.cash",
      "data":{
         "authToken":"123456",
         "account":"#ACCOUNTID#",
         "portfolio":"true",
         "historical":"true"
      }
   }
}'''

j = json.loads(jstr)
j['EZMessage']['data']['authToken'] = 654321
jstr = json.dumps(j)

rawDescription: writing to a json file from python

description: Writing to a json file from python


code:
import numpy
values = numpy.array([1,0,2,0,3,0])
counts = numpy.array([4,5,3,3,2,2])
numpy.repeat(values, counts)

rawDescription: Assigning multiple array indices at once in Python/Numpy


rawDescription: Python PIL bitmap/png from array with mode=1


code:
import httplib
from threading import Thread

from flask import Flask, Response

from mymodule import heavy_lift

app = Flask(__name__)

@app.route("/async")
def async_start():
    Thread(target=heavy_lift).start()
    return Response(status=httplib.ACCEPTED)

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

rawDescription: Python Flask Immediate Response

description: Python Flask Immediate Response


code:
class TestPreReqs(unittest.TestCase):
    ...

def create_test (pair):
    def do_test_expected(self):
        self.assertEqual(under_test(pair[0]), pair[1])
    return do_test_expected

for k, pair in enumerate ([(23, 55), (4, 32)]):
    test_method = create_test (pair)
    test_method.__name__ = 'test_expected_%d' % k
    setattr (TestPreReqs, test_method.__name__, test_method)

rawDescription: Python unittest: Generate multiple tests programmatically?


rawDescription: Reverse Indexing in Python?

description: Reverse Indexing in Python


code:
start = bigx[0]
step = bigx[1] - bigx[0]
indices = ((x - start)/step).round().astype(int)

rawDescription: Python: efficient way to match 2 different length arrays and find index in larger array


code:
lst = [foo, bar, baz, ...]  # add to this list
for func in lst:
    v = func()
    if v:
        return v

rawDescription: Pythonic Solution to Multiple Checks

description: Pythonic Solution to Multiple Checks


code:
class Account(Base):
    ...
    # please note added *backref*, which is needed to build the
    #query in Account.get_other_collections(...)
    collections = relation("Collection", secondary=account_to_collection_map, backref="accounts")

    def get_other_collections(self, maxrows=None):
        """ Returns the collections this Account does not have yet.  """
        q = Session.object_session(self).query(Collection)
        q = q.filter(~Collection.accounts.any(id=self.id))
        # note: you might also want to order the results
        return q[:maxrows] if maxrows else q.all()
...

rawDescription: sqlalchemy many-to-many, but inverse?

description: Sqlalchemy many-to-many, but inverse


code:
def AddRecordHandler():
        print("added")
def DeleteRecordHandler():
        print("deleted")
def CreateDatabaseHandler():
        print("done")
def FlushToDiskHandler():
        print("i feel flushed")
def SearchHandler():
        print("not found")
def CleanupAndQuit():
        print("byez")

menuchoices = {'a':AddRecordHandler, 'd':DeleteRecordHandler, 'c':CreateDatabaseHandler, 'f':FlushToDiskHandler, 's':SearchHandler, 'q':CleanupAndQuit}
ret = menuchoices[input()]()
if ret is None:
    print("Something went wrong! Call the police!")
menuchoices['q']()

rawDescription: Since Python doesn't have a switch statement, what should I use?


code:
self.forms = (...)
tokens = company.split(' ')
return ' '.join([ t for t in tokens if t not in self.forms ])

rawDescription: How can I make this regex code more efficient?

description: Make this regex code more efficient


code: batch_data = [allData[i] for i in rowIndices]

rawDescription: Access indexed rows in a python list (similar to Matlab cell array)


code:
seen = set(item[:3] for item in list1)
list1.extend(item for item in list2 if item[:3] not in seen)

rawDescription: How to merge two lists of arrays, (x,y,z,m), excluding duplicates based on only (x,y,z)

description: Merge two lists of arrays, (x,y,z,m), excluding duplicates based on only (x,y,z)


code:
import matplotlib.pyplot as plt
from matplotlib.dates import MonthLocator, YearLocator
import numpy as np

fig, ax = plt.subplots(1, 1)

x = np.arange('1965-01', '1975-07', dtype='datetime64[D]')
y = np.random.randn(x.size).cumsum()
ax.plot(x, y)

yloc = YearLocator()
mloc = MonthLocator()
ax.xaxis.set_major_locator(yloc)
ax.xaxis.set_minor_locator(mloc)
ax.grid(True)

rawDescription: Set matplotlib grid ticks based on specific dates


code: plt.xticks(xdata, xdata)

rawDescription: matplotlib : plot in semilogx while displaying the actual values

description: Matplotlib : plot in semilogx while displaying the actual values


code: chart = pygal.StackedLine(width=1000, height=800)

rawDescription: How to limit the width/height of svg in pygal

description: Limit the width/height of svg in pygal


code:
class myBool():
    def __init__(self, val):
        self.value = val

    def __repr__(self):
        return self.value

    def __invert__(self):
        if self.value == 'A':
            return 'B'
        else:
            return 'A'

def main():
    a = myBool('A')
    print(a)
    print(~a)

if __name__ == '__main__':
    main()

rawDescription: Model boolean variables in Python

description: Model boolean variables in Python


code:
from beaker.cache import cache_managers
for _cache in cache_managers.values():
    _cache.clear()

rawDescription: How can you refresh all regions in Beaker cache in Pyramid?

description: Refresh all regions in Beaker cache in Pyramid


code:
@event.listens_for(DBSession, 'before_flush')
def before_flush(session, flush_context, instances):
    time_stamp = datetime.datetime.utcnow()

    if session.new:
        for elem in session.new:
            print(" ### NEW {0}".format(repr(elem)))

    if session.dirty:
        for elem in session.dirty:
            # Below check was added to solve the problem
            if ( session.is_modified(elem, include_collections=False) ):
                print(" ### DIRTY {0}".format(repr(elem)))

    if session.deleted:
        for elem in session.deleted:
            print(" ### DELETED {0}".format(repr(elem)))

rawDescription: Make parent object not appearing within session.dirty of before_flush event listener


code:
from matplotlib import pyplot as plt
from numpy import arange, sin, cos

xx = arange(100)
cut = (xx > 0) & (xx % 17 == 0)
y1 = sin(xx)
y2 = (xx**2) % 2.0+cos(xx+0.5)

fig = plt.figure()
ax1 = fig.add_subplot(211)
ax1.plot(xx, y1, c="blue",zorder=1)
ax1.scatter(xx[cut], y1[cut], c="red",zorder=2)
ax2 = fig.add_subplot(212)
ax2.plot(xx, y2, c="green",zorder=1)
ax2.scatter(xx[cut], y2[cut], c="red",zorder=2)

for x in xx[cut]:
    ax1.axvline(x=x,ymin=-1.2,ymax=1,c="red",linewidth=2,zorder=0, clip_on=False)
    ax2.axvline(x=x,ymin=0,ymax=1.2,c="red",linewidth=2, zorder=0,clip_on=False)

plt.draw()
fig.savefig('pic.png')

rawDescription: Plotting a line over several graphs

description: Plotting a line over several graphs


code:
import pickle, copyreg, ssl
def save_sslcontext(obj):
  return obj.__class__, (obj.protocol,)

copyreg.pickle(ssl.SSLContext, save_sslcontext)

context = ssl.create_default_context()
foo = pickle.dumps(context)
_foo = pickle.loads(foo)
_foo
_foo.protocol

rawDescription: How to pickle a ssl.SSLContext object

description: Pickle a ssl.SSLContext object


code:
import itertools
t = [[1,2,3], [4,5], [6,7]]
[x for x in itertools.product(*t[::-1])]
[list(x) for x in itertools.product(*t[::-1])]

rawDescription: Generating a 2-d array with iterations using Python


code:
import datetime

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

from matplotlib import mlab

from mpl_toolkits.axes_grid1 import make_axes_locatable

def main():
    #-- Make a series of dates
    start = datetime.datetime(2010,9,15,8,0)
    end = datetime.datetime(2010,9,15,18,0)
    delta = datetime.timedelta(seconds=1)

    # Note: "time" is now an array of floats, where 1.0 corresponds
    # to one day, and 0.0 corresponds to 1900 (I think...)
    # It's _not_ an array of datetime objects!
    time = mpl.dates.drange(start, end, delta)

    num = time.size

    #-- Generate some data
    x = brownian_noise(num)
    y = brownian_noise(num)
    z = brownian_noise(num)

    plot(x, y, z, time)
    plt.show()

def plot(x, y, z, time):
    fig = plt.figure()

    #-- Panel 1
    ax1 = fig.add_subplot(311)
    im, cbar = specgram(x, time, ax1, fig)
    ax1.set_ylabel('X Freq. (Hz)')
    ax1.set_title('Fake Analysis of Something')

    #-- Panel 2
    ax2 = fig.add_subplot(312, sharex=ax1)
    im, cbar = specgram(y, time, ax2, fig)
    ax2.set_ylabel('Y Freq. (Hz)')

    #-- Panel 3
    ax3 = fig.add_subplot(313, sharex=ax1)
    # Plot the 3 source datasets
    xline = ax3.plot_date(time, x, 'r-')
    yline = ax3.plot_date(time, y, 'b-')
    zline = ax3.plot_date(time, z, 'g-')
    ax3.set_ylabel(r'Units $(\mu \phi)$')

    # Make an invisible spacer...
    cax = make_legend_axes(ax3)
    plt.setp(cax, visible=False)

    # Make a legend
    ax3.legend((xline, yline, zline), ('X', 'Y', 'Z'), loc='center left',
            bbox_to_anchor=(1.0, 0.5), frameon=False)

    # Set the labels to be rotated at 20 deg and aligned left to use less space
    plt.setp(ax3.get_xticklabels(), rotation=-20, horizontalalignment='left')

    # Remove space between subplots
    plt.subplots_adjust(hspace=0.0)

def specgram(x, time, ax, fig):
    """Make and plot a log-scaled spectrogram"""
    dt = np.diff(time)[0] # In days...
    fs = dt * (3600 * 24) # Samples per second

    spec_img, freq, _ = mlab.specgram(x, Fs=fs, noverlap=200)
    t = np.linspace(time.min(), time.max(), spec_img.shape[1])

    # Log scaling for amplitude values
    spec_img = np.log10(spec_img)

    # Log scaling for frequency values (y-axis)
    ax.set_yscale('log')

    # Plot amplitudes
    im = ax.pcolormesh(t, freq, spec_img)

    # Add the colorbar in a seperate axis
    cax = make_legend_axes(ax)
    cbar = fig.colorbar(im, cax=cax, format=r'$10^{%0.1f}$')
    cbar.set_label('Amplitude', rotation=-90)

    ax.set_ylim([freq[1], freq.max()])

    # Hide x-axis tick labels
    plt.setp(ax.get_xticklabels(), visible=False)

    return im, cbar

def make_legend_axes(ax):
    divider = make_axes_locatable(ax)
    legend_ax = divider.append_axes('right', 0.4, pad=0.2)
    return legend_ax

def brownian_noise(num):
    x = np.random.random(num) - 0.5
    x = np.cumsum(x)
    return x

if __name__ == '__main__':
    main()

rawDescription: Multi-panel time series of lines and filled contours using matplotlib?


code:
class DecodedRedis(StrictRedis):
    @classmethod
    def from_url(cls, url, db=None, **kwargs):
        kwargs['decode_responses'] = True
        return StrictRedis.from_url(url, db, **kwargs)

redis = FlaskRedis.from_custom_provider(DecodedRedis, app)

rawDescription: How to decode Redis responses in Flask?

description: Decode Redis responses in Flask


code:
next_record = {}
for client in client_list:
    s = s_dates_dict[client.pk]
    e = e_dates_dict[client.pk]
    next_record[client.pk] = client.tasks_set.filter(date__range(s,e), task_type__in=[A,B])

rawDescription: How do I filter by a date range based on a dictionary value in python, otherwise filter a list by a dictionary?

description: Filter by a date range based on a dictionary value in python, otherwise filter a list by a dictionary


code:
from functools import wraps

def some_decorator(arg1, arg2):
    def wrapper(func):

       @wraps(func)
       def inner_wrapper(*args, **kwargs):
           func(*args, **kwargs)

       inner_wrapper.arg1 = arg1
       inner_wrapper.arg2 = arg2
       return inner_wrapper

    return wrapper

rawDescription: Decorator converting given kwargs to attrs of function


code:
import Tkinter as tk
import random

class ServoDrive(object):
    # simulate values
    def getVelocity(self): return random.randint(0,50)
    def getTorque(self): return random.randint(50,100)

class Example(tk.Frame):
    def __init__(self, *args, **kwargs):
        tk.Frame.__init__(self, *args, **kwargs)
        self.servo = ServoDrive()
        self.canvas = tk.Canvas(self, background="black")
        self.canvas.pack(side="top", fill="both", expand=True)

        # create lines for velocity and torque
        self.velocity_line = self.canvas.create_line(0,0,0,0, fill="red")
        self.torque_line = self.canvas.create_line(0,0,0,0, fill="blue")

        # start the update process
        self.update_plot()

    def update_plot(self):
        v = self.servo.getVelocity()
        t = self.servo.getTorque()
        self.add_point(self.velocity_line, v)
        self.add_point(self.torque_line, t)
        self.canvas.xview_moveto(1.0)
        self.after(100, self.update_plot)

    def add_point(self, line, y):
        coords = self.canvas.coords(line)
        x = coords[-2] + 1
        coords.append(x)
        coords.append(y)
        coords = coords[-200:] # keep # of points to a manageable size
        self.canvas.coords(line, *coords)
        self.canvas.configure(scrollregion=self.canvas.bbox("all"))

if __name__ == "__main__":
    root = tk.Tk()
    Example(root).pack(side="top", fill="both", expand=True)
    root.mainloop()

rawDescription: Live Plot in Python GUI

description: Live Plot in Python GUI


rawDescription: Django - initialize many to many fields on database level


code:
import ctypes
import time

SendInput = ctypes.windll.user32.SendInput

# C struct redefinitions
PUL = ctypes.POINTER(ctypes.c_ulong)
class KeyBdInput(ctypes.Structure):
    _fields_ = [("wVk", ctypes.c_ushort),
                ("wScan", ctypes.c_ushort),
                ("dwFlags", ctypes.c_ulong),
                ("time", ctypes.c_ulong),
                ("dwExtraInfo", PUL)]

class HardwareInput(ctypes.Structure):
    _fields_ = [("uMsg", ctypes.c_ulong),
                ("wParamL", ctypes.c_short),
                ("wParamH", ctypes.c_ushort)]

class MouseInput(ctypes.Structure):
    _fields_ = [("dx", ctypes.c_long),
                ("dy", ctypes.c_long),
                ("mouseData", ctypes.c_ulong),
                ("dwFlags", ctypes.c_ulong),
                ("time",ctypes.c_ulong),
                ("dwExtraInfo", PUL)]

class Input_I(ctypes.Union):
    _fields_ = [("ki", KeyBdInput),
                 ("mi", MouseInput),
                 ("hi", HardwareInput)]

class Input(ctypes.Structure):
    _fields_ = [("type", ctypes.c_ulong),
                ("ii", Input_I)]

# Actuals Functions

def PressKey(hexKeyCode):
    extra = ctypes.c_ulong(0)
    ii_ = Input_I()
    ii_.ki = KeyBdInput( 0, hexKeyCode, 0x0008, 0, ctypes.pointer(extra) )
    x = Input( ctypes.c_ulong(1), ii_ )
    ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))

def ReleaseKey(hexKeyCode):
    extra = ctypes.c_ulong(0)
    ii_ = Input_I()
    ii_.ki = KeyBdInput( 0, hexKeyCode, 0x0008 | 0x0002, 0, ctypes.pointer(extra) )
    x = Input( ctypes.c_ulong(1), ii_ )
    ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))

rawDescription: Simulating a keypress in python

description: Simulating a keypress in python


code: string.replace(' ', 'x')

rawDescription: Replacing spaces with a letter in python


code:
@asyncio.coroutine
def periodic(reader, delay):
    data = yield from reader.read_exactly(100)  # read 100 bytes
    yield from asyncio.sleep(delay)

task = asyncio.Task(reader, 30*60)

rawDescription: Python asyncio read file and execute another activity at intervals


code:
# assume the html variable is a beautifulsoup object
input_values = [
    element.get('value') for element in
    html.findAll('input', {"class": "category-checkbox"})
]
# category_input_values is now [ 'apples', 'pears', 'oranges' ]

rawDescription: Extract a list of HTML attribute values using beautifulsoup


code:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1, 2, 3], [4, 5, 6], linestyle='-', color='r', linewidth=2)
fig.savefig('plot_with_red_line.png', dpi=100)

rawDescription: can't change line's color in matplotlib

description: Can't change line's color in matplotlib


code:
etree.tostring(tree)
bookname=tree[0]
text2=bookname[1]
bookname.remove(text2)
etree.tostring(tree)

rawDescription: How to delete specific tags

description: Delete specific tags


code:
from selenium.webdriver import Firefox
from selenium.webdriver.support.ui import WebDriverWait

from selenium.common.exceptions import TimeoutException
from selenium.common.exceptions import NoSuchElementException

class MyFirefox(Firefox):

    RETRIES = 3
    TIMEOUT_SECONDS = 10

    def find_element_by_id(self, id):
        tries = 0
        element = None

        while tries < self.RETRIES:
            try:
                element = WebDriverWait(self, self.TIMEOUT_SECONDS).until(
                    lambda browser: super(MyFirefox, browser).find_element_by_id(id)
                )
            except TimeoutException:
                tries = tries + 1
                self.switch_to_window(self.window_handles[0])
                continue
            else:
                return element

        raise NoSuchElementException("Element with id=%s was not found." % id)

rawDescription: Set up a default exception handler when unable to locate an element in selenium?


code:
appendText='_'
names=open("name.txt",'r')
updatedNames=open("name2.txt",'a')
for name in names:
  updatedNames.write(appendText + name.rstrip() + appendText + '\n')
updatedNames.close()

rawDescription: Add a char to the beginning and end of each line in a file


code:
import random

ops = ['+', '-', '*', '/']
num1 = random.randint(0,12)
num2 = random.randint(0,10)
operation = random.choice(ops)

print(num1)
print(num2)
print(operation)

maths = eval(str(num1) + operation + str(num2))

print(maths)

rawDescription: How can I randomly choose a maths operator and ask recurring maths questions with it?

description: Randomly choose a maths operator and ask recurring maths questions with it


code:
import glob
glob.glob("testdir/*")
[f for f in glob.glob("testdir/*") if f.lower().endswith((".ext", ".ext2"))]

rawDescription: concise way to match filenames that end in certain extension in Python?

description: Concise way to match filenames that end in certain extension in Python


code:
class MyDescriptor(object):

    def __get__(self, instance, owner):
        return instance._value

    def __set__(self, instance, value):
        instance._value = value

    def __delete__(self, instance):
        del(instance._value)

rawDescription: Python: why can't descriptors be instance variables?


code:
class CollectorContext(object):
    """Sets the meta_path hook with the passed import hook when
    entering and clean up when exiting
    """

    def __init__(self, collector, argv, output_file):
        self.collector = collector
        self.old_argv = argv[:]
        self.output_file = output_file
        self.progname = self.old_argv[1]

    def __enter__(self):
        sys.argv = self.old_argv[1:]
        sys.meta_path.append(self.collector)
        return self

    def __exit__(self, type, value, traceback):
        # TODO: should assert that the variables are None, otherwise
        # we are quitting with some exceptions
        self.collector.dump_to_file(self.output_file)
        sys.meta_path.remove(self.collector)
        sys.argv = self.old_argv[:]

    def run(self):
        code = compile(open(self.progname).read(), self.progname, 'exec')
        exec(code)

def main_context():
    cl = CollectImports()

    with CollectorContext(cl, sys.argv, 'imports.log') as cc:
        cc.run()

rawDescription: Is a context manager right for this job?

description: Is a context manager right for this job


code:
for kitten in kittens:
    then = kitten.date
    now = datetime.datetime.now()
    tdelta = now - then

if tdelta.total_seconds() > 300:
    kitten.delete()

rawDescription: How to compare a google datastore datetime to python datetime?

description: Compare a google datastore datetime to python datetime


code:
driver = webdriver.Chrome()
driver.get('http://www.yahoo.com')
search = driver.find_element_by_css_selector('input[title=Search]')
search.get_attribute('value')
search.send_keys('SO the best!')
search.get_attribute('value')

rawDescription: How to get length of text box from webpage in python

description: Get length of text box from webpage in python


rawDescription: Redis data lost when stopping service

description: Redis data lost when stopping service


code: df.groupby(['Type', 'Major'], as_index=False).GPA.count().sort_values(['Major', 'GPA'])

rawDescription: Sort values within dataframe grouped by multiple columns


code:
class Details(db.Model):
    data = db.ReferenceProperty(reference_class=Data)
    has_data = db.BooleanProperty(default=False)

    def add_data(self, data):
        """ Adds data"""
        if not data: return
        self.has_data = True
        self.data = data
        return self.put()

rawDescription: Querying for not None

description: Querying for not None


code:
def splitRoute():
  route = []

  for line in open('route.txt', 'r'):
    route.append(line.strip().split('>'))

  return route

rawDescription: Python split file into list

description: Python split file into list


code:
import copy, re

myMassage = [(re.compile('<!-([^-])'), lambda match: '<!--' + match.group(1))]
myNewMassage = copy.copy(BeautifulSoup.MARKUP_MASSAGE)
myNewMassage.extend(myMassage)

BeautifulSoup(badString, markupMassage=myNewMassage)
# Foo<!--This comment is malformed.-->Bar<br />Baz

rawDescription: Massage with BeatifulSoup or clean with Regex


code:
api = twitter.Api(consumer_key='consumer_key', consumer_secret='consumer_secret',
          access_token_key='access_token', access_token_secret='access_token_secret')

rawDescription: How to tweet from Django?

description: Tweet from Django


code:
import logging, logging.handlers
from logging.handlers import TimedRotatingFileHandler

class Logger(object):
    def __init__(self, log_filename, name):
        logging.basicConfig(format='%(asctime)s %(message)s')
        formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
        loghandler = TimedRotatingFileHandler(
            log_filename, when="midnight", backupCount=50
        )
        loghandler.setFormatter(formatter)
        self.logger = logging.getLogger(name)
        self.logger.setLevel(logging.INFO)
        self.logger.addHandler(loghandler)

    def getLogger(self):
        return self.logger

class ClassA(object):
    def __init__(self):
        log = Logger(log_filename='class_logger.log', name="Class")
        self.logger = log.getLogger()
        self.logger.info('Started ClassA')

    def run(self):
        self.logger.info('Into method run')

A = ClassA()
log = Logger(log_filename='script_logger.log', name="Script")
logger = log.getLogger()
logger.info('Initiated Script')

for x in range(5):
    logger.info('Looping')
    A.run()

rawDescription: Strange behaviour on my logging class

description: Strange behaviour on my logging class


code:
from classes.MyHelper import MyHelper
MyHelper.calling_my_class_method_here()

rawDescription: Packages, Modules, and classes within those


code:
from Tkinter import *

def radio_action():
    value1 = var1.get()
    changeable_label['text'] = value1

the_window = Tk()
the_window.title('Example')

the_window.geometry("200x150")

var1 = StringVar()

changeable_label = Label(the_window, text = "Null")
button1 = Radiobutton(the_window, text = 'Button1', variable = var1,
                     value="Something", command = radio_action)

changeable_label.pack(side = TOP)
button1.pack()

the_window.mainloop()

rawDescription: Getting tkinter labels to update when variable changes


code:
#At starting of script take the username as input

name = raw_input("Enter Your Name : ")
name.lower() #To make input name lowercase

if name == 'bob': #name for which you have to call b
   b()
else:
   a()

rawDescription: How to decide whether if run a function by user in script

description: Decide whether if run a function by user in script


code:
import wx
import gettext

class MyFrame(wx.Frame):
    def __init__(self, *args, **kwds):
        kwds["style"] = wx.DEFAULT_FRAME_STYLE
        wx.Frame.__init__(self, *args, **kwds)
        self.panel_1 = wx.Panel(self, wx.ID_ANY)
        self.button_1 = wx.Button(self.panel_1, wx.ID_ANY, _("button_1"))

        self.__set_properties()
        self.__do_layout()

    def __set_properties(self):
        self.SetTitle(_("frame_1"))

    def __do_layout(self):
        sizer_1 = wx.BoxSizer(wx.VERTICAL)
        sizer_2 = wx.BoxSizer(wx.HORIZONTAL)
        sizer_2.Add(self.button_1, 0, 0, 0)
        self.panel_1.SetSizer(sizer_2)
        sizer_1.Add(self.panel_1, 1, wx.EXPAND, 0)
        self.SetSizer(sizer_1)
        sizer_1.Fit(self)
        self.Layout()

if __name__ == "__main__":
    gettext.install("app")

    app = wx.PySimpleApp(0)
    wx.InitAllImageHandlers()
    frame_1 = MyFrame(None, wx.ID_ANY, "")
    app.SetTopWindow(frame_1)
    frame_1.Show()
    app.MainLoop()

rawDescription: Can't make buttons to appear (wxpython) on ubuntu


rawDescription: pandas - check for non unique values in dataframe groupby

description: Pandas - check for non unique values in dataframe groupby


code:
def acquire_data(list_or_filename):
    # assuming py3 here, for py2 use 'isinstance(list_or_filename, basestring)
    if isinstance(list_or_filename, str):
        with open(list_or_filename,"r") as f:
            return acquire_data_from_file(f)
    else:
        return acquire_data_from_list(list_or_filename)

rawDescription: coding style of a python function

description: Coding style of a python function


code:
import matplotlib.pyplot as plt
import numpy as np
data = np.random.rand(24,7)
heatmap = plt.pcolor(data)
plt.ylim(0, 24)
plt.show()

rawDescription: White pcolor introduces white bar

description: White pcolor introduces white bar


code:
from xlwt import Workbook
import xlwt
book = Workbook()
sheet1 = book.add_sheet('Sheet 1')
book.add_sheet('Sheet 2')
st = xlwt.easyxf('pattern: pattern solid;')
for i in range(0, 100):
    st = xlwt.easyxf('pattern: pattern solid;')
    st.pattern.pattern_fore_colour = i
    sheet1.write(i % 24, i / 24, 'Test text',st)
book.save('simple.xls')

rawDescription: How to change background color of excel cell with python xlwt library?

description: Change background color of excel cell with python xlwt library


code:
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup('foo')
soup.a["title"] = "Some cool title"

rawDescription: How to interfere some text in a html link string in python

description: Interfere some text in a html link string in python


code:
import sqlite3
import pprint

def init_db(conn):
    with conn:
        conn.execute("""create table People (
                            Id integer primary key ASC,
                            Name)""")
        conn.execute("""insert into People values
                            ( 1, "Homer"),
                            ( 2, "Bart"),
                            ( 3, "Lisa"),
                            ( 4, "Maggie"),
                            ( 5, "Abe" )""")

        conn.execute("""create table Parent_Child (
                            ChildId INTEGER UNIQUE,
                            ParentId INTEGER )""")
        conn.execute("""insert into Parent_Child values
                            (1, 5),
                            (3, 1), (4, 1), (2, 1)""")

def Parenting(conn):
    global root
    population_by_id = {}
    sql =  "select ParentId, ChildId from Parent_Child"
    for parent_id, child_id in conn.execute(sql):
        parent = population_by_id.setdefault(parent_id, {})
        child = population_by_id.setdefault(child_id, {})
        parent[child_id] = child
    sql = """select ParentID from Parent_Child
              where ParentID not in (select ChildID from Parent_Child)"""
    eldest = next(conn.execute(sql))[0]
    root = { eldest : population_by_id[eldest] }

if __name__=="__main__":
    conn = sqlite3.connect(':memory:')
    init_db(conn)
    Parenting(conn)
    pprint.pprint(root)

rawDescription: How do I build a dictionary from child to parent?

description: Build a dictionary from child to parent


code:
count = 0
def dft(y):
     N = len(y)
     c = np.zeros(N//2+1,complex)
     for k in range(N//2+1):
         for n in range(N):
             c[k] += y[k]*np.exp(-2j*np.pi*k*n/N)
             count+=1
     return c

print(count)

rawDescription: Fourier Transform: Computational Scaling as a function of vector length