code:
for li in reversed(lvl):
    print li

rawDescription: How to for loop in reverse?

description: For loop in reverse


code:
for n in sorted(l, key=lambda x: int(x.split('_')[1])):
    print n

rawDescription: Python: get the names of specific file types in a given folder


code:
import ast
with open('x.txt') as input_file:
    for line in input_file:
        strings = ast.literal_eval(ast.literal_eval(line))
        # You can do whatever you want with the `strings` var, e.g:
        assert(strings[0] == "foo'bar")
        assert(strings[0] == 'foo\'bar')
        print strings[0]

rawDescription: Single and Double Quotes Auto-Switching

description: Single and Double Quotes Auto-Switching


code:
print "\x1b[8;40;80t"

print "ok"

rawDescription: Want to resize terminal windows in python, working but not quite right


code:
class BobyDog( Dog ):
    def bark( self ):
        super(BobyDog, self).bark()
        print "WoOoOoF!!"

rawDescription: Python: call parent instancemethod

description: Python: call parent instancemethod


rawDescription: Is there a simple feature that builds a sublist based on value conditioning in Python?


code:
def f(t,ys,a):
    print "f(%.17f) is returning %f" % (t, a)
    return a

rawDescription: How to use scipy.integrate.ode.set_f_params() to make time dependant parameter changes?

description: Use scipy.integrate.ode.set_f_params() to make time dependant parameter changes


code:
response = """
Server: nginx/1.6.2 (Ubuntu)
Date: Thu, 03 Mar 2016 07:00:00 GMT
Content-Type: text/html
Content-Length: 13471
Last-Modified: Sat, 19 Dec 2015 02:42:32 GMT
Connection: close
ETag: "5674c418-349f"
Cache-Control: no-store
Accept-Ranges: bytes

<!doctype html> // or <!DOCTYPE html>
# remaining of the page content here.
"""

print response[response.lower().find('<!doctype html>'):]

rawDescription: Stripping headers response - Python

description: Stripping headers response - Python


code: print tuple( delistify(x) for x in my_list )

rawDescription: How to convert some items in a tuple from list to float?

description: Convert some items in a tuple from list to float


code:
import re
numpairs = re.compile(r'\b(-?\d+)\s*:\s*(-?\d+)\b')
with open('data.txt') as file:
    for line in file:
        for pair in numpairs.findall(line):
            print pair

rawDescription: What is the best way to split a line of numbers separated by a marker and spaces and store it into a tuple?


code:
array1 = np.array(list1)
array2 = np.array(list2)

print array1 + array2
# [3 5 7 9]

rawDescription: Confused myself with matrix and array addition


code:
import threading

interrupt=None

def flag_activator():
    global interrupt
    interrupt = raw_input("(!!) Type yes when you wanna stop\n\n")
    print "Oh gosh! The user input %s" % interrupt

th = threading.Thread(target=flag_activator)
th.start()

fr = open('q0.txt', 'r')
lines = fr.readlines()
fr.close()

while lines and interrupt != 'yes':
    print "I read this line: %s" % lines.pop()

if len(lines) > 0:
    print "Crap! There are still lines"
    fw = open('q0.txt', 'w')
    fw.writelines(lines)
    fw.close()

rawDescription: Removing the line from file once processed


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

browser = webdriver.Firefox()
browser.get('http://www.pastebin.com')

search = browser.find_element_by_name('q')
search.send_keys("test")
search.send_keys(Keys.RETURN)

# wait for results to appear
wait = WebDriverWait(browser, 10)
results = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.gsc-resultsbox-visible")))

# grab results
for link in results.find_elements_by_css_selector("a.gs-title"):
    print link.get_attribute("href")

browser.close()

rawDescription: Python, Selenium, and Beautiful Soup for URL


code:
from pandas.io.html import read_html
from selenium import webdriver

driver = webdriver.Firefox()
driver.get('http://www1.nyse.com/about/listed/IPO_Index.html')

table = driver.find_element_by_xpath('//div[@class="sp5"]/table//table/..')
table_html = table.get_attribute('innerHTML')

df = read_html(table_html)[0]
print df

driver.close()

rawDescription: Python Parsing HTML Table Generated by JavaScript


code: print p.communicate(answer)[0]

rawDescription: How do I take the output of one program and use it as the input of another?

description: Take the output of one program and use it as the input of another


rawDescription: scipy curve fitting negative value

description: Scipy curve fitting negative value


code:
with open ('test.txt', 'r') as infile:
    data = infile.readlines()
    for line, content in enumerate(data, start=1):
            if content.strip() == 'this is my horse':
                print line

rawDescription: how to find the line number where specific text exists?

description: Find the line number where specific text exists


code:
print 'Roll the second row one place'
print independent_roll_copy(grid, 1, 1)
print 'Roll the second row two places'
print independent_roll_copy(grid, 1, 2)
print 'Roll the second row three places'
print independent_roll_copy(grid, 1, 3)

rawDescription: Numpy: how to roll 1 "row" in an array of arrays


code:
from functools import wraps

def subscribe_coro(uri, loop=None):
    def decorator(f):
        @subscribe(uri)
        @wraps(f)
        def wrapper(*args, **kwargs):
            coro = f(*args, **kwargs)
            asyncio.async(coro, loop=loop)
        return wrapper
    return decorator

rawDescription: Calling a remote procedure from a subscriber and resolving the asyncio promise


rawDescription: How to get the position in a certain percentile range of 2-d array with np.NAN in it

description: Get the position in a certain percentile range of 2-d array with np.NAN in it


code: print content.read()

rawDescription: How to examine a urllib2 object in Python?

description: Examine a urllib2 object in Python


code:
enter_count = df.start.value_counts()
exit_count = df.end.value_counts()
df2 = pd.concat([enter_count, exit_count], axis=1, keys=["enter", "exit"])
df2.fillna(0, inplace=True)
print df2.head(5)

rawDescription: Pandas TimeSeries With duration of event


code:
import sys
from StringIO import StringIO
from scapy.layers import inet
from scapy.all import *

#Create scapy packet
pack=inet.Ether()/inet.IP()/inet.TCP()

#Redirect output of print to variable 'capture'
capture = StringIO()
save_stdout = sys.stdout
sys.stdout = capture
pack.show()
sys.stdout = save_stdout

#capture.getvalue() is a string with the output of 'pack.show()'
print capture.getvalue()

#Verify that capture.getvalue() is a string
print isinstance(capture.getvalue(), basestring)

rawDescription: Get info string from scapy packet

description: Get info string from scapy packet


code:
myList = ['string', 'cat', 'mouse', 'gradient']

print max(myList, key=len)
'gradient'

rawDescription: Searching a list for the longest string

description: Searching a list for the longest string


code:
from itertools import chain, permutations, product
tuples_by_length = {}
for t in L:
    tuples_by_length.setdefault(len(t), []).append(t)
for x, y in product(permutations(tuples_by_length[2]),
                    permutations(tuples_by_length[3])):
    print list(chain(x, y))

rawDescription: Iterating through permutations that fit a specific key


code:
def search(values, searchFor):
    for element, details in values.items():
        if element == searchFor:
           print details #As @PM 2Ring says, for Python 3x you should print (details)

rawDescription: search python dictionary not showing

description: Search python dictionary not showing


code:
def foo(): print 'bar'

somedict = {'howdy': foo}
somedict['howdy']()
somedict['howdy']
somedict.get('non-existent', 'not found')
somedict.get('howdy', 'not found')
somedict.get('howdy', 'not found')()

rawDescription: Python dictionary commands with dynamic functions?


code:
def start():
    return increment(0)

def fizz(n):
    print 'fizz'
    return increment(n)

def buzz(n):
    print 'buzz'
    return increment(n)

def fizzbuzz(n):
    print 'fizzbuzz'
    return increment(n)

def increment(n):
    n = n + 1
    if n > 100:
        return terminate()
    elif n % 3 == 0 and n % 5 == 0:
        return fizzbuzz(n)
    elif n % 3 == 0:
        return fizz(n)
    elif n % 5 == 0:
        return buzz(n)
    else:
        print n
        return increment(n)

def terminate():
    raise StopIteration

try:
    start()
except StopIteration:
    pass

rawDescription: Is it advisable to write recursive functions in Python


code: print clideetsresp;

rawDescription: Interactively writing/reading from an external program


rawDescription: Find integer nearest-neighbour in a dict


code:
from selenium import webdriver

url = "http://markets.iowafarmbureau.com/markets/fixed.php?page=egrains"

driver = webdriver.Firefox()
driver.get(url)

table = driver.find_element_by_xpath('//td[contains(div[@class="fixedpage_heading"], "CORN")]/table[@class="homepage_quoteboard"]')
for row in table.find_elements_by_tag_name('tr')[1:]:
    month = row.find_element_by_class_name('quotefield_shortmonthonly').text
    low = row.find_element_by_class_name('quotefield_low').text
    high = row.find_element_by_class_name('quotefield_high').text

    print month, low, high

driver.close()

rawDescription: BeautifulSoup Scraping td & tr

description: BeautifulSoup Scraping td & tr


code:
import numpy as np

headerfmt='20i,20f,a80'
dt = np.dtype(headerfmt)

# Note the 0-index!
x = np.zeros(1, dtype=dt)[0]

print x['f0'], x['f1'], x['f2']
ints, floats, chars = x

rawDescription: numpy fromfile and structured arrays

description: Numpy fromfile and structured arrays


code:
def sort(L):
  if len(L) == 0:
    return []
  else:
    z = max(L)
    g = list(L)
    g.remove(z)
    return [z] + sort(g)

if __name__ == '__main__':
    s = sort([1,5,8,49,29,2])
    print s

rawDescription: Number sorting by a recursive function

description: Number sorting by a recursive function


code:
def generator_func():
    yield "Even"
    yield "generators"
    yield "participate"

w1, w2, w3 = generator_func()
print w1
print w2
print w3
# Even
# generators
# participate

rawDescription: Accessing multiple values from a function within a function


rawDescription: I need to read in a text file with data into python and assign the data the variables


code:
a = ['item1', 'item2', 'item3', 'item4', 'item5', 'item6', 'item7', 'item8', 'item9', 'item10']

print zip(a, a[1:])

rawDescription: How should I grab pairs from a list in python?


code:
import numpy as np
import pandas as pd
from cStringIO import StringIO

# Create example DataFrame
df_text = '''
078401115X|                                                0
0790747324|                                                0
0790750708|[(354, 1), (393, 1), (447, 1), (642, 1), (886,1)]
0800103688|                                                0
5556167281|[(41, 1), (86, 1), (341, 1), (362, 1), (419, 10)]
6300157423|                                                0
6300266850|                                                0
6301699599|                                                0
6301723465|                                                0
'''
df = pd.read_table(StringIO(df_text), sep='|', index_col=0, header=None, skipinitialspace=True)

print 'Original DataFrame:'
print df
print

# Find indexes with zero data in first column
zero_indexes = df[df[1] == '0'].index

print 'Zero Indexes:'
print zero_indexes.tolist()
print

# Assign numpy zero array to indexes
df.loc[zero_indexes] = pd.DataFrame([[np.zeros(4)]], index=zero_indexes, columns=[1])

print 'New DataFrame:'
print df

rawDescription: Store numpy array in multiples cells of pandas dataframe (Python)


code:
soup.a['title']
print soup.a['title']
soup.a.text
print soup.a.text

rawDescription: how to decode and encode web page with python?

description: Decode and encode web page with python


code:
import urllib
from bs4 import BeautifulSoup

url = "http://www.nba.com/gameline/20160323/"
page = urllib.urlopen(url).read()
soup = BeautifulSoup(page)
indicateGameDone = soup.find("div", {"class": "nbaModTopStatus"})
print indicateGameDone.text ## "LiveFinal "

rawDescription: Beautiful Soup not returning everything in HTML file?


code:
def x():
    t = time.clock()
    instance = A()
    for i in xrange(100):
        b2(instance)
    print 'elapsed: %0.1fs'%(time.clock()-t)

def b2(instance=None):
    a2()
    if instance is None:
        instance = A()
    instance.a1()

rawDescription: Python: performance issue implemenating nested classes with staticmethod


code:
for i, idx in enumerate(idx_n):
    print i, idx
    cluster_entries[ int(idx) ].append( list_from_files[i] )

