code:
class Foo:
    name1 = 'class variable'

    def __init__(self):
        self.name2 = 'instance variable'
        name3 = 'local variable'

    def test(self):
        print self.name1  # ok
        print self.name2  # ok
        print name3       # no

rawDescription: python: var vs. self.var (what are the differences?)

description: Python: var vs. self.var (what are the differences?)


code:
if len(cliente) == 14:
    print "ID"

elif len(cliente) == 18:
    print "Registration"

else:
    print "You entered an incorrect option"

rawDescription: Check how many characters in input

description: Check how many characters in input


code:
import csv

def parse_csv():
    csv_file = open('data.csv', 'r')
    r = csv.reader(csv_file)
    grade_averages = {}
    for row in r:
        if row[0].startswith('Name'):
            continue
        #print "Student: ", row[0]
        grades = []
        for column in row[1:]:
            #print "Grade: ", column
            grades.append(int(column.strip()))
        grade_total = 0
        for i in grades:
            grade_total += i
        grade_averages[row[0]] = grade_total / len(grades)

    #print "grade_averages: ", grade_averages
    return grade_averages

def get_grade(student_name):
    grade_averages = parse_csv()
    return grade_averages[student_name]

print "Rick: ", get_grade('Rick')
print "Robin: ", get_grade('Robin')

rawDescription: How to call in a specifc csv field value in python

description: Call in a specifc csv field value in python


code:
markup = """

ab
link
link1link2
"""

# Double curly brackets to avoid problems with .format()
stripped_markup = markup.replace('{','{{').replace('}','}}')

stripped_markup = BeautifulSoup(stripped_markup)

unformatted_tag_list = []

for i, tag in enumerate(stripped_markup.find_all(['span', 'a'])):
    unformatted_tag_list.append(str(tag))
    tag.replace_with('{' + 'unformatted_tag_list[{0}]'.format(i) + '}')

pretty_markup = stripped_markup.prettify().format(unformatted_tag_list=unformatted_tag_list)

print pretty_markup

rawDescription: customize BeautifulSoup's prettify by tag

description: Customize BeautifulSoup's prettify by tag


code:
import datetime
from dateutil.relativedelta import relativedelta
now = datetime.datetime.now()
td = datetime.timedelta(days=500)
five_hundred_days_ago = now - td
print relativedelta(now, five_hundred_days_ago)

rawDescription: Is there a best way to change given number of days to years months weeks days in Python?


code:
import os
import logging

class MyFileHandler(object):

    def __init__(self, dir, logger, handlerFactory, **kw):
        kw['filename'] = os.path.join(dir, logger.name)
        self._handler = handlerFactory(**kw)

    def __getattr__(self, n):
        if hasattr(self._handler, n):
            return getattr(self._handler, n)
        raise AttributeError, n

logger = logging.getLogger('test')
logger.setLevel(logging.INFO)
handler = MyFileHandler(os.curdir, logger, logging.FileHandler)
logger.addHandler(handler)
logger.info('hello mylogger')

rawDescription: Python logger dynamic filename

description: Python logger dynamic filename


code:
def toUTCc(d):
    return tz.normalize(tz.localize(d)).astimezone(pytz.utc)

print "Test: ", datetime.datetime.utcnow(), " = ", toUTC(datetime.datetime.now())

rawDescription: pytz utc conversion

description: Pytz utc conversion


code:
from collections import OrderedDict
my_lst = ['b','c','a']
D = OrderedDict()
for i in my_lst:
    D[i] = []
D
print D.items()

rawDescription: python : use elements from a list as keys to a dictionary in order of list

description: Python : use elements from a list as keys to a dictionary in order of list


code:
# whatever your input is
x = [1, 2, 3, 4, 5]

# set the initial total to 1, and wrap it in a list so we can modify it in an expression
total = [1]

# did I mention you shouldn't do this?
[total.__setitem__(0, xi * total.__getitem__(0)) for xi in x]

print total[0]
120

rawDescription: Multiply a list of ints using list comprehension


code: print Parent.Nested() # works fine, print calls __str__ resulting in 'Child'

rawDescription: How to override __str__ in nested class

description: Override __str__ in nested class


code:
class Doer(object):
    def __init__(self):
        self.name = "Bob"

    def doSomething(self):
        print "%s got it done" % self.name

def doItBetter(self):
    print "%s got it done better" % self.name

Doer.doSomething = doItBetter

rawDescription: Dynamically assigning function implementation in Python


code:
lista = [('ab','tall',3),
('go','cd',2),
('gb','my',1),
('game','me', 2),
('uk','try',4),
('me','hello',1),
('good','try',3)]

# items that fullfill the condition
is_valid = [1 if item[2] < 3 else 0 for item in lista]

# handling "next to each other condition" of the first item
valid_items = []
if is_valid[0] == 1 and is_valid[1]:
    valid_items.append(lista[0])

# handling "next to each other condition" of items that are not the first and not the last
for item_id in range(1, len(is_valid)-1):
    if is_valid[item_id] == 1 and (is_valid[item_id - 1] == 1 or is_valid[item_id + 1] == 1):
        valid_items.append(lista[item_id])
# handling "next to each other condition" of the last item in the list
if is_valid[-2] == 1 and is_valid[-1] == 1:
    valid_items.append(lista[-1])

# just print the result
print valid_items

rawDescription: List of tuples in Python

description: List of tuples in Python


code:
import numpy as np
array = np.random.random((5,5))
print array

density = np.histogram(array, density=True)
print(density)

rawDescription: Creating density estimate in numpy

description: Creating density estimate in numpy


code:
import xml.etree.ElementTree as ET

def perf_func(elem, func, level=0):
    func(elem,level)
    for child in elem.getchildren():
        perf_func(child, func, level+1)

def print_level(elem,level):
    print '-'*level+elem.tag

root = ET.parse('XML_file.xml')
perf_func(root.getroot(), print_level)

rawDescription: Python - How to determine hierarchy level of parsed XML elements?


code:
#!/usr/bin/python
#Access the registry to find out what plugins are available
#list elements within a plugin
#list all elements within a Klass
from gi.repository import Gst
Gst.init()
reg = Gst.Registry.get()

print "List Available Plugins\n"
for x in reg.get_plugin_list():
    print x.get_name()
print "End Available Plugins\n"

print "List Plugins in AudioVisual\n"
for x in reg.get_feature_list_by_plugin("audiovisualizers"):
    print x.get_name(), "\t", x.get_longname()
print "END\n"

print "All Available visualisations\n"
vis_list = [filt for filt in reg.get_feature_list(Gst.ElementFactory) \
        if (filt.get_klass().find("Visualization") >= 0)]
for x in vis_list:
    short = x.get_name()
    name = x.get_longname()
    print (short + "\t\t" + name)
print "END\n"

print "All Available Audio filters\n"
audio_filter_list = [filt for filt in reg.get_feature_list(Gst.ElementFactory) \
        if (filt.get_klass().find("Filter/Effect/Audio") >= 0)]
for x in audio_filter_list:
    short = x.get_name()
    name = x.get_longname()
    print (short + "\t\t" + name)
print "END\n"

rawDescription: How do you access Gstreamer Registry to get a list of what plugins are available programatically

description: Access Gstreamer Registry to get a list of what plugins are available programatically


code:
from mechanize import Browser, _http
from BeautifulSoup import BeautifulSoup

br = Browser()
br.set_handle_robots(False)
br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')]

url = "http://www.delicious.com/varunsrin"
page = br.open(url)
html = page.read()

soup = BeautifulSoup(html)
print soup.prettify()

rawDescription: Python + Mechanize not working with Delicious


code:
class Thingy(object):
    def __init__(self, color):
        self.color = color

x = Thingy('red')
print x.color
'red'

rawDescription: What is the function of __init__(self,Name1,Name2,...)?


code:
#######################
# define the function #
#######################

def readfile():

    """ Reads a file consisting of a list of tuples (x, y) line-by-line. Prints x and y of the current line and the next line as reading ensues. """

    file_in = open("./tuples.txt","r")  # read the file in, I assume the script is run in the same directory as the tuples list

    result = []

    while True:

        line      = file_in.readline()  # read the file line-by-line
        go_back   = file_in.tell()      # "saves" the current line so we can step back
        next_line = file_in.readline()  # reads the line ahead

        x,y  = str(line).replace("(","").replace(")","").replace(" ","").rstrip().lstrip().split(",")

        # Have we reached the end of the file?
        try:
            # No...
            x_next, y_next = str(next_line).replace("(","").replace(")","").replace(" ","").rstrip().lstrip().split(",")
            result.append([float(x),float(y)])
            print "current line: "+str(x)+" "+str(y)+" ..next line: "+str(x_next)+" "+str(y_next)

        except ValueError:
            # Yes...
            print "current line: "+str(x)+" "+str(y)+" ..next line: "+"NaN NaN"
            break # break once we read a "next line" that does not exist, i.e. number of lines in file + 1

        line = file_in.seek(go_back) # go back to previous line

    return result

####################
# run the function #
####################

result = readfile()

print "\nresult: "+str(result)

rawDescription: How can I iterate tuples in this code python?

description: Iterate tuples in this code python


code:
import subprocess
def get_eth_iface():
    awk_sort = subprocess.Popen( ["dir" ], stdin= subprocess.PIPE, stdout= subprocess.PIPE)
    awk_sort.wait()
    output = awk_sort.communicate()[0]
    print output.rstrip()
get_eth_iface()

rawDescription: Save result from system command to a variable using subprocess


code:
import collections

the_inputs = []
for i in range(3):
    the_inputs.append(raw_input("Enter numbers {}... ".format(i+1)))