rawDescription: Python list of list selective insertion

description: Python list of list selective insertion


code:
import numpy, scipy
from scipy.signal import correlate

# Load datasets, taking mean of 100 values in each table row
A = numpy.loadtxt("vb-sync-XReport.txt")[:,1:].mean(axis=1)
B = numpy.loadtxt("vb-sync-YReport.txt")[:,1:].mean(axis=1)

nsamples = A.size

# regularize datasets by subtracting mean and dividing by s.d.
A -= A.mean(); A /= A.std()
B -= B.mean(); B /= B.std()

# Put in an artificial time shift between the two datasets
time_shift = 20
A = numpy.roll(A, time_shift)

# Find cross-correlation
xcorr = correlate(A, B)

# delta time array to match xcorr
dt = numpy.arange(1-nsamples, nsamples)

recovered_time_shift = dt[xcorr.argmax()]

print "Added time shift: %d" % (time_shift)
print "Recovered time shift: %d" % (recovered_time_shift)

# SAMPLE OUTPUT:
# Added time shift: 20
# Recovered time shift: 20

rawDescription: Find phase difference between two (inharmonic) waves


rawDescription: How to read a dictionary from a file in Python 2.7?

description: Read a dictionary from a file in Python 2.7


code:
with open(to_file, 'r+') as out_file:
  out_file.write(indata)
  print out_file.read()

rawDescription: Open file, write in to it and print out the result


code:
from types import MethodType

class DefaultClassMethods(type):
    def __getattr__(cls, attr):
        def _defaultClassMethod(cls):
            print 'Hi, I am the default class method!'
        return MethodType(_defaultClassMethod, cls, cls.__metaclass__)

rawDescription: Python dynamic class methods

description: Python dynamic class methods


code:
import re

text = "root_user pts/1        2015-09-16 08:32 (windows-host.net)"
var1, var2, var3, var4 = re.search(r'(.*?)\s.*?(\d{4}\-\d{2}\-\d{2})\s(\d{2}:\d{2})\s+\((.*)\)', text).groups()

print 'var1 =', var1
print 'var2 =', var2
print 'var3 =', var3
print 'var4 =', var4

rawDescription: How do i split output of "who -m"command in linux?

description: Split output of "who -m"command in linux


code:
print sum(
    os.path.isfile(os.path.join(homedir, name)) for name in os.listdir(homedir)
)

rawDescription: would like to get count of files in home dir in python

description: Would like to get count of files in home dir in python


code:
myJson = [
    {
      "name":"Folder 2",
      "id":"zRDg",
      "parent":"OY00",
      "type":"folder"
    },
    {
      "name":"Folder 1",
      "id":"OY00",
      "type":"folder"
    },
    {
      "name":"Folder 3",
      "id":"ZDE1",
      "type":"folder"
    },
    {
      "name":"DX00025.jpg",
      "id":"9Xdd",
      "parent":"OY00",
      "type":"jpeg"
    }
]

#this creates a dictionary that maps id names to JSON items.
#ex. itemsKeyedById["9Xdd"] gives the jpg item with id "9Xdd"
itemsKeyedById = {i["id"]: i for i in myJson}

#iterate through each item in the `myJson` list.
for item in myJson:
    #does the item have a parent?
    if "parent" in item:
        #get the parent item
        parent = itemsKeyedById[item["parent"]]
        #if the parent item doesn't have a "children" member,
        #we must create one.
        if "children" not in parent:
            parent["children"] = []
        #add the item to its parent's "children" list.
        parent["children"].append(item)

#filter out any item that has a parent.
#They don't need to appear at the top level,
#since they will appear underneath another item elsewhere.
topLevelItems = [item for item in myJson if "parent" not in item]
print topLevelItems

rawDescription: Sorting JSON object(s) into a Hierarchy

description: Sorting JSON object(s) into a Hierarchy


code:
lists = [
 [u'a', 11, u'P'],
 [u'a', 11, u'A'],
 [u'b', 2, u'P'],
 [u'c', 1, u'P'],
 [u'c', 2, u'P'],
 [u'd', 1, u'P'],
 [u'e', 3, u'P'],
 [u'f', 2, u'P'],
 [u'a', 1, u'P'],
 [u'a', 2, u'P'],
 [u'b', 1, u'P'],
 [u'b', 11, u'P']]

# Each key in this dictionary will be one of the first elements
# from the lists shown above.  The values will be dictionaries
# mapping a letter (one of the third elements in each list) to
# their total count (i.e. the sum of the second elements matching
# the other two columns)
from collections import defaultdict
results = defaultdict(dict)

for main_key, count, subkey in lists:
    d = results[main_key]
    d[subkey] = d.get(subkey,0) + count

for main_key, values in results.items():
    print main_key, "=>", values

rawDescription: how to merge multiple lists in python

description: Merge multiple lists in python


code:
# test.py:

#!/usr/bin/env python
a = raw_input('Type something!: \n') #the '\n' flushes the prompt
print a

rawDescription: subprocess.call() interacting with GUI (Tkinter)

description: Subprocess.call() interacting with GUI (Tkinter)


code: print dict([[x.name,x] for x in ast.walk(ast.parse(inspect.getsource(some_function))) if type(x).__name__=='FunctionDef'])

rawDescription: python - list all inner functions of a function?

description: Python - list all inner functions of a function


code:
import re

text = "
Date: 06/12/2010
"
m = re.search("(Date:.*?)", text)
print m.group(1)

rawDescription: Newbie Python Regex question: Pulling dates from webpage


code:
with open('example.txt', 'r') as f:
    for eachLine in f:
        a = eachLine.strip().split(" ",2)
        req_list = [int(x) for x in a[2].strip('[]').split(',')]
        print req_list

rawDescription: Read a list from a file in python

description: Read a list from a file in python


code:
s = ""
for x in range(1,5):
    s += "_%d_" % x
print s

rawDescription: Python: Loop: formatting string

description: Python: Loop: formatting string


code:
# Process --set command line option
import sys
# This module can be imported several times,
# check if the option has been retrieved already.
if not hasattr(sys, 'arg_set'):
    # Search for the option.
    args = filter(lambda arg: arg[:6] == '--set=', sys.argv[1:])
    if len(args) > 0:
        expr = args[0][6:]
        # Remove the option from argument list, because the actual command
        # knows nothing about it.
        sys.argv.remove(args[0])
    else:
        # --set is not provided.
        expr = ''
    # Save option value for future use.
    sys.arg_set = expr
# Execute the option value.
exec sys.arg_set

rawDescription: Django: how to pass individual setting to manage.py


code:
def install():
       print "In install"

method_name = 'install' # set by the command line options
possibles = globals().copy()
possibles.update(locals())
method = possibles.get(method_name)
if not method:
     raise NotImplementedError("Method %s not implemented" % method_name)
method()

rawDescription: Python: call a function from string name


code:
from itertools import permutations

for b in B:
    for cperm in permutations(C):
        res = {''.join([a, b, c]) for a, c in zip(A, cperm)}
        print res

rawDescription: Permutation between three sets in python


code:
class XAttrib( XElement):
    '''
     Wraps a property in an attribute on the containing xml tag specified by 'path'
    '''

    def __get__( self, instance, owner=None ):
        return self._get_xml( instance ).attrib[self.path]
        # again, using ElementTree under the hood

    def __set__( self, instance, value, owner=None ):
        myxml = self._get_xml( instance )
        has_element = myxml.get( self.path, 'NOT_FOUND' )
        if has_element == 'NOT_FOUND':
           raise Exception, "instance has no element path"
        myxml.set( self.path, value )

    def _get_element( self ):
        return None  #so outside code knows we are an attrib

    def _get_attribute( self ):
        return self.path

rawDescription: Python XML Serialisation using attributes


code:
foo = MyInt(8)
print foo.difference(7)

rawDescription: Setting a lambda function as a property

description: Setting a lambda function as a property


code:
class Page(object):
    cache = []
    @classmethod
    def __getCache(cls, title):
        """ Return cached object """
        for o in Page.cache:
            if o.__searchTerm == title or o.title == title:
                return o
        return None
    def __new__(cls, title, *args, **kwargs):
        """ Initilize the class and start processing """
        existing = cls.__getCache(title)
        if existing:
            return existing
        page = super(Page, cls).__new__(cls)
        return page
    def __init__(self, title, api=None):
        if self in self.cache:
            return
        self.cache.append(self)
        self.title = title
        self.api = api
        self.__searchTerm = title
        # ...etc

a = Page('test')
b = Page('test')

print a.title # works
print b.title
assert a is b
assert a.cache is Page.cache

rawDescription: Python object cache

description: Python object cache


code:
my_species = {}
current_class = None
for node in species.xpath("child::node()"):
    if isinstance(node, lxml.etree._ElementStringResult):
        text = node.strip(' \n\t:')
        if text:
            current_class = my_species.setdefault(text, [])
    elif isinstance(node, lxml.etree._Element):
        if current_class is not None:
            current_class.append(node.tag)
print my_species

rawDescription: Iterate over both text and elements in lxml etree


code:
idx=np.unique(d[:,0])
print idx

rawDescription: Composite a numpy array/matrix based on column values and variables?


code:
class Article(object):
    def __init__(self, pub_date):
        self.pub_date = pub_date

if __name__ == '__main__':
    from datetime import date
    import itertools
    import operator

    # You'll use your Article query here instead:
    # a_list = Article.objects.filter(pub_date__lte = date.today())
    a_list = [
        Article(date(2010, 1, 2)),
        Article(date(2010, 2, 3)),
        Article(date(2010, 1, 2)),
        Article(date(2011, 3, 2)),
    ]

    keyfunc = operator.attrgetter('pub_date')

    a_list = sorted(a_list, key = keyfunc)
    group_list = [{ k.strftime('%Y-%m-%d') : list(g)}
                  for k, g in itertools.groupby(a_list, keyfunc)]

    print group_list

rawDescription: How can I group objects by their date in Django?

description: Group objects by their date in Django


code:
import sys

def f1(): print "1"
f1.safe = True
def f2(): print "2"
f2.safe = True
def f3(): print "3"

for fname in sys.argv[1:]:
    fn = globals()[fname]
    if fn.__dict__.get('safe'):
        fn()
    else:
        print "No %s for you!" % fname

rawDescription: Using arguments to to run functions

description: Using arguments to to run functions


code:
tests = """\
1
1.0
1/2
1.0/2.0
1 1/2
1.0 1/2
1.0 1.0/2.0""".splitlines()

for t in tests:
    print t, fractExpr.parseString(t)

rawDescription: How can fractional number expressions be parsed using pyparsing?


code:
import libxml2
data = """
<bundles>
  <bundle>
    <bitstreams>
      <bitstream>
        <id>1234</id>
      </bitstream>
    </bitstreams>
    <name>FOO</name>
  </bundle>
</bundles>
"""
doc = xmllib2.parseDoc(data)
for node in doc.xpathEval('/bundles/bundle/name[.="FOO"]/../bitstreams/bitstream/id'):
    print node

rawDescription: Python, lxml - get a sibling tag's (grand)child's text


code:
from Tkinter import *

def fadein(color):
    if color < 111111:
        animal_menu.config(fg='#000000')
    else:
        print color
        animal_menu.config(fg='#' + str(color))
        root.after(100, fadein, color - 111111)

root = Tk()
menubutton = Menubutton(root, text="Animals")
animal_menu = Menu(menubutton, tearoff=0, postcommand=lambda: fadein(999999))
animal_menu.add_command(label="Lion")
animal_menu.add_command(label="Tiger")
animal_menu.add_command(label="Bear")
menubutton.menu = animal_menu
menubutton["menu"]  =  menubutton.menu
menubutton.pack()
root.config()
root.mainloop()

rawDescription: customize tkinter menu while menu is open

description: Customize tkinter menu while menu is open


code:
start = 0
end = 5
while (end<len(data)):
   print data[start:end]
   start = end+1
   end = end+5
print data[start:]

rawDescription: Parsing fixed-format data embedded in HTML in python


code:
from bs4 import BeautifulSoup
import requests

URL = 'https://apps.ap.invesco.com/invee/fund_info/fund_price_ns_mpf.do?version=en&haaccount=N&url=http://www.mpf.invesco.com.hk/html/pdf/factsheets/mpf'
response = requests.get(URL)

soup = BeautifulSoup(response.content)
table = soup.find_all('table')[1]

# getting the first row for example
print table.tr.text.strip()

rawDescription: Webcrawling while bypassing 'important information page'


code:
words_par = 0
for words_par in lines:
    if words_par.startswith("P1" or "P2" or "P3") & words_par.endswith("P1" or "P2" or "P3"):
        words_par = line.split()
    print len(words_par)
    print words_par.replace('P1', '') #doesn't display it but still counts
else:
    print 'No words'

rawDescription: How to count the number of words in a paragraph and exclude some words (from file)?

description: Count the number of words in a paragraph and exclude some words (from file)


code: print re.findall('['+tab+']',line) # Here we add a bracket to each side

rawDescription: Findall regex in python

description: Findall regex in python


code:
a = 5
b = a
b = b + 1          # created a new int
print id(a), id(b) # different

rawDescription: Why equal integers behaves differently to equal lists?


code:
if len(sys.argv) > 3:
    # all three arguments are present
    print 'arg1', sys.argv[1], 'arg2', sys.argv[2], 'arg3', sys.argv[3]

rawDescription: How to know if third argument is passed to script?

description: Know if third argument is passed to script


code:
from PIL import Image
file_data = Image.open('b1.png')
file_data = file_data.convert('RGB') # conversion to RGB
data = file_data.load()
print data[0,0]

rawDescription: PIL import png pixels as single value instead of 3 values vector


rawDescription: How do I split a list at ones?

description: Split a list at ones


code:
key = 'MyKey'
text = 'test'

encoded = encrypt(key, text)
print repr(encoded)
# prints 'I+KlvwIK2e690lPLDQMMUf5kfZmdZRIexYJp1SLWRJY='

decoded = decrypt(key, encoded)
print repr(decoded)
# prints 'test'

rawDescription: Decrypting strings in Python that were encrypted with MCRYPT_RIJNDAEL_256 in PHP


rawDescription: Python pandas calculate rolling stock beta using rolling apply to groupby object in vectorized fashion


code:
with open("parser.txt", "r") as input_file, open("output_parser.txt","w") as output_file:
    for i, line in enumerate(input_file):
        output_file.write ('\n')
        marker_info= line.split()
        end= len(marker_info)
        x=4
        y=8

        while y<=end: #x<=end:
            intensities= marker_info[x:y]
            AA= intensities[0]
            BB= intensities[1]
            AB= intensities[2]
            NN= intensities[3]
            output_file.write ('%s' '\t' '%s' '\t' '%s' '\t' % (AA, AB, BB))
            print end, x, y, marker_info[x:y], AA, AB, BB

            x= y
            y= x + 4

rawDescription: Python - parse a line of text

description: Python - parse a line of text


code:
data = input('Enter a phrase: ') # get user input
data = [i[0] for i in data.upper().split(' ')]

# 1. String converted to uppercase.
# 2. String split at spaces.
# 3. First letters are taken.

print ''.join(data) # back to string

rawDescription: Strings- taking out a letter at the start of each string in a list


code:
class simpleTelnet(logger):
    def __init__(self):
        print 'Inside simpleTelnt Constructor'
        logger.__init__(self,"myfilename.txt")
        self.log.write('Writing into the log file')

rawDescription: How do i write the output to a file and to the stdout using pexpect module

description: Write the output to a file and to the stdout using pexpect module


rawDescription: Drop some Pandas dataframe rows using group based condition


code:
obj1 = MyClass(10)
print obj1.val1
del obj1
obj2 = MyClass(20)
print obj2.val1
del obj2
del type(MyClass)._instances[MyClass]
obj3 = MyClass(30)
print obj3.val1

rawDescription: How to deregister a class entry from Metaclass?

description: Deregister a class entry from Metaclass


code:
import os
for root, dirs, files in os.walk(os.path.abspath("/parent/dir/")):
  for file in files:
    if os.path.splitext(file)[1] == '.py':
      print os.path.join(root, file)

rawDescription: execute similar files in different directories python

description: Execute similar files in different directories python


code:
var  = 'John1'
value = 42

exec "%s = %d" % (var,value)
exec "print %s" % (var)

print (dir())

rawDescription: Dynamic variables in Python

description: Dynamic variables in Python


code: print form['email'].value

rawDescription: How to get data from instancetype variable in python

description: Get data from instancetype variable in python


code:
from datetime import datetime, timedelta

date_select = datetime.strptime('2011-12-1', '%Y-%m-%d')
delta = timedelta(days=1)
target_date = date_select + delta
print target_date

rawDescription: how to convert string to datetime.timedelta()?

description: Convert string to datetime.timedelta()


code:
for i, j in itertools.combinations(range(len(s.T)), 2):
    c = s[:, [i,j]]
    counts = collections.Counter(map(tuple,c))
    print 'columns {} and {}'.format(i,j)
    for k in sorted(counts):
        print 'Frequency of {} = {}/{}'.format(k, counts[k], len(c))
    print

rawDescription: How to retrieve frequencies of the number of unique occurrences of pair letters for every possible pair of columns from a numpy matrix in python

description: Retrieve frequencies of the number of unique occurrences of pair letters for every possible pair of columns from a numpy matrix in python


code:
def func(*vargs):
    for a in vargs:
       print a

func(*[1,2,3])
1
2

rawDescription: Python function parameters inside a list of lists


code:
from lxml import html

doc = html.fromstring(content)
print doc.text_content()

rawDescription: Problems faced while scraping webpages in Python


code:
pdfname = "statementConcentrator"
if (pdfname in open("line56.good").read()):
    print "Found it"

lineNum = 0
for line in open("line56.good").readlines():
    lineNum = lineNum + 1
    if pdfname in line:
        print "#%5d: %s"%(lineNum, line[:-1])

rawDescription: find a matching line in a txt with python

description: Find a matching line in a txt with python


code:
def do_stuff(data):
    print 'bob does stuff with %s' % data

rawDescription: Spawning a thread in python

description: Spawning a thread in python


code:
from tornado import ioloop

def my_function(a, b):
    print a, b

x = 1
y = 2

periodic_callback = PeriodicCallback(
    lambda: my_function(x, y),
    10)

ioloop.IOLoop.current().start()

rawDescription: tornado PeriodicCallback: provide callback with arguments?

description: Tornado PeriodicCallback: provide callback with arguments


rawDescription: Python's handling of shell strings

description: Python's handling of shell strings


code:
from Bio import AlignIO
from Bio import SeqIO
from Bio import Seq
import os

input_file = '/path/to/fa_alignment_PF00205.txt'
records = SeqIO.parse(input_file, 'fasta')
records = list(records) # make a copy, otherwise our generator
                        # is exhausted after calculating maxlen
maxlen = max(len(record.seq) for record in records)

# pad sequences so that they all have the same length
for record in records:
    if len(record.seq) != maxlen:
        sequence = str(record.seq).ljust(maxlen, '.')
        record.seq = Seq.Seq(sequence)
assert all(len(record.seq) == maxlen for record in records)

# write to temporary file and do alignment
output_file = '{}_padded.fasta'.format(os.path.splitext(input_file)[0])
with open(output_file, 'w') as f:
    SeqIO.write(records, f, 'fasta')
alignment = AlignIO.read(output_file, "fasta")
print alignment

rawDescription: BioPython AlignIO ValueError says strings must be same length?


code:
import json
import requests

URL = 'http://calculator.shipito.com/en/rates'
data = {"location": "10", "country": "GB", "city": "London",
        "postalcode": "123456",
        "packages": [{"dimensions_units": "in", "weight_units": "lbs", "dimension": {"width": "9", "height": "20.4", "length": "17"},
        "weight": "9", "value": "170"}]}

response = requests.post(URL, data=json.dumps(data))
print response.json()

rawDescription: Scrapy and Selenium submit form that renders dynamically


code:
import numpy as np
a = np.array(['b','a','b','b','d','a','a','c','c'])
_, idx = np.unique(a, return_index=True)
print a[np.sort(idx)]

rawDescription: numpy.unique with order preserved

description: Numpy.unique with order preserved


code:
import numpy as np

class Thing:

    def __init__(self, words, images, audios, videos):
        self.words  = words
        self.images = images
        self.audios = audios
        self.videos = videos

    def compare(self, other):
        score = 0
        # Assuming the attribute lists have the same length for both objects
        # and that they are sorted in the same manner:
        for i in range(len(self.words)):
            if self.words[i] == other.words[i]:
                score += 1
        for i in range(len(self.images)):
            if self.images[i] == other.images[i]:
                score += 1
        for i in range(len(self.audios)):
            if self.audios[i] == other.audios[i]:
                score += 1
        for i in range(len(self.videos)):
            if self.videos[i] == other.videos[i]:
                score += 1
        # You have to make sure you know what method to use for determining
        # when an image/audio/video are equal.
        return score

N = 1000
things = []
words  = np.random.randint(5, size=(N,5))
images = np.random.randint(5, size=(N,5))
audios = np.random.randint(5, size=(N,5))
videos = np.random.randint(5, size=(N,5))
# For testing purposes I assign each attribute to a list (array) containing
# five random integers. I don't know how you actually intend to do it.
for i in xrange(N):
    things.append(Thing(words[i], images[i], audios[i], videos[i]))

################################################################################
############################# This is the new part: ############################
################################################################################
scores = np.zeros((N, N))
# Scores will become a triangular matrix where scores[i, j]=value means that
# value is the number of attrributes thing[i] and thing[j] have in common.
for i in xrange(N):
    for j in xrange(N):
        if i == j:
            break
            # Break the loop here because:
            # * When i==j we would compare thing[i] with itself, and we don't
            #   want that.
            # * For every combination where j>i we would repeat all the
            #   comparisons for j<i and create duplicates. We don't want that.
        scores[i, j] = (things[i].compare(things[j]))

# I want the 5 most similar pairs:
n = 5
# This list will contain a tuple for each of the n most similar pairs:
best_list = []
for k in xrange(n):
    ij = np.argmax(scores) # Returns a single integer: ij = i*n + j
    i = ij / N
    j = ij % N
    best_list.append((i, j))
    # Erease this score so that on next iteration the second largest score
    # is found:
    scores[i, j] = 0

for k, (i, j) in enumerate(best_list):
    # The number 1 most similar pair is the BEST match of all.
    # The number N most similar pair is the WORST match of all.
    print "The number %d most similar pair is thing number %d and %d." \
          % (k+1, i, j)
    print "Thing%4d:" % i, \
          things[i].words, things[i].images, things[i].audios, things[i].videos
    print "Thing%4d:" % j, \
          things[j].words, things[j].images, things[j].audios, things[j].videos
    print

rawDescription: Algorithm for matching objects

description: Algorithm for matching objects


code:
def search_student(database=None, ID=None, roll=False, email=False):
    if ID is None or ID == 0:
        print 'Provide the arguments properly'
        return False
    for each in database:
        if each.id == ID:
            print 'Student Name: {}'.format(each.name)
            if roll:
                print 'Stutent Roll: {}'.format(each.roll_no)
            if email:
                print("Student email: {}".format(each.email))
            break
    else:
        return "User does not exist in database"

studentDatabase = collections.namedtuple("student", "id name roll_no phone email")

DATABASE = [studentDatabase(1, 'Mayukh Sarkar', 9, '555-2312', 'mayukh2012@hotmail,com'),
            studentDatabase(2, 'Alisha Sengupta', 7, '555-1345', 'alisha@gmail.com')]

rawDescription: How can I pass the optional parameter of a namedtuple in a function

description: Pass the optional parameter of a namedtuple in a function


code:
not_same_length = list(item for item in range(50,55))
data_frame['nsl'] = pd.Series(not_same_length)
print data_frame

rawDescription: Append a list of arrays as column to pandas Data Frame with same column indices


code:
words = ['elephant', 'dog', 'blue', 'sam', 'white', 'red', 'sun', 'moon']
colors = set(['red', 'green', 'blue', 'orange', 'white'])
print [word for word in words if word in colors]

rawDescription: Remove all but certain words from a list (like a white list)


code:
contents = rules[ser]
if code == 'V':
    print contents[:2]
else:
    print contents[2:]

rawDescription: Splitting letters and numbers to figure out and assign value in table