the_lists = []
for the_input in the_inputs:
    the_lists.append([int(x)//10 for x in the_input.strip("[]").split(",")])

for i, the_list in enumerate(the_lists):
    print "Input {}".format(i+1)
    group_counter = collections.Counter(the_list)
    bin_range = range (6)
    for bin_tens in bin_range:
        print "There were {} in {} to {}".format(group_counter[bin_tens], bin_tens*10, bin_tens*10+9)

rawDescription: Multiple user input prints particular style


code:
strings = ["some", "example", "words", "that", "i", "am", "fond", "of"]

print min(strings, key=len) # prints "i"

rawDescription: How to find the shortest string in a list in Python

description: Find the shortest string in a list in Python


code:
import importlib

response = raw_input("Please type module_name function_name: ")
module_name, function_name = response.split()
print "User entered module_name %r, function_name %r" % (module_name, function_name)

try:
    module = importlib.import_module(module_name)
    result = getattr(module, function_name)()
    print "%s.%s() returned %r" % (module_name, function_name, result)
except ImportError, e:
    print "Failed to import module %r" % module
except AttributeError, e:
    print "Function %r not found in module %s" % (function_name, module_name)

rawDescription: Import scripts and execute the one the user needs


code:
students = [{'name': 'Tom',
         'subjects': {'math': 50,
                      'english': 100,
                      'science': 72}},
        {'name': 'Alex',
         'subjects': {'math': 100,
                      'english': 90,
                      'science': 95}}]

weighting_coefficient = {'math': 2,
                     'english': 10,
                     'science': 8}

total = sum(weighting_coefficient.values())

for student in students:
    student['weighted_average'] = float( sum( [student['subjects'][subj] * weighting_coefficient[subj] for subj in student['subjects'].keys() ] ) ) / total

print students

rawDescription: How to implement about calculating weighted average if it's without for loop

description: Implement about calculating weighted average if it's without for loop


code:
import difflib

varA = 'plaimountain'
varB = 'piaimauntain'
varC = 'skymountain'
varS = ['piaimauntain','sky','skymountain','dog','231']

#it parse varB by letters
best = difflib.get_close_matches(varA, varB)
print best

best = difflib.get_close_matches(varA, [varB])
print best

best = difflib.get_close_matches(varA, [varB,varC])
print best

best = difflib.get_close_matches(varA, [varB,varS])
print best

rawDescription: Find the closest match between two string variables using difflib


code:
class VisitCalls(ast.NodeVisitor):
  def visit_Call(self, what):
    if what.func.value.id == 'self':
      print what.func.attr

f='''def x(self):
  return self.bar() + self.baz()
'''
xx = ast.parse(f)
VisitCalls().visit(xx)

rawDescription: Python AST processing

description: Python AST processing


code:
def listen(self, buffsize):
    self.sock.listen(5)

    while True:
        # Listen for a new client.
        clisock, (remhost, remport) = self.sock.accept()

        # Start listening to the new client.
        t = threading.Thread(target=self._handle_client, args=(clisock, buffsize))
        t.start()

def _handle_client(self, clisock, buffsize):
    while True:
        received = clisock.recv(buffsize)
        if not received:
            # The client has closed the connection.
            break

        print received

rawDescription: Multiple socket threads on same computer


code:
original_date_string = '22.12.2015'
print type(original_date_string)
import datetime
python_date_object_for_insert_mongo = datetime.datetime.strptime(original_date_string, '%d.%m.%Y')
print python_date_object_for_insert_mongo
print type(python_date_object_for_insert_mongo)
python_date_object_retrive_from_mongo = python_date_object_for_insert_mongo
transfer_to_original_format = datetime.datetime.strftime(python_date_object_retrive_from_mongo, '%d.%m.%Y')
print transfer_to_original_format
print type(transfer_to_original_format)

rawDescription: How to store and retrieve date as dd/mm/yyyy in MongoDB?

description: Store and retrieve date as dd/mm/yyyy in MongoDB


code:
capital = False
lowercase = False
number = False
if len(passwd) < 6:
    print 'That was not more than 6 characters'
else:
    for character in passwd:
        if character.islower():
            lowercase = True
        elif character.isupper():
            capital = True
        elif character.isdigit():
            number = True
        if capital and lowercase and number:
            break
    else:
        print 'That did not have a capital letter, lowercase letter, and a digit'

rawDescription: Having trouble learning how to look at individual characters in a string checking for case or digit


code:
from collections import defaultdict

lst = [("a",4), ("b",4), ("a",5), ("b",3)]

result = defaultdict(list)
for a, b in lst:
    result[a].append(b)

print sorted(result.items())

# prints: [('a', [4, 5]), ('b', [4, 3])]

rawDescription: Filter operation in Python

description: Filter operation in Python


code:
import os, re
dirname = 'android_tools/sdk/platforms'
files = os.listdir(my_dir)
def mykeyfunc(fname):
    digits = re.search(r'\d+$', fname).group()
    return int(digits)
print max(files, mykeyfunc)

rawDescription: How do I get the "biggest" path?

description: Get the "biggest" path


code:
from sklearn.ensemble import RandomForestClassifier
from sklearn.cross_validation import train_test_split
from sklearn.datasets import load_iris

def generate_rf(X_train, y_train, X_test, y_test):
    rf = RandomForestClassifier(n_estimators=5, min_samples_leaf=3)
    rf.fit(X_train, y_train)
    print "rf score ", rf.score(X_test, y_test)
    return rf

def combine_rfs(rf_a, rf_b):
    rf_a.estimators_ += rf_b.estimators_
    rf_a.n_estimators = len(rf_a.estimators_)
    return rf_a

iris = load_iris()
X, y = iris.data[:, [0,1,2]], iris.target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.33)
# in the line below, we create 10 random forest classifier models
rfs = [generate_rf(X_train, y_train, X_test, y_test) for i in xrange(10)]
# in this step below, we combine the list of random forest models into one giant model
rf_combined = reduce(combine_rfs, rfs)
# the combined model scores better than *most* of the component models
print "rf combined score", rf_combined.score(X_test, y_test)

rawDescription: Combining random forest models in scikit learn


code:
import os
import sys
def foo():
  print "foo"
if __name__ == "__main__":
  out = sys.stdout
  null = open(os.devnull, 'w')
  sys.stdout = null
  foo()
  sys.stdout = out
  print "Hello"

rawDescription: Python IO: disable standard output stream and print what we want


code:
class Name(object):
    def __init__(self, *params):
        self.__dict__.update(DEFAULT_PARAMS)
        self.__dict__.update(params)

b = Name(position=[1,2])
print b.position

rawDescription: Python: unpack dictionary inside a method


code:
import urllib2

def ranker(host):
    api_key = 'xxxxxxxxxxxxxxxxx'
    url = 'http://pagerank.my-addr.com/external_fakepr_api/%s/%s'%(api_key, host)

    link =  urllib2.urlopen(url)
    data = link.readline()
    return data.split('|')[0]

print 'www.example.com', ranker('www.example.com')

rawDescription: Using web-based API in python - retrieving response in Python


code:
from datetime import date

d0 = date(2008, 8, 18)
d1 = date(2008, 9, 26)
delta = d0 - d1
print delta.days

rawDescription: How do I calculate number of days betwen two dates using Python?

description: Calculate number of days betwen two dates using Python


code:
called = set()

def onlyonce(fn):
    def decorated(*largs, **kargs):
        if fn not in called:
            called.add(fn)
            print "Calling"
            fn(*largs, **kargs)
        else:
            print "Already called"
    return decorated

@onlyonce
def test_function():
    print "I am getting called now"

test_function()
test_function()
test_function()
test_function()

rawDescription: how to get function's name from within the function (or kind of "self" reference to the function)?

description: Get function's name from within the function (or kind of "self" reference to the function)


code:
import re
p = re.compile(ur'PAGE\(enter\)[\S ]+\s((?:(?![^\n]+PAGE\(leave\)).)*)', re.IGNORECASE | re.DOTALL)
test_str = u"Jan 01 01:25:08 AMIRA-134500021 user.notice gui-monitor[770]: ACTION:401b0836:8:PAGE(leave) 'X_0_Gui_Menu_322_Menu_Outputs_SDI_overlays'\nJan 01 01:25:08 AMIRA-134500021 user.notice gui-monitor[770]: ACTION:401b0836:8:PAGE(enter) 'X_0_Gui_Menu_321_Menu_Outputs_SDI_processing'\nJan 01 01:25:09 AMIRA-134500021 user.notice butler[774]: LOG:200708a0:12:Button 11 released.\nJan 01 01:25:12 AMIRA-134500021 user.notice butler[774]: LOG:200708a0:12:Wheel 4 turned from 31 to 30.\nJan 01 01:25:12 AMIRA-134500021 user.notice butler[774]: LOG:200708a0:12:Button 9 pressed.\nJan 01 01:25:12 AMIRA-134500021 user.notice gui-monitor[770]: ACTION:401b0836:8:PAGE(leave) 'X_0_Gui_Menu_321_Menu_Outputs_SDI_processing'\nJan 01 01:25:12 AMIRA-134500021 user.notice gui-monitor[770]: ACTION:401b0836:8:PAGE(enter) 'X_0_Gui_Menu_322_Menu_Outputs_SDI_overlays'\nJan 01 01:25:25 AMIRA-134500021 user.notice butler[774]: LOG:200708a0:12:Button 9 released.\nJan 01 01:25:25 AMIRA-134500021 user.notice concen[655]: LOG:2011088a:4:Setting parameters saved.\nJan 1 01:25:27 AMIRA-134500021 daemon.warn dnsmasq-dhcp[738]: DHCP packet received on eth0 which has no address\nJan 01 01:25:28 AMIRA-134500021 user.notice butler[774]: LOG:200708a0:12:Wheel 4 turned from 29 to 34.\nJan 01 01:25:28 AMIRA-134500021 user.notice butler[774]: LOG:200708a0:12:Button 9 pressed.\nJan 01 01:25:28 AMIRA-134500021 user.notice gui-monitor[770]: ACTION:401b0836:8:PAGE(leave) 'X_0_Gui_Menu_322_Menu_Outputs_SDI_overlays'\nJan 01 01:25:28 AMIRA-134500021 user.notice gui-monitor[770]: ACTION:401b0836:8:PAGE(enter) 'X_0_Gui_Menu_3231_Menu_Outputs_SDI_status'"

ll=re.findall(p, test_str)

rawDescription: Getting all the lines inbetween two strings and storing the data in another file in python 2.7


code:
Example
#!/usr/bin/env python
from argparse import ArgumentParser

if __name__ == "__main__":
    parser = ArgumentParser(prog='script.py')
    parser.add_argument('--foo', nargs='?', metavar='bar', default='baz')

    parser.print_usage()
    for args in ([], ['--foo'], ['--foo', 'bar']):
        print "$ %s %s -> foo=%s" % (
            parser.prog, ' '.join(args).ljust(9), parser.parse_args(args).foo)

rawDescription: Command line options with optional arguments in Python


code:
i = 0
j = 1
while i < 10:
    j= 1 #<-- here
    while j < 11:
        print i, j
        j+=1
    i+=1

rawDescription: How to use a double while loop in python?

description: Use a double while loop in python


code:
def run(self):
    while datetime.utcnow() < self.life:
        #do stuff that i do
        print "hi"
        time.sleep(5)

rawDescription: Make a thread execute for no more than 24 hrs then die


code:
checkSql = 'SELECT userid FROM bs_members WHERE userid = :checkUser'
while True:
    newUser.userID = ga.getInput('Enter userID: ', "\w+$")
    ds.execute(checkSql,checkUser=newUser.userID)
    if ds.fetchone() is None:
        # This userID is available.
        break
    else:
        print 'That user name is already in use.  Please enter a new username.'

rawDescription: I don't understand why this loop terminates the way it does


code:
import sys
import os
import xmpp

if len(sys.argv) < 3:
    print "Syntax: register.py [JID] [Password]"
    sys.exita(64)

jid=xmpp.protocol.JID(sys.argv[1])
cli=xmpp.Client(jid.getDomain(), debug=[])
cli.connect()

# getRegInfo has a bug that puts the username as a direct child of the
# IQ, instead of inside the query element.  The below will work, but
# won't return an error when the user is known, however the register
# call will return the error.
xmpp.features.getRegInfo(cli,
                         jid.getDomain(),
                         #{'username':jid.getNode()},
                         sync=True)

if xmpp.features.register(cli,
                          jid.getDomain(),
                          {'username':jid.getNode(),
                           'password':sys.argv[2]}):
    sys.stderr.write("Success!\n")
    sys.exit(0)
else:
    sys.stderr.write("Error!\n")
    sys.exit(1)

rawDescription: Is there any python xmpp library that supports adding/removing users?


code:
import random

TRIES = 365

def generate_random_numbers(n):
    """Generates a list of n random numbers"""

    random_numbers = []
    for _ in range(n):
        random_number = random.randint(1, n)
        random_numbers.append(random_number)

    return random_numbers

def repetition(random_numbers):
    """Given a list of random numbers, it will return the index of the first repeated element"""

    for index, random_number in enumerate(random_numbers):
        if random_number in random_numbers[:index]:
            # You can print the list up to but not including the first repeated element
            # using list slicing: print '{}'.format(random_numbers[:index])
            return index

def repeater(n):
    indices_of_first_duplicates = []
    for i in range(n):
        random_numbers = generate_random_numbers(n)
        indices_of_first_duplicates.append(repetition(random_numbers))

    return indices_of_first_duplicates

repeater_result = repeater(TRIES)

print '{}'.format(repetition(repeater_result))

rawDescription: Random Number Repetition in a List

description: Random Number Repetition in a List


code:
from selenium import webdriver
from selenium.webdriver.support.ui import Select, WebDriverWait
from selenium.common.exceptions import NoSuchFrameException
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

username = 'agora username'
password = 'agora password'
def go_to_page(br):
    #page_num = page_num - 1
    #start_results = page_num * 100
    #start_results = str(start_results)
    url = 'http://agorahooawayyfoe.onion'
    print '[*] loading url: '+url
    br.get(url)
    #br.get_screenshot_as_file('agora.tiff')
    usernamed = br.find_element_by_name("username")
    usernamed.send_keys(username) # password
    passwordd = br.find_element_by_name("password") # enterCaptcha
    passwordd.send_keys(password)
    captchad = br.find_element_by_name("enterCaptcha")
    capt = raw_input('enter captcha you see on screen: ')
    captchad.send_keys(capt)
    br.implicitly_wait(3)
    br.find_element_by_name("submit").click()

def start_browser():
    profiler = webdriver.FirefoxProfile('/Users/your username/Library/Application Support/Firefox/Profiles/vxh0qxtt.tor')
    br = webdriver.Firefox(firefox_profile=profiler)
    br.implicitly_wait(10)
    return br

def main():
    br = start_browser()
    go_to_page(br)

main()

rawDescription: selenium python runing firefox with TOR (windows)

description: Selenium python runing firefox with TOR (windows)


code:
from tornado import ioloop, httpclient

def get_file(url):
    http_client = httpclient.AsyncHTTPClient()
    http_client.fetch(url, callback=done)

def done(response):
    with open("my_favorite_directory/my_favorite_filename.pdf", "w") as f:
        f.write(response.body)
    print "DONE"

get_file("http://samplepdf.com/sample.pdf")
ioloop.IOLoop.instance().start()

rawDescription: how to give a name to downloaded file with async tornado client

description: Give a name to downloaded file with async tornado client


code:
import httplib2
from oauth2client.file import Storage
from oauth2client.client import flow_from_clientsecrets
from oauth2client.tools import run
from apiclient.discovery import build

storage = Storage("saved_user_creds.dat")
credentials = storage.get()
if credentials is None or credentials.invalid:
  credentials = run(flow_from_clientsecrets("client_secrets2.json", scope=["https://www.googleapis.com/auth/drive"]), storage)
http = credentials.authorize(httplib2.Http())
service = build("drive", "v2", http)
print service.files().list().execute()

rawDescription: How can I reuse an existing verification code / token to access Google Drive?

description: Reuse an existing verification code / token to access Google Drive


code:
destination_object_resource = {}
req = client.objects().copy(
        sourceBucket=bucket1,
        sourceObject=old_object,
        destinationBucket=bucket2,
        destinationObject=new_object,
        body=destination_object_resource)
resp = req.execute()
print json.dumps(resp, indent=2)

client.objects().delete(
        bucket=bucket1,
        object=old_object).execute()

rawDescription: How to move files in Google Cloud Storage from one bucket to another bucket by Python

description: Move files in Google Cloud Storage from one bucket to another bucket by Python


code:
import numpy as np

def submatrix(arr):
    x, y = np.nonzero(arr)
    # Using the smallest and largest x and y indices of nonzero elements,
    # we can find the desired rectangular bounds.
    # And don't forget to add 1 to the top bound to avoid the fencepost problem.
    return arr[x.min():x.max()+1, y.min():y.max()+1]

test = np.array([[0, 0, 0, 0, 0, 0],
                 [0, 1, 1, 1, 1, 0],
                 [0, 0, 1, 1, 0, 0]])

print submatrix(test)

# Result:
# [[1 1 1 1]
#  [0 1 1 0]]

rawDescription: Numpy: given the nonzero indices of a matrix how to extract the elements into a submatrix


code:
from webscraping import common, download, xpath

# download html
D = download.Download()
html = D.get('http://www.expatistan.com/cost-of-living/comparison/melbourne/auckland')

# extract data
items = xpath.search(html, '//td[@class="item-name"]')
city1_prices = xpath.search(html, '//td[@class="price city-1"]')
city2_prices = xpath.search(html, '//td[@class="price city-2"]')

# display and format
for item, city1_price, city2_price in zip(items, city1_prices, city2_prices):
    print item.strip(), city1_price.strip(), common.remove_tags(city2_price, False).strip()

rawDescription: Python Web Scraping; Beautiful Soup

description: Python Web Scraping; Beautiful Soup


rawDescription: How to vertically print 2d list with different lengths in python

description: Vertically print 2d list with different lengths in python


code:
import collections

pos_list = nltk.pos_tag(list)
pos_counts = collections.Counter((subl[1] for subl in pos_list))
print "the five most common tags are", pos_counts.most_common(5)

rawDescription: Using Python and NLP to get the most frequent POS tag from a list


code:
import os

file_path = '/var/log/app/access.log'

with open(file_path) as f:
    file_size = 0
    while True:
        line = f.readline()
        if line:
            print line
        file_status_obj = os.stat(file_path)
        if file_size < file_status_obj.st_size:
            f.seek(0)
        file_size = file_status_obj.st_size

rawDescription: Python Parse log file in realtime, reload when the log rotates


code:
with open('/root/Desktop/test.txt', 'r+') as f:
    for line in f:
        found = line.find('Server version:')
        if found != -1:
            version = line[found+len('Server version:')+1:]
            print version

rawDescription: How to read next word or words till next line from file in python?

description: Read next word or words till next line from file in python


code:
d={'server1':{'3389': 'Microsoft Terminal Service', '49160': 'Microsoft Windows RPC', '49163': 'Microsoft Windows RPC', '135': 'Microsoft Windows RPC', '49152': 'Microsoft Windows RPC', '49153':'Microsoft Windows RPC'},'server2':{'morekeys':'morevalues'}}
print json.dumps(d, indent=4)

rawDescription: Printing nested dictionaries in nice readable fashion


code:
from datetime import datetime

dtstr = '2010-12-19 03:44:34.778000'
format = "%Y-%m-%d %H:%M:%S.%f"
a = datetime.strptime(dtstr,format)
print a.microsecond

rawDescription: Microsecond part lost when converting a date string to a datetime object in python


code:
import itertools
def update_dict(A, result): #update vaules to the same set
    for k in A:
        result[k] = result.get(k, {k}).union(set(A[k]))
        tmp = None
        for i in result[k]:
            tmp = result.get(k, {k}).union(result.get(i, {i}))
        result[k] = tmp
        for i in result[k]:
            result[i] = result.get(i, {i}).union(result.get(k, {k}))

A = {0:('b',), 1:('c',), 2:('c',), 3:('c',)}
B = {'a':(3,), 'b':(0,), 'c':(1,2,3)}
result = dict()
update_dict(A, result)
update_dict(B, result)
update_dict(A, result) #update to fix bugs
update_dict(B, result)

k = sorted([sorted(list(v)) for v in result.values()])
k = list( k for k, _ in itertools.groupby(k))  #sort and remove dumplicated set

final_result = dict()
for v in k: #merge the result as expected
    final_result.update({tuple([i for i in v if isinstance(i, int)]):tuple([i for i in v if not isinstance(i, int)])})
print final_result

#output
{(0,): ('b',), (1, 2, 3): ('a', 'c')}

rawDescription: merge python dictionary of sets

description: Merge python dictionary of sets


code:
from sqlalchemy import Column, DateTime, Integer, String, Table, MetaData
from sqlalchemy.orm import mapper
from sqlalchemy import create_engine, orm

metadata = MetaData()

product = Table('product', metadata,
    Column('id', Integer, primary_key=True),
    Column('name', String(1024), nullable=False, unique=True),

)

class Product(object):
    def __init__(self, id, name):
        self.id = id
        self.name = name
    def __repr__(self):
        return "%s(%r,%r)" % (self.__class__.name,self.id,self.name)

mapper(Product, product)

db = create_engine('sqlite:////temp/test123.db')
metadata.create_all(db)

sm = orm.sessionmaker(bind=db, autoflush=True, autocommit=True, expire_on_commit=True)
session = orm.scoped_session(sm)

#create new Product record:
if session.query(Product).filter(Product.id==1).count()==0:

    new_prod = Product("1","Product1")
    print "Creating new product: %r" % new_prod
    session.add(new_prod)
    session.flush()
else:
    print "product with id 1 already exists: %r" % session.query(Product).filter(Product.id==1).one()

print "loading Product with id=1"
prod = session.query(Product).filter(Product.id==1).one()
print "current name: %s" % prod.name
prod.name = "new name"

print prod

prod.name = 'test'

session.add(prod)
session.flush()

print prod

#session.delete(prod)
#session.flush()

rawDescription: Updating row in SqlAlchemy ORM

description: Updating row in SqlAlchemy ORM


code:
import json

json_data = json.loads(myjson)

for key, entry in json_data['data'].iteritems():
    print key, entry['subject']

rawDescription: Python json decode and search

description: Python json decode and search


code:
for line in paragraphInput.splitlines():
    print "This is " + line + " !"

rawDescription: Extract lines from user's input paragraphs


code:
import os, sys

child_pid = os.fork()
if child_pid == 0:
  print 'in child'
  os._exit(os.EX_OK)
  print 'hm... wasn''t supposed to get here'
else:
  print 'in parent'

rawDescription: ipython and fork()

description: Ipython and fork()


code:
import csv, sys

filename = sys.argv[1]
csvfile = open(filename, 'r')
csvreader = csv.DictReader(csvfile)
rows = []
for row in csvreader:
  try:
      row['keywords'].decode('ascii')
      rows.append(row)
  except UnicodeDecodeError:
      pass

print rows

rawDescription: How to remove non-ascii infected rows in my csv

description: Remove non-ascii infected rows in my csv


code:
result = raw_input('What would you like to do? Type q to quit: ')

while result.lower() != 'q':
    if result == 'x':
       print 'y'
    if result == 'z':
       print 'a'
    result = raw_input('What would you like to do? Type q to quit: ')
print('Quitting. Good bye!')

rawDescription: Program Looping:Making a certain statement loop forever in Python


code:
from django.core.management.base import BaseCommand

class Command(BaseCommand):
    help = 'prints no args if there are no args'

    def handle(self, *args, **options):
        if len(args) == 0:
            print 'no args'
        else:
            for pkid in args:
                print pkid

rawDescription: Django admin commands with/without args

description: Django admin commands with/without args


code:
import re

s="""

    Reissue of:
     **VALUES_TO_FIND**

"""

p="""

    Reissue of:
    (.*)

"""

m=re.search(p, s)
print m.group(1)

rawDescription: How to create a regex for the following scenario (HTML)?

description: Create a regex for the following scenario (HTML)


code:
print seq(y), '\t', ', '.join('%s' % i if i == j else '%s-%s' % (i, j)
                              for i in holetbl[y])

rawDescription: How to adapt Python loop generation to be conditional?

description: Adapt Python loop generation to be conditional


code:
from xml.etree import ElementTree

tree = ElementTree.fromstring("""<?xml version="1.0" encoding="UTF-8"?>
<rooms>
    <total-results>1</total-results>
    <items-per-page>1</items-per-page>
    <start-index>0</start-index>
    <room>
        <id>xxxxxxxx</id>
        <etag>5</etag>
        <link rel="http://schemas.com.mysite.building" title="building" href="https://mysite.me.myschool.edu:8443/ess/scheduleapi/v1/buildings/yyyyyyyyy" />
        <name>1.306</name>
        <status>active</status>
        <link rel="self" title="self" href="https://mysite.me.myschool.edu:8443/ess/scheduleapi/v1/rooms/aaaaaaaaa" />
    </room>
</rooms>
""")

# Select the first link element in the example XML
for node in tree.findall('./room/link[@title="building"]'):
    # the 'attrib' attribute is a dictionary containing the node attributes
    print node.attrib['href']

rawDescription: How do I access the link data in an xml node in python?

description: Access the link data in an xml node in python


code:
#!/usr/bin/python
import ipcalc
import sys

for data in sys.argv[1:]:
  with open(data) as data:
    for data in data:
      data = data.split()
      # Convert subnet mask to count
      data[1] = ipcalc.IP(data[1]).bin().count('0')
      data = ipcalc.Network(*data)
      data = list(data)
      if len(data) == 1:
        print data[0]
      else:
        for data in data[1:-1]:
          print data

rawDescription: output expanded ip list from text in python

description: Output expanded ip list from text in python


code:
import subprocess
cmd = 'wmic process where "name=\'notepad.exe\'" get ExecutablePath'
proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
print proc.stdout.read()

rawDescription: How to get process location using Python 2.7?

description: Get process location using Python 2.7


code:
foreign_currencies = set(currencies)
foreign_currencies.discard('USD') #do not assign this as `discard does not return anything.
print foreign_currencies #now you have the currect result

rawDescription: What don't I understand about the order of execution and/or operations in Python 2.7?


code:
s = '{"_id": {"$oid": "4edebd262ae5e93b41000000"}}'
u = json.loads(s, object_hook=json_util.object_hook)

print u  # Result:  {u'_id': ObjectId('4edebd262ae5e93b41000000')}

s = json.dumps(u, default=json_util.default)

print s  # Result:  {"_id": {"$oid": "4edebd262ae5e93b41000000"}}

rawDescription: Unable to deserialize PyMongo ObjectId from JSON


code:
list1 = ['543', '432']
list2 = ['543242', '43299919', '2322242', '245533']

def match_numbers (nlist, nlist1):
    results = {}
    for x in nlist1:
        results.setdefault(x[0:3], [])
        results[x[0:3]].append(x)

    for x in nlist:
        if x in results:
            print results[x]

match_numbers(list1, list2)

rawDescription: Function Definition: Matching two input lists


code:
import itertools
from collections import Counter

with open('/usr/share/dict/american-english', 'r') as handle:
    dictionary = frozenset(line.strip() for line in handle)

def existing_words(letters, length):
    letters_counter = Counter(letters)
    letters_set = frozenset(letters)

    for word in dictionary:
        if len(word) != length:
            continue

        if set(word) <= letters_set and Counter(word) <= letters_counter:
            yield word

if __name__ == '__main__':
    for word in existing_words('abcdefghijklmnopqrst', 5):
        print word

rawDescription: Subdivide itertools.permutations process in Python


code:
import datetime as dt
from collections import deque
from itertools import tee, islice, izip

def dayiter(start, end):
    one = dt.timedelta(days=1)
    day = start
    while day <= end:
        yield day
        day += one

def moving_average(mapping, window, dft=0):
    n = float(window)
    t1, t2 = tee(dayiter(min(mapping), max(mapping)))
    s = sum(mapping.get(day, dft) for day in islice(t2, window))
    yield s / n
    for olddate, newdate in izip(t1, t2):
        oldvalue = mapping.get(olddate, dft)
        newvalue = mapping.get(newdate, dft)
        s += newvalue - oldvalue
        yield s / n

example = {dt.datetime(2008, 1, 1) : 5, dt.datetime(2008, 1, 2) : 6, dt.datetime(2008, 1, 3) : 7, dt.datetime(2008, 1, 4) : 9, dt.datetime(2008, 1, 5) : 12,
dt.datetime(2008, 1, 6) : 15, dt.datetime(2008, 1, 7) : 20, dt.datetime(2008, 1, 8) :     22, dt.datetime(2008, 1, 9) : 25, dt.datetime(2008, 1, 10) : 35}

for ma in moving_average(example, window=3):
    print ma

rawDescription: Calculating moving average for values in a dictionary with keys in a specific range


code:
import networkx as nx
g = nx.DiGraph()
g.add_nodes_from(['London', 'Boston', 'NY', 'Dallas'])
g.add_edge('NY', 'Boston', capacity)
g.add_edge('Dallas', 'Boston')
g.add_edge('Dallas', 'London')
# add capacity to existing edge
g.edge['Dallas']['London']['capacity'] = 2
# create edge with capacity attribute
g.add_edge('NY', 'London', capacity=3)
print nx.min_cut(g, 'NY', 'London')

rawDescription: How should I create my object so it works with networkx pretty well?


code: print row [1] + " has been checked " + ('in' if row[3] else 'out')

rawDescription: Rename true false boolean

description: Rename true false boolean


code:
import Image
from ImageColor import getcolor, getrgb
from ImageOps import grayscale

def image_tint(src, tint='#ffffff'):
    if Image.isStringType(src):  # file path?
        src = Image.open(src)
    if src.mode not in ['RGB', 'RGBA']:
        raise TypeError('Unsupported source image mode: {}'.format(src.mode))
    src.load()

    tr, tg, tb = getrgb(tint)
    tl = getcolor(tint, "L")  # tint color's overall luminosity
    if not tl: tl = 1  # avoid division by zero
    tl = float(tl)  # compute luminosity preserving tint factors
    sr, sg, sb = map(lambda tv: tv/tl, (tr, tg, tb))  # per component adjustments

    # create look-up tables to map luminosity to adjusted tint
    # (using floating-point math only to compute table)
    luts = (map(lambda lr: int(lr*sr + 0.5), range(256)) +
            map(lambda lg: int(lg*sg + 0.5), range(256)) +
            map(lambda lb: int(lb*sb + 0.5), range(256)))
    l = grayscale(src)  # 8-bit luminosity version of whole image
    if Image.getmodebands(src.mode) < 4:
        merge_args = (src.mode, (l, l, l))  # for RGB verion of grayscale
    else:  # include copy of src image's alpha layer
        a = Image.new("L", src.size)
        a.putdata(src.getdata(3))
        merge_args = (src.mode, (l, l, l, a))  # for RGBA verion of grayscale
        luts += range(256)  # for 1:1 mapping of copied alpha values

    return Image.merge(*merge_args).point(luts)

if __name__ == '__main__':
    import os

    input_image_path = 'image1.png'
    print 'tinting "{}"'.format(input_image_path)

    root, ext = os.path.splitext(input_image_path)
    result_image_path = root+'_result'+ext

    print 'creating "{}"'.format(result_image_path)
    result = image_tint(input_image_path, '#33b5e5')
    if os.path.exists(result_image_path):  # delete any previous result file
        os.remove(result_image_path)
    result.save(result_image_path)  # file name's extension determines format

    print 'done'

rawDescription: Colorize image while preserving transparency with PIL?


code:
from bottle import hook

@hook('after_request')
def separator():
    print 3 * "\n",

rawDescription: How can I attach an event/hook to all requests my Bottle app receives?

description: Attach an event/hook to all requests my Bottle app receives


code:
import pandas as pd
import numpy as np

np.random.seed([3, 1415])
df = pd.DataFrame(np.random.rand(10, 3).round(2), columns=['one', 'two', 'three'])

# pandas approach
print df.mul(df).sum().sum()

# numpy approach
print np.square(df.values).sum()

10.9148
10.9148

rawDescription: inner product of a matrix

description: Inner product of a matrix


code:
import csv

print 'Enter file location or press enter for default location.'
aPath = raw_input('> ')  # user path to file
if aPath == '':
    aPath = '/default/path/to/file'  # default path
aFile = raw_input('Enter file name: ')  # user file name
if aFile == '':
    aFile = 'orginal.csv'  # default file name
myCSV = csv.DictReader(open(aPath + aFile, 'r'), delimiter=',')
print myCSV.fieldnames # verify fieldnames

with open("output.csv", "wb") as ofile:
    w = csv.writer(ofile)
    for p in myCSV:
        try:
            p = dict((k, v) for k, v in p.iteritems()
                if v.lower() != 'null')
        except AttributeError, e:
            print e
            print p
            raise Exception()
    # reformats the columns of data for the output.csv
        pID = p.get('Last Name')[-4:]
        pName = p.get('Last Name')[:-4].strip() + ', ' + p.get('First Name')
        pDate = p.get('Start Time')[:-5]
        pBlank = p.get('')
        pCourse = p.get('Assigned Through')
        pScore = p.get('Score')[:-1]

    # verifies the new columns
        print pID, pName, pDate, pBlank, pCourse, pBlank, pBlank, pScore

    # NOT working...Only writes the last row of the orginal.csv to output.csv
        w.writerow([pID, pName, pDate, pBlank, pCourse, pBlank, pBlank, pScore])

rawDescription: In python 2.7 - How to read data from csv, reformat data, and write to new csv


code:
import pypyodbc as pyodbc
import urllib
from xml.dom.minidom import parse, parseString
xmlpath = "example.xml"

cnxn = pyodbc.connect(
    'Trusted_Connection=yes;DRIVER={SQL Server};SERVER=localhost;DATABASE=HOLA;UID=sa;PWD=HOLAMUNDO'
)

idPerson = 2

cursor = cnxn.cursor()
cursor.execute('SELECT id, xml FROM prueba WHERE id=?', (idPerson,))

for row in cursor.fetchall():
    print row[1]

xml = row[1]

#Generate the xml file from the string
dom = parseString(xml)

# Write the new xml file
xml_str = dom.toprettyxml(indent="  ")
with open("example.xml", "w") as f:
    f.write(xml_str)

rawDescription: Python - Convert XML field from SQL SERVER into XML FILE using pyodbc


code:
from PIL import Image
import base64
import pytesseract
import cStringIO

imgstring = 'data: image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGcAAAAVCAYAAABbq/AzAAAACXBIWXMAAA7EAAAOxAGVKw4bAAADiUlEQVRoge3YTWgeVRQG4IcQJJQSQihBNIQiXYUSpJSgIF1IkSKllCJFQggutBQRQRfFH3RTRFwVERdBRHcuREVEupASRIP4C7VoFSmWSq2gtRGjNm21Ls79+k0mM3cmLrpxXhjm++aec973/sy55w4dOnTo0KFDhw4FLOIe3IWrmWtbwWcfLuDhinj7avzvTjyLDXp24F2cxx84gQMVdgfxHVbwFe5tqaEObXxynDCAQ/g2af+8hjM3ftcwIzoPQ5iouObEQG1INvP4PvlVBT+IYxVxhlJ7Vad6GMICHsQkNqWO/I7Zgt1s6twejGEvfhMLrI2GKjT5NHHCs6l/dyTtM8nnzkL/msbvGhbFTOdwDIfT7514GyN4ryb403glE+8JvN/AWcY8Xi/8P45HK+J+0FJDFZp8mjgHxRu1o2TzkH62aDN+YFS8tlMZQdP4S6yCMhZqgr8oVlAdtuFvDGdsyngHL6Xfw0L31pq4Qy00VCHn04bzlmSzsWQznmw2lJ7XjZ8BbMclfJ0R/CRexS8ZmzJGcb/+nnFcrJ6B1P4lroiJb8I4nhGD8FzhGZwu2Z5OHJtbaFiv7jacvTG6qWSzKdmMZbjX4D78kGnfisvYUtNeN/PDYr8Yxo2iCDiH5ws2ZxN/HY7ob8insKvQtj09Hyz5DOkXLm00rEd3G04iZR3Vn8xpkdKuWjtptW+O1HAyI/Y1vJFpzwYvYUakx17nTjb4Dor0MIH9YgPtpZxJ1emjl6YnGzTMWF2NzbTQ3ZZzRKTfc6KIOSoKiMu4oeRbO36DWK4g62GLGJTbM8LXg2/EKtuIpXRfzthfSe3LOJPub+EpkUr+ERNXTMkT6X6mQcObuLnw/NcWuttyLuGBUoxZkcovZXhWYQA/6efDMh7Hh/ikbcAGTCe+Jf38++M6/Iur7k98ZnWqk/5/oX7SexouJu7edbGF7v/KOYBH8HKGoxJjqqu1cVES5g5s1L+Wh3GbyNvjYm+5oH+QnEq8oxW+t4rSfkqkiDHsFmltvmC3R2zcu5LdbnHm2N9SQxWafJo4iYwwIhbTtCiXF1S/AI3bwqfWnnNeEAepJuRK6VOi4vlZnGmKK+4QPq6JuVmcZ86KBXI+2R6wtoNz4iS+Ik7txYFv0lCFNj45TuJguqL/ZeMxa/eaHhonZ07/C8H1wonE26EFPhKfSK4H9ia+Dh06dOjw/8G/sXcmUir28IcAAAAASUVORK5CYII='
imgstring = imgstring.split('base64,')[-1].strip()
pic = cStringIO.StringIO()
image_string = cStringIO.StringIO(base64.b64decode(imgstring))
image = Image.open(image_string)

# Overlay on white background, see http://stackoverflow.com/a/7911663/1703216
bg = Image.new("RGB", image.size, (255,255,255))
bg.paste(image,image)

print pytesseract.image_to_string(bg)

# Save the image passed to pytesseract for debugging purposes
bg.save('pic.png')

rawDescription: pytesseract on base64 string python

description: Pytesseract on base64 string python


code:
@app.route("/upload", methods=["POST"])
def upload():
    uploaded_files = flask.request.files.getlist("file[]")
    print uploaded_files
    return ""

rawDescription: Uploading multiple files with Flask

description: Uploading multiple files with Flask


code:
filename = 'C:\Users\Riemmman\Desktop\SAMPLE_AAPL_DATA_FOR_Python.csv'
with open(filename, 'rb') as datafile:
    datareader = csv.reader(datafile)
    columns = zip(*datareader)

rawDescription: Parsing CSV File into Python into a contigous block


code:
func = "def f():\n"
if config_f1:
    func += " f1()\n"
if config_f2:
    func += " f2()\n"
exec func in globals()

rawDescription: python constructing functions on the fly

description: Python constructing functions on the fly


code:
if args.analysis is not None:
    print args.analysis

if args.barcode is not None:
    print args.barcode

rawDescription: how to pass mutually exclusive argument as a variable

description: Pass mutually exclusive argument as a variable


code:
import sys

from IPython.Shell import IPShellEmbed

class IPShellDoctest(IPShellEmbed):
   def __call__(self, *a, **kw):
       sys_stdout_saved = sys.stdout
       sys.stdout = sys.stderr
       try:
           IPShellEmbed.__call__(self, *a, **kw)
       finally:
           sys.stdout = sys_stdout_saved

def some_function():
  """
  >>> some_function()
  'someoutput'
  """
  # now try to drop into an ipython shell to help
  # with development
  IPShellDoctest()(local_ns=locals())
  return 'someoutput'

if __name__ == '__main__':
  import doctest
  print "Running doctest . . ."
  doctest.testmod()

rawDescription: How to use ipython's IPShellEmbed from within a running doctest

description: Use ipython's IPShellEmbed from within a running doctest


code:
import sys, argparse

def parseCmdLineArgs():
    parser = argparse.ArgumentParser(description='Simple plotting using MayaVi2')
    parser.add_argument('--scale', dest='scale', action='store',help='Sets the axis scaling')
    parser.set_defaults(scale=1.0)
    args = parser.parse_args(sys.argv[1:])
    return args

if __name__ == '__main__':
    args=parseCmdLineArgs()

from mayavi.scripts import mayavi2
from mayavi import mlab

@mayavi2.standalone
def view():
    mayavi.new_scene()
    mlab.test_plot3d()

if __name__ == '__main__':
    print "Scale=%g" % args.scale
    view()

rawDescription: Mayavi2 standalone script with command line arguments


code:
import datetime
import dateutil.relativedelta

dt1 = datetime.datetime.fromtimestamp(123456789) # 1973-11-29 22:33:09
dt2 = datetime.datetime.fromtimestamp(234567890) # 1977-06-07 23:44:50
rd = dateutil.relativedelta.relativedelta (dt2, dt1)

print "%d years, %d months, %d days, %d hours, %d minutes and %d seconds" % (rd.years, rd.months, rd.days, rd.hours, rd.minutes, rd.seconds)
# 3 years, 6 months, 9 days, 1 hours, 11 minutes and 41 seconds

rawDescription: How can I produce a human readable difference when subtracting two UNIX timestamps using Python?

description: Produce a human readable difference when subtracting two UNIX timestamps using Python


code:
def splitter( s, points ):
    c = 0
    for x,y in points:
        yield s[c:x]
        yield "(%s)" % s[x:y+1]
        c=y+1
    yield s[c:]

print list(splitter(str, split_points))
# => ['M', '(SEP)', 'AGD', '(VRQN)', 'P', '(CG)', 'SKAC']

# if some start and endpoints are the same remove empty strings.
print list(x for x in splitter(str, split_points) if x != '')

rawDescription: Given a list of slices, how do I split a sequence by them?


rawDescription: python equivalent of R table

description: Python equivalent of R table


code:
import win32con
import win32gui

def isRealWindow(hWnd):
    '''Return True iff given window is a real Windows application window.'''
    if not win32gui.IsWindowVisible(hWnd):
        return False
    if win32gui.GetParent(hWnd) != 0:
        return False
    hasNoOwner = win32gui.GetWindow(hWnd, win32con.GW_OWNER) == 0
    lExStyle = win32gui.GetWindowLong(hWnd, win32con.GWL_EXSTYLE)
    if (((lExStyle & win32con.WS_EX_TOOLWINDOW) == 0 and hasNoOwner)
      or ((lExStyle & win32con.WS_EX_APPWINDOW != 0) and not hasNoOwner)):
        if win32gui.GetWindowText(hWnd):
            return True
    return False

def getWindowSizes():
    '''
    Return a list of tuples (handler, (width, height)) for each real window.
    '''
    def callback(hWnd, windows):
        if not isRealWindow(hWnd):
            return
        rect = win32gui.GetWindowRect(hWnd)
        windows.append((hWnd, (rect[2] - rect[0], rect[3] - rect[1])))
    windows = []
    win32gui.EnumWindows(callback, windows)
    return windows

for win in getWindowSizes():
    print win

rawDescription: Get other running processes window sizes in Python


code:
class MC(type):
  def __rshift__(self, other):
    return something(self, other)

class C(object):
  __metaclass__ = MC

print C >> None

rawDescription: Can an operator be overloaded as a class method in python?


code:
from lxml import etree

data = """
<Items>
    <Name>Hello</Name>
    <Cost>9.99</Cost>
    <Condition/>
</Items>
"""

root = etree.fromstring(data)
for element in root.xpath(".//*[not(node())]"):
    element.getparent().remove(element)

print etree.tostring(root, pretty_print=True)

rawDescription: Clean xml ==> Remove line if any empty tags


code:
#!/usr/bin/env python
import sys
from scapy import *
conf.verb=0

if len(sys.argv) != 4:
    print "Usage: ./spoof.py <target> <spoofed_ip> <port>"
    sys.exit(1)

target = sys.argv[1]
spoofed_ip = sys.argv[2]
port = int(sys.argv[3])

p1=IP(dst=target,src=spoofed_ip)/TCP(dport=port,sport=5000,flags='S')
send(p1)
print "Okay, SYN sent. Enter the sniffed sequence number now: "

seq=sys.stdin.readline()
print "Okay, using sequence number " + seq

seq=int(seq[:-1])
p2=IP(dst=target,src=spoofed_ip)/TCP(dport=port,sport=5000,flags='A',
                                     ack=seq+1,seq=1)
send(p2)

print "Okay, final ACK sent. Check netstat on your target :-)"

rawDescription: Is there a Python library than can simulate network traffic from different addresses


code:
# list_a and list_b contain two different mappings between integer numbers
for line in file:
  words = re.findall("(\s*\S+)", line)
  a = int(words[0])
  b = int(words[5])
  c = list_a[a]
  d = list_b[b]
  modline = str(c).rjust(len(words[0])) + "".join(words[1:5]) + str(d).rjust(len(words[5])) + "".join(words[6:])
  print modline

rawDescription: Replace numbers of varying length in a string


code:
from nltk.tokenize.stanford import StanfordTokenizer
token = StanfordTokenizer('stanford-ner-2014-06-16/stanford-ner.jar')
qry="In the UK, the class is relatively crowded with Zacc competing with Abc's Popol (market leader) and  Xyz's Abcvd."
tok = token.tokenize(qry)
print tok

rawDescription: How to clean sentences for StanfordNER

description: Clean sentences for StanfordNER


code:
import re
print re.subn('Co$','',"Company & Co")

rawDescription: How to use regular expressions to only capture a word by itself rather than in another word?

description: Use regular expressions to only capture a word by itself rather than in another word


code:
from threading import Thread
from Queue import Queue
from win32com.client import Dispatch
import pythoncom
import time

class IEThread(Thread):
    def __init__(self):
        Thread.__init__(self)
        self.queue = Queue()

    def run(self):
        ie = None
        # as IE Com object will be used in thread, do CoInitialize
        pythoncom.CoInitialize()
        try:
            ie = Dispatch("InternetExplorer.Application")
            ie.Visible = 1
            while 1:
                url = self.queue.get()
                print "Visiting...",url
                ie.Navigate(url)
                while ie.Busy:
                    time.sleep(0.1)
        except Exception,e:
            print "Error in IEThread:",e

        if ie is not None:
            ie.Quit()

ieThread = IEThread()
ieThread.start()
while 1:
    url = raw_input("enter url to visit:")
    if url == 'q':
        break
    ieThread.queue.put(url)

rawDescription: How to close not responsive Win32 Internet Explorer COM interface?

description: Close not responsive Win32 Internet Explorer COM interface


code:
import socket, select
s1 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s1.bind(('0.0.0.0', 1337))
s2 = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_UDP)
s2.bind(('0.0.0.0', 1337))
while True:
    r, w, x = select.select([s1, s2], [], [])
    for i in r:
        print i, i.recvfrom(131072)

rawDescription: Python raw socket listening for UDP packets; only half of the packets received


code:
def interpreter1():
        b=que2.get(block=True)
        a=que1.get(block=True)
        print "prameters are :" ,a ,b ,"\r\n"
        c='python C:\\workspace\\Project_Interpreter\\Tool-v1.0.py -s %s %s'%(b,a)
        startupinfo = subprocess.STARTUPINFO()
        startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
        ps=sp.Popen(['cmd','/K',c] , creationflags=0, shell=False, startupinfo=startupinfo, stdout=PIPE, stderr=sp.STDOUT, stdin=PIPE)
        texte01= ps.stdout.readlines()

rawDescription: python script only works when I close the console

description: Python script only works when I close the console


code:
class FourVector:
    def __init__(self, ct = 0, x = 0, y = 0, z = 0, r = None):
        self.a = (ct, x, y, z)
        if r is not None:
            self.a = (ct, r[0], r[1], r[2])

P0 = FourVector()
print P0.a

P1 = FourVector(ct = 9, x = 1, y = 2, z = 4)
print P1.a

P2 = FourVector(ct = 99.9, r = [1, 2, 4])
print P2.a

rawDescription: Using __init__ to create a class for four vectors


code:
from selenium.webdriver.common.by import By

# max records textfield has the value 1,000.000 as default
def print_maxrecords_textfield(self):
    max_records_textfield = self.driver.find_element((By.XPATH, '//span[@class="gwt-InlineLabel myinlineblock marginbelow" and contains(text(), "Max records")]/following-sibling::*'))
    print "max_records_textfield = "
    print max_records_textfield.get_attribute('value')