code:
from collections import OrderedDict as od
with open("abc") as f:
   dic = od()
   for line in f:
       row  = map(int,line.split())
       idx, num  = row[2], row[0]
       val = [num] + [row[3:-1]]
       dic.setdefault(idx,[]).append(val)

for k,v in dic.items():
    for val in v:
        print k,val

rawDescription: How to find duplicate values in next lines?

description: Find duplicate values in next lines


code:
my_data = {
    'something1': 5.5,
    'something2': u'Some info',
    'something3': b'\x01\x03\x00\x00 ...\x00\x00',
}
import json
r = json.dumps(my_data, cls=MyJsonEncoder)
print r
r = json.dumps(my_data)

rawDescription: How can I override behavior of JSONEncoder for binary data?

description: Override behavior of JSONEncoder for binary data


code:
f = open(file_name)
total = len([line for line in f if line.endswith("pizza")])
f.close()
print total

rawDescription: How do i count and dispaly number of occurance word ending in "pizza" (only pizza) using input text

description: Count and dispaly number of occurance word ending in "pizza" (only pizza) using input text


code:
from collections import Counter

cnt = Counter(lst)
print {gender: {name: cnt[name] for name in persons if persons[name] == gender}
          for gender in set(persons.values())}

# {'Eunuch': {'Varys': 1},
# 'Male': {'Tyrion': 3, 'Hodor': 2, 'Theon': 0},
# 'Female': {'Daenerys': 2, 'Arya': 1, 'Sansa': 0}}

rawDescription: Reverse multiple values with keys in dictionary


code:
import dis

def test_integers():
    print "-6 is -6 ?", -6 is -6 # True
    print "(0-6) is -6 ?", (0 - 6) is -6 # False

dis.dis(test_integers)

rawDescription: Is it possible for the Python compiler to optimize away some integer arithmetic?


code:
rule="A(B|C)D[E]FG"

def generate_strings(rule):
    if not rule:
        return [""]
    begin,end=rule[0],rule[1:]
    if begin=='[':
        i=end.find(']')
        if i==-1:
            raise Exception("Unmatched '['")
        alt,end=end[0:i],end[i+1:]
        return [a+e for e in generate_strings(end) for a in [alt,""]]
    if begin=='(':
        i=end.find(')')
        if i==-1:
            raise Exception("Unmatched '('")
        alt,end=end[0:i].split('|'),end[i+1:]
        return [a+e for e in generate_strings(end) for a in alt]
    if begin in [']',')','|']:
        raise Exception("Unexpected " + begin)
    return [begin + e for e in generate_strings(end)]

print generate_strings(rule)

rawDescription: How can I generate all possible strings given a grammar rule?

description: Generate all possible strings given a grammar rule


code:
xml_file = myform.cleaned_data.get('xml_file')
print xml_file.read()

rawDescription: Django: Open uploaded file while still in memory; In the Form Clean method?


code:
string = list('The quick brown fox jusmps over the lazy dog')
result = []
for i in string:
        if i == 'o':
                i = '0'
        result.append(i)
print ''.join(result)

rawDescription: Python: replacing characters in string without replace() function


code:
with open('file.txt', 'r') as handle:
    for line in handle:
        print line

rawDescription: Python - reading from file into a list

description: Python - reading from file into a list


code:
txt = u'\\u003c? abc ?\\u003eDas Modell des Adaptiven Zyklus wurde aus vergleichenden Untersuchungen zur Dynamik von \xd6kosystemen abgeleitet.\\u003c? /abc ?\\u003e'
content = txt.encode('utf8')
content
import json
json.loads('"{0}"'.format(content))
print json.loads('"{0}"'.format(content))

rawDescription: python mixed single and double unicode escape sequences

description: Python mixed single and double unicode escape sequences


code:
from string import punctuation

from inappropriate_words import inappropriate # a list of     inappropriate words
import sys

for word in sys.argv[1:]:
    if word.strip(punctuation) in st:
        print "{} is inappropriate.".format(word)

rawDescription: Output the specific word (from a list) that was found in a string


code:
import itertools

rows =  [("A", 9),  ("B", 56), ("C", 42), ("D", 31), ("E", 31), ("F", 25), ("G", 999)]

def print_multi_cols(lrows, split_at=5, space_each=4, left_justify=None):
    if not left_justify:
        left_justify = [True] * len(lrows[0])

    for row in itertools.izip(*itertools.izip_longest(*[iter(lrows)]*split_at, fillvalue=(" ", " "))):
        for col in row:
            print " ".join([("%-*s " if left else "%*s ") % (space_each, item) for item, left in itertools.izip(col, left_justify)]),
        print
    print

print_multi_cols(rows, split_at=5, space_each=3, left_justify=[True, False])

rawDescription: How to columnate a list in python?

description: Columnate a list in python


rawDescription: Two Basic Python Dictionary Questions

description: Two Basic Python Dictionary Questions


code: print "some log test"

rawDescription: Python 'Logger' class repeats timestamp

description: Python 'Logger' class repeats timestamp


code:
from PyQt4 import QtCore, QtGui

from multiprocessing import Process, Manager, Pool
manager = Manager()
myDict=manager.dict()
myDict['state'] = True
myDict['value'] = 0

class PbWidget(QtGui.QProgressBar):
    def __init__(self, parent=None, total=20):
        super(PbWidget, self).__init__()
        self.setMinimum(1)
        self.setMaximum(total)
        self._active = False

    def update_bar(self, to_add_number):
        while True:
            time.sleep(0.01)
            value = self.value() + to_add_number
            self.setValue(value)
            QtGui.qApp.processEvents()
            if (not self._active or value >= self.maximum()):
                break
        self._active = False

    def closeEvent(self, event):
        self._active = False

def externalFunc(arg=None):
    print "\t\t Attempting to update Progress Bar by changing dictionary values"
    myDict['value']=arg
    myDict['state']=True