rawDescription: Python Selenium print out value of textfield is showing empty. The value is not printing


code:
import csv
from datetime import datetime

with open(filename, 'rb') as infile:
    reader = csv.DictReader(infile)
    for row in reader:
         birthdate = row['Birthdate']  # keys are named in the first row of your CSV
         birthdate = datetime.strptime(birthdate, '%m-%d-%Y %H:%M:%S')
         print birthdate.strftime('%A')

rawDescription: Python: how to get the weekday from a CSV?


code:
numbers = []

while len(numbers) < 5:
    number = raw_input('Please input 5 numbers: ')
    if number.isdigit():
        numbers.append(int(number)) #may want to use float here instead of int
    else:
        print "You entered something that isn't a number"

search = raw_input('Search for the numer: ')
if int(search) in numbers:
    print "Found it!"

rawDescription: Python searching list thats inputted by user


code:
import time
from threading import Thread # This is the right package name

class UpdateThread(Thread):
    def __init__(self):
        self.stopped = False
        Thread.__init__(self) # Call the super construcor (Thread's one)
    def run(self):
        while not self.stopped:
            self.downloadValue()
            time.sleep(15)
    def downloadValue(self):
        print "Hello"

myThread = UpdateThread()
myThread.start()

for i in range(10):
    print "MainThread"
    time.sleep(2)

rawDescription: Repeat function at an interval?

description: Repeat function at an interval


code:
def getText(nodelist):
    rc = []
    for outer in nodelist:
        for node in outer.childNodes:
            if node.nodeType == node.TEXT_NODE:
                rc.append(node.data)
            else:
                print "not text: "+ node.toxml()

    return ''.join(rc)

rawDescription: Accessing python minidom node data

description: Accessing python minidom node data


code: print [x.strip() for x in re.findall('<textarea.*?>(.*)</textarea>', content, re.MULTILINE | re.DOTALL)]

rawDescription: How to extract text from between html tag using Regular Expressions?

description: Extract text from between html tag using Regular Expressions


code:
# "Stateless"
for line in stdin:
    res = compute_1(line) + compute_2(line) + compute_3(line)
    print res, line

# "Shared" state
for line in stdin:
    res = compute_1(line)
    res = compute_2(line, res)
    res = compute_3(line, res)
    print res, line

rawDescription: Is it possible to avoid locking overhead when sharing dicts between threads in Python?


code:
a = ('id', ('name', ('name_float_fml',)), ('user', ('email',)), ('user', ('last_login',)))
b = (('baz', ('bing', ('fizz', 'frozz',('frazz', ('fry', 'bleep', 'blop'))))), ('baz', ('zap', ('zang',))), 'foo', 'bar')

def preserve_path(value):
    if len(value) == 2 and isinstance(value[1], (list, tuple)):
        return [value]
    else:
        return value

def flatten_group(my_list):
    d = {}
    for item in my_list:
        # Only items with one string, followed by one tuple represent a path
        # segment. In all other situations, strings are leaves.
        if isinstance(item, (list, tuple)) and len(item) == 2:
            key, value = item
            if key in d:
                d[key].extend(flatten_group(preserve_path(value)))
            else:
                d[key] = preserve_path(list(flatten_group(value)))
        else:
            yield item

    for item in d.iteritems():
        yield item

print list(flatten_group(a))
# ['id', ('name', ['name_float_fml']), ('user', ['email', 'last_login'])]
print list(flatten_group(b))
# ['foo', 'bar', ('baz', [['bing', ('fizz', 'frozz', ('frazz', ('fry', 'bleep', 'blop')))], ('zap', ['zang'])])]

rawDescription: How to merge nested tuples

description: Merge nested tuples


code:
import logging
def force_decode(string, codecs=['utf8', 'cp1252']):
    for i in codecs:
        try:
            return string.decode(i)
        except:
            pass

    logging.warn("cannot decode url %s" % ([string]))

for item in os.listdir(rootPath):
    #Convert to Unicode
    if isinstance(item, str):
        item = force_decode(item)
    print item

rawDescription: Python detect string byte encoding

description: Python detect string byte encoding