class MainWindow(QtGui.QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.progressBarCurrentValue=0
        self.main_layout = QtGui.QVBoxLayout()

        self.pb=PbWidget(total=101)
        self.main_layout.addWidget(self.pb)

        ok_button = QtGui.QPushButton("OK")
        ok_button.clicked.connect(self.OK)
        self.main_layout.addWidget(ok_button)

        central_widget = QtGui.QWidget()
        central_widget.setLayout(self.main_layout)
        self.setCentralWidget(central_widget)

    def OK(self):
        myList=[10,10,10,10,10,10,10,10,10,10,10,10,10]
        pool = Pool(processes=10)
        pool.map_async( externalFunc, myList)

    def EventListener(self):
        while myDict['state']:
            value=myDict['value']
            self.pb.update_bar(value)

            self.progressBarCurrentValue=self.pb.value()
            print "...running sicne current Progress Bar value is < 99:", self.progressBarCurrentValue, myDict['state']

            if self.progressBarCurrentValue>99:
                myDict['state'] = False
                print "...stopping"

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    jobDialog = MainWindow()
    jobDialog.resize(480, 320)
    jobDialog.show()
    jobDialog.EventListener()
    sys.exit(app.exec_())

rawDescription: Python: Update Widgets from outside function using multipocessing Pool


code:
import struct

IMAGE_FILE_MACHINE_I386=332
IMAGE_FILE_MACHINE_IA64=512
IMAGE_FILE_MACHINE_AMD64=34404

f=open("c:\windows\explorer.exe", "rb")

s=f.read(2)
if s!="MZ":
    print "Not an EXE file"
else:
    f.seek(60)
    s=f.read(4)
    header_offset=struct.unpack("<L", s)[0]
    f.seek(header_offset+4)
    s=f.read(2)
    machine=struct.unpack("<H", s)[0]

    if machine==IMAGE_FILE_MACHINE_I386:
        print "IA-32 (32-bit x86)"
    elif machine==IMAGE_FILE_MACHINE_IA64:
        print "IA-64 (Itanium)"
    elif machine==IMAGE_FILE_MACHINE_AMD64:
        print "AMD64 (64-bit x86)"
    else:
        print "Unknown architecture"

f.close()

rawDescription: Determine if an executable (or library) is 32 -or 64-bits (on Windows)


code:
import xmltodict

message = """<?xml version="1.0"?><note><to>Tove</to><from>Jani</from><heading>Reminder</heading><body>Don't forget me this weekend!</body></note>"""
print xmltodict.parse(message)['note']

rawDescription: convert xml to python dict

description: Convert xml to python dict


code:
def divide(fn):
    # get total lines in file
    with open(fn) as f:
        lc=sum(1 for _ in f)

    with open(fn) as fin:
        # top half of file:
        for i, line in enumerate(fin):
            print line
            if i>=lc/2:
                break
        # middle
        print "======="
        # remainder
        for line in fin:
            print line

rawDescription: python script to split a file in two parts, name each one seperately

description: Python script to split a file in two parts, name each one seperately


code:
import itertools

lst = range(10)
it = iter(lst)

while True:
    print it.next(), '>>',
    it, saved = itertools.tee(it)
    for subitem in it:
        print subitem,
    it = saved
    print

rawDescription: How to start a loop with a specific iterator

description: Start a loop with a specific iterator


code:
import operator
print reduce(operator.iand, map(set, x))

rawDescription: Find (and keep) duplicates of sublist in python


code:
hugelist = [(0,0,0), (1,0,0), (3,0,0), (4,1,1), (4,2,2), (5,0,0)]
maxx = 0
deltax = 1
istart = 0
while istart < len(hugelist):
    ifinish = bisect_left(hugelist, (maxx, 0, 0), lo=istart)
    # Now work on the slice hugelist[istart:ifinish].
    # It's possible that istart == ifinish, i.e. that the
    # slice is empty!
    print "for maxx =", maxx, hugelist[istart:ifinish]
    maxx += deltax
    istart = ifinish

rawDescription: python while loop to break up sorted list/array

description: Python while loop to break up sorted list/array


code:
io.savemat('temp.mat',{'data':np.ones(10)})  # write
with open('temp.mat','ab') as f:
    io.savemat(f, {'newdata':np.arange(5)})   # append
print io.loadmat('temp.mat').keys()           # read
# dict_keys(['data', '__globals__', 'newdata', '__header__', '__version__'])

rawDescription: How to append to .mat file using scipy.io.savemat?

description: Append to .mat file using scipy.io.savemat


code:
class Car(object):
    def __init__(self, name, tank_size=10, mpg=30):
        self.name = name
        self.tank_size = tank_size
        self.mpg = mpg

class Favorite(object):
    def __init__(self, car):
        self.car = car
    def __getattr__(self, attr):
        return getattr(self.car, attr)
    @property
    def range(self):
        return self.mpg * self.tank_size

cars = []
cars.append(Car("Toyota", 11, 29))
cars.append(Car("Ford", 15, 12))
cars.append(Car("Honda", 12, 25))

my_current_fav = Favorite(cars[1])

print my_current_fav.range

rawDescription: Pointing to another object's attributes and adding your own


code:
import modules
hello = 'Hello'
for m in dir(modules):
    obj = getattr(modules,m)
    if hasattr( obj, "__call__" ): #or use `if callable(obj):`
        print obj(hello)

rawDescription: Executing a list of imported functions

description: Executing a list of imported functions


code:
from glob import glob
import re

re1 = r'\d{4}(?:\d?|\d{2})(?:\d?|\d{2})\.faifb1p16m2\.nc'
re2 = r'\d{8}\.faifb1p16m2\.nc'

l = [f for f in glob('*.faifb1p16m2.nc') if re.search(re1, f)]
m = [f for f in glob('*.faifb1p16m2.nc') if re.search(re2, f)]

print l
print
print m
#Then, suppose you want to filter and select everything with '12' in the list m
print filter(lambda x: x[4:6] == '12', m)

rawDescription: select files from path

description: Select files from path


code:
import operator

class Foo:
    def __init__(self, name):
        self.name = name

l = [Foo('AA'), Foo('a'), Foo('AB')]
l.sort(key=operator.attrgetter('name'))
print [o.name for o in l]
['AA', 'AB', 'a']

rawDescription: How to sort alphanumeric list of Django model objects

description: Sort alphanumeric list of Django model objects


code:
import ImageOps
im=Image.open("flowers_white_border.jpg")
invert_im = ImageOps.invert(im)
print invert_im.getbbox()
# output:
(16, 16, 288, 216)

rawDescription: getbbox method from python image library (PIL) not working

description: Getbbox method from python image library (PIL) not working


code:
myvariable = [['test', 'xxxx', 'DDDt', 'EEEst', '2323t', 'test', 'test', 'test'],
              ['test', 'xxxx', 'DDDt', 'EEEst', '2323t', 'test', 'test', 'test'],
              ['test', 'X1', 'DDDt', 'EEEst', '2323t', 'test', 'test', 'test']
             ]

seen=set()
print [li for li in myvariable
         if tuple(li[:2]) not in seen and not seen.add(tuple(li[:2]))]

rawDescription: Cycling through a list of list, checking and removing?


code:
import sys
from os import listdir
from os.path import isfile, join

onlyfiles = [ f for f in listdir() if isfile(f) and str(f)[-4:]==".yml" ]

for file in onlyfiles:
  wdata = ''
  with open(file, 'r') as a: #Lets open it make sure it is good
    for line in a:
        if line == "  world: Trolling\n":
            line = "  world: world\n" # You already know what it should be
        print line
        wdata += line
  with open(file, 'w') as repl:
    repl.write(wdata)

rawDescription: a program to replace a line in a .yml file(PYTHON)

description: A program to replace a line in a .yml file(PYTHON)


code:
class Test(object): #Inherit from `object` to make it a new-style class(Python 2)
    x = "me"
    def hello(self):
        if self.x == "me":
            type(self).x = "Hei..!"
            return "success"

Test().hello()
print Test.x

rawDescription: How to access global variable in Python?

description: Access global variable in Python


code:
class RevealAccess(object):
    """A data descriptor that sets and returns values
       normally and prints a message logging their access.
    """
    def __init__(self, initval=None, name='var'):
        self.val = initval
        self.name = name
    def __get__(self, obj, objtype):
        print 'Retrieving', self.name
        return self.val
    def __set__(self, obj, val):
        print 'Updating' , self.name
        self.val = val

class MyClass(object):
    x = RevealAccess(10, 'var "x"')
    y = RevealAccess(5, 'var "y"')

m = MyClass()
m.x
m.x = 20
m.x
m.y

rawDescription: Where does a python descriptor's state go?


code:
url = "www.abc.com/category-city_area_name-deal/"
city = "AreaName"

if city.replace('_', '').lower() in url.replace('_', '').lower():
    print 'ok'

rawDescription: Python regex- match a string like MGRoad to a sting like MG_Road


code:
args = p.parse_args()
args.remaining = " ".join(args.remaining)
print args

rawDescription: Python argparse treat arguments in different ways


code:
import requests

from bs4 import BeautifulSoup

url = "http://www.aidn.org.au/Industry-ViewCompany.asp?CID=3113"
html = requests.get(url).text
soup = BeautifulSoup(html)

for feature_heading in soup.find_all("td", {"class": "Feature-Heading"}):
    print "\n=== %s ===" % feature_heading.text
    details = feature_heading.find_next_sibling("td")
    for item in details.find_all("td", {"class": ["bodytext", "paraheading"]}):
        print("\t".join([item["class"][0], " ".join(item.text.split())]))

rawDescription: Scrape a series of tables with BeautifulSoup


rawDescription: Understanding how to multiply specific values in tuples in Python


code:
class Foo (object) :
    def baz (self) :
        return 324

class Bar (object) :
    def __init__ (self) :
        self.foo = Foo()

    def __getattr__(self, attr):
        return getattr(self.foo, attr)

bar = Bar()
print bar.foo.baz()
print bar.baz()

rawDescription: Calling an instance variable's method from the instance itself


code:
import re

ss = '''This is the [first]       line
(And) another line
   [Inter][A] initially shifted
[Finally][B] the last
    Additional ending lines (this one without brackets):
[Note that [ by the way [ref [ 1]] there are]    [some] other ]cases
tuvulu[]gusti perena[3]              bdiiii
    [Away [is this] [][4] ] shifted content
    fgjezhr][fgh
'''

def clean(x, rag = re.compile('\[.*\]',re.MULTILINE),
          regx = re.compile('(\n)|(?=^( ))?( |(?<! ))+((?<!])\[[^[\]\n]*\])( *)',re.MULTILINE)):

    def repl(mat, cnt = None, dico_lignes = None):
        if mat.group(1):
            print "line %s: detecting %s  ==> count incremented to %s" % (cnt[0],str(mat.groups('')),cnt[0]+1)
            cnt[0] += 1
            return mat.group(1)
        if mat.group(4):
            print "line %s: removing %s   IN   %s" % (cnt[0],repr(mat.group(4)),dico_lignes[cnt[0]])
            return '' if mat.group(2) else mat.group(3)

    while rag.search(x):
        print '\n--------------------------\n'+x
        repl.func_defaults = ([1],dict( (n,repr(line)) for n,line in enumerate(x.splitlines(True),1)))
        x = regx.sub(repl,x)
    return x

print '\n==========================\n'+clean(ss)

rawDescription: Using regex to replace object within brackets in a text file


code:
list_of_scores = range(50, 100, 5)  # a list of scores [50, 55, 60, 65, 70, 75, 80, 85, 90, 95]
for score in list_of_scores:
    print "The grade is {}".format(letter_grade(score))

rawDescription: How do I take a list of integers, take the function letter_grade and print 'The grade is A' for example.

description: Take a list of integers, take the function letter_grade and print 'The grade is A' for example.


code:
from itertools import groupby
from operator import itemgetter

ordered = sorted(colour.iteritems(), key=itemgetter(1))
bykey = groupby(ordered, key=itemgetter(1))
print map(itemgetter(0), next(bykey)[1])
# ['green', 'red']

rawDescription: How to return smallest value in dictionary?

description: Return smallest value in dictionary


code:
for document in r.table('users').run(): print(document)
new_record = {"name": "john smith", "Age": 30, "phone_number": "556"}
filter_predicate = {"phone_number": new_record["phone_number"]}
test = r.table('users').filter(filter_predicate).count().eq(0)
r.branch(test, r.table('users').insert(new_record), None).run()
for document in r.table('users').run(): print document
r.branch(test, r.table('users').insert(new_record), None).run()
for document in r.table('users').run(): print document

rawDescription: How do i prevent duplicate records on rethinkdb using python

description: Prevent duplicate records on rethinkdb using python


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

q  = 1.602e-19    #Coulombs   Charge of electron
c  = 3.0e8        #m/s        Speed of light
eo = 8.8541e-12   #C^2/(Nm^2) Permittivity of vacuum
me = 9.109e-31    #kg         Mass of electron
ke = 8.985551e9   #N m^2 C-2  Coulomb's constant

def tunnel_position(tb,intensity,wavelength,pulseFWHM,Ip):
    Ip = 15.13 * q
    Eb = E_laser(tb,intensity,wavelength,pulseFWHM)
    return -Ip / (Eb*q)

def E_laser(t,intensity,wavelength,pulseFWHM):
    w = c/wavelength * 2. * np.pi #Angular frequency of the laser
    Eo = np.sqrt(2*intensity*10**4/(c*8.85e-12)) # Electric field in V/m
    return Eo*np.sin(w*t) * np.exp(-t**2/(2*(pulseFWHM / 2.35482)**2))

def vectorfield(variables,t,params):
    x,y,z,vx,vy,vz = variables
    intensity,wavelength,pulseFWHM,tb = params
    r = np.sqrt(x**2+y**2+z**2)
    Ac = -ke*q**2/(r**2*me)
    return [vx,vy,vz,
         Ac*x/r,
         Ac*y/r + q/me * E_laser((t-tb),intensity,wavelength,pulseFWHM),
         Ac*z/r]

Ip  = 15.13   # Ionization potential of Argon eV
intensity  = 2e14
wavelength = 800e-9
pulseFWHM  = 40e-15

period  = wavelength/c
t = np.linspace(0,20*period,10000)

birth_times = np.linspace(0.01*period,0.999*period,50)
max_field   = np.max(np.abs(E_laser(birth_times,intensity,wavelength,pulseFWHM)))

for tb in birth_times:
    x0  = 0
    y0  = tunnel_position(tb,intensity,wavelength,pulseFWHM,Ip)
    z0  = 0
    vx0 = 2e4
    vy0 = 0
    vz0 = 0

    p = [intensity,wavelength,pulseFWHM,tb]
    w0 = [x0,y0,z0,vx0,vy0,vz0]

    solution,info = scipy.integrate.odeint(vectorfield,w0,t, args=(p,),full_output=True)
    print 'Tb: %.2f fs - smallest step : %.05f attosec'%((tb*1e15),np.min(info['hu'])*1e18)

    y = solution[:,1]

    importance = (np.abs(E_laser(tb,intensity,wavelength,pulseFWHM))/max_field)
    plt.plot(t,y,alpha=importance*0.8,lw=1)

plt.xlabel('Time (sec)')
plt.ylabel('Y-distance (meters)')

plt.show()

rawDescription: Simulating electron motion - differential equation with adaptive step size in python


code:
from multiprocessing import Process, Pipe
from threading import Thread
import time

alive = {
    'sub': 1,
    'test': 1,
}

def listener_factory(key):
    def listener(conn): #listens for kill from main
        while True:
            data = conn.recv()
            if data == "kill":
                alive[key] = False #value for kill
                break
    return listener

def process_factory(key):
    listener = listener_factory(key)
    def subprocess(conn, threadNum):
        t = Thread(target=listener, args=(conn,))
        count = 0
        threadVal = threadNum
        t.start()
        while alive[key]:
            print "Thread[%s] %d Run number = %d" % (key, threadVal, count)
            count = count + 1
    return subprocess

def main():
    sub_parent, sub_child = Pipe()
    test_parent, test_child = Pipe()
    runNum = int(raw_input("Enter a number: "))
    threadNum = int(raw_input("Enter number of threads: "))
    print "Starting threads"
    for i in range(threadNum):
        p = Process(target=process_factory('sub'), args=(sub_child, i))
        p.start()
    print "Subprocess started"
    for i in range(threadNum):
        p2 = Process(target=process_factory('test'), args=(test_child, i))
        p2.start()
    print "Testproccess started"
    print "Starting run"
    time.sleep(runNum)
    print "Terminating Subprocess run"
    for i in range(threadNum):
        sub_parent.send("kill") #sends kill to listener
    print "Terminating Testprocess run"
    for i in range(threadNum):
        test_parent.send("kill") #sends kill to listener
    p.join()
    p2.join()

if __name__ == '__main__':
    main()

rawDescription: How to streamline this script

description: Streamline this script


rawDescription: How to "unpack" this tuple

description: "unpack" this tuple


code: print my_dict['a']['c']    # Outputs: 2

rawDescription: Django view: How to display data from a dictionary


code:
if (x, y) in cat_dict:
    print cat_dict[x, y]
else:
    print cat_dict[x, 'default']

rawDescription: python for loop logic to check variables against

description: Python for loop logic to check variables against


code:
import __main__
from itertools import permutations
from time import time

def replace1(txt, pos, new_char):
    return txt[:pos] + new_char + txt[pos+1:]

def replace2(txt, pos, new_char):
    return '{0}{1}{2}'.format(txt[:pos], new_char, txt[pos+1:])

def replace3(txt, pos, new_char):
    return ''.join({pos: new_char}.get(idx, c) for idx, c in enumerate(txt))

def replace4(txt, pos, new_char):
    txt = list('12345')
    txt[pos] = new_char
    ''.join(txt)

def replace5(txt, pos, new_char):
    return '%s%s%s' % (txt[:pos], new_char, txt[pos+1:])

words = [''.join(x) for x in permutations('abcdefgij')]

for i in range(1, 6):
    func = getattr(__main__, 'replace{}'.format(i))

    start = time()
    for word in words:
        result = func(word, 2, 'X')
    print time() - start

rawDescription: Other ways to replace single character

description: Other ways to replace single character


rawDescription: python print in format way unknow list length

description: Python print in format way unknow list length


code:
with open('/tmp/src.txt','r') as src:
    for line in src:
        print line.strip()

rawDescription: Dictionary accession numbers

description: Dictionary accession numbers


code:
from __future__ import division
import math

function = int(raw_input("Type function no.: "))

while function > 0:
    if function == 1:
        a = float(raw_input ("Enter average speed: "))
        b = float(raw_input ("Enter length of path: "))
        answer = b/a
        print "Answer=", float(answer),
    elif function == 2:
        mass_kg = int(input("What is your mass in kilograms?" ))
        mass_stone = mass_kg * 2.2 / 14
        print "You weigh", mass_stone, "stone."

    print 'Enter a value <= 0 for function number to quit.'
    function = int(raw_input("Type function no.: "))

rawDescription: Integrating a for loop into an if statement


code:
doc = """

Name

Fees

Awards

Total

Tony

    7,800
    7
    15,400

Paul

    7,800
    7
    15,400

Richard

    7,800
    7
    15,400

Name

Fees

Awards

Total

Tony

    7,800
    7
    15,400

Paul

    7,800
    7
    15,400

Richard

    7,800
    7
    15,400

"""
import lxml.html
root = lxml.html.fromstring(doc)
root.xpath('//tr/td//text()')
for tbl in root.xpath('//table'):
    elements = tbl.xpath('.//tr/td//text()')
    print elements

rawDescription: python parse html table using lxml

description: Python parse html table using lxml


code:
import fileinput
for line in fileinput.input('thefile.name', inplace=True):
    line = transform(line)
    print line,

rawDescription: Most Logical Way (in Python) to Edit JSON file on disk


code:
li = [10000, 1000, 100, 10, 1]

if binary_search(li, 500) is None: print '500 not found!'
else: print '500 found!'

i = binary_search(li, 10)
if i is None: print '10 not found!'
else: print 'Found 10 at index ' + str(i) + '!'

rawDescription: Not printing output ? python

description: Not printing output ? python


code:
import threading
import time
import sys
import gobject
gobject.threads_init()

class Child:
    def __init__(self):
        self.result = None

    def play(self, count):
        print "Child starting to play."
        for i in range(count):
            print "Child playing."
            time.sleep(1)
        print "Child finished playing."
        self.result = 42

    def get_result(self, obj):
        print "The result was "+str(self.result)

class AutoJoiningThread(threading.Thread, gobject.GObject):
    __gsignals__ = {
        'finished': (gobject.SIGNAL_RUN_LAST,
                     gobject.TYPE_NONE,
                     ())
        }

    def __init__(self, *args, **kwargs):
        threading.Thread.__init__(self, *args, **kwargs)
        gobject.GObject.__init__(self)

    def run(self):
        threading.Thread.run(self)
        gobject.idle_add(self.join)
        gobject.idle_add(self.emit, 'finished')

    def join(self):
        threading.Thread.join(self)
        print "Called Thread.join()"

if __name__ == '__main__':
    print "Creating child"
    child = Child()
    print "Creating thread"
    thread = AutoJoiningThread(target=child.play,
                               args=(3,))
    thread.connect('finished', child.get_result)
    print "Starting thread"
    thread.start()
    print "Running mainloop (Ctrl+C to exit)"
    mainloop = gobject.MainLoop()

    try:
        mainloop.run()
    except KeyboardInterrupt:
        print "Received KeyboardInterrupt.  Quiting."
        sys.exit()

    print "God knows how we got here.  Quiting."
    sys.exit()

rawDescription: In Python, how do I know when a process is finished?


code:
import ast
s = 'Trentem\u00f8ller'                   # a regular string
print ast.literal_eval('u"""' + s + '"""')

rawDescription: Unicode being re-unicoded

description: Unicode being re-unicoded


code:
list=['asdf', '123', 'more items...']
print ', '.join([str(x) for x in list])

rawDescription: Convert a list into a string and allow for a separator


code:
import re
check="""'Aadhirai' 'A special star' '6' 'Boy' '' "\rgoogletag.cmd.push(function() { googletag.display('div-gpt-ad-1445572280350-0'); });\r" 'Aadhiren' 'Dark' '6' 'Boy' '' 'Aadhish' 'King Commanded Counselled' '5' 'Boy' '' 'Aadhyatm' 'Dhyan' '1' 'Boy' '' 'Aadi' 'First Most important Beginning Ornament Adornment' '6' 'Boy' '' 'Aadia' 'Being a gift' '7' 'Boy' '' 'Aadidev' 'The first God' '1' 'Boy' '' 'Aadijay' 'The first victory' '6' 'Boy' '' 'Aadim' 'Entire universe' '1' 'Boy' '' 'Aadinath' 'The first Lord Lord Vishnu' '4' 'Boy' '' 'Aadipta' 'Bright' '7' 'Boy' '' 'Aadish' 'Full of wisdom Intelligent' '6' 'Boy' '' 'Aadishankar' 'Sri shankaracharya Founder of Adwaitha philosophy' '6' 'Boy' '' 'Aadit' 'Peak Lord of Sun' '8' 'Boy' '' 'Aaditey' 'Son of Aditi' '11' 'Boy' '' '\r        (adsbygoogle = window.adsbygoogle || ).push({});\r    '"""
print re.sub(r"\r.*?\r"," ",check)

rawDescription: How to remove text in between \r's including \r from a text file?? And if any text contains \r in between ' ' that also should be removed

description: Remove text in between \r's including \r from a text file?? And if any text contains \r in between ' ' that also should be removed


code:
from imdb import IMDb
ia = IMDb()
s = ia.search_movie('Deadpool')
dp = s[0]
ia.update(dp)
print dp.get('production companies')

rawDescription: get the company info for a movie from IMDB using IMDBPY

description: Get the company info for a movie from IMDB using IMDBPY


rawDescription: How to discard values in a python panda series?

description: Discard values in a python panda series


code:
class A(object):

    def __init__(self):
        self._myprop = "Hello"

    @property
    def myprop(self):
        return self._myprop

    @myprop.setter
    def myprop(self, v):
        self._myprop = v

prop = getattr(A, "myprop")

print prop
# <property object at 0x7fe1b595a2b8>

rawDescription: Set and Get @property method in Python by string variable


rawDescription: Elegant way to iterate over heads of lists in Python


rawDescription: How to convert a Date string to a DateTime object?

description: Convert a Date string to a DateTime object


code:
import pyparsing as P
key = P.oneOf("ids fields")
equal = P.Literal('=')
key_equal = key + equal
val = ~key_equal + P.delimitedList(P.Word(P.alphanums), ", ", combine=True)
gr = P.OneOrMore(P.Group(key_equal+val))
print gr.parseString("ids = 12, 13, 14 fields = name, title")

rawDescription: Non greedy parsing with pyparsing

description: Non greedy parsing with pyparsing


code:
import threading

lock = threading.Lock()

class PyThread(threading.Thread):

    def __init__(self, name):
        super(PyThread, self).__init__()
        self.name = name

    def run(self):

        for i in range(10):
            lock.acquire()
            print i, self.name,
            lock.release()

threads = []
for i in range(5):
    name = chr(i + ord('a'))
    threads.append(PyThread(name))

for thread in threads:
    thread.start()

for thread in threads:
    thread.join()

rawDescription: Custom Locks Threading python

description: Custom Locks Threading python


code: print type(a)

rawDescription: How to get Qt widget type

description: Get Qt widget type


code:
from Bio.Blast import NCBIXML
from Bio.Blast import NCBIWWW

lst=['TGCCCCGAAAATGAACTCAGTAAAGAATGACAGTTTCGCAAGACCCGTTGCTTTTTCAGTGCTAGCTAGCTGACTGATCGTAGCTGACGTAGTCTAGCTAGC','ATCGATCGTACTACGTAGCTGATCGTAGCTAGCTAGCTGATCGTAGCTATCGTACGTAGCTGATCGATCGTAGCTGACTGACGTACGTAGCTGATCGTAGCTAGCTAGCTAGCTGATCGATC']
eq="Homo sapiens[Organism]"
# download with lst[1]
print "download start"
rslt  = NCBIWWW.qblast("blastn", "nr", lst[1],entrez_query=eq)
print "download end"
print "parsing start"
rcrds = NCBIXML.parse(rslt)
print "parsing end"
br = rcrds.next()
print "br.alignments"
print br.alignments

rawDescription: Using for loop for downloading results from blast


code:
import re
with open('abc') as f:
    for line in f:
        line = re.sub(r'\+|;','\n',line.strip())
        print line

rawDescription: Python - In a string find a character and print remaining part of string in a new line


code:
def isAscending(xs):
    for n in range(len(xs) - 1):
        if xs[n] > xs[n+1]:
            return False
    return True

print isAscending([1,2,3,4]) # True
print isAscending([1,2,4,3]) # False

rawDescription: How do I tell if a list is in ascending order? Just needs to return True or False

description: Tell if a list is in ascending order? Just needs to return True or False


code:
for match in matches:
    print match

rawDescription: Regex: How to match sequence of key-value pairs at end of string


code:
for column in inspect(Dog).columns:
    print column.foreign_keys
# set([])
# set([ForeignKey('owner.id')]

rawDescription: SQLAlchemy determine whether an Integer attribute is a Foreign Key or not using inspector


code:
import serial

def my_usb():
    s_handle = serial.Serial('/dev/tty.usbmodem422651', 115200)

# or any other end condition
while True:
    try:
        if s_handle.inWaiting():
            print s_handle.read(s_handle.inWaiting())
    except KeyboardInterrupt:
        print "exiting...."
    finally:
        s_handle.close()

if __name__ == "__main__":
    my_usb()

rawDescription: pySerial: port only works the first I use it after I power it on

description: PySerial: port only works the first I use it after I power it on


code:
import time
lis = ['a', 'b', 'c', 'd', 'e']
for x in lis:
    print x
    time.sleep(1)

rawDescription: Print each item in list one second after the other (PYTHON)


code:
def both_ends(s):
    return s[:2] + s[-2:] if len(s) > 4 else s

lst = ('apple', 'pizza', 'x', 'joke')
print map(both_ends, lst)          #You would need `list(map(...))` for Python 3.x

rawDescription: How do I loop through each string in my list?

description: Loop through each string in my list


code:
import numpy as np

x = np.arange(9)
y = x.reshape(3,3)

print x
print y

y[2,2] = 10000

print x
print y

rawDescription: Python 3.1- Grid Simulation Conceptual issue


code:
from operator import attrgetter
from itertools import groupby
def getMatches(people, prop):
    people = sorted(people, key = attrgetter(prop))
    return [list(grp) for k, grp in groupby(people, attrgetter(prop))]

print getMatches(people, "age")

rawDescription: Python get objects in list with matching attributes


code:
class CallableValue(object):
    def __init__(self, name):
        self.name = name
    def __call__(self, *args, **kwargs):
        print "Lo, {} was called!".format(self.name)

class Bar(object):
    def __getattr__(self, name):
        return CallableValue(name)

b = Bar()
something = b.test_method
something
something()

rawDescription: Determine if __getattr__ is method or attribute call


code:
from itertools import groupby

class splitter(object):

    def __init__(self, breaker):
        self.breaker = breaker
        self.current_group = 0

    def __call__(self, item):
        if item == self.breaker:
            self.current_group+=1
        return self.current_group

    def group(self, items):
        return (list(v) for k,v in groupby(items,self))

print list(splitter('00:00').group(items))

rawDescription: Python: how to split a list into an unknown number of smaller lists based on a delimeter


code:
class baz:    # old-style class in Python 2.x where x >= 2
    def __getitem__(self, option):
        return option

c = baz()
print c[:]    # slice(0, 2147483647, None)

rawDescription: Subclass' __getitem__ returns unexpected slice


rawDescription: Group data in csv by season and year using python and pandas


code:
import time
import numpy as np
import cv2

gray = cv2.imread('lena_full.jpg',0)
height, width = gray.shape
h = np.empty((height,width,3), np.uint8)

t = time.time()
for i in xrange(height):
    for j in xrange(width):
        k = gray.item(i, j)
        if k == 127:
            h.itemset(i, j, 0, 255)
            h.itemset(i, j, 1, 255)
            h.itemset(i, j, 2, 255)
        elif k > 127:
            h.itemset(i, j, 0, 0)
            h.itemset(i, j, 1, 0)
            h.itemset(i, j, 2, 255-k)
        else:
            h.itemset(i, j, 0, k)
            h.itemset(i, j, 1, 0)
            h.itemset(i, j, 2, 0)
print time.time()-t

rawDescription: Performance comparison of OpenCV-Python interfaces, cv and cv2


code:
from collections import defaultdict
import re

PATTERN = '''
    \s*                         # Any amount of space
    (dylankid|senpai)           # Capture person
    :\s                         # Colon and single space
    (.*?)                       # Capture everything, non-greedy
    (?=\sdylankid:|\ssenpai:|$) # Until we find following person or end of string
'''
s = "  dylankid: *random words* senpai: *random words* dylankid: *random words* senpai: *random words*"
res = defaultdict(list)
for person, message in re.findall(PATTERN, s, re.VERBOSE):
    res[person].append(message)

print res['dylankid']
print res['senpai']

rawDescription: Slicing a String after certain key words are mentioned into a list


code:
import random
messages = {
    'animal': "rawr I'm a tiger",
    'vegetable': "Woof, I'm a carrot",
    'mineral': "Rumble, I'm a rock",
}
print messages[random.choice(messages.keys())]

rawDescription: I can select randomly from a list... but how do I use this as a variable for different commands? Python


code:
def findExclude(string, search_str, exclude_str):
    string = string.lower()
    return search_str in string and exclude_str not in string

print findExclude("CatBlablablaDog", 'cat', 'dog')
print findExclude("blablaCatBlabla", 'cat', 'dog')
print findExclude("Dog_blabla_Cat", 'cat', 'dog')

rawDescription: RegExp Look for part but exclude If

description: RegExp Look for part but exclude If


code:
from bs4 import BeautifulSoup

data = """

"""

soup = BeautifulSoup(data, 'html.parser')
for index, image in enumerate(soup.find_all('img'), start=1):
    tag = soup.new_tag('img', src='cid:image{}'.format(index))
    image.replace_with(tag)

print soup.prettify()

rawDescription: How to replace a number of string with incremental count in python

description: Replace a number of string with incremental count in python


code:
import sys

def main():
    # check and load command line arguments
    # your code
    if len(sys.argv) != 4:
        print('Incorrect number of arguments, should be 3')
        sys.exit(1)

    # open files using file io
    # your code
    f1 = open(log1, 'r')
    f2 = open(log2, 'r')

    # list comprehension to process and filter log files
    l1 = [ x.strip().split(" ",2) for x in f1.readlines() if x.strip() != "---" ]
    l2 = [ x.strip().split(" ",2) for x in f2.readlines() if x.strip() != "---" ]

    f1.close()
    f2.close()

    sorted_merged_lists = sorted(l1 + l2)

    results = [ x for x in sorted_merged_lists if x[1] == name ]

    for result in results:
        print result

main()

rawDescription: How to merge two lists at a delimited token in python3

description: Merge two lists at a delimited token in python3


code:
globals()['p234'] = Point(1, 2)
print p234

rawDescription: Dynamically define variable names

description: Dynamically define variable names


code:
class Descriptor(object):
    def __get__(self, obj, type=None):
        print '__get__(%r, %r)' % (obj, type)
class A(object):
    desc = Descriptor()
A.desc
A().desc

rawDescription: Accessing function from class and from instance of this class


code:
import json
import ansible.runner
import ansible.playbook
import ansible.inventory

example_inventory = ansible.inventory.Inventory('path/to/your/inventory')
pm = ansible.runner.Runner( module_name = 'debug', module_args = 'var=hostvars', timeout = 5, inventory = example_inventory, subset = 'all')
out = pm.run()
print json.dumps(out, sort_keys=True, indent=4, separators=(',', ': '))

rawDescription: How to run ansible module in python

description: Run ansible module in python


code:
print re.findall(r'[\w@#]+', 'talking about #python with @someone is so much fun! Is there a     140 char limit? So not cool!')
# ['talking', 'about', '#python', 'with', '@someone', 'is', 'so', 'much', 'fun', 'Is', 'there', 'a', '140', 'char', 'limit', 'So', 'not', 'cool']

rawDescription: How to format tweets using python through twitter api?

description: Format tweets using python through twitter api


code:
def method():
    print "implemented method"

rawDescription: Creating Python Façade Package

description: Creating Python Façade Package


code:
# Find rows where 'r_val' = 1 and replace its 'fld1' with 'fld2' in
# the entire frame.
df = df.replace(list(df['fld1'][df['r_val']==1]), list(df['fld2'][df['r_val']==1]))

# Eliminate all edges that have collapsed
df = df[df['fld1'] <> df['fld2']]

# Sum up 'r_val' for all edges with the same 'fld1' and 'fld2'
df = df.groupby(['fld1','fld2'], group_keys=1)['r_val'].sum().reset_index()

rawDescription: Edge Contraction in Pandas

description: Edge Contraction in Pandas


code:
#!/home/python
import cgi
import cgitb
cgitb.enable()

form = cgi.FieldStorage()

keyword = form.getvalue('keyword')

print 'Content-type: text/html\r\n\r'
print '<html>'
print keyword
print '</html>'

rawDescription: CGI form submit button using python

description: CGI form submit button using python


rawDescription: Datetime in Python, just printing out the time and formatting


code:
def fn(n):
    return [[j for j in range(1,i+1) if not i % j and i >= j]
            for i in n if isinstance(n, list)]

print fn([4, 12, 15])

rawDescription: Storing a list of results in a list

description: Storing a list of results in a list


code:
from lepl import *

survey = '''GPS,PN1,LA52.125133215643,LN21.031048525561,EL116.898812'''

number = Real() >> float

with Separator(~Literal(',')):
    latitude = ~Literal('LA') + number
    longitude = ~Literal('LN') + number
    elevation = ~Literal('EL') + number

    line = (~Literal('GPS')
             & ~Literal('PN1')
             & latitude
             & longitude
             & elevation)

print line.parse(survey)

rawDescription: pyparsing example

description: Pyparsing example


code:
from bs4 import BeautifulSoup as bs

soup = bs(souce_code)
elements = soup.find_all('p')

for e in elements:
    style = e.get('style').split(';')  # Here I'm account for multiple entries in the style
    for s in style:
        if 'display' in s:
            print s.split(':')[1]  # Prints 'none', 'block' or any other display style.

rawDescription: Python scrape style display:none

description: Python scrape style display:none


code:
import re, string, timeit

s = "string. With. Punctuation"
exclude = set(string.punctuation)
table = string.maketrans("","")
regex = re.compile('[%s]' % re.escape(string.punctuation))

def test_set(s):
    return ''.join(ch for ch in s if ch not in exclude)

def test_re(s):  # From Vinko's solution, with fix.
    return regex.sub('', s)

def test_trans(s):
    return s.translate(table, string.punctuation)

def test_repl(s):  # From S.Lott's solution
    for c in string.punctuation:
        s=s.replace(c,"")
    return s

print "sets      :",timeit.Timer('f(s)', 'from __main__ import s,test_set as f').timeit(1000000)
print "regex     :",timeit.Timer('f(s)', 'from __main__ import s,test_re as f').timeit(1000000)
print "translate :",timeit.Timer('f(s)', 'from __main__ import s,test_trans as f').timeit(1000000)
print "replace   :",timeit.Timer('f(s)', 'from __main__ import s,test_repl as f').timeit(1000000)

rawDescription: Best way to strip punctuation from a string in Python

description: Strip punctuation from a string in Python


code:
def my_func2():
    print 'func2'

rawDescription: Importing Modules from Multiple Parallel Subdirectories (Python)


code:
import numpy as np

aa= np.random.random([4,3])
print aa
print
print np.max(aa,axis=0)
print
print np.max(aa,axis=1)

rawDescription: finding the max of a column in an array

description: Finding the max of a column in an array


code: print "%-10s" % s, "<this will be 9 spaces away from the '5'>"

rawDescription: How to Send Packets to a Remote Minecraft Classic Server in Python?


code: print dict_list[0]["Client"], dict_list[0]['Contact Name'], dict_list[0]['Email']

rawDescription: Python Dictionary inside a list (pulling individual values)


code:
import script1
print script1.main()

rawDescription: Return values from one script to another script


code:
found = False
range_lower_bound = 1
range_high_bound = 100

print "Think of a number between 1 and 100 (inclusive)."
print "Answer the following questions with letters y or Y for yes and n or N for no."

while not found:
    range_mid = (range_high_bound + range_lower_bound) / 2
    x = raw_input('interval: [%s,%s]. Is your number <= %s? ' % (range_lower_bound, range_high_bound, range_mid))
    if x.lower() == 'y':
        # Check if this is the last question we need to guess the number
        if range_mid == range_lower_bound:
            print "Your number is %s" % (range_lower_bound)
            found = True
        range_high_bound = range_mid
    # here i'm defaulting "anything" no N for simplicity
    else:
        # Check if this is the last question we need to guess the number
        if range_mid == range_lower_bound:
            print "Your number is %s" % (range_high_bound)
            found = True
        range_lower_bound = range_mid + 1

rawDescription: Python number guessing game

description: Python number guessing game


code:
class Foo:
    def __init__(self, val): self.val = val
    def __hash__(self): return hash(self.val)
    def __eq__(self, other): return self.val == other.val
    def __repr__(self): return 'Foo(%r)' % self.val

print set([Foo(3), Foo("bar")])

rawDescription: Operator Overloading Python

description: Operator Overloading Python


code:
s= 'Hello, World!'
codeList = [ord(c) for c in s]
if len(codeList)%2 > 0:    codeList.append(0)
finalList = [codeList[d]*256+codeList[d+1] for d in range(0,len(codeList)-1,2)]

print codeList
print finalList

rawDescription: ascii string to sequence of 16-bit values

description: Ascii string to sequence of 16-bit values


code: print things.get(find)

rawDescription: More efficient way of getting things from a dictionary


code:
from Tkinter import *

def double_clicked(event):
    """ This function will be called when a user double-clicks on a list element.
        It will print the filename of the selected file. """
    file_id = event.widget.curselection()  # get an index of the selected element
    filename = event.widget.get(file_id[0])  # get the content of the first selected element
    print filename

if __name__ == '__main__':
    root = Tk()
    files = ['file1.h264', 'file2.txt', 'file3.csv']

    # create a listbox
    listbox = Listbox(root)
    listbox.pack()

    # fill the listbox with the file list
    for file in files:
        listbox.insert(END, file)

    # make it so when you double-click on the list's element, the double_clicked function runs (see above)
    listbox.bind("<Double-Button-1>", double_clicked)

    # run the tkinter window
    root.mainloop()

rawDescription: File Selection From Remote Machine In Python


rawDescription: Split list of datetime objects into keys(date) and values(times)


rawDescription: Python regular expression issues

description: Python regular expression issues


code:
print strfdelta(delta_obj, "%D days %H:%M:%S")
print strfdelta(delta_obj, "%H hours and %M to go")

rawDescription: formatting python timedelta objects

description: Formatting python timedelta objects


code:
import urllib2
from bs4 import BeautifulSoup
response = urllib2.urlopen("http://fantasy.premierleague.com/entry/38861/event-history/8/")
html = response.read()
tablestart = html.find('<!-- pitch view -->') + 19
print tablestart
tableend = html.find('<!-- end ismPitch -->')
print tableend
html = html[tablestart:tableend]
soup = BeautifulSoup(html)

rawDescription: the Html and the soup result is way different

description: The Html and the soup result is way different


code:
# defining the function f - won't print anything, since it's just a function definition
def f(x):
    print x
# and now calling the function on the argument "Hello!" - this should print "Hello!"
f("Hello!")

rawDescription: Running python script in terminal, nothing prints or shows up - why?


code:
def make_properties(skip=None):
    if skip is None:
        skip=[]
    def f(c):
        from collections import defaultdict
        props=defaultdict(dict)
        for k,v in vars(c).items():
            if k.startswith("Get"):
                props[k[3:]]['getter']=v
            if k.startswith("Set"):
                props[k[3:]]['setter']=v
        for k,v in props.items():
            if k in skip:
                continue
            setattr(c,k,property(v.get('getter'),v.get('setter')))
        return c
    return f

@make_properties(skip=['Y'])
class C(object):
    def GetX(self):
        print "GetX"
        return self._x

    def SetX(self, value):
        print "SetX"
        self._x = value

    def GetY(self):
        print "GetY"
        return self._y

    def SetY(self, value):
        print "SetY"
        self._y = value

c=C()
c.X=5
c.X
c.Y=5
c.Y

rawDescription: Automatic transformation from getter/setter to properties


code:
a = 25

def enclosing():
   a = 2
   def enclosed():
       global a  # <<< We're adding this
       print a
   enclosed()

enclosing()

# Prints 25, as supplied in the global scope

rawDescription: Python : Why is it said that variables that are only referenced are implicitly global?


code:
def unique_append(left, right):
  return left + [elem for elem in right if elem not in left]
  # Example only! Don't do this with lists, use sets!

arr = [[1, 2], [3, 6, 8, 1], [2, 4, 7]]
print reduce(unique_append, arr)
# [1, 2, 3, 6, 8, 4, 7]

rawDescription: operate through subarrays of an array recursively merging them (python)

description: Operate through subarrays of an array recursively merging them (python)


code:
import numpy as np

M = np.arange(1500*2000).reshape(1500, 2000)
z = np.zeros(700)

# broadcasting over the first dimension
_, M_broadcast = np.broadcast_arrays(z[:, None, None], M[None, ...])

print M_broadcast.shape, M_broadcast.flags.owndata
# (700, 1500, 2000), False

rawDescription: python - repeating numpy array without replicating data

description: Python - repeating numpy array without replicating data


code:
for i in range(len(l)):
  for c in map(' | '.join, itertools.combinations(l, i + 1)):
    print c

rawDescription: Algorithm to perform K-combinations for all k on sentences


rawDescription: Comparing an arbitrary number of lists element by element


code:
import subprocess

def ExecCMS_AGT_DB(cmd):
        outfile = open(cmd+'.txt','w')
        print "\ncmd $: "+cmd+" start"
        subprocess.call([cmd, "start"], stdout=outfile)
        print "\ncmd $: "+cmd+" stop"
        subprocess.call([cmd, "stop"], stdout=outfile)
        outfile.close()

def ExecCmd():
        ExecCMS_AGT_DB("srocms")

if __name__=="__main__":
        ExecCmd()

rawDescription: Why os.system is not able to redirect to a file? How to enable that?


rawDescription: Python: Replace ith occurence of x with ith element in list


code:
def addContact(self):
    self.name = str(self.nameLe.text())
    print self.name

rawDescription: How do I get the input from a PyQt linedit object?

description: Get the input from a PyQt linedit object


code:
# get_zip_data() gets a zip archive containing 'foo.txt', reading 'hey, foo'

from StringIO import StringIO
zipdata = StringIO()
zipdata.write(get_zip_data())
myzipfile = zipfile.ZipFile(zipdata)
foofile = myzipfile.open('foo.txt')
print foofile.read()

# output: "hey, foo"

rawDescription: Python: downloading and unzipping a .zip file without writing to disk


code:
words = ['road', 'roadwork', 'pill', 'pillbox', 'pillow', 'ball', 'football', 'basketball', 'work', 'box', 'foot', 'basket']

wordSet = set(words)

def isWord(w):
    return w in wordSet

def isCompoundWord(word):
    for idx in range(1, len(word)):
        left = word[:idx]
        right = word[idx:]
        if isWord(left) and isWord(right):
            return True
    return False

nonCompoundWords = [word for word in words if not isCompoundWord(word)]
print nonCompoundWords

rawDescription: Separating compound nouns from basic nouns part 2


code:
import requests, lxml
from bs4 import BeautifulSoup

parsedsongs = []
result = requests.get('http://www.swr3.de//-/id=47424/cf=42/did=65794/93avs/index.html?hour=5&date=2015-10-23')
soup = BeautifulSoup(result.content, "lxml")
detailbodys = soup.find_all('div', 'detail-body')
for detailbody in detailbodys:
    title = detailbody.h4.string.encode('utf-8').strip()
    if detailbody.h5:
        artist = detailbody.h5.string.encode('utf-8').strip()
    else:
        artist = detailbody.span.string.encode('utf-8').strip()
    parsedsongs.append({'artist': artist, 'title': title})

for entry in parsedsongs:
    print 'Artist: {}\tTitle: {}'.format(entry['artist'], entry['title'])

rawDescription: Extracting text from HTML file using Python (Music Artist / Title)


code: `sentiment`

rawDescription: reStructuredText: README.rst not parsing on PyPI

description: ReStructuredText: README.rst not parsing on PyPI


code:
import fileinput
for line in fileinput.input(['file1.txt', 'file2.txt']):
    print line

rawDescription: Iterate across lines in two files in sequence


code:
A = np.zeros(4, dtype=float)
B=np.array([1,2,3,4])
C=np.array([1,2,1,3])
A[C] += B
print A

rawDescription: Assembly numpy vector

description: Assembly numpy vector


code:
gg = df.groupby(df["ORGANIZATION"].str.contains("Org1"))
for k,g in gg:
    print k
    print g

rawDescription: Filtering content by whether field contains a value


rawDescription: Joining all rows of a CSV file that have the same 1st column value in Python


code:
from threading import Thread

def server():
    while True:
        c, addr = s.accept()
        print 'Got connection from', addr
        c.send('Hi blork...')
        c.close()

t = Thread(target=server)
t.start()

rawDescription: Socket Programming with python

description: Socket Programming with python


code:
import re
from bs4 import BeautifulSoup

html = """

My HomePage
Sections

"""

soup = BeautifulSoup(html)
for a in soup.find_all("a", text=re.compile('Home')):
    print a['href']

rawDescription: Extract links if anchor text contains keyword


code:
from remainder import xy
def GCD(x,y):
    #gives the Greatest Common Divisor of two values.
    while y != 0:
        r = xy(x,y)
        x = y
        y = r
    print x

rawDescription: Python - Trying to use the value of a name from one module in a different module


code:
x = 1;
class Point:
    x = 2
print x # will print 1

rawDescription: Resetting variables

description: Resetting variables


code:
from bs4 import BeautifulSoup

html = """<frameset border="0" framespacing="0" frameborder="0" rows="85,*">
<frame border="0" marginheight="0" name="logoframe" scrolling="no" noresize target="middle" src="a.html" onload="reload()">

<frameset cols="235,*">
<frame border="0" name="left" src="b.html" scrolling="no"><frame border="0" noresize name="main" src="c.html"  scrolling="auto"></frameset><noframes>

This page uses frames, but your browser doesn't support them.

</noframes>
</frameset>"""

soup = BeautifulSoup(html)

frame = soup.find('frame', attrs={'name': 'main'})
print frame['src']

rawDescription: Regex: How to find attribute in html, that includes another attribute


code:
import sys

if __name__=="__main__":
    print "argument:", sys.argv

    inputfile = sys.argv[1]
    print "inputfile:", inputfile

    outputfile = inputfile.split(".")[0] + "__output.txt"

    print "outputfile:", outputfile

    with open(outputfile, "wb" ) as fp:
        fp.write("some content")

rawDescription: Beginner Python: save output file as argv input filename


code:
loop1 = 10
loop2 = 10
num = 1

while(loop1>0):
    while(loop2>0):
        print num,
        num = num+1
        loop2=loop2-1
    print
    loop2=10
    loop1=loop1-1

rawDescription: Ten numbers per row using a pair of nested while loops


code:
if p.poll() is None: # Make sure you check against None, since it could return 0 when the process is complete.
    print "Process is still running"

rawDescription: Python subprocess calls hang?

description: Python subprocess calls hang


code:
import sys
from PyQt4.QtGui import *
from datetime import datetime

date = datetime.now()
filename = date.strftime('%Y-%m-%d_%H-%M-%S.jpg')
app = QApplication(sys.argv)
widget = QWidget()
# set up the QWidget...
widget.setLayout(QVBoxLayout())

label = QLabel()
widget.layout().addWidget(label)

def shoot():
    p = QPixmap.grabWindow(widget.winId())
    p.save(filename, 'jpg')
    label.setPixmap(p)        # just for fun :)
    print "shot taken"

widget.layout().addWidget(QPushButton('take screenshot', clicked=shoot))

widget.show()
app.exec_()

rawDescription: Screenshot of a window using python

description: Screenshot of a window using python


code:
mydata = "クラ"
print mydata.decode('utf-8')
print mydata

rawDescription: How to read oslo config value in unicode

description: Read oslo config value in unicode


code:
li=range(10,100)
while True:
    new_li=[]
    for e in li:
        s=str(e)
        n=abs(int(s[-2])-int(s[-1]))
        if len(set(s+str(n)))==len(s)+1:
            new_li.append(int(s+str(n)))
    if new_li:
        li=new_li
    else:
        print max(li)
        break

rawDescription: Lucky Number Finder

description: Lucky Number Finder


code:
a = 0
f = open('test.txt')
while a < 50:
    a = a + 1
    print f.readline(),
else:
    f.close()

rawDescription: Python - Loadtext for specific number of lines


code:
import pandas as pd
import numpy as np

times = pd.date_range('1/1/2011', periods=72, freq='M')
times = times[(times < times[20]) | (times > times[40])]

s = pd.DataFrame({"value":np.random.rand(len(times)), "times":times})
g = (s.times.diff() > np.timedelta64(60, "D")).astype(int).cumsum()
print s.groupby(g).min()

rawDescription: Python Pandas groupby closely spaced events


code:
def m1(name, bases, atts):
    print "m1 called for " + name
    return type(name, bases, atts)
def m2(name, bases, atts):
    print "m2 called for " + name
    return type(name, bases, atts)
class c1(object):
    __metaclass__ = m1
type(c1)
class sub1(c1):
    pass
type(sub1)
class c2(object):
    __metaclass__ = m2
class sub2(c1, c2):
    pass
type(sub2)

rawDescription: Customary To Inherit Metaclasses From type?


code:
import re

# Goal:  '717 N 2ND ST, MANKATO, MN 56001',
# Goal:  '717 N 2ND ST, MANKATO, MN, 56001',
regex = r'''
    (?x)            # verbose regular expression
    (?i)            # ignore case
    (?P<HouseNumber>\d+)\s+        # Matches '717 '
    (?P<Direction>[news])\s+       # Matches 'N '
    (?P<StreetName>\w+)\s+         # Matches '2ND '
    (?P<StreetDesignator>\w+),\s+  # Matches 'ST, '
    (?P<TownName>.*),\s+           # Matches 'MANKATO, '
    (?P<State>[A-Z]{2}),?\s+       # Matches 'MN ' and 'MN, '
    (?P<ZIP>\d{5})                 # Matches '56001'
'''

regex = re.compile(regex)

for item in (
    '717 N 2ND ST, MANKATO, MN 56001',
    '717 N 2ND ST, MANKATO, MN, 56001',
    '717 N 2ND, Makata, 56001',   # Should reject this one
    '1234 N D AVE, East Boston, MA, 02134',
    ):
    match = regex.match(item)
    print item
    if match:
        print "    House is on {Direction} side of {TownName}".format(**match.groupdict())
    else:
        print "    invalid entry"

rawDescription: Python make sure address matches specific format


code:
import re
urls_parts=['week', 'weeklytop', 'week/day']
urls_parts = sorted(urls_parts, key=lambda x: len(x), reverse=True)
rexes = [re.compile(r'{part}\b'.format(part=part)) for part in urls_parts]

urls = ['www.mysite.com/weeklytop/2', 'www.mysite.com/week/day/2', 'www.mysite.com/week/4']
for url in urls:
    for i, rex in enumerate(rexes):
        if rex.search(url):
            print url
            print urls_parts[i]
            print
            break

rawDescription: String comparing in python

description: String comparing in python


code:
class TextToNumbers():
    def __init__(self, number):
        self.text = str(number)
        self.chunks = self.parse_text_to_chunks(self.text)
        print self.chunks

    def parse_text_to_chunks(self, text_to_parse):
    # 1st parameter passed is the current INSTANCE on which this method is called
        self.var1 = text_to_parse[1:]
        return self.var1

TextToNumbers(123)

rawDescription: Python: How to define a variable in an __init__ function with a class method?


code:
for riga in array:
    if riga.strip() != '':     # <= riga here not line
        print riga.strip()     # Print add a new line so strip the stored \n

rawDescription: Print line of a txt file in python create break line when print


code:
with open('test.txt') as f:
    for line in f:
        print f.tell()

rawDescription: What is the difference between the buffering argument to open() and the hardcoded readahead buffer size used when iterating through a file?