code:
with open("d:/aaa.csv", "rb") as input_file:
    reader = csv.DictReader(input_file)
    for row in reader:
        row = {k: converters[k](v) for k, v in row.items()}
        print row

rawDescription: Is there a strongly typed csv reader in python?


code:
import textwrap
class Album(object):
    def __init__(self, title, artist, tracks, length, bitrate, md5):
        self.title=title
        self.artist=artist
        self.tracks=tracks
        self.length=length
        self.bitrate=bitrate
        self.md5=md5
    def __str__(self):
        return textwrap.dedent("""
        %(artist)s;
        %(title)s;
                      %(tracks)s - %(length)s - %(bitrate)s - %(md5)s"""%(vars(self)))

a=Album("album title","artist name",10,52.1,"320kb/s","4d53b0cb432ec371ca93ea30b62521d9")
print a

rawDescription: Formatting an output file

description: Formatting an output file


code:
for i in final:
   if i.count('T') and len(i) > i.index('T') and i[i.index('T')+1] == 'D':
       print 1
   else:
       print 0

rawDescription: Python searching patterns in For Loop

description: Python searching patterns in For Loop


code:
for p, r, s in itertools.product(prefix, roots, suffix):
    print p, r, s

rawDescription: Find all possible combinations

description: Find all possible combinations


code:
FRAME_SIZE = 10000

def gen_lines(filename):
    with open(filename, "r") as fp:
        for line in fp:
            yield line[:-1]

def gen_frames(lines):
    count = 0
    frame = []

    for line in lines:
        if count < FRAME_SIZE:
            frame.append(line)
            count += 1

        if count == FRAME_SIZE:
            yield frame
            frame = []
            count = 0

    if count > 0:
        yield frame

def process_frames(frames):
    for frame in frames:
        # do stuff with frame
        print len(frame)

lines = gen_lines("/path/to/input.file")
frames = gen_frames(lines)
process_frames(frames)

rawDescription: data processing pipeline python

description: Data processing pipeline python


code:
import math
from decimal import Decimal

def s(x):
    return (Decimal(0.298**k))/ Decimal(math.factorial(k))

prevSK = 0
sum=0
valueList = {}
for k in (range(0,501)):

    try:
        a = (round(s(k),5))
        r = (round(s(k)/prevSK,5))
        print "a{n}: {a}".format(n=k, a=a)
        print "r{n}: {r}".format(n=k, r=r)
        valueList[k] = {"a{n}".format(n=k) : a, "r{n}".format(n=k) : r}
        prevSK = s(k)
        summa = sum=sum+a
    except Exception, e:
        print e
        prevSK = (Decimal(s(k),))

    continue

print "The sum is:", summa

rawDescription: labeling, numbering loop elements + summing them up

description: Labeling, numbering loop elements + summing them up


code:
import fileinput
import re
from time import strptime

f_names = ['1.log', '2.log'] # names of log files
lines = list(fileinput.input(f_names))
t_fmt = '%a %b %d %H:%M:%S %Y' # format of time stamps
t_pat = re.compile(r'\[(.+?)\]') # pattern to extract timestamp
for l in sorted(lines, key=lambda l: strptime(t_pat.search(l).group(1), t_fmt)):
    print l,

rawDescription: Merging and sorting log files in Python

description: Merging and sorting log files in Python


code:
import re

for s in reversed(re.findall('abcd.', 'abcd1_abcd2')):
    print s

rawDescription: about python regular expression match from right direction

description: About python regular expression match from right direction


code: re.sub(ur"§|a|á|Á", u"_", u"Halo §Ásdf")

rawDescription: Regex with unicode in Python

description: Regex with unicode in Python


code:
#!/usr/bin/env python
import SimpleHTTPServer
import SocketServer
import subprocess
import uuid

class MyRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
    def do_POST(self):
        print 'in do_POST'
        uuid_gen = str(uuid.uuid1())
        subprocess.Popen(['python', 'sleep.py'])
        print 'subprocess spawned'
        self.send_response(200)
        self.send_header("Content-Length", str(len(uuid_gen)))
        self.end_headers()
        self.wfile.write(uuid_gen)

Handler = MyRequestHandler

server = SocketServer.TCPServer(('127.0.0.1', 9019), Handler)

server.serve_forever()

rawDescription: Why does subprocess.Popen block the response of SimpleHTTPServer.SimpleHTTPRequestHandler


code:
import urllib,MultipartPostHandler,urllib2,cookielib
cookies = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookies),MultipartPostHandler.MultipartPostHandler)
urllib2.install_opener(opener)
login = urllib.urlencode(dict(admin_user='admin',admin_pass='****'))
o=opener.open('http://some_domain_name.com/admin/index.php',login)
print o.read()
raw_params={"adtitle":"sample title",
        "area":"sample area",
        "addesc":"
sample post
",
    "pic[0]":open("indian_eye.jpg", "rb"), #File Goes Here
    "pic[1]":open("nature.jpg", "rb"),
        "subcatid":"1",
    "do":"post",
        }
url="http://YOUR.php?cityid=15&subcatid=1"
opener.open(url, raw_params)

rawDescription: Send file to remote php from local python in $_FILES


code:
import os
print os.path.dirname(os.path.abspath(__file__))

rawDescription: Store user defined data after inputted

description: Store user defined data after inputted


code:
import time
import datetime
import calendar

TIME_FORMAT = '%Y-%m-%d %H:%M:%S'

def local_datetime_2_timestamp(local_datetime):
    '''strptime takes local datetime as parameter'''
    timestamp = str(time.mktime(datetime.datetime.
        strptime(local_datetime, TIME_FORMAT).timetuple()))[:-2]
    return timestamp

def utc_2_timestamp(utc_datetime):
    '''timegm takes UTC time as parameter'''
    return calendar.timegm(utc_datetime.timetuple())

print local_datetime_2_timestamp("2016-03-10 00:06:21.903".split(".")[0])
print utc_2_timestamp(datetime.datetime(2016,3,10,0,6,21))

rawDescription: Difference between epoch time and normal date in seconds - python


code:
def curry(x, argc=None):
    if argc is None:
        argc = x.func_code.co_argcount
    def p(*a):
        if len(a) == argc:
            return x(*a)
        def q(*b):
            return x(*(a + b))
        return curry(q, argc - len(a))
    return p

@curry
def myfun(a,b,c):
    print '%d-%d-%d' % (a,b,c)

myfun(11,22,33)
myfun(44,55)(66)
myfun(77)(88)(99)

rawDescription: Currying decorator in python

description: Currying decorator in python


code:
for line in open('basin_stclair.txt', 'U'):
    print line[0:64]

rawDescription: Extracting a substring makes the for loop break in python


code:
import errno
import fnmatch
import os
import re
import shutil
import tarfile

cwd = os.getcwd()
REPO = os.path.join(cwd, "repo")

def find(directory, pattern):
    for root, dirnames, filenames in os.walk(directory):
        for fn in filenames:
            if fnmatch.fnmatch(fn.lower(), pattern.lower()):
                yield os.path.join(root, fn)

def mkdir_p(path):
    try:
        os.makedirs(path)
    except OSError as exc:
        if exc.errno == errno.EEXIST and os.path.isdir(path):
            pass
        else:
            raise

def mv(src, dst):
    try:
        shutil.move(src, dst)
    except shutil.Error, e:
        print "%s, moving on" % e

def matching_tif_files(members):
    pattern = re.compile(r'.*B[4568].tif', re.I)
    for tarinfo in members:
        if pattern.match(tarinfo.name):
            print "Extracting %s" % tarinfo.name
            yield tarinfo

targz_files = find(cwd, '*.tgz')

for tgz in targz_files:
    print tgz
    with tarfile.open(tgz) as tar:
        tar.extractall(path=REPO, members=matching_tif_files(tar))

b4 = os.path.join(cwd, 'Band_4')
b5 = os.path.join(cwd, 'Band_5')

mkdir_p(b4)
mkdir_p(b5)

b4_tifs = find(cwd, '*B4.tif')
for tif in b4_tifs:
    mv(tif, b4)

b5_tifs = find(cwd, '*B5.tif')
for tif in b5_tifs:
    mv(tif, b5)

rawDescription: Python script using Linux commands, does not run on Windows. Is there any way to make it OS agnostic?


code:
x = 'a and (b and c) and d or e and (f or g)'
import re

matches = re.findall(r'\(.*?\)|\w+', x)
print ','.join(matches)

rawDescription: Parse boolean arithmetic including parentheses with regex?


code:
import threading
import time

master_wish = True # global variable

def kill_all_demons(demon):
    while True:
        print "killing %s\n" % demon
        if not master_wish:
            return

def van_helsing():
    print "Yes Master your wish is my command"
    t1 = threading.Thread(target=kill_all_demons, args=('Dracula',))
    t2 = threading.Thread(target=kill_all_demons, args=('Wolf',))
    t1.start()
    t2.start()

def other_func():
    global master_wish
    master_wish = False
    print("good will prevail over evil")

van_helsing()
time.sleep(10)
other_func()

rawDescription: Threading in python, need help to make the program wait based on a condition on another function


rawDescription: Python: Count and Remove duplicates in the list of list


code:
import csv
from itertools import chain

with open('path/to/your/file.csv', 'rb') as csvfile:
  tmp = (r['PIN'].split('&') for r in csv.DictReader(csvfile, delimiter='|'))
  pins = list(chain.from_iterable(tmp))

for pin in pins:
    print pin

rawDescription: Get a string in the last column using Python


code:
from BeautifulSoup import BeautifulSoup

VALID_TAGS = ['div', 'p']

soup = BeautifulSoup(value)

for tag in soup.findAll('p'):
    if tag.name not in VALID_TAGS:
        tag.replaceWith(tag.renderContents())

print soup.renderContents()

rawDescription: How to find all text inside <p> elements in an HTML page using BeautifulSoup

description: Find all text inside <p> elements in an HTML page using BeautifulSoup


code:
if set(list2) & set(list1):
   print "there is something in list2 that matches something in list1"

print "The days in list2 are", set(list2) & set(list1)

rawDescription: Inline for loop Python. Checking every member of a list to another list inline


code:
import sys
from collections import defaultdict
from multiprocessing import Pool, Queue
import re

GLOBAL_CONCORDANCE = defaultdict(lambda: defaultdict(lambda: defaultdict(list)))

def concordance_worker(index_sentence):
    sent_index, sentence = index_sentence
    words = sentence.split()

    return [(word, colo_word, colo_index, sent_index)
            for i, word in enumerate(words)
            for colo_index, colo_word in enumerate(words[i:])]

def build_concordance(sentences):
    global GLOBAL_CONCORDANCE
    pool = Pool(8)

    results = pool.map(concordance_worker, enumerate(sentences))

    for result in results:
        for word, colo_word, colo_index, sent_index in result:
            GLOBAL_CONCORDANCE[word][colo_word][colo_index].append(sent_index)

    print len(GLOBAL_CONCORDANCE)

def main():
    sentences = ["Sentence 1", "Sentence 2", "Sentence 3", "Sentence 4"]
    build_concordance(sentences)

if __name__ == "__main__":
    main()

rawDescription: How can I parallelize this word counting function?

description: Parallelize this word counting function


code:
from matplotlib import pyplot as plt
# make a square figure and axes
plt.figure(figsize=(6,6))
ax = plt.axes([0.1, 0.1, 0.8, 0.8])

labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
fracs = [15,30,45, 10]

explode=(0, 0.05, 0, 0)
p = plt.pie(fracs, explode=explode, labels=labels, autopct='%1.1f%%', shadow=True)
plt.title('Raining Hogs and Dogs', bbox={'facecolor':'0.8', 'pad':5})

w = p[0][0]
plt.show()

class PieEventHandler:
    def __init__(self,p):
        self.p = p
        self.fig = p[0].figure
        self.ax = p[0].axes
        self.fig.canvas.mpl_connect('button_press_event', self.onpress)

    def onpress(self, event):
        if event.inaxes!=self.ax:
            return

        for w in self.p:
            (hit,_) = w.contains(event)
            if hit:
                print w.get_label()

handler = PieEventHandler(p[0])

rawDescription: matplotlib mouseclick event in pie chart

description: Matplotlib mouseclick event in pie chart


code:
from lxml import etree

xmlschema_doc = etree.parse('schema.xsd')
xml_doc = etree.parse('my.xml')
xmlschema = etree.XMLSchema(xmlschema_doc)

if xmlschema.validate(xml_doc):
   print 'Valid xml'
else:
   print 'Invalid xml'

rawDescription: Python xml.dom.minidom schema validation


code:
import csv
inp = csv.reader(open("/tmp/HSN.csv", "r"), delimiter = ',')
for line in inp:
    a = (line[0]) #street name column
    b = int(line[1]) #first house number column
    c = int(line[2]) #last house number column
    for d in range(b, c+1):
        print a, d

rawDescription: Python: printing ranges for each row

description: Python: printing ranges for each row


code:
from sklearn.feature_extraction.text import CountVectorizer
from nltk.stem import SnowballStemmer

list2 = ["rain", "raining", "rainy", "rainful", "rains", "raining!", "rain?"]

def preprocessor(data):
        return " ".join([SnowballStemmer("english").stem(word) for word in data.split()])

vectorizer = CountVectorizer(preprocessor=preprocessor).fit(list2)
print vectorizer.vocabulary_

# Should print this:
# {'raining': 2, 'raini': 1, 'rain': 0}

rawDescription: Bag of words representation using sklearn plus Snowballstemmer


code:
from random import randrange
area_code = "240"
print "Your new phone number is ({}) {}{}{}-{}{}{}{}".format(area_code, *[randrange(10) for i in range(7)])

rawDescription: I'm trying to write a program that generates a PHONE NUMBER using Python


code:
import paramiko, base64
import StringIO
import os

key = paramiko.RSAKey.from_private_key(StringIO.StringIO(str(os.environ.get("AWS_PRIVATE_KEY"))))
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(str(os.environ.get("EC2_PUBLIC_DNS")), username='ec2-user', pkey=key)
stdin, stdout, stderr = ssh.exec_command('ps')

for line in stdout:
    print '... ' + line.strip('\n')
ssh.close()

rawDescription: How to store private key on Heroku?

description: Store private key on Heroku


code:
import socket, sys

HOST = 'localhost'        # The remote host
PORT = 50007              # The same port as used by the server

recvbuff = bytearray(16)
recvview = memoryview(recvbuff)

size = 0

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
while True:
    nbytes = s.recv_into(recvview)
    if not nbytes:
        break
    size += nbytes
    recvview = recvview[nbytes:]
    if not len(recvview):
        print "filled a chunk", recvbuff
        recvview = memoryview(recvbuff)

print 'end of data', recvbuff[:len(recvview)], size

s.close()

rawDescription: Reusing Python Bytearray/Memoryview

description: Reusing Python Bytearray/Memoryview


code:
from datetime import datetime

date_strs = ['07-06-2010', '06-24-2010', '07-05-2010', '06-25-2010']
# date_strs = ['02-29-2012', '02-28-2012', '03-01-2012']
# date_strs = ['01-01-2000']
dates = [datetime.strptime(d, "%m-%d-%Y") for d in date_strs]

date_ints = set([d.toordinal() for d in dates])

if len(date_ints) == 1:
    print "unique"
elif max(date_ints) - min(date_ints) == len(date_ints) - 1:
    print "consecutive"
else:
    print "not consecutive"

rawDescription: How to detect if dates are consecutive in Python?

description: Detect if dates are consecutive in Python


code:
import re
s = 'Now is 20m before 10h'
rgx = re.compile(r'[0-9]+[hms](?= *before)')
print rgx.findall(s) # ['20m']

rawDescription: Python: how to separate certain number-text combination from string?


code:
class Derived(Base):
    @property
    def member(self):
        print "intercepting getter"
        return self._member

    @member.setter
    def member(self, value):
        print "intercepting setter"
        self._member = value

rawDescription: How do I override a field in a base class with a property in a derived class?

description: Override a field in a base class with a property in a derived class


code:
from ctypes import *
STD_OUTPUT_HANDLE_ID = c_ulong(0xfffffff5)
windll.Kernel32.GetStdHandle.restype = c_ulong
std_output_hdl = windll.Kernel32.GetStdHandle(STD_OUTPUT_HANDLE_ID)
for color in xrange(16):
    windll.Kernel32.SetConsoleTextAttribute(std_output_hdl, color)
    print "hello"

rawDescription: How do I use colour with Windows command prompt using Python?

description: Use colour with Windows command prompt using Python


code:
infile = open(source,'r')

file_contents_lines = infile.readlines()

for line in file_contents_lines:
    print line

rawDescription: How to read and divide individual lines of a file in python?

description: Read and divide individual lines of a file in python


code:
child = subprocess.Popen(whatever, stdout=subprocess.PIPE)
for line in child.stdout:
  print "One more line:", line

rawDescription: Python popen wont work with block devices


code:
import sys
stdout = sys.stdout
import StringIO
s = StringIO.StringIO()
sys.stdout = s
print "hello"
sys.stdout = stdout
s.seek(0)
s.read()

rawDescription: python: getting output from `print` inside a function

description: Python: getting output from `print` inside a function


code:
a= 6500
b= 3600
c=.000900
from __future__ import division
print b/a - c

rawDescription: Formatting a string to microseconds

description: Formatting a string to microseconds


code:
with open("/tmp/blip.txt") as f:
    for line in f:
        if line.startswith("test:"):
            test_name = line.strip().split(None, 1)[1]
            result = next(f)
            if not result.startswith("outcome:"):
                raise ValueError("Test name not followed by outcome for test "+test_name)
            outcome = result.strip().split(None, 1)[1]
            print test_name, outcome

rawDescription: writing the data in text file while converting it to csv

description: Writing the data in text file while converting it to csv


code:
csv_str = """X,,,
X,A,,
X,A,R,
X,A,R,X
X,A,R,Y
X,B,,
X,B,S,
X,B,S,X
"""

reader = csv.reader(StringIO.StringIO(csv_str))

idx = 0
data = []

for row in reader:
    # insert the row id
    row.insert(0, idx + 1)

    # insert a dummy parent id, it will be replaced with the real
    # value later
    row.insert(1, -1)

    # how deep is the current row
    depth = len([r for r in row if r is not ''])
    # insert the depth as the last value in the row
    row.append(depth)

    if idx > 0:
        # if it's not the first row, calculate it's parent

        # calculate the depth of the previous row
        prev_depth = data[idx - 1][-1]
        if depth > prev_depth:
            # if it's deeper than the previous row, then the previous
            # row is the parent row
            row[1] = data[idx - 1][0]
        elif depth == prev_depth:
            # if it's the same depth as the previous row then it has
            # the same parent as the previous row
            row[1] = data[idx - 1][3]
        else:
            # if it's shallower than the previos row, find the
            # nearest previous row with the same depth and use it's
            # parent as this row's parent.
            ridx = idx - 1
            while (prev_depth != depth and ridx >= 0):
                prev_depth = data[ridx - 1][-1]
                ridx -= 1
            row[1] = data[ridx - 1][0]
    else:
        # if it's the first row it's parent is 0
        row[1] = 0

    # store the new row
    data.append(row)
    idx += 1

# write the CSV
output = StringIO.StringIO()
writer = csv.writer(output)
for row in data:
    # skip the depth value in each row
    writer.writerow(row[:-1])

print output.getvalue()

rawDescription: Insert parent id for csv data

description: Insert parent id for csv data


code:
with open('coords.txt') as f:
    count = 1
    while True:
        for line in f:
            print 'val: {}'.format(count)
            c1, c2 = map(float, line.split(','))
            print("c1 = {!r}".format(c1))
            if count == 2:
                break
            count += 1
        break

rawDescription: Reading numbers in python

description: Reading numbers in python


code:
class TestThreadPoolWin(QtGui.QMainWindow):
    def __init__(self,  parent=rsui.getMayaMainWindow()):
        ''' Constructor '''
        super(TestThreadPoolWin, self).__init__(parent)

        self.setWindowTitle('Test Threading')

        self.centralWidget = QtGui.QPlainTextEdit()
        self.setCentralWidget(self.centralWidget)

        self.centralWidget.appendPlainText("test")

        numThreads = 7
        threadPool = QtCore.QThreadPool.globalInstance()
        for i in range(numThreads):
            runnable = TestRunnableWorker(i)
            runnable.finishedProcessing.connect(self.updateStuff)
            threadPool.start(runnable)

        print 'done creating all threads'

    def updateStuff(self, message):
        self.centralWidget.appendPlainText(message)

class TestRunnableWorker(QtCore.QObject, QtCore.QRunnable):
    finishedProcessing = QtCore.Signal(str)

    def __init__(self, num, parent=None):
        # Be sure to run the __init__ of both parent classes, or else you will
        # get a crash.
        QtCore.QObject.__init__(self, parent)
        QtCore.QRunnable.__init__(self)

        self._num = num

    def run(self):
        time.sleep(1)
        choiceList = ['cat', 'bat', 'hat', 'tissue', 'paper', 'qwerty', 'mouse']
        stuff = random.choice(choiceList)
        stuff2 = '{0} {1}'.format(self._num, stuff)
        self.finishedProcessing.emit(stuff2)

def openThreadPoolWin():
    '''This ensures that only one instance of the UI is open at a time.'''

    global testingThreadPoolWin
    try:
        testingThreadPoolWin.close()
        testingThreadPoolWin.deleteLater()
    except: pass
    testingThreadPoolWin = TestThreadPoolWin()
    testingThreadPoolWin.show()

rawDescription: Multiple QThread keep crashing PySide

description: Multiple QThread keep crashing PySide


code:
list_ = [1, 2, 3, 4, 5] #or range(1, 6)
squares = [x*x for x in list_]
print squares
#[1, 4, 9, 16, 25]

rawDescription: What does "masterlist = [row for row in c2]" syntax mean where masterlist and c2 are variable names


code:
x=3

for combination in itertools.combinations(files, x):
  counter = counter + 1
  output = " and ".join(combination)
  print output, counter

rawDescription: python itertools combination scalability

description: Python itertools combination scalability


code:
for page in pages:
    url = "http://company.com/" + page
    page = urllib2.urlopen(url)
    soup = BeautifulSoup(page.read())
    page_title = soup.find_all("title") #This will return a list of titles
    for title in page_title:
        if title != "<title>Nil</title>":
            print title

rawDescription: Using Python: excluding certain outputs (webpage titles)


code:
from decimal import Decimal

def number2string(a):
    b = format(Decimal(str(a)).normalize(), 'f')
    print a,"->",b

rawDescription: Python any number to non-scientific string


code:
def uniq_perms(a, b, c):
    if a < 0 or b < 0 or c < 0:
        return
    if a + b + c == 0:
        yield []
    for s in uniq_perms(a - 1, b, c):
        yield [0] + s
    for s in uniq_perms(a, b - 1, c):
        yield [1] + s
    for s in uniq_perms(a, b, c - 1):
        yield [-1] + s

for s in uniq_perms(2, 1, 1):
    print s

rawDescription: Iterate over lists with a certain number of 1s, 0s and -1s


code:
def euler(h, t, y, f):
    return (y + h*v for y,v in zip(y,f(t,y)))

def f1(t,status):
    x, = status
    return -2*t*x,

def f2(t,status):
    x, y = status
    return x - t*y, y + x/t

print list(euler(0.01, 1, (1,2), f2))
print list(euler(0.01, 1, (1,), f1))

rawDescription: Transparently handling a numeric type as a single-valued sequence (or vice-versa)


code:
if __name__ == '__main__':
  X, y = generate_dataset()
  print X[:20, :]
  X_transformed, y_transformed = drop_first_component(X, y)
  print X_transformed[:20, :]

rawDescription: Scikit-Learn FunctionTransformer in pipeline with no other functionality - not returning original data?


code:
import pandas as pd
df1 = pd.DataFrame({'A': ['A0', 'A1', 'A2', 'A3'],
                    'B': ['B0', 'B1', 'B2', 'B3'],
                    'C': ['C0', 'C1', 'C2', 'C3'],
                    'D': ['D0', 'D1', 'D2', 'D3']},
                    index=[0, 1, 2, 3])

df2 = pd.DataFrame({'X': ['A4', 'A5', 'A6', 'A7'],
                    'XB': ['B4', 'B5', 'B6', 'B7'],
                    'XC': ['C4', 'C5', 'C6', 'C7'],
                    'XD': ['D4', 'D5', 'D6', 'D7']},
                     index=[4, 5, 6, 7])

df3 = pd.DataFrame({'YA': ['A8', 'A9', 'A10', 'A11'],
                    'YB': ['B8', 'B9', 'B10', 'B11'],
                    'YC': ['C8', 'C9', 'C10', 'C11'],
                    'YD': ['D8', 'D9', 'D10', 'D11']},
                    index=[8, 9, 10, 11])

#To get the desired result you are looking for you need to reset the index.
#With the dataframes you have you may not be able to merge as well
#Since merge would need a common index or column
frames = [df1.reset_index(drop=True), df2.reset_index(drop=True), df3.reset_index(drop=True)]

df4 = pd.concat(frames, axis=1)

print df4

rawDescription: Pandas dataframe add columns with automatic adding missing indices


code:
import __builtin__
class MyClass:
    def __init__(self):
        self.a = [2]
        __builtin__.a = self.a
myclass = MyClass()
myclass.a[0] = 4
a[0] = 2
print a
print myclass.a

rawDescription: making __builtin__'s from your class attributes?

description: Making __builtin__'s from your class attributes


code:
def Runner():
    Lists = []
    for G in range(someRange):
        Lists[G] = []
        Lists[G].append(G*500000 or whatever)
        print Lists[G]
        #This way, you have Lists[0], Lists[1], ..., Lists[someRange]

rawDescription: How to create a function in Python that makes objects (i.e lists)

description: Create a function in Python that makes objects (i.e lists)


code:
chained = 0
finished = 0

# home() and club() act as rooms in the game
def home():
    global chained,current_room
    if chained == 1:
        # there's a way to unchain yourself that works
        chained = 0
    if chained == 0:
        print 'your are in the room'
        input = raw_input('> ')
        if 'exit' in input or 'leave' in input or 'club' in input:
            current_room = 'club'
            club()

# Not sure if finished is a local or global variable
def club():
    global finished,current_room
    print "this is messy code!!"
# These sort of move you around the rooms.
# current_room keeps track of what room you're in
    current_room = 'home'
    if finished == 0:
        if current_room == 'home':
            home()
        if current_room == 'club':
            club()
home()

rawDescription: Can't break out of a while loop

description: Can't break out of a while loop


code:
import numpy as np

dtype=[('name', object), ('score', int)]
data = np.loadtxt('nouns.txt', delimiter=',', dtype=dtype)
data.sort(order='score')
print data

rawDescription: How to order an external list in python

description: Order an external list in python


code:
import urllib
import json

serviceurl = 'http://python-data.dr-chuck.net/geojson'

while True:
    address = raw_input('Enter location: ')
    if len(address) < 1 : break

    url = serviceurl + '?' + urllib.urlencode({'sensor':'false', 'address':  address})
    print 'Retrieving', url
    uh = urllib.urlopen(url)
    data = uh.read()
    print 'Retrieved',len(data),'characters'

    try: js = json.loads(str(data))
    except: js = None
    if 'status' not in js or js['status'] != 'OK':
        print '==== Failure To Retrieve ===='
        print data
        continue
    #print json.dumps(js, indent=4) # commented out to stop filling my screen with place names - easily put back in
    placeid = js['results'][0]['place_id']

    print "Place ID: ", placeid
    print placeid
    print address    # location not defined

rawDescription: Python JSON cant pull out and print textual identifier


code:
suits = {'queen': 2, 'jack': 1, 'king': 2}
l = ['queen','jack','king']
print sorted(l, key=suits.get)

rawDescription: sorting strings based on your own values in python

description: Sorting strings based on your own values in python


code:
import os
prefix = 'tests/unit'
for dirpath, dirnames, filenames in os.walk(prefix):
    trimmedmods = [f[:f.find('.py')] for f in filenames if not f.startswith('__') and f.find('.py') > 0]
    for m in trimmedmods:
        mod = dirpath.replace('/','.')+'.'+m
        print mod
        __import__(mod)

rawDescription: Python - Import all files in a directory tree


code:
arg = raw_input()
arg
exec 'def f(x,y): return ' + arg
f

rawDescription: Input in terms of variables

description: Input in terms of variables


code:
s = [1 , 4 ,6 , 9  ,10 ]
import bisect

x = 5
n = bisect.bisect_left(s, x)
if s[n:n+1] == [x]:
    print x, 'is in the list'
else:
    print x, 'comes between', s[n-1:n], 'and', s[n:n+1]

rawDescription: Better way to find if a number is present in between two numbers of a sorted list


code:
class GUIForm(Ui_MainWindow):
    def __init__(self, parent=None):
        Ui_MainWindow.__init__(self, parent)
        self.threadData()

    def closeEvent(self, event):
        print "User has clicked the red x on the main window"
        event.accept()

if __name__ == "__main__":

    app = QtGui.QApplication(sys.argv)
    myapp = GUIForm()
    myapp.show()
    ret = app.exec_()
    sys.exit(ret)

rawDescription: Proper way to handle the close button in a main window PyQt, (Red "X")


code:
class Link:
    empty = ()
    def __init__(self, first, rest=empty):
        self.first = first
        self.rest = rest

    def __getitem__(self, i):
        if i == 0:
            return self.first
        else:
            return self.rest[i-1]

    def __len__(self):
        return 1 + len(self.rest)

    def __repr__(self):
        if self.rest:
            rest_str = ', ' + repr(self.rest)
        else:
            rest_str = ''
        return 'Link({0}{1})'.format(self.first, rest_str)

def insert(link, value, index):
    if index >= link.__len__():
        print "Index out of bounds"
    else:
        if index == 0:
            tmp = link.first
            link.first = value
            link.rest = Link(tmp, link.rest)
        else:
            insert(link.rest, value, index - 1)

a = Link(1, Link(2, Link(3, Link(4))))
print a
insert(a,23,0)
print a
insert(a,12,2)
print a
insert(a,3,6)
print a
insert(a,3,5)
print a

rawDescription: Insert a value into a link at the given index


code:
if not myList:
  print "Nothing here"

rawDescription: How to check if a list is empty in Python?

description: Check if a list is empty in Python


code:
print repr(u'あいうえお'.encode('utf-16be'))
print repr(u'あいうえお'.encode('utf-16le'))

rawDescription: Convert unicode string to array of bytes


code:
import pandas as pd
from joblib import Parallel, delayed
import multiprocessing

def tmpFunc(df):
    df['c'] = df.a + df.b
    return df

def applyParallel(dfGrouped, func):
    retLst = Parallel(n_jobs=multiprocessing.cpu_count())(delayed(func)(group) for name, group in dfGrouped)
    return pd.concat(retLst)

if __name__ == '__main__':
    df = pd.DataFrame({'a': [6, 2, 2], 'b': [4, 5, 6]},index= ['g1', 'g1', 'g2'])
    print 'parallel version: '
    print applyParallel(df.groupby(df.index), tmpFunc)

    print 'regular version: '
    print df.groupby(df.index).apply(tmpFunc)

    print 'ideal version (does not work): '
    print df.groupby(df.index).applyParallel(tmpFunc)

rawDescription: Parallelize apply after pandas groupby

description: Parallelize apply after pandas groupby


code:
finished = false
while not finished:
    trueLine = testFile.readline()
    if not trueLine: # end of file
        finished = true
    else:
        trueLine = trueLine.split() # tokenise by whitespace
        taggedLine = taggedFile.readline()
        if not taggedLine:
            print 'Error: files are out of sync.'
        taggedLine = taggedLine.split()
        if len(trueLine) != len(taggedLine):
            print 'Error: files are out of sync.'
        for i in range(len(trueLine)):
            truePair = trueLine[i].split('/')
            taggedPair = taggedLine[i].split('/')
            if truePair[0] != taggedPair[0]: # the words should match
                print 'Error: files are out of sync.'
            trueTag = truePair[1]
            guessedTag = taggedPair[1]
            if trueTag == guessedTag:
                totals[trueTag]['truePositives'] += 1
            else:
                totals[trueTag]['falseNegatives'] += 1
                totals[guessedTag]['falsePositives'] += 1

rawDescription: How to calculate tag-wise precision and recall for POS tagger?

description: Calculate tag-wise precision and recall for POS tagger


code:
import threading

def loop():
    for i in range(3):
        print "running in a loop"
        sleep(3)
    print "success"

if __name__ == '__main__':

    t = threading.Thread(target=loop)
    t.start()
    user_input = raw_input("Please enter a value:")
    print user_input
    t.join()

rawDescription: Break loop on keypress

description: Break loop on keypress


code:
import cv2
cam = cv2.VideoCapture(0)
w = cam.get(cv2.CV_CAP_PROP_FRAME_WIDTH)
h = cam.get(cv2.CV_CAP_PROP_FRAME_HEIGHT)
print w,h
while cam.isOpened():
    err,img = cam.read()
    cv2.imshow("lalala", img)
    k = cv2.waitKey(10) & 0xff
    if k==27:
        break

rawDescription: How can I test the actual resolution of my camera when I acquire a frame using OpenCV?

description: Test the actual resolution of my camera when I acquire a frame using OpenCV


code:
import humanfriendly
user_input = raw_input("Enter a readable file size: ")
num_bytes = humanfriendly.parse_size(user_input)
print num_bytes
print "You entered:", humanfriendly.format_size(num_bytes)

rawDescription: Convert number with units in python to NON human readable format


code:
my_list = [0,1,2,3,4,5,6,7,8,9,10]

move_amount = 2
slice_size = 4
print [my_list[i:i + slice_size] for i in range(
  0, len(my_list) - move_amount, move_amount)]

rawDescription: Python: List shift

description: Python: List shift


rawDescription: Pandas dataframe to_datetime() is converting date incorrectly


code:
from dejavu import Dejavu
from dejavu.recognize import FileRecognizer
import os, fnmatch

def find_files(directory, pattern):
    """http://stackoverflow.com/a/2186673/712997"""
    for root, dirs, files in os.walk(directory):
        for basename in files:
            if fnmatch.fnmatch(basename, pattern):
                filename = os.path.join(root, basename)
                yield filename

config = {
     "database": {
         "host": "127.0.0.1",
         "user": "root",
         "passwd": "Password123",
         "db": "dejavu_db",
     },
     "database_type" : "mysql",
     "fingerprint_limit" : 10
}

# create a dejavu object
djv = Dejavu(config)

# gather files to fingerprint
UNLABELED_AUDIO_DIR = "/home/me/music/unknown/"
PATTERN = "*.mp3"
audio_paths = find_files(UNLABELED_AUDIO_DIR, PATTERN)

# recognize them one at a time
original_file_to_song = {}
for path in audio_paths:
    print "Attempting to recognize %s..." % path
    song = djv.recognize(FileRecognizer, path)
    original_file_to_song[path] = song

# see the songs you've recognized
for path, song in original_file_to_song.iteritems():
    print "Audio file at: %s was recognized as %s" % (path, song)

rawDescription: Loop for recognizing all files in a folder using Dejavu library for audio fingerprinting


code:
from Tkinter import *
import dill
import sys
boxes=[]
no_of_boxes=0
root=Tk()
current_row=1
current_box=0
data={}

class Main(object):
#this is used every time a new entry is created
    def save_data(self):
        global current_box
        global current_row
        global no_of_boxes
        ###this it the key. It creates the entries
        ###in a list so that we can access them
        ###without the name
        boxes.append(Entry(root))
        boxes[-1].grid(column=1, row=current_row)
        ###
        try:
            data["Name"+str(current_box)]=boxes[-2].get()
        except:
            data["Name"+str(current_box)]=boxes[-1].get()
        current_row+=1
        current_box+=1
        no_of_boxes+=1
        print no_of_boxes
        print boxes
        print data
        with open("test.json","wb") as f:
            dill.dump(data,f)
    #to save when closing
    def save_close(self):
        global current_box
        global current_row
        boxes.append(Entry(root))
        boxes[-1].grid(column=1, row=current_row)
        data["Name"+str(current_box)]=boxes[-2].get()
        with open("test.json","wb") as f:
            dill.dump(data,f)
        print no_of_boxes
        print boxes
        print data
        sys.exit()

    def load_data(self):
        with open("test.json","rb") as f:
            data=dill.load(f)

    def entry_1(self):
        global current_row
        global no_of_boxes
        nameLabel=Label(root,text="NAME")
        nameLabel.grid(column=0,row=current_row)
        self.save_data()

app=Main()
MoreButton=Button(root,text="+",command=app.entry_1)
MoreButton.grid(column=1,row=0)
CloseButton=Button(root, text="Close and save", command=app.save_close)
CloseButton.grid(column=2, row=0)

root.mainloop()

rawDescription: Serializing saves only the last entered value GUI tkinter


code:
import requests
with open('urls.txt') as urls:
    for url in urls:
        url = url.strip()
        r = requests.get(url)
        print url, r.status_code

rawDescription: Requests.get module python getting 404-400