code:
import sys
import numpy as np
import matplotlib.pyplot as pl
import matplotlib.mlab as mlab

n_epochs = 120
a = 140
while n_epochs <= a:
    sfreq = 1000.
    duration = 1000.
    times = np.arange(0, duration, 1 / sfreq)
    amp = 1.
    amp2 = 1.
    nse_amp = 0.5
    nfft = 512
    nse1 = np.random.rand(times.size) * nse_amp
    nse2 = np.random.rand(times.size) * nse_amp
    x =  amp * np.sin(2 * np.pi * 200 * times) + nse1
    y =  amp * np.sin(2 * np.pi * 200 * times + np.pi/5) + nse2

    shift = 100  # integer
    assert shift < sfreq * duration, 'Choose a smaller shift.'
    #y = amp2 * np.roll(x, shift) + nse2

    # coherence using mlab function
    cohxy, freqs = mlab.cohere(x, y, Fs=sfreq, NFFT=nfft)

    n_freqs = nfft/2 + 1

    def compute_mean_psd_csd(x, y, n_epochs, nfft, sfreq):
        '''Computes mean of PSD and CSD for signals.'''
        x2 = np.array_split(x, n_epochs)
        y2 = np.array_split(y, n_epochs)

        Rxy = np.zeros((n_epochs, n_freqs), dtype=np.complex)
        Rxx = np.zeros((n_epochs, n_freqs), dtype=np.complex)
        Ryy = np.zeros((n_epochs, n_freqs), dtype=np.complex)

        for i in range(n_epochs):
            Rxy[i], freqs = mlab.csd(x2[i], y2[i], NFFT=nfft, Fs=sfreq)
            Rxx[i], _ = mlab.psd(x2[i], NFFT=nfft, Fs=sfreq)
            Ryy[i], _ = mlab.psd(y2[i], NFFT=nfft, Fs=sfreq)

        Rxy_mean = np.mean(Rxy, axis=0)
        Rxx_mean = np.mean(Rxx, axis=0)
        Ryy_mean = np.mean(Ryy, axis=0)

        return freqs, Rxy, Rxy_mean, np.real(Rxx_mean), np.real(Ryy_mean)

    def my_coherence(n_freqs, Rxy_mean, Rxx_mean, Ryy_mean):
        ''' Computes coherence. '''

        coh = np.zeros((n_freqs))
        for i in range(0, n_freqs):
            coh[i] = np.abs(Rxy_mean[i]) / np.sqrt(Rxx_mean[i] * Ryy_mean[i])

        return coh

    def my_con(x, y, n_epochs, nfft, sfreq, con_name='coh'):
        '''Computes connectivity measure mentioned on provided signal pair and its surrogates.'''

        freqs, Rxy, Rxy_mean, Rxx_mean, Ryy_mean = compute_mean_psd_csd(x, y, n_epochs, nfft, sfreq)

        # compute surrogates
        x_surr = x.copy()
        y_surr = y.copy()
        np.random.shuffle(x_surr)
        np.random.shuffle(y_surr)
        freqs_surro, Rxy_s, Rxy_s_mean, Rxx_s_mean, Ryy_s_mean = compute_mean_psd_csd(x_surr, y_surr, n_epochs, nfft, sfreq)

        if con_name == 'coh':
            coh = my_coherence(n_freqs, Rxy_mean, Rxx_mean, Ryy_mean)
            coh_surro = my_coherence(n_freqs, Rxy_s_mean, Rxx_s_mean, Ryy_s_mean)
            return coh, coh_surro, freqs, freqs_surro

        if con_name == '':
            print 'Please provided the connectivity method to use.'
            sys.exit()
        else:
            print 'Connectivity method unrecognized.'
            sys.exit()

    con_name = 'coh'

    con, con_surro, freqs, freqs_surro = my_con(x, y, n_epochs, nfft, sfreq, con_name) # for doing every con_surro calc. too add [i]

    # coherence using mlab function
    #cohxy, freqs = mlab.cohere(x, y, Fs=sfreq, NFFT=nfft)
    #pl.plot(freqs, cohxy)

    # plot results
    pl.figure('Connectivity')
    pl.plot(freqs, con)
    pl.plot(freqs_surro, con_surro)
    pl.legend(['Con', 'Surrogates'])
    pl.tight_layout()
    pl.show(False)
    pl.draw()
    n_epochs = n_epochs +1

rawDescription: Python while loop mulitple plotting

description: Python while loop mulitple plotting


code:
from time import time
start=time() # time just before raw_input called
raw_input('What is your name?')
end= time() # time just after user give some input
print end -start

rawDescription: Capruting time difference for the raw_input Python


code:
import xml.etree.ElementTree as ET

tree = ET.parse('input.xml')
tree_ = tree.findall('bar')

for i in tree_:
    i_ = i.findall('type')

    for elem in i_:
        if elem.attrib['name'] == 'controller':
            print elem.text

rawDescription: Python XML Parse with xml attributes

description: Python XML Parse with xml attributes


code:
class num(object):
  def __init__(self, x, flag):
    self.x = x
    self.flag = flag
  def __float__(self):
    return float(self.x)
  from functools import wraps
def wrapper(f):
  @wraps(f)
  def wrapped(*a):
    if not all(getattr(x, 'flag', True) for x in a):
      return None
    return f(*(getattr(x, 'x', x) for x in a))
  return wrapped

import inspect
import math
for n, v in inspect.getmembers(math, inspect.isroutine):
  setattr(math, n, wrapper(v))

a = num(3, True)
print math.sqrt(a)
b = num(4, False)
print math.sqrt(b)

rawDescription: Decorate a whole library in Python

description: Decorate a whole library in Python


code:
import os

a = 'c:' # removed slash
b = 'myFirstDirectory' # removed slash
c = 'mySecondDirectory'
d = 'myThirdDirectory'
e = 'myExecutable.exe'

print os.path.join(a + os.sep, b, c, d, e)

rawDescription: mixed slashes with os.path.join on windows

description: Mixed slashes with os.path.join on windows


code:
class Cls1(object):
    def __init__(self, attribute_1):
        self.attribute_1 = attribute_1

class Cls2(object):
    def __init__(self, obj):
        self.wrapped_obj = obj
        self.attribute_2 = 2

    def __getattr__(self,name):
        # get in here only when attribute requested is not defined.
        # for Cls2. let's try to get it from our wrapped Cls1
        # object instead.
        return getattr(self.wrapped_obj, name)

cls1 = Cls1(1)
cls2 = Cls2(cls1)

## ideal output should be:
print cls2.attribute_1  # outputs 1
print cls2.attribute_2  # outputs 2

rawDescription: Pythonic way to inherit attribute values between classes


code:
rows = table.findAll('tr')
for tr in rows:
    cols = tr.findAll('td')
    if 'cell_c' in cols[0]['class']:
        # currency row
        digital_code, letter_code, units, name, rate = [c.text for c in cols]
        print digital_code, letter_code, units, name, rate

rawDescription: How to parse html table with python and beautifulsoup and write to csv

description: Parse html table with python and beautifulsoup and write to csv


code:
class A(object):
    def __init__(self, s=''):
        self.s = s

    def __eq__(self, other):
        return self.s.lower() == other.s.lower()

a = A('aaaa')
b = A('AAAA')
print a == b # prints True
b = A('bbbb')
print a == b # prints False

rawDescription: python equivalent of Comparable

description: Python equivalent of Comparable


code:
a = [3, 2, 1]
print a.sort()
a
sorted(a)

rawDescription: Why can't I sort a list right after I make it?


code:
# Python_2

def copy_with_callback(sourceFile, destinationFile, callbackFunction):
    chunk = 4*1024
    sourceSize = os.path.getsize(sourceFile)
    destSize = 0
    with open(sourceFile, 'rb') as fSrc:
        with open(destinationFile, 'wb') as fDest:
            data = fSrc.read(chunk)
            if len(data) == 0:
                break
            fDest.write(data)
            destSize += len(data)
            callbackFunction(sourceSize, destSize)

def example_callback_function(srcSize, dstSize):
    ''' Just an example with print.  Your viewer code will vary '''
    print 'Do something with these values:', srcSize, dstSize
    print 'Percent?', 100.0 * dstSize / srcSize

def main():
    src = '/tmp/A/path/to/a/file.txt'
    dest = '/tmp/Another/path/to/a/file.txt'
    copy_with_callback(src, dest, example_callback_function)

rawDescription: How can you get real time copy progress of a large file with Python?

description: Get real time copy progress of a large file with Python


rawDescription: Python enforce unicode escape

description: Python enforce unicode escape


code:
from multiprocessing import Pool
from multiprocessing import Manager
import random

manager = Manager()
dproxy = manager.dict()

urls = ['www.yahoo.com','www.google.com','www.microsoft.com','www.apple.com','www.cisco.com']

def f(url):
    shared_dict = dproxy[0]
    key = random.randrange(1,10)
    value = random.randrange(11,20)
    shared_dict[key] = value
    dproxy[0] = shared_dict

if __name__ == '__main__':
    dproxy[0] = {}
    pool = Pool(processes=5)

    pool.map(f, urls)
    print dproxy[0]

rawDescription: how do I write to a parent dictionary?

description: Write to a parent dictionary


code:
print json.dumps({'4': 5, '6': 7}, sort_keys=True,
                 indent=4, separators=(',', ': '))

rawDescription: How to prettyprint (human readably print) a Python dict in json format (double quotes)?

description: Prettyprint (human readably print) a Python dict in json format (double quotes)


code:
def test_quests(quests):
    num_total = len(quests)
    different_ids = len(set((q.ID for q in quests)))
    different_names = len(set((q.name for q in quests)))
    print "Multiple ID's found = %d" % (num_total - different_ids)
    print "Multiple Name's found = %d" % (num_total - different_names)

rawDescription: How to check for multiple attributes in a list

description: Check for multiple attributes in a list


code:
t = Session.query(
    Posts.user_id,
    func.max(Posts.post_time).label('max_post_time'),
).group_by(Posts.user_id).subquery('t')

query = Session.query(User, Posts).filter(and_(
    User.user_id == Posts.user_id,
    User.user_id == t.c.user_id,
    Posts.post_time == t.c.max_post_time,
))

for user, post in query:
    print user.user_id, post.post_id

rawDescription: SQLAlchemy - subquery in a WHERE clause

description: SQLAlchemy - subquery in a WHERE clause


code:
number_list = []
while True:
    line = raw_input('Enter number:')
    if line == 'done':
        break
    try:
        n = int(line)
        number_list.append(n)
    except ValueError:
        print 'invalid input'
print 'Done!'
print number_list

rawDescription: creating a list of in raw_input

description: Creating a list of in raw_input


code:
names = [u'Putin', u'Fattah', u'Vladimir',u'Cameron', u'Bashar', u'al-Baghdadi']
counts = [3, 6, 1, 1, 1, 0]
results = [6, 6, 1, 1, 1, 0]

all_vals = zip(names, counts, results)
in_order = sorted(all_vals, key = lambda x: x[2], reverse = True)
print in_order
print in_order[0][0] #Putin
print in_order[1][0] #Fattah

for i,e in enumerate(in_order):
     print i, e[0]

# 0 Putin
# 1 Fattah
# 2 Vladimir
# ...

rawDescription: Getting elements by index [Python]

description: Getting elements by index [Python]


code:
from bs4 import BeautifulSoup
mysoup = BeautifulSoup('hello	')
td = mysoup.find('td')
print [s for s in td.children if isinstance(s, basestring)]

rawDescription: How to elegantly get top level text of a html td with BeautifulSoup4?

description: Elegantly get top level text of a html td with BeautifulSoup4


code:
def common(a,b,c):
    common = set(a) & set(b) & set(c)
    return True if common else False

a=[3, 8, 5, 10]
b=[4, 2, 6, 8]
c=[5, 3, 8, 7]
print common(a,b,c)

rawDescription: Common List Elements

description: Common List Elements


code:
from sqlalchemy import create_engine, Column, Integer, String, ForeignKey, Table
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship

engine = create_engine('sqlite:///:memory:', echo=True)
Session = sessionmaker(bind=engine)
session = Session()
Base = declarative_base(bind=engine)

class Product(Base):
    __tablename__ = 'product'

    id = Column(Integer, primary_key=True)
    name = Column(String, nullable=False)

    # cover image foreign key
    # use_alter=True along with name='' adds this foreign key after Image has been created to avoid circular dependency
    cover_id = Column(Integer, ForeignKey('image.id', use_alter=True, name='fk_product_cover_id'))

    # cover image one-to-one relationship
    # set post_update=True to avoid circular dependency during
    cover = relationship('Image', foreign_keys=cover_id, post_update=True)

class Image(Base):
    __tablename__ = 'image'

    id = Column(Integer, primary_key=True)
    path = Column(String, nullable=False)
    product_id = Column(Integer, ForeignKey(Product.id))

    # product gallery many-to-one
    product = relationship(Product, foreign_keys=product_id, backref='images')

    # nothing special was need in Image, all circular dependencies were solved in Product

Base.metadata.create_all()

# create some images
i1 = Image(path='img1')
i2 = Image(path='img2')
i3 = Image(path='img3')
i4 = Image(path='img4')

# create a product with those images, one of which will also be the cover
p1 = Product(name='sample', images=[i1, i2, i3, i4], cover=i2)

session.add(p1)
session.commit()

print 'cover:', p1.cover.path  # prints one cover image path
print 'images:', [i.path for i in p1.images]  # prints 4 gallery image paths

print 'image product:', p1.images[0].product.name  # prints product name from image perspective

rawDescription: flask-sqlalchemy multiple relationship types between two tables

description: Flask-sqlalchemy multiple relationship types between two tables


code:
for x in texts:
    for y in texts:
        print round(similarity(x,y),2),
    print

rawDescription: Print Table in Python

description: Print Table in Python


code:
import re
pattern = re.compile(r'foo(.*)bar')
with open(inFile, 'r') as fileList:
  searchResults = (pattern.search(line) for line in fileList)
  groups = (result.group(1) for result in searchResults if result is not None)
  print '\n'.join(groups)

rawDescription: How to improve my Python regex syntax?

description: Improve my Python regex syntax


code:
import re
text = """UINT32 CacheSize() const { return _cacheSize; }
    UINT32 LineSize() const { return _lineSize; }
    UINT32 Associativity(UINT64 obj, INT8 obj2) const { return _associativity; }
    VOID SplitAddress(const ADDRINT addr, CACHE_TAG & tag, UINT32 & setIndex) const
    VOID SplitAddress(const ADDRINT addr, CACHE_TAG & tag, UINT32 & setIndex, UINT32 & lineIndex) const
    {
        const UINT32 lineMask  = _lineSize - 1 INT8;
"""
for line in text.split("\n"):
    print re.sub(r'(U?INT\d+?)',r'PIN_\1', line)

rawDescription: Smart replace repeated values python

description: Smart replace repeated values python


code:
from BeautifulSoup import BeautifulStoneSoup
import cgi

def HTMLEntitiesToUnicode(text):
    """Converts HTML entities to unicode.  For example '&' becomes '&'."""
    text = unicode(BeautifulStoneSoup(text, convertEntities=BeautifulStoneSoup.ALL_ENTITIES))
    return text

def unicodeToHTMLEntities(text):
    """Converts unicode to HTML entities.  For example '&' becomes '&'."""
    text = cgi.escape(text).encode('ascii', 'xmlcharrefreplace')
    return text

text = "&, ®, <, >, ¢, £, ¥, €, §, ©"

uni = HTMLEntitiesToUnicode(text)
htmlent = unicodeToHTMLEntities(uni)

print uni
print htmlent
# &, ®, <, >, ¢, £, ¥, €, §, ©
# &, ®, <, >, ¢, £, ¥, €, §, ©

rawDescription: Convert HTML entities to Unicode and vice versa


code:
for line in file:
    line = line[1:].replace("\n", "")
    if not line: continue
    lines = line.split(" ")
    lines.sort(key=str.lower)
    line = ''.join(lines)
    print line

rawDescription: How to optimize this script

description: Optimize this script


code:
from comtypes import client, COMError
myclassinst = client.CreateObject('MyCOMClass.MyCOMClass')
try:
    myclassinst.DoInvalidOperation()
except COMError as e:
    print e.args
    print e.hresult
    print e.text

rawDescription: How to debug ctypes call of c++ dll?

description: Debug ctypes call of c++ dll


code:
s
s.split("HTTP")[0]
if "puzzle" in s.split("HTTP")[0].split("GET")[-1]:
  print "found puzzle"

rawDescription: Regular Expressions - testing if a String contains another String


code:
count = []
s='azcbobobegghakl'
a=''
b=''
word=''
for i in xrange(len(s)-1):
    a = s[i:i+1]
    b = s[i+1:i+2]
    if(ord(a)<ord(b)):
        word = word+a+b
    else:
        count.append(word)
print count

rawDescription: Python 2.7 Slice

description: Python 2.7 Slice


code:
print "Welcome to the student checker!"

students = ['Andreas', 'Martina', 'Maria']

def is_present(name_student):
    if name_student in students:
        print "Yes, {} is enrolled in the class!".format(name_student)
        return True

    elif name_student not in students:
        print "No, {} is not in the class.".format(name_student)
        return False

while True:
    name_student = raw_input("Please give me the name of a student (enter 'q' to quit): ")

    if name_student == 'q':
        print "Goodbye!"
        break

    is_present(name_student)

rawDescription: Function loop True or False

description: Function loop True or False


code:
import sys
import StringIO

# create file-like string to capture output
codeOut = StringIO.StringIO()
codeErr = StringIO.StringIO()

code = """
def f(x):
    x = x + 1
    return x

print 'This is my output.'
"""

# capture output and errors
sys.stdout = codeOut
sys.stderr = codeErr

exec code

# restore stdout and stderr
sys.stdout = sys.__stdout__
sys.stderr = sys.__stderr__

print f(4)

s = codeErr.getvalue()

print "error:\n%s\n" % s

s = codeOut.getvalue()

print "output:\n%s" % s

codeOut.close()
codeErr.close()

rawDescription: How do I execute a string containing Python code in Python?

description: Execute a string containing Python code in Python


code:
#! /usr/bin/python2
import os
import sys

space = 0L  # L means "long" - not necessary in Python 3
for root, dirs, files in os.walk(sys.argv[1]):
    for f in files:
        fpath = os.path.join(root, f)
        try:
            space += os.stat(fpath).st_size
        except OSError:
            print("could not read "+fpath)

sys.stdout.write("Total: {:d}\n".format(space))

rawDescription: Python os.walk and symlinks

description: Python os.walk and symlinks


code:
import sys
import os
import time

children = []

for i in range(0,3):
    pid = os.fork()

    if pid == -1:
        continue
    elif pid == 0:
        # Do work...
        print 'Child %d spawned' % os.getpid()
        sys.exit(0)
    else:
        children.append(pid)

time.sleep(5)

# ADD NEXT TWO LINES:
for pid in children:
    os.waitpid(pid, 0)

for pid in children:
    proc_path = '/proc/%d' % pid
    if not os.path.exists(proc_path):
        print 'Child %d is dead' % pid
    else:
        print 'Child %d is alive' % pid

rawDescription: Python forked processes won't die

description: Python forked processes won't die


code:
import os
import datetime

dict_final = {}
for elt in os.listdir('./tags'):
    if os.path.isdir(elt):
        # dict that compiles all filenames with last changes date
        files_stats = {filename: os.stat(os.path.join(elt, filename)).st_mtime
                       for filename in os.listdir(elt)}
        # Extract file changed last
        filename, last_changes = max(files_stats.iteritems(), key=lambda x:x[1])
        dict_final.update({elt: datetime.datetime.fromtimestamp(last_changes)})

print dict_final

rawDescription: Parse latest change to folder SVN with Python


code:
nouns = ['house','bee','ducks','blouse','cars']
for index, word in enumerate(nouns):
    if word[-1] == 'e':
        # if this word ends with e, add s
        nouns[index] = word+'s'
    elif word[-1] == 's':
        # if this word ends with s, remove last char
        nouns[index] = word[:-1]
print nouns

rawDescription: Python strings within lists

description: Python strings within lists


code:
d = [("xxx", "yyy") for i in range(8154741)]
a = numpy.array(d)
print a.nbytes/1024**2
print a[2,1]

rawDescription: A list with 70 MB on disk but 500MB in memory


rawDescription: string encode / decode

description: String encode / decode


code:
from Tkinter import *
import time
import random

l=["Thomas", "Philip", "John", "Adam", "Kate", "Sophie", "Anna"]       #creates a list with 7 items
def pri():  #function that asigns randomly item from l list to     variable a and prints it in CLI
    a = random.choice(l) #HOW CAN I PRINT a variable IN label     textvarible????
    print a     #prints in CLI
    time.sleep(0.5)
    return a

root = Tk()

var = IntVar() # instantiate the IntVar variable class
var.set("Philip")     # set it to 0 as the initial value

# the button command is a lambda expression that calls the set method on the var,
# with the var value (var.get) increased by 1 as the argument
Button(root, text="Choose name", command=lambda: var.set(pri())).pack()

# the label's textvariable is set to the variable class instance
Label(root, textvariable=var).pack()

mainloop()

rawDescription: How to print a variable in a Tkinter Label using Python?

description: Print a variable in a Tkinter Label using Python


code: print "\n".join(["%s     %s" % t for t in zip(x,y)])

rawDescription: Python conversion from array to string column


code:
import matplotlib.pyplot as plt
import subprocess, glob, re

def get_magnification(filename):
    p = subprocess.check_output('exiftool -tab %s'%filename,shell=True)

    xpix = float(re.findall('XpixCal=\d*.\d*',p)[0][8:])
    ypix = float(re.findall('YpixCal=\d*.\d*',p)[0][8:])

    mag = int(re.findall('p.\d+',p)[0][2:])

    return xpix,ypix,mag

xpix,ypix,mag = get_magnification('E3-9.tif')

print 'X pixels per nm: %.3f'%(xpix)
print 'Y pixels per nm: %.3f'%(ypix)
print 'Magnification:   %ix'%(mag)

rawDescription: Reading long exif tags in python

description: Reading long exif tags in python


code:
l = ['absolute', 'nicest']
print 'P', " ".join(l), 'Score'

rawDescription: Print list items in one line along with other things


code:
N = 4

def supers(number):
    zeros = sum(1 for bit in xrange(N) if (number >> bit) & 1 == 0)
    return 2**zeros

def solve(a,b,c):
    total = supers(a) + supers(b) + supers(c)
    total -= supers(a | b) # counted twice, remove one
    total -= supers(b | c) # counted twice, remove one
    total -= supers(a | c) # counted twice, remove one
    total += supers(a | b | c) # counted three times, removed three times, add one

    return total

print solve(0b1001,0b0011,0b0110)

rawDescription: Count bitmasks, enumerate 0s

description: Count bitmasks, enumerate 0s


code:
import pycurl, os

def send(file_contents, name):
    print "Sending file to pastebin...."
    curl = pycurl.Curl()
    curl.setopt(pycurl.URL, "http://pastebin.com/api_public.php")
    curl.setopt(pycurl.POST, True)
    curl.setopt(pycurl.POSTFIELDS, "paste_code=%s&paste_name=%s" \
                                   % (file_contents, name))
    curl.setopt(pycurl.NOPROGRESS, True)
    curl.perform()

if __name__ == "__main__":
    content = raw_input("Provide the FULL path to the file: ")
    with open(content, 'r') as f:
        send(f.read(), "yournamehere")
    print

rawDescription: Newbie question about file formatting in Python


code:
import scrapy

class TestSpider(scrapy.Spider):

    name = 'quoka'
    start_urls = ['http://www.quoka.de/immobilien/bueros-gewerbeflaechen']

    def parse(self, response):

        request = scrapy.FormRequest.from_response(
            response,
            formname='frmSearch',
            formdata={'classtype': 'of'},
            callback=self.parse_filtered
        )
        # print request.body
        yield request

    def parse_filtered(self,response):

        searchResults = response.xpath('//div[@id="ResultListData"]/ul/li')
        for result in searchResults:
            title = result.xpath('.//div[@class="q-col n2"]/a/@title').extract()
            print title

rawDescription: Python scrapy spider

description: Python scrapy spider


code:
import re
f=open("input.txt","r")
x="asasd3243sdfdsf23234sdsdf"
print re.findall(r""+f.readline(),x)

rawDescription: Loading regular expression patterns from external source?


code: print mail_accounts[0]["i"]

rawDescription: Python: json.loads returns items prefixing with 'u'


code:
import re

BAD_WORDS = ["spam", "ham"]
BAD_WORDS_RE = re.compile(r"\b(%s)\b" % "|".join(BAD_WORDS))

for i, line in enumerate(open("file.txt").readlines()):
    words = set(BAD_WORDS_RE.findall(line))
    if words:
        print "Found the following words on line %i: %s" % (i + 1, ", ".join(words))
        print line

rawDescription: python django analyze a file for a list of keywords

description: Python django analyze a file for a list of keywords


code:
#!/usr/bin/env python

import MySQLdb

# Open databse connection
db = MySQLdb.connect(host="****",user="****",passwd="****",db="****")

#Prepare a cursor object using cursor() method
cur = db.cursor(MySQLdb.cursors.DictCursor)

#Execute SQL query using execute() method
cur.execute("SELECT sensor_id, sensor_types.type_name FROM sensors INNER JOIN sensor_types ON sensors.type_id=sensor_types.type_id")

#Fetch the results
data = cur.fetchall()

#Print out results
for row in data:
    print row["sensor_id"],row["type_name"]

#Disconnect from server
db.close()

rawDescription: Python SQL query to retrieve data from relational DB


code:
import csv
reader = csv.reader(open("file.csv", "rb"), delimiter=',')
for line in reader:
    if "-1" not in line:
        print line

rawDescription: using python, how to remove whole line in csv file if specific character is present in this line?

description: Using python, how to remove whole line in csv file if specific character is present in this line


code:
for Line in file("Text.txt", "r"):
  if Line.find("sum") >= 0:
    print Line.split()[0]

rawDescription: Python Text file searching

description: Python Text file searching


code:
import fnmatch
import os
import os.path
import re

includes = ['*.doc', '*.odt'] # for files only
excludes = ['/home/paulo-freitas/Documents'] # for dirs and files

# transform glob patterns to regular expressions
includes = r'|'.join([fnmatch.translate(x) for x in includes])
excludes = r'|'.join([fnmatch.translate(x) for x in excludes]) or r'$.'

for root, dirs, files in os.walk('/home/paulo-freitas'):

    # exclude dirs
    dirs[:] = [os.path.join(root, d) for d in dirs]
    dirs[:] = [d for d in dirs if not re.match(excludes, d)]

    # exclude/include files
    files = [os.path.join(root, f) for f in files]
    files = [f for f in files if not re.match(excludes, f)]
    files = [f for f in files if re.match(includes, f)]

    for fname in files:
        print fname

rawDescription: Filtering os.walk() dirs and files

description: Filtering os.walk() dirs and files


code:
import xlwt, xlrd, csv, os

files = ['file1.csv','file2.csv','file3.csv','file4.csv']
outputfile = 'outputList.xls'
wbk = xlwt.Workbook()
sheetw = wbk.add_sheet('sheet 1')
row_offset, col_offset = 2, 2 # i.e. 2, 2 to print in C3 instead of A1

for fname in files:
    currentfile = xlrd.open_workbook(fname,'r')
    sheetr = currentfile.sheet_by_index(0)
    data = sheetr.cell(11,0).value
    print data #for testing
    sheetw.write(files.index(fname) + row_offset, 0 + col_offset, data)

wbk.save(outputfile)

rawDescription: Python: looking to capture a particular cell value from individual csv files in a directory and then list the values in a new Excel file


code:
def add_line(self, line, source, *lineno):
    """Append one line of generated reST to the output."""
    print self.indent + line
    self.directive.result.append(self.indent + line, source, *lineno)

rawDescription: Make Sphinx generate RST class documentation from pydoc


code:
# assumptions:
# - [('hates','DT'),('alice','JJ'),('but','CC')] is typoed and should be:
#   [('hates','VB'),('alice','NN'),('but','CC')]
# - matches can't overlap, matched elements are excluded from further checking
# - bigrams precede unigrams

main_text = [
  [('the','DT'),('mad','JJ'),('hatter','NN'),('likes','VB'),('tea','NN'),('and','CC'),('hats','NN')],
  [('the','DT'),('red','JJ'),('queen','NN'),('hates','VB'),('alice','NN')]
]
ngrams_to_match = [
  [('likes','VB'),('tea','NN'),('and','CC')],
  [('the','DT'),('mad','JJ'),('hatter','NN')],
  [('hates','VB'),('alice','NN'),('but','CC')],
  [('and','CC'),('the','DT'),('rabbit','NN')]
]

def slice_generator(sentence,size=3):
  """
  Generate slices through the sentence in decreasing sized windows. If True is sent to the
  generator, the elements from the previous window will be excluded from future slices.
  """
  sent = list(sentence)
  for c in range(size,0,-1):
    for i in range(len(sent)):
      slice = tuple(sent[i:i+c])
      if all(x is not None for x in slice) and len(slice) == c:
        used = yield slice
        if used:
          sent[i:i+size] = [None] * c

def gram_search(text,matches):
  tri_bi_uni = set(tuple(x) for x in matches) | set(tuple(x[:2]) for x in matches) | set(tuple(x[:1]) for x in matches)
  found = set()
  for i, sentence in enumerate(text):
    gen = slice_generator(sentence)
    send = None
    try:
      while True:
        row = gen.send(send)
        if row in tri_bi_uni - found:
          send = True
          found |= set(tuple(row[:x]) for x in range(1,len(row)))
          print "%s_gram_match, sentence[%s] = %r" % (len(row),i,row)
        else:
          send = False
    except StopIteration:
      pass

gram_search(main_text,ngrams_to_match)

rawDescription: Match trigrams, bigrams, and unigrams to a text; if unigram or bigram a substring of already matched trigram, pass; python


code:
import Tkinter as tkinter
import random
class MyGUI:
    def __init__(self):
        self.main_window = tkinter.Tk()
        self.button1 = tkinter.Button(self.main_window,text='Average',command=self.average)
        self.button1.pack()
        tkinter.mainloop()
    def average(self):
        self.mini_window = tkinter.Toplevel()
        self.avg_mess = tkinter.Label(self.mini_window,text='Results:')
        self.avg_result_var = tkinter.StringVar()
        self.avg_result_display = tkinter.Label(self.mini_window,textvariable=self.avg_result_var)
        self.avg_mess.pack(fill="both")
        self.avg_result_display.pack()
        self.button2 = tkinter.Button(self.mini_window,text='Calculate',command=self.avg_calc)
        self.button2.pack()
    def avg_calc(self):
        x = random.randint(100,200)
        self.avg_result = (100+300+x)/3
        print "result:", self.avg_result
        self.avg_result_var.set(self.avg_result)
gui = MyGUI()

rawDescription: Button Command with class in Python

description: Button Command with class in Python


code:
def setGlobals():
    global currentUserClientID, currentUserMaxLicences, currentUserActivatedLicences
    currentUserClientID             = 1
    currentUserMaxLicences          = 1
    currentUserActivatedLicences    = 1
    print "Set Globals"
    print currentUserClientID, currentUserMaxLicences, currentUserActivatedLicences

rawDescription: Set Global Variables in Function

description: Set Global Variables in Function


code:
def title_changed(widget, frame, title):
    print title

browser.connect('title-changed', title_changed)

rawDescription: How can I get title & scripts inside a webpage using webkit + gtk?

description: Get title & scripts inside a webpage using webkit + gtk


code:
a = [0, 1, 2]
for element in a:
    if not element:
        pass
    print element

for element in a:
    if not element:
        continue
    print element

rawDescription: Is there a different between `continue` and `pass` in a for loop in python?


code:
soup = BeautifulSoup(urllib2.urlopen('http://stackoverflow.com/'))
first_link = soup('a')[0]
print first_link
# current community
first_link['href'] = first_link['href'].replace('//', 'http://')
print first_link
# current community

rawDescription: BeautifulSoup modify an anchor tag in place?


rawDescription: Searching for hidden key-value pairs in dictionary


code:
def not_zeroes(arr):
    return any([x!=0 for x in arr])

vectors = []
for line in open('myfile.txt'):

    numbers = list(map(float,line.split()))
    for i in range(0, len(numbers), 10):
        vector = numbers[i:i+10]
        if not_zeroes(vector):
            vectors.append(vector)
print vectors

rawDescription: python: loading numbers from text file to arrays skipping certain entries

description: Python: loading numbers from text file to arrays skipping certain entries


code:
work_stack = list('abcde')

prev_item = ''
while work_stack:
    item = work_stack.pop(0)
    print item
    if prev_item=='a' and item == 'b':
        work_stack.insert(0,item)
    prev_item = item

rawDescription: How to prevent a for loop from advancing in Python?

description: Prevent a for loop from advancing in Python


code:
def divide(arr, depth, m):
    if len(complements) <= depth:
        complements.append(2 ** (depth + 2) + 1)
    complement = complements[depth]
    for i in range(2):
        if complement - arr[i] <= m:
            arr[i] = [arr[i], complement - arr[i]]
            divide(arr[i], depth + 1, m)

m = int(raw_input())

arr = [1, 2]
complements = []

divide(arr, 0, m)
print arr

rawDescription: Algorithm for generating a bracket model list in Python


code:
import subprocess

p = subprocess.Popen(["ag", "fit"], stdout=subprocess.PIPE)
print p.communicate()

rawDescription: Can't get output from The Silver Searcher through Subprocess call


rawDescription: python formating float numbers

description: Python formating float numbers


code:
def paren_matcher(string, opens, closes):
    """Yield (in order) the parts of a string that are contained
    in matching parentheses.  That is, upon encounting an "open
    parenthesis" character (one in <opens>), we require a
    corresponding "close parenthesis" character (the corresponding
    one from <closes>) to close it.

    If there are embedded <open>s they increment the count and
    also require corresponding <close>s.  If an <open> is closed
    by the wrong <close>, we raise a ValueError.
    """
    stack = []
    if len(opens) != len(closes):
        raise TypeError("opens and closes must have the same length")
    # could make sure that no closes[i] is present in opens, but
    # won't bother here...

    result = []
    for char in string:
        # If it's an open parenthesis, push corresponding closer onto stack.
        pos = opens.find(char)
        if pos >= 0:
            if result and not stack: # yield accumulated pre-paren stuff
               yield ''.join(result)
               result = []
            result.append(char)
            stack.append(closes[pos])
            continue
        result.append(char)
        # If it's a close parenthesis, match it up.
        pos = closes.find(char)
        if pos >= 0:
            if not stack or stack[-1] != char:
                raise ValueError("unbalanced parentheses: %s" %
                    ''.join(result))
            stack.pop()
            if not stack: # final paren closed
                yield ''.join(result)
                result = []
    if stack:
        raise ValueError("unclosed parentheses: %s" % ''.join(result))
    if result:
        yield ''.join(result)

print list(paren_matcher('(([a] b) c ) [d] (e) f', '([', ')]'))
print list(paren_matcher('foo (bar (baz))', '(', ')'))

rawDescription: separate string into contents in parentheses vs brackets vs flat text

description: Separate string into contents in parentheses vs brackets vs flat text


code:
class CTabWidget(QTabWidget):
    def __init__(self, parent=None):
        super(CTabWidget, self).__init__(parent)
        self.tabBar = CTabBar(self)
        self.setTabBar(self.tabBar)
        self.setTabPosition(QTabWidget.West)
        self.tab1 = QWidget(self)
        self.tab2 = QWidget(self)
        self.addTab(self.tab1, "Foo")
        self.addTab(self.tab2, "Bar")

class CTabBar(QTabBar):
    def __init__(self, parent=None):
        super(CTabBar, self).__init__(parent)
        self.setMovable(True)

    def mouseDoubleClickEvent(self, event):
        print "Change name"

rawDescription: pyQt4 QTabWidget setMovable crashes with custom QTabBar

description: PyQt4 QTabWidget setMovable crashes with custom QTabBar


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

testData = np.array([[0,0], [0.1, 0], [0, 0.3], [-0.4, 0], [0, -0.5]])
fig, ax = plt.subplots()
coll = ax.scatter(testData[:,0], testData[:,1], color=["blue"]*len(testData), picker = 5, s=[50]*len(testData))
plt.grid(True)
plt.axis([-0.5, 0.5, -0.5, 0.5])

def on_pick(event):
    print testData[event.ind], "clicked"
    coll._facecolors[event.ind,:] = (1, 0, 0, 1)
    coll._edgecolors[event.ind,:] = (1, 0, 0, 1)
    fig.canvas.draw()

fig.canvas.mpl_connect('pick_event', on_pick)
plt.show()

rawDescription: Python, Matplotlib, Scatter plot, Change color on the clicked point


code:
def query_db( no_of_rows, table_name ):
  cur = db.cursor()
  query = """
    select top %d rows from %s
  """ %( int(no_of_rows), table_name )
  cur.execute(query)
  for row in cur.fetchall() :
    print row[0]

rawDescription: Python function to select records from a mysql table


code:
import jinja2

# NOTE: in this template there is no data relating to specific posts.
# There are only references to data structures passed in from your main code
page_template = jinja2.Template('''

    {% block blog_posts %}

        {% for post in posts %}

{{ post.title }}
                                       - {{ post.date }}

        {% endfor %}
    {% endblock %}

    {% block content %}

{{ current.title }}

{{ current.date }}

{{ current.content }}

    {% endblock %}
''')

# NOTE your main code would create a data structure such as this
# list of dictionaries ready to pass in to your template
list_of_posts = [
         { 'url' : '#post1',
          'title' : 'My first post',
          'date' : 'Feb 2012',
          'content' : 'My first post is about Hello World.'},

         { 'url' : '#post2',
          'title' : 'My second post',
          'date' : 'Apr 2012',
          'content' : 'My second post is about Foo Bar.'}
         ]

# Pass in a full list of posts and a variable containing the last
# post in the list, assumed to be the most recent.
print page_template.render(posts = list_of_posts,
                           current = list_of_posts[-1])

rawDescription: webapp2, Jinja2: how to cut large html file into multiple html files

description: Webapp2, Jinja2: how to cut large html file into multiple html files


code:
def two_two(lst):
    for i, val in enumerate(lst):
        # if any two that appears in the list
        if val == 2:
            left = i > 0 and lst[i - 1] == 2
            right = i < len(lst) - 1 and lst[i + 1] == 2
            # is not next to another two
            if not left and not right:
                return False
    # otherwise,
    return True

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

rawDescription: twoTwo riddle by CodingBat

description: TwoTwo riddle by CodingBat


code:
element = browser.find_by_id('stWelcomeInbox').first
print element.text

rawDescription: How can i get text between <span> </span>using python splinter lib

description: Get text between <span> </span>using python splinter lib


code:
def test_fetch_google_links():

    links = []

    # Setup driver
    driver = webdriver.Firefox()
    driver.implicitly_wait(10)
    driver.maximize_window()

    # Visit google
    driver.get("https://www.google.com")

    # Enter search query
    search_data = driver.find_element_by_name("q")
    search_data.send_keys("test")

    # Submit search query
    search_button = driver.find_element_by_xpath("//button[@type='submit']")
    search_button.click()

    while True:
        # Find and collect all anchors
        anchors = driver.find_elements_by_xpath("//h3//a")
        links += [a.get_attribute("href") for a in anchors]

        try:
            # Find the next page button
            next_button = driver.find_element_by_xpath("//a[@id='pnnext']")
            location = next_button.get_attribute("href")
            driver.get(location)

        except NoSuchElementException:
            break

    # Do something with the links
    for l in links:
        print l

    print "Found {} links".format(len(links))

    driver.quit()

rawDescription: Unable to fetch all the necessary links during Iteration - Selenium Python


code:
raw_data = """<?xml version="1.0"?>
<rdf:RDF
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:dbp="http://dbpedia.org/ontology/"
xmlns:dbprop="http://dbpedia.org/property/"
xmlns:foaf="http://xmlns.com/foaf/0.1/">
    <rdf:Description rdf:about="http://dbpedia.org/page/Johann_Sebastian_Bach">
      <dbp:birthDate>1685-03-21</dbp:birthDate>
      <dbp:deathDate>1750-07-28</dbp:deathDate>
      <dbp:birthPlace>Eisenach</dbp:birthPlace>
      <dbp:deathPlace>Leipzig</dbp:deathPlace>
      <dbprop:shortDescription>German composer and organist</dbprop:shortDescription>
      <foaf:name>Johann Sebastian Bach</foaf:name>
      <rdf:type rdf:resource="http://dbpedia.org/class/yago/GermanComposers"/>
      <rdf:type rdf:resource="http://xmlns.com/foaf/0.1/Person"/>
    </rdf:Description>
</rdf:RDF>"""
import rdflib
graph = rdflib.Graph()
graph.parse(data=raw_data)

output = []

for s, p, o in graph:
    if type(o) == rdflib.term.Literal:
        output.append(o.toPython())

print ', '.join(output)

rawDescription: Text from RDF with RDFlib in Python

description: Text from RDF with RDFlib in Python


code:
from snowballstemmer import stemmer
ar_stemmer = stemmer("arabic")
sentence = u"مكتبة لمعالجة الكلمات العربية وتجذيعها"
for word in sentence.split(" "):
    stem = ar_stemmer.stemWord(word)
    print stem

rawDescription: Arabic stemmer doesn't work for sentences


code:
class Column:
    creation_counter = 0

    def __init__(self):
            self.creation_counter = Column.creation_counter
            Column.creation_counter += 1

class Base:
    def show(self):
        fields = [(name, (obj, obj.value)) for name, obj in self.__class__.__dict__.items() if isinstance(obj, Column)]
        fields.sort(lambda (name1, (obj1, value1)), (name2, (obj2, value2)): cmp(obj1.creation_counter, obj2.creation_counter))
        return fields

rawDescription: attribute assignment order in class definition

description: Attribute assignment order in class definition


code:
#!/usr/bin/python2

import sys, os
import subprocess
import fcntl

dump = open("/tmp/dump", "w")
dump.write("### starting %s ###" % " ".join(sys.argv))

proc = subprocess.Popen(["<real app>"] + sys.argv[1:], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

def nonblocking(fd):
  fl = fcntl.fcntl(fd, fcntl.F_GETFL)
  fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)

nonblocking(proc.stdin)
nonblocking(proc.stdout)
nonblocking(proc.stderr)

nonblocking(sys.__stdin__)
nonblocking(sys.__stdout__)
nonblocking(sys.__stderr__)

def me_to_proc():
  x_to_y(sys.__stdin__, proc.stdin, "~in> ")

def proc_to_me():
  x_to_y(proc.stdout, sys.__stdout__, "<out~ ")

def proc_to_me_err():
  x_to_y(proc.stderr, sys.__stderr__, "<err~ ")

def x_to_y(x, y, prefix=""):
  try:
    while True:
       line = x.readline()
       to_dump = "%s%s" % (prefix, line)
       print >> dump, to_dump
       print to_dump
       y.write(line)
       y.flush()
       dump.flush()
  except:
    pass

recode = None
while recode is None:
  proc_to_me()
  #proc_to_me_err()
  me_to_proc()

  retcode = proc.poll()

exit(retcode)

rawDescription: How to intercept transparently stdin/out/err

description: Intercept transparently stdin/out/err


code:
from Tkinter import *
import tkFileDialog

def askdirectory():
  dirname = tkFileDialog.askdirectory()
  if dirname:
    var.set(dirname)

def UserFileInput(status,name):
  optionFrame = Frame(root)
  optionLabel = Label(optionFrame)
  optionLabel["text"] = name
  optionLabel.pack(side=LEFT)
  text = status
  var = StringVar(root)
  var.set(text)
  w = Entry(optionFrame, textvariable= var)
  w.pack(side = LEFT)
  optionFrame.pack()
  return w, var

def Print_entry():
  print var.get()

if __name__ == '__main__':
  root = Tk()

  dirBut = Button(root, text='askdirectory', command = askdirectory)
  dirBut.pack(side = RIGHT)
  getBut = Button(root, text='print entry text', command = Print_entry)
  getBut.pack(side = BOTTOM)

  w, var = UserFileInput("", "Directory")

  root.mainloop()

rawDescription: How can I use the output from tkFileDialog.askdirectory to fill a tkinter Entry box

description: Use the output from tkFileDialog.askdirectory to fill a tkinter Entry box


code:
graph = {'A': set(['B', 'C']),
         'B': set(['A', 'D', 'E']),
         'C': set(['A', 'F']),
         'D': set(['B']),
         'E': set(['B', 'F']),
         'F': set(['C', 'E'])}

def dfs(graph, start):
    visited, stack = [], [start]
    while stack:
        vertex = stack.pop()
        if vertex not in visited:
            visited.append(vertex)
            stack.extend(graph[vertex] - set(visited))
    return visited

print dfs(graph, 'A') # ['A', 'B', 'D', 'E', 'F', 'C']

rawDescription: not understanding the return order based on DFS in graph traversal

description: Not understanding the return order based on DFS in graph traversal


code:
for node in Tree.getiterator():
    print node.tag, node.attrib, node.text

rawDescription: Grab Content from XML using Python? almost there


code:
import socket
import struct
address = ("10.0.0.12", 5000)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(address)
s.listen(1000)

client, addr = s.accept()
print 'got connected from', addr

buf = ''
while len(buf)<4:
    buf += client.recv(4-len(buf))
size = struct.unpack('!i', buf)
print "receiving %s bytes" % size

with open('tst.jpg', 'wb') as img:
    while True:
        data = client.recv(1024)
        if not data:
            break
        img.write(data)
print 'received, yay!'

client.close()

rawDescription: Python socket server receive image

description: Python socket server receive image


code:
#Creates a list with the first ten Fibonacci numbers.
l = [1,2]
for i in range(10):
    l.append(l[i]+l[i+1])

for i in range(len(l)):
    #If an element of the Fibonacci list is uneven, replace it with zero.
    if l[i]%2 != 0:
        l[i] = 0

#Print the sum of the list with all even Fibonacci numbers.
print sum(l)

rawDescription: How is this list index out of range? (Fibonacci numbers exercice)


code:
a = "fkjdlfjzgjkdsheiwqueqpwnvkasdakpp"
print a[10]

rawDescription: Python: Finding the value of a character in a string


code:
def perm(chars, prefix):
    result = []
    if len(prefix) < len(chars):
        for char in chars:
            result.append(prefix + char)
        for char in chars:
            result.extend(perm(chars, prefix + char))
    return result

print perm(["a", "b", "c"], "")

rawDescription: python all possible permutation using recursion

description: Python all possible permutation using recursion


code:
from uuid import uuid4

@periodic_task(run_every=crontab(minute='*/5'))
def create_user():
    try:
        username = uuid4().hex # username should be unique
        user = registrations(username=username,password='pass123')
        user.save()
        # user = User.objects.create(username=username,password='pass123')  # If you are using Django auth user model, which you should. No need to call .save() on this
    except Exception, e:
        print str(e)  # Log the error

rawDescription: How to add a user in database in every 5min using celery/cronjobs

description: Add a user in database in every 5min using celery/cronjobs


code:
for sublist in input_data:

    if 'min' == sublist[0]:
        answer = "The minimum number of the list {} is {}".format(
                sublist[1:], min(sublist[1:]))
    elif 'max' == sublist[0]:
        answer = "The maximum number of the list {} is {}".format(
                sublist[1:], max(sublist[1:]))

    print answer

rawDescription: Using both Strings and Integers in one list separately?


code:
import fileinput
import os, shutil, tempfile

# create a copy of the source file into a system specified
# temporary directory. You could just put this in the original
# folder, if you wanted
def create_temp_copy(src_filename):
    temp_dir = tempfile.gettempdir()
    temp_path = os.path.join(temp_dir, 'temp-history.txt')
    shutil.copy2(src_filename,temp_path)
    return temp_path

# create a temporary copy of the input file
temp = create_temp_copy('HISTORY.txt')

# open up the input file for writing
dst = open('HISTORY.txt','w+')

for line in fileinput.input(temp):

    # Added a try/catch to handle errors during processing.
    # If this isn't present, any exceptions that are raised
    # during processing could cause unrecoverable loss of
    # the HISTORY file
    try:
        # some sort of replacement
        if line.startswith('e'):
            line = line.strip() + '@\n' # notice the newline here

        # occasional status updates to stdout
        if '0' in line:
            print 'info:',line.strip() # notice the removal of the newline
    except:
        # when a problem occurs, just output a message
        print 'Error processing input file'

    finally:
        # re-write the original input file
        # even if there are exceptions
        dst.write(line)

# deletes the temporary file
os.remove(temp)

# close the original file
dst.close()

rawDescription: How to redirect stdout to only the console when within fileinput loop

description: Redirect stdout to only the console when within fileinput loop


code:
class Something:
    def __init__(self):
        self.parent = None

    def setParent(self, parent=None):
        self.parent = self if not parent else parent

inst = Something()
print inst # prints <__main__.Something instance at 0xblah>
print inst.parent # prints None
inst.setParent()
print inst.parent # prints <__main__.Something instance at 0xblah>
inst.setParent(inst)
print inst.parent # prints <__main__.Something instance at 0xblah>

rawDescription: What is the right way to assign/reassign a reference to an object in Python 2.x?


code:
import sys
import re
def formatnumber(arg1) :
    pattern = "[0-9]+"
    if re.compile(pattern).match(arg1) :
        return arg1
    elif type(arg1) == type(str()):
        return "It's not a number"
if __name__=="__main__" :
    arg1=sys.argv[1]
    res = formatnumber(arg1)
    print res

rawDescription: How to use print with return in a function?

description: Use print with return in a function


code:
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.item import Item, Field

class MyItem(Item):
    content = Field()

class TestSpider(CrawlSpider):
    name = 'test_spider'
    allowed_domains = ['hamshahrionline.ir']
    start_urls = ['http://www.hamshahrionline.ir']

    rules = (
        Rule(SgmlLinkExtractor(allow=('service/\w+', ), ), callback='parse_item'),
    )

    def parse_item(self, response):
        print response.url

        item = MyItem()
        item['content'] = response.body
        return item

rawDescription: How to dig to site wiithin links in scrapy

description: Dig to site wiithin links in scrapy


code:
def print_var(variable_list):
    for i, element in enumerate(variable_list):
        print 'x' + str(i) + ' = ' + element

mylist = ['var','var1','var2','var3']
anotherlist = ['var','var1','var2','var4','var5']
print_var(mylist)
print_var(anotherlist)

rawDescription: how to write a function to split out elements in the list to string in python

description: Write a function to split out elements in the list to string in python


code:
import datetime
date_value = 41381.0
date_conv= datetime.date(1900, 1, 1) + datetime.timedelta(int(date_value))
print date_conv.strftime('%d-%m-%Y')

rawDescription: Changing date format after converting from int value in python


code:
def search(doc):
    print "Visiting", doc
    f = open(doc, 'r')
    for line in f:
        if line.strip():
            search(line.strip())

rawDescription: Opening and Printing files using Recursion in python


code:
def display(A,B,C):
    for x in (A, B):
        if x:
            print "--",'{0:^34}'.format(x),"--"

rawDescription: Condition Statement printing in python

description: Condition Statement printing in python


rawDescription: Returning http status codes in Python CGI


code:
entry = """{%block price%}$259{%endblock%}
{%block buy%}http://www.highbeam.co.nz/store/index.php?route=product/product&path=6&product_id=116{%endblock%}
{%block info%}http://www.inov-8.co.nz/oroc280.html{%endblock%}   """

parsedentry = dict([(j[0].split(' ')[-1], j[-1]) for j in [i.partition("%}") for i in entry.split("{%endblock%}")] if j[0].split(' ')[-1]])

print parsedentry['price']

rawDescription: Appengine Django Template - Read template tags


code:
import dbus
bus = dbus.SystemBus()
obj = bus.get_object("org.freedesktop.Hal", "/org/freedesktop/Hal/Manager")
iface = dbus.Interface(obj, "org.freedesktop.Hal.Manager")
print iface.FindDeviceStringMatch("block.device", "/dev/sda")

rawDescription: Find a HAL object based on /dev node path


code:
for POI in POIs:
    print POI, POIs[POI]

rawDescription: Iterating over multidimensional list in Python


code:
import requests

payload = {'board': {BOARD}, 'flightNum': {FLIGHTNUM}}
r = requests.get('https://url.com/InfoService/GetFlightByFlightNum', params=payload)

# print the response result
print r.text

rawDescription: Using a specific API with Python

description: Using a specific API with Python


code:
from itertools import izip_longest

def add_column(lst, col):

    #create the list col, append None's if the length is less than table's length
    col = col + [None] * (len(lst)- len(col))

    for x, y in izip_longest(lst, col):
        # here the if-condition will run only when items in col are greater than
        # the length of table list, i.e prepend None's in this case.
        if x is None:
            yield [None] *(len(lst[0])) + [y]
        else:
            yield x + [y]

print list(add_column(table, list1))
#[[1, 2, 0, 1], [3, 4, 1, 2], [4, 4, 4, 3], [None, None, None, 4]]
print list(add_column(table, list2))
#[[1, 2, 0, 1], [3, 4, 1, 2], [4, 4, 4, None]]

rawDescription: How to insert a list as a column in a 2D-list?

description: Insert a list as a column in a 2D-list


code:
def capital(n):
    for word in n:
        if word==word.upper():
            return n.upper()
    return n

n=raw_input()
print capital(n)

rawDescription: How to get the result from a loop in (python)

description: Get the result from a loop in (python)


code:
import numpy as np, numpy.random,scipy.optimize
def residuals(p, dRA, dDE, RA, DEC):
    ex,ey,ez = p
    f1 = dRA-(ex*np.sin(DEC)*np.cos(RA)+ey*np.sin(DEC)*np.sin(RA)-ez*np.cos(DEC))
    f2 = dDE-(-ex*np.sin(RA)+ey*np.cos(RA))
    err = np.concatenate((f1,f2))
    return err
ex, ey, ez = 0.2, 0.3, 0.4
N = 100
err = 1e-3
ra, dec = np.random.uniform(0,1,N), np.random.uniform(0,.5,N)
dra = (ex*np.sin(dec)*np.cos(ra)+ey*np.sin(dec)*np.sin(ra)-ez*np.cos(dec))+np.random.normal(size=N)*err
ddec = (-ex*np.sin(ra)+ey*np.cos(ra))+np.random.normal(size=N)*err
print scipy.optimize.leastsq(residuals, p0, args=(dra, ddec, ra, dec))

rawDescription: Least squares in a set of equations with optimize.leastsq() (Python)


code:
from django.contrib.gis.gdal import SpatialReference, CoordTransform
from django.contrib.gis.geos import Point
gcoord = SpatialReference(4326)
mycoord = SpatialReference(22186)
trans = CoordTransform(gcoord, mycoord)
pnt = Point(30, 50, srid=4326)
print 'x: %s; y: %s; srid: %s' % (pnt.x, pnt.y, pnt.srid)
pnt.transform(trans)
print 'x: %s; y: %s; srid: %s' % (pnt.x, pnt.y, pnt.srid)

rawDescription: Convert between coordinate systems with GeoDjango


code:
def send_req():
    global flag
    while flag==False:
        pass          # stay here unless the flag gets true
    start = time.time()
    response = http_lib.request(ip,port,headers,body,url)
    end = time.time()
    response_time = start - end
    print "Response Time: ", response_time
    run_once=True

def main():
 flag=False
 thread_list = []
 for thread in range(10):
    t = threading.Thread(target=send_req)  # creating threads one by one
    #t.start()
    thread_list.append(t)

 for j in thread_list:   # now starting threads (still one by one)
    j.start()

 flag=True      # now start the working of each thread by releasing this flag from False to true

 for i in thread_list:
    i.join()

rawDescription: Wait and notify multiple threads at the same time python


code:
with open('file.csv') as f:
    f.readline() # ignore first line (header)
    mydict = dict(csv.reader(f, delimiter=','))

print mydict

rawDescription: how to convert csv into dict format

description: Convert csv into dict format


code:
from sklearn.metrics import classification_report
from sklearn.linear_model import SGDClassifier
from sklearn.datasets import load_digits
digits = load_digits()
n_samples, n_features = digits.data.shape
n_split = n_samples / 2
clf = SGDClassifier().fit(digits.data[:n_split], digits.target[:n_split])
predictions = clf.predict(digits.data[n_split:])
expected = digits.target[n_split:]
print classification_report(expected, predictions)

rawDescription: Scipy/Numpy/scikits - calculating precision/recall scores based on two arrays


code:
#!/usr/bin/env python
import gtk, pygtk, gobject, string

class HexEntry(gtk.Entry):
    """A PyGTK text entry field which allows only Hex characters to be entered"""

    def __init__(self):
        gtk.Entry.__init__(self)
        self.connect("changed", self.entryChanged)
        self.connect("insert_text", self.entryInsert)

    def entryChanged(self, entry):
        # Called only if the entry text has really changed.
        print "Entry changed"

    def entryInsert(self, entry, text, length, position):
        # Called when the user inserts some text, by typing or pasting.
        print "Text inserted"

        position = entry.get_position() # Because the method parameter 'position' is useless

        # Build a new string with allowed characters only.
        result = ''.join([c for c in text if c in string.hexdigits])

        # The above line could also be written like so (more readable but less efficient):
        # result = ''
        # for c in text:
        #     if c in string.hexdigits:
        #         result += c

        if result != '':
            # Insert the new text at cursor (and block the handler to avoid recursion).
            entry.handler_block_by_func(self.entryInsert)
            entry.insert_text(result, position)
            entry.handler_unblock_by_func(self.entryInsert)

            # Set the new cursor position immediately after the inserted text.
            new_pos = position + len(result)

            # Can't modify the cursor position from within this handler,
            # so we add it to be done at the end of the main loop:
            gobject.idle_add(entry.set_position, new_pos)

        # We handled the signal so stop it from being processed further.
        entry.stop_emission("insert_text")

def main():
    window = gtk.Window()
    window.connect("delete-event", gtk.main_quit)
    entry = HexEntry()
    window.add(entry)
    window.show_all()
    gtk.main()

if __name__ == "__main__":
    main()

rawDescription: How can I filter or limit the text being entered in a PyGTK text entry field?

description: Filter or limit the text being entered in a PyGTK text entry field


code:
def is_pal(c):
    return int(str(c)[::-1]) == c

maxpal = 0
for a in range(999, 99, -1):
    for b in range(a, 99, -1):
        prod = a * b
        if is_pal(prod) and prod > maxpal:
            maxpal = prod

print maxpal

rawDescription: Palindrome from the product of two 3-digit numbers


code:
import urllib2
from urllib import urlencode
import json

class apiclient:
    def __init__(self,
                request_url,
                api_key,
                client_id,
                grant_type="password",
                username="username",
                password="password"):

        values = {
                "client_id": client_id,
                "grant_type": grant_type,
                "username": username,
                "password": password
            }

        data = urlencode(values)

        req = urllib2.Request(request_url, data)
        req.add_header("Api-Key", api_key)
        response = urllib2.urlopen(req)

        response_header = response.info().dict
        response_body = response.read()
        json_acceptable_string = response_body.replace("'", "\"")
        self.response_body_dict = json.loads(json_acceptable_string)

    def get_response_body(self):
        return self.response_body_dict

if __name__ == "__main__":

    API_KEY = "75b5cc58a5cdc0a583f91301cefedf0c"
    CLIENT_ID = "ef5f7a03-58e8-48d7-a38a-abbd2696bdb6.hmhco.com"
    REQUEST_URL = "http://some.url"

    client = apiclient(request_url=REQUEST_URL,
                        api_key=API_KEY,
                        client_id=CLIENT_ID)
    response = client.get_response_body()

    print client

rawDescription: Creating a python wrapper for an API using classes


code:
def mymethod():
    return [[1,2,3,4],
            [1,2,3,4],
            [1,2,3,4],
            [1,2,3,4]]

mylist = mymethod()

for thing in (i[1] for i in mylist):
    print thing

# this bit is meant to be outside the for loop,
# I mean it to represent the last value thing was in the for
if thing:
    print thing

rawDescription: For loop for second items in list of lists only. (python)


code:
import websocket
import threading
from time import sleep

def on_message(ws, message):
    print message

def on_close(ws):
    print "### closed ###"

if __name__ == "__main__":
    websocket.enableTrace(True)
    ws = websocket.WebSocketApp("ws://echo.websocket.org/", on_message = on_message, on_close = on_close)
    wst = threading.Thread(target=ws.run_forever)
    wst.daemon = True
    wst.start()

    conn_timeout = 5
    while not ws.sock.connected and conn_timeout:
        sleep(1)
        conn_timeout -= 1

    msg_counter = 0
    while ws.sock.connected:
        ws.send('Hello world %d'%msg_counter)
        sleep(1)
        msg_counter += 1

rawDescription: Threaded, non-blocking websocket client in python


code:
import itertools

rowlists = [[1,5,9],[2,6,10],[3,7,11],[4,8,12]]
for combination in itertools.product(*rowlists):
    print combination

rawDescription: Generate all possible combinations in Python


code:
haystack = "lorem ipsum dorlor lorem ipsum dorlor lorem ipsum dorlor lorem ipsum dorlor lorem ipsum dorlor lorem ipsum dorlor lorem ipsum dorlor lorem ipsum dorlor lorem ipsum dorlor lorem ipsum dorlor lorem ipsum dorlor lorem ipsum dorlor lorem ipsum dorlor lorem ipsum dorlor lorem ipsum dorlor lorem ipsum dorlor lorem ipsum dorlor lorem ipsum dorlor lorem ipsum dorlor lorem ipsum dorlor lorem ipsum dorlor lorem ipsum dorlor lorem ipsum dorlor lorem ipsum dorlor lorem ipsum dorlor it is no wonder that nike is one of the largest brands in the world is not lorem ipsum dorlor lorem ipsum dorlor lorem ipsum dorlor lorem ipsum dorlor lorem ipsum dorlor lorem ipsum dorlor lorem ipsum dorlor"

needle = "nike342"

lookahead = 7  # Number of tokens to show before "nike"

tokens = haystack.split(" ")  # Split string into a list of tokens

found_index = -1  #  Represents the index of the token.  Initialize to -1 and assume it doesn't exist.

# Loop through tokens and compare each to the needle.  If we find the needle, rememeber the index and break out of the loop

found_index = tokens.index(needle)

try:
    found_index = tokens.index(needle)
    # Get the max of the found index minus the number of words to show before the needle, and 0
    found_index = max(found_index - lookahead, 0)

    # Create a sub list of the tokens from the found_index and end, then join those terms back together with a space.
    snippet = " ".join(tokens[found_index:len(tokens)])

except ValueError:
    snippet = ""  # No snippet or whatever error handling you are going to do

print snippet

rawDescription: How to create a Google Like Text Snippet from String in Python?

description: Create a Google Like Text Snippet from String in Python


code:
#!/usr/bin/python

import xml.etree.ElementTree as ET
from itertools import chain

def parse(filename):
    tree = ET.parse(filename)
    root = tree.getroot()
    result = {}
    for target in root.findall('target'):
        target_name = target.get('name')
        result[target_name] = []
        for antcall in target.findall('.//antcall'):
            result[target_name].append(antcall.get('target'))
    return result

def display(tree):
    def recurse(node, indent):
        print "%*s%s"%(indent*4, "", node)
        for node in sorted(tree[node]):
            recurse(node, indent+1)
    for item in sorted(tree):
        if item in chain(*tree.values()): continue
        recurse(item,0)

if __name__=="__main__":
    import argparse
    parser = argparse.ArgumentParser(description='Dump ANT files')
    parser.add_argument('antfile',
                        nargs='+',
                        type=argparse.FileType('r'),
                        help='ANT build file')
    args = parser.parse_args()
    for antfile in args.antfile:
        display(parse(antfile))

rawDescription: parsing parent/children relationship of XML elements

description: Parsing parent/children relationship of XML elements


code:
#!/usr/bin/python

import cmd

class T(cmd.Cmd):
    def completedefault(self, *a):
        print 'completedefault called'
        return []

    def test(self, *args):
        print "test args: ", args

t=T()
t.cmdloop()

rawDescription: python cmd completedefault() method not called

description: Python cmd completedefault() method not called


code:
modifiers = []
if event.state & 1:
    modifiers.append('Shift')
if event.state & 4:
    modifiers.append('Control')
# ... etc
print '-'.join(modifiers)

rawDescription: Python/Tkinter: Getting the full Event name?


code:
# Monkey patching - an occasionally necessary evil.
from social import utils
from social.exceptions import InvalidEmail

from django.core import signing
from django.core.signing import BadSignature
from django.contrib.sessions.models import Session
from django.conf import settings

def partial_pipeline_data(backend, user=None, *args, **kwargs):
    """
    Monkey-patch utils.partial_pipeline_data to enable us to retrieve session data by signature key in request.
    This is necessary to allow users to follow a link in an email to validate their account from a different
    browser than the one they were using to sign up for the account, or after they've closed/re-opened said
    browser and potentially flushed their cookies. By adding the session key to a signed base64 encoded signature
    on the email request, we can retrieve the necessary details from our Django session table.
    We fetch only the needed details to complete the pipeline authorization process from the session, to prevent
    nefarious use.
    """
    data = backend.strategy.request_data()
    if 'signature' in data:
        try:
            signed_details = signing.loads(data['signature'], key=settings.EMAIL_SECRET_KEY)
            session = Session.objects.get(pk=signed_details['session_key'])
        except BadSignature, Session.DoesNotExist:
            raise InvalidEmail(backend)

        session_details = session.get_decoded()
        backend.strategy.session_set('email_validation_address', session_details['email_validation_address'])
        backend.strategy.session_set('next', session_details.get('next'))
        backend.strategy.session_set('partial_pipeline', session_details['partial_pipeline'])
        backend.strategy.session_set(backend.name + '_state', session_details.get(backend.name + '_state'))
        backend.strategy.session_set(backend.name + 'unauthorized_token_name',
                                     session_details.get(backend.name + 'unauthorized_token_name'))

    partial = backend.strategy.session_get('partial_pipeline', None)
    if partial:
        idx, backend_name, xargs, xkwargs = \
            backend.strategy.partial_from_session(partial)
        if backend_name == backend.name:
            kwargs.setdefault('pipeline_index', idx)
            if user:  # don't update user if it's None
                kwargs.setdefault('user', user)
            kwargs.setdefault('request', backend.strategy.request_data())
            xkwargs.update(kwargs)
            return xargs, xkwargs
        else:
            backend.strategy.clean_partial_pipeline()
utils.partial_pipeline_data = partial_pipeline_data

rawDescription: Missing needed parameter state Python social auth Email Validation


code:
# Your starting point
course = 87
finalProject = 75
exam = 82

# What I would "crunch" into a calculator besides the variables
total1 = (course * 0.6) + (finalProject * 0.2) + (exam * 0.2)
total2 = (course * 0.7) + (finalProject * 0.1) + (exam * 0.2)

# Printing my computed answers just to make sure I can tell if it gives the right output
print "Total1: %s\tTotal2: %s" % (total1, total2)

# Printing the highest one.
print "\nYour mark is: %s" % max(total1, total2)

rawDescription: How to output highest number out of 3 numbers?

description: Output highest number out of 3 numbers


code:
import clr
clr.AddReference('System.Data')
from System.Data.SqlClient import SqlConnection, SqlParameter

conn_string = 'data source=SRG3SERVER; initial catalog=vijaykumarDB; trusted_connection=True'
connection = SqlConnection(conn_string)
connection.Open()
command = connection.CreateCommand()
command.CommandText = 'Select Ename from tbl_Empployee where Emp_id=@employeeId'
command.Parameters.Add(SqlParameter('@employeeId', 1))

reader = command.ExecuteReader()
while reader.Read():
    print reader['Ename']

connection.Close()

rawDescription: Can we acess SQL Server data from Iron Python Script File if so how I m trying this following code?


code:
import numpy as np, numpy.random
print np.random.dirichlet(np.ones(10),size=1)
print np.random.dirichlet(np.ones(10)/1000.,size=1)
print np.random.dirichlet(np.ones(10)*1000.,size=1)

rawDescription: Generating a list of random numbers, summing to 1


code:
#!/usr/bin/env python
import cairo
import gtk

class MyWin (gtk.Window):
  def __init__(self):
    super(MyWin, self).__init__()
    self.set_position(gtk.WIN_POS_CENTER)

    self.set_size_request(300, 220)
    self.set_border_width(11)

    self.screen = self.get_screen()
    colormap = self.screen.get_rgba_colormap()
    if (colormap is not None and self.screen.is_composited()):
        print "yay"
        self.set_colormap(colormap)

    self.set_app_paintable(True)
    self.connect("expose-event", self.area_draw)
    self.show_all()

  def area_draw(self, widget, event):
    cr = widget.get_window().cairo_create()
    cr.set_source_rgba(.2, .2, .2, 0.3)
    cr.set_operator(cairo.OPERATOR_SOURCE)
    cr.paint()
    cr.set_operator(cairo.OPERATOR_OVER)
    return False

MyWin()
gtk.main()

rawDescription: Python - how to make transparent window with gtk.Window but not with Gtk.Window?


code:
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import scipy
import pyfits
import numpy as np
import re
import os
import glob
import time

global numbers
numbers=re.compile(r'(\d+)')

def numericalSort(value):
    parts = numbers.split(value)
    parts[1::2] = map(int, parts[1::2])
    return parts

fig=plt.figure()
ax1=fig.add_subplot(1,1,1)

def animate(i):
    image_list=sorted(glob.glob('*.fit'), key=numericalSort)
    cas,maxy=[],[]
    files=open("data.dat","wr")
    for n in range(len(image_list)):
        hdulist=pyfits.open(image_list[n])
        data=hdulist[0].data
        maxy=data.max()
        time=hdulist[0].header['TIME']
        hours=int(float(time[:2])*3600)
        minutes=int(float(time[3:5])*60)
        sec=int(float(time[6:]))
        cas=hours+minutes+sec
        files.write("\n{},{}".format(cas,maxy))
    files.close()

    pool=open('data.dat','r')
    data=pool.read()
    dataA=data.split('\n')
    xar=[]
    yar=[]
    pool.close()
    for line in dataA:
        if len(line)>1:
            x,y=line.split(',')
            xar.append(int(x))
            yar.append(int(y))
    print xar,yar
    ax1.clear()
    ax1.plot(xar,yar,'b-')
    ax1.plot(xar,yar,'ro')
    plt.title('Light curve')
    plt.xlabel('TIME')
    plt.ylabel('Max intensity')
    plt.grid()

rawDescription: line graph from loop in Python

description: Line graph from loop in Python


code:
import csv
file1 = open('/a1.csv','rb')
file2 = open('/test.csv','rb')
a1 = csv.reader(file1, delimiter=',')
test = csv.reader(file2, delimiter=',')

for row1 in test:
    new=""
    found = False
    for row in a1:
        if row1[0] in row:
            new = row[0]
            found = True
    if not found:
        new = row1[0]
    print new
    file1.seek(0)

rawDescription: Row level string comparison in Python

description: Row level string comparison in Python


code:
inp = set(raw_input("Please enter the scrable letters you have: "))
with open('/usr/share/dict/words', 'r') as words:
    for word in words:
        if inp <= set(word):
            print word,

rawDescription: Search string for set of characters

description: Search string for set of characters


code:
Solution
import numpy as np

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

rows,cols = A.shape
drops = np.zeros(cols).astype(bool)

# sparse nonzero elements
C = np.nonzero(A)

# create a list of sets containing the indices of non-zero elements of each column
D = [set() for j in range(cols)]
for i in range(len(C[0])):
    D[C[1][i]].add(C[0][i])

# find subsets, ignoring columns that are known to already be subsets
for i in range(cols):
    if drops[i]==True:
        continue
    col1 = D[i]
    for j in range(i+1,cols):
        col2 = D[j]
        if col2.issubset(col1):
            # I tried `if drops[j]==True: continue` here, but that was slower
            print "%d is a subset of %d" % (j, i)
            drops[j] = True
        elif col1.issubset(col2):
            print "%d is a subset of %d" % (i, j)
            drops[i] = True
            break

B = A[:, ~drops]
print B

rawDescription: 2-D Matrix: Finding and deleting columns that are subsets of other columns


code:
import maya.cmds as cmd
import maya.OpenMaya as om

def test_if_inside_mesh(point=(0.0, 0.0, 0.0), dir=(0.0, 0.0, 1.0)):
    sel = om.MSelectionList()
    dag = om.MDagPath()

    #replace torus with arbitrary shape name
    sel.add("pTorusShape1")
    sel.getDagPath(0,dag)

    mesh = om.MFnMesh(dag)

    point = om.MFloatPoint(*point)
    dir = om.MFloatVector(*dir)
    farray = om.MFloatPointArray()

    mesh.allIntersections(
            point, dir,
            None, None,
            False, om.MSpace.kWorld,
            10000, False,
            None, # replace none with a mesh look up accelerator if needed
            False,
            farray,
            None, None,
            None, None,
            None
        )
    return farray.length()%2 == 1

#test
cmd.polyTorus()
print test_if_inside_mesh()
print test_if_inside_mesh((1,0,0))

rawDescription: Querying of a point is within a mesh maya python api


code:
import imaplib
imap_server = imaplib.IMAP4_SSL("imap.server.com")
print "\n".join(i for i in imap_server.capabilities if i.startswith("AUTH="))

rawDescription: Avoid storing passwords in plaintext for IMAP access via Python


code:
from PyQt4 import QtGui, QtCore, QtSql
import time

class Window(QtGui.QDialog):

    update_ready = QtCore.pyqtSignal()

    def __init__(self):
        super(Window, self).__init__()

        self.layout = QtGui.QVBoxLayout(self)
        self.table = QtGui.QTableView()
        self.layout.addWidget(self.table)

        self.db = QtSql.QSqlDatabase.addDatabase("QMYSQL")
        self.db.setHostName("server")
        self.db.setDatabaseName("db")
        self.db.setUserName("user")
        self.db.setPassword("pass")
        self.db.open()

        self.model = QtSql.QSqlTableModel(self, self.db)
        self.model.setTable("cpu_alert")
        self.model.setEditStrategy(self.model.OnManualSubmit)
        self.model.setQuery(QtSql.QSqlQuery("""
            SELECT *
            FROM cpu_alert
            WHERE date = (SELECT MAX(date) FROM cpu_alert)"""))
        self.model.select()

        self.table.setModel(self.model)

        self.button = QtGui.QPushButton("Select")
        self.layout.addWidget(self.button)

        self.button.clicked.connect(self.model.select)
        self.update_ready.connect(self.model.select)

        self.timer = QtCore.QTimer()
        self.timer.timeout.connect(self.cpu_alert_checker)
        # check every second
        self.timer.start(1000*1)

        # this is only for the temp time test
        self._now = time.time()

    def cpu_alert_checker(self):
        # You would do whatever check you want
        # in this function
        if time.time() - self._now > 5:
            print "Update ready!"
            # emit this signal if the table should refresh
            self.update_ready.emit()
            self._now = time.time()

rawDescription: Displaying a long loop function in pyqt4 scroll area python


code:
class API():
    api_url = 'http://api.bitbucket.org/1.0/'

    def __init__(self, username, password, proxy=None):
        encodedstring = base64.encodestring("%s:%s" % (username, password))[:-1]
        self._auth = "Basic %s" % encodedstring
        self._opener = self._create_opener(proxy)

    def _create_opener(self, proxy=None):
        cj = cookielib.LWPCookieJar()
        cookie_handler = urllib2.HTTPCookieProcessor(cj)
        if proxy:
            proxy_handler = urllib2.ProxyHandler(proxy)
            opener = urllib2.build_opener(cookie_handler, proxy_handler)
        else:
            opener = urllib2.build_opener(cookie_handler)
        return opener

    def get_issues(self, username, repository):
        query_url = self.api_url + 'repositories/%s/%s/issues/' % (username, repository)
        try:
            req = urllib2.Request(query_url, None, {"Authorization": self._auth })
            handler = self._opener.open(req)
        except urllib2.HTTPError, e:
            print e.headers
            raise e
        return json.load(handler)

rawDescription: Bitbucket API authentication with Python's HTTPBasicAuthHandler


code:
import pygame

clock = pygame.time.Clock()
FPS = 60
timer = pygame.time.Clock()
storydelay = 5000
time_count = 0

story = True
timer.tick()

while story:
    time_count += timer.tick()
    if time_count < storydelay:
        pass
    if time_count > storydelay:
        time_count = 0
        print "story done"
        story = False
    clock.tick(FPS)

main_menu = True
timer.tick()

while main_menu:
    time_count += timer.tick()
    if time_count > 3000:
        time_count = 0
        print "menu done"
        main_menu = False
    clock.tick(FPS)

print "done"

rawDescription: How to stop timer tick

description: Stop timer tick


code:
#!/usr/bin/env python
import re
from multiprocessing.dummy import Pool # use threads
from subprocess import Popen, PIPE

def get_ips(filename):
    ips = []
    with open(filename) as f:
        for line in f:
            line = line.strip()
            if line and line != "end":
                ips.append(line)
    return ips

def ping(ip):
    cmd = ["ping", "-n", "1", "-l", "1", "-w", "100", ip]
    ping = Popen(cmd, stdout=PIPE, stderr=PIPE)

    # Get and parse output
    output, err = ping.communicate()
    out = ''.join([output, err])

    lost = re.findall(r"Lost = (\d+)", out)
    minimum = re.findall(r"Minimum = (\d+)", out)
    maximum = re.findall(r"Maximum = (\d+)", out)
    avg = re.findall(r"Average = (\d+)", out)
    no =  re.findall(r"Sent = (\d+)", out)

    # Change output to integers
    lost = [int(x) for x in lost]
    minimum = [int(x) for x in minimum]
    maximum = [int(x) for x in maximum]
    avg = [int(x) for x in avg]
    no = [int(x) for x in no]

    return "%s \t \t %s \t \t%s \t \t %s \t \t%s" % (
        no, lost, maximum, minimum, avg)

def main():
    # grab IP address list
    ips = get_ips(r'C:\Python26\ARPips.prn')

    # Header for output
    print "Packets \t loss(%) \t Max(ms) \t Min(ms) \t Average(ms)"

    # Instantiate Pool objects, and set size of pool
    pool = Pool(processes=12)

    #Ping ips in own threads and return the results
    results = pool.map(ping, ips)

    # Close the pool and wait for work to finish
    pool.close()
    pool.join()

    # print the results
    print "\n".join(results)

if __name__ == '__main__':
    main()

rawDescription: Strange output for threaded subprocesses


code:
import sys
print "Hello",sys.argv[1]

rawDescription: One Python script giving "user input" to another python script


code:
with open("file.txt") as fp:
    for line in fp:
        if line.startswith('?'):
            print line

rawDescription: Read Specific line and ignore others using python


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

class MyApp(QWidget):
    def __init__(self,*args,**kwargs):
        QWidget.__init__(self,*args,**kwargs)
        self.current_timer = None
        self.layout = QVBoxLayout(self)
        self.button = QPushButton('start timer')
        self.button.clicked.connect(self.start_timer)
        self.layout.addWidget(self.button)

    def start_timer(self):
        if self.current_timer:
            self.current_timer.stop()
            self.current_timer.deleteLater()
        self.current_timer = QTimer()
        self.current_timer.timeout.connect(self.print_hello)
        self.current_timer.setSingleShot(True)
        self.current_timer.start(3000)

    def print_hello(self):
        print 'hello'

# Create QApplication and QWidget
qapp = QApplication(sys.argv)
app = MyApp()
app.show()
qapp.exec_()

rawDescription: How can I kill a single shot QtCore.QTimer in PyQt4?

description: Kill a single shot QtCore.QTimer in PyQt4


code:
import numpy as np

a = np.arange(12)
b = np.array([5, 9, 2, 4])
b = np.append(b, b[0])

for i in range(0, len(b)-1):
    print np.roll(a, len(a)-b[i])[:b[i+1]-b[i]+1]

rawDescription: Python/Numpy - Wrap Slice Around End of Array


code:
import lxml.html
text_string = '''

Hello World!

Goodbye!

'''
root = lxml.html.document_fromstring(text_string)
text_elements = root.xpath('//text()')
for t in text_elements:
    print t.getparent(), type(t), repr(t)

rawDescription: How do I select all text nodes in a document?

description: Select all text nodes in a document


code:
import sympy
for i in range(0, 360, 15):
    print i, sympy.sin(sympy.Rational(i, 180) * sympy.pi)

rawDescription: Using Python to create a Unit Circle calculator?


code:
chars_per_line = 50
for i in range(0, len(s), chars_per_line):
    print s[i:i+chars_per_line]

rawDescription: Print only a certain number of characters in Python


code:
y0_ = y0.copy()
def g(i, y = y0_):
    print "y that goes to g (every time is different) \n", y
    etc

rawDescription: how to keep a default value of key parameter constant? (python)

description: Keep a default value of key parameter constant? (python)


code:
"""defined earlier in the script:"""
COMMANDS=['show', 'exit', 'ship']
def complete(text, state, list = COMMANDS):
    for option in list:
        if option.startswith(text):
            if not state:
                return option
            else:
                state -= 1
def precomplete(text, state):
    BUFFER=readline.get_line_buffer()
    args=[None,None,None,None,None,None,None,None,None,None]
    argtemp=[]
    if BUFFER != "":
        i=-1
        while i != BUFFER.count(" "):
            if BUFFER.count(" ") >= 0:
                if BUFFER.count(" ") == 0: #1 because len() starts couting at 1
                    return complete(text, state)
                else:
                    print "Else triggered"
                    o=0
                    verb=[]
                    while complete(BUFFER.split()[0],o):
                        verb.append(complete(BUFFER.split()[0],o))
                        o=o+1
                    if len(verb) == 1:
                        verb=verb[0]
                        print verb
            if BUFFER.count(" ") >= 1:
                if  BUFFER.count(" ") == 1:
                    if verb == 'show':
                        return complete(text, state, ['mac', 'ip', 'arp'])
                else:
                    o=0
                    while complete(BUFFER[1],o,['mac', 'ip', 'arp']):
                        argtemp.append(complete(BUFFER[1],o,['mac', 'ip', 'arp']))
                        o=o+1
                    if len(argtemp) == 1:
                       argtemp==argtemp[0]
            i=i+1
    else:
        return complete(text,state)
readline.parse_and_bind("tab: complete")
readline.set_completer(precomplete)

rawDescription: Python: Homemade Tab Completion Help

description: Python: Homemade Tab Completion Help


code:
def lookup(elem):
    # do your SQL call here for a given category 'elem' and return
    # a list of it's subcategories
    return []

def leaves(lst):
    if lst:
        for elem in lst:                          # for every category
            for sublist in leaves(lookup(elem)):  # enumerate it's sub categories
                yield sublist                     # and return it
            yield elem                            # once lookup(elem) is [] return elem

d = { 111: [Run, Jump, swim] , 222: [Eat, drink] }

for key, lst in d.items():
    print key, [elem for elem in leaves(lst)]

rawDescription: Python: Algorithm Traverse Tree that expands at each node


rawDescription: Solving linear equations w. three variables using numpy


code:
endNum = int(raw_input("Enter the end number here "))
divisable_by = int(raw_input("Sum all numbers in the sequence that divide by: "))

# below is the same as "a, b = 0, 1"
a = 0
b = 1
""" gave single letter variables to those above to use in formula below
(longer strings do not seem to work)"""
c = endNum
d = divisable_by

fib_list = []
# while b is less than or equal to the ending number, it will loop.
while b <= c:
    print b
    fib_list.append(b)
# below is the same as "a, b = b, a+b"
    a_old = a
    a = b
    b = a_old + b
# the below helps with summing the numbers that are divisable by number chosen.
total = 0
for i in fib_list:
  if i%d == 0:
    total += i
#prints text and number calculated above.
print "Sum of all natural numbers that divide by the number you chose"
print "and are less than the other number you chose is: ", total

rawDescription: While loop and Fibonacci in Python (without importing or using "fib")


code:
import socket

class UDPServer:
    def __init__(self, dst_ip, rcv_port, snd_port):
        self._dstip = dst_ip
        self._rcv_port = rcv_port
        self._snd_port = snd_port
        self._create_socket()

    def _create_socket(self):

        # Create Datagram (udp) socket
        try :
            self._sock = socket.socket(socket.AF_INET, # Internet
                                       socket.SOCK_DGRAM) # UDP
            print 'Socket created.'
        except socket.error, msg :
            print 'Failed to create socket. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
            sys.exit()

        # Bind socket to local host and port
        try:
            self._sock.bind(("", self._rcv_port))
        except socket.error , msg:
            print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
            sys.exit()

        if(self._sock == None):
            print "self._sock is None after bind!!"
        print 'Socket bind complete.'

    def _receive_msg(self):
        print "waiting on port:", self._rcv_port
        while True:
            if not self._sock:
                print "self._sock is None!"
            data, addr = self._sock.recvfrom(1024) # buffer size is 1024 bytes
            print "received message:", data

def main():
    DST_IP = "100.1.11.275"
    UDP_RCV_PORT = 30001
    UDP_SND_PORT = 30002

    # Create UDP Server
    udpServer = UDPServer(DST_IP, UDP_RCV_PORT, UDP_SND_PORT)
    udpServer._receive_msg()

if __name__ == "__main__":
    main()

rawDescription: Why is this python UDP socket getting reset to 'None'?


code:
for paragraph in document.paragraphs:
    for run in paragraph.runs:
        if run.bold:
            print run.text

rawDescription: Checking for particular style using python-docx


code:
import numpy as np
import cv2

im = cv2.imread('sun0016.bmp')
height, width, depth = im.shape
print height, width, depth
thresh = 132
imgray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(imgray,(5,5),0)
edges = cv2.Canny(blur,thresh,thresh*2)
contours, hierarchy = cv2.findContours(edges,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
cnt = contours[0]
cv2.drawContours(im,contours,-1,(0,255,0),-1)

#centroid_x = M10/M00 and centroid_y = M01/M00
M = cv2.moments(cnt)
x = int(M['m10']/M['m00'])
y = int(M['m01']/M['m00'])
print x,y
print width/2.0,height/2.0
print width/2-x,height/2-y

cv2.circle(im,(x,y),1,(0,0,255),2)
cv2.putText(im,"center of Sun contour", (x,y), cv2.FONT_HERSHEY_SIMPLEX, 1, (0,0,255))
cv2.circle(im,(width/2,height/2),1,(255,0,0),2)
cv2.putText(im,"center of image", (width/2,height/2), cv2.FONT_HERSHEY_SIMPLEX, 1, (255,0,0))
cv2.imshow('contour',im)
cv2.waitKey(0)

rawDescription: python opencv-finding circle (Sun) , coordinates of center the circle from picture

description: Python opencv-finding circle (Sun) , coordinates of center the circle from picture


code:
def somedecorator(fn):
    import traceback
    print "decorating function:", fn
    print "function class:", fn.__class__
    print traceback.extract_stack()[-2][2]
    return fn

rawDescription: Python instancemethods & decorators

description: Python instancemethods & decorators


code:
class Map(object):

 def __init__(self):

    self.quips = [
        "You died. You suck at this.",
        "Your mom would be proud, if she were smarter",
        "Such a luser.",
        "I have a small puppy that's better at this."
    ]

 def death(self):
    print self.quips[randint (0, len(self.quips)-1)]
    exit(1)

 def princess_lives_here(self):
    print "You see a beautiful Princess with a shiny crown."
    print "She offers you some cake."

    eat_it = raw_input(">")

    if eat_it == "eat it":
        print "You explode like a pinata full of frogs."
        print "The Princess cackles and eats the frogs. Yum!"
        return 'death'

    elif eat_it == "do not eat it":
        print "She throws the cake at you and it cuts off your head."
        print "The last thing you see is her munching on your face. Yum!"
        return 'death'

    elif eat_it == "make her eat it":
        print "The Princess screams as you cram the cake in her mouth."
        print "Then she smiles and cries and thank you for saving her."
        print "She points to a tiny door and says, 'The Koi needs cake too.'"
        print "She gives you the very last bit of cake and shoves you in."
        return 'gold_koi_pond'

    else:
        print "The Princess looks at you confused and just points at the cake."
        return 'princess_lives_here'

class Engine(object):

 def __init__(self, map, start):
    self.quips = [
        "You died. You suck at this.",
        "Your mom would be proud, if she were smarter",
        "Such a luser.",
        "I have a small puppy that's better at this."
    ]
    self.map = map
    self.start = start

 def play(self):
    next = self.start

    while True:
        print "\n-----"
        room = getattr(self.map, next)
    next = room()

rawDescription: Python requiring an attribute be converted to a string


code:
from bs4 import BeautifulSoup

txt = """

Test 1

Test 2

"""

def clone(soup, tag):
   newtag = soup.new_tag(tag.name)
   for attr in tag.attrs:
      newtag[attr] = tag[attr]
   return newtag

soup = BeautifulSoup(txt)
tags = soup.find_all("li")
for tag in tags:
   print tag.wrap(clone(soup, tag.parent))

rawDescription: Get an element and its parent ONLY, using BeautifulSoup in Python


code:
# track blanks
blanks_before_line = [0]
with open('data.xml') as f:
    for line in f:
        new_blanks = blanks_before_line[-1]
        if not line.strip():
            new_blanks += 1
        blanks_before_line.append(new_blanks)

# now in your code subtract it
# .....
real_sourceline = ElementsList[0].sourceline
adjusted_sourceline = real_sourceline - blanks_before_line[real_sourceline - 1]
print "The line number of Time element is = ", adjusted_sourceline

rawDescription: how to exclude line numbers for an empty line

description: Exclude line numbers for an empty line


code:
body_element = frame.findFirstElement("body")

for el in body_element.findAll("div").toList():
    print el.tagName()

rawDescription: Problems with finding QWebElements by tag in PySide


code:
import os
for j in cursor.fetchall():
    best_fuzzy_file = ''
    s1=j[0]

    def good_ratio(a):
        return fuzz.token_set_ratio(a, s1)
    for dir_entry in os.listdir(path):
        dir_entry_path = os.path.join(path, dir_entry)
        if os.path.isfile(dir_entry_path):

            condition_matched_in_file = False
            with open(dir_entry_path, 'r') as my_file:
               try:
                   my_sum, my_len = reduce(lambda a, b: (a[0]+b[0], a[1]+b[1]), ((good_ratio(i), 1) for i in my_file))
               except TypeError:
                   # file empty, move to next file
                   continue
               fuzzinessav=(my_sum/my_len)
               filenames2fuzz[dir_entry_path].append(fuzzinessav)
            best_fuzziness_ratio = 0
            for k, v in filenames2fuzz.items():
                    if max(v) > best_fuzziness_ratio:
                        best_fuzzy_file = k
                        best_fuzziness_ratio = max(v)
    if os.path.exists(file_location+'/'+best_fuzzy_file): # can be checked using other modules
         with open(best_fuzzy_file) as f:
             print best_fuzzy_file

rawDescription: python NameError from the max fuzzy value file chosen

description: Python NameError from the max fuzzy value file chosen


rawDescription: Python logging messages "out of order"

description: Python logging messages "out of order"


code:
import mechanize
import lxml.etree as etree

url = 'something'

br = mechanize.Browser()
resp = br.open(url)
parser = etree.parser()
tree = etree.parse(resp,parser)
forms = list(br.forms())
id_info = {}
for form in forms:
    elements = form.controls
    for element in elements:
        id_info[element.attrs['id']]=''

inputs = tree.findall('.//input')
for i in inputs:
    index = list(i.getparent()).index(i)
    id_info[i.attrib['id']] = list(i.getparent)[index+1]

for j in id_info:
    print j,id_info(j)

rawDescription: Python mechanize: read table element next to input


code:
def insertRowInPostgreSQL():
    con = psycopg2.connect("dbname='myDb' user='bond'")
    cur = con.cursor()
    cur.execute("SELECT array_to_string(ARRAY(SELECT url FROM urls),',') AS required_urls;")
    allEmailUrls = cur.fetchone()
    allEmailUrls = allEmailUrls[0]
    allEmailUrls = [url.strip() for url in allEmailUrls.split(',')]
    for individualUrl in allEmailUrls:
        print individualUrl
    con.commit()

insertRowInPostgreSQL()

rawDescription: Save postgreSQL data point as python variable


code:
pk = open( 'file.txt', 'r' ).readlines() #or 'rb' if there's a need

if len(pk) > 2:
    for line in pk[1:-1]:
        print line,
        #or do anything you like to do with line

rawDescription: How to extract necessary content from file in python?

description: Extract necessary content from file in python


code:
def setUp():
    print "In method", self._testMethodName

rawDescription: A way to output pyunit test name in setup()


code:
def myDic(self,selObjects):
        print "Recieved ",selObjects
        print "Length ", len(selObjects)
        #self.objDic={}
        for index,each in enumerate(reversed(selObjects)):
            ##print index,each
            if index%2==0:
                value=each
            elif index % 2!=0:
                key=each
                self.objDic[key]=value
                #self.objDic.update({key:value})
        print self.objDic, len(self.objDic)

rawDescription: stuck at a logic filling dictionary from list values

description: Stuck at a logic filling dictionary from list values


code:
import os
import importlib
try:
    # Do a dynamic 'from DJANGO_SETTINGS_MODULE import *'
    settings = importlib.import_module(os.environ['DJANGO_SETTINGS_MODULE'])
    for v in dir(settings):
        if v.startswith("__"): continue
        globals()[v] = getattr(settings, v)
except ImportError, KeyError:
    # default to the production settings if environment variable not set or improperly specified
    from production import *

rawDescription: How to create a default python submodule for import

description: Create a default python submodule for import


code:
def _generate_row (row_number, prev_row):
    if row_number == 1:
        return [1]

    row_data = [0] + prev_row + [0]
    return [sum(row_data[a:a+2]) for a in xrange(0, len(row_data)-1)]

def generate(num_rows):
    prev_row = None
    for i in xrange(1, num_rows+1):
        prev_row = _generate_row(i, prev_row)
        yield prev_row

print list(generate(5))

rawDescription: How can I improve this code in python?

description: Improve this code in python


code:
from datetime import datetime, timedelta
now = datetime.utcnow()
rounded = now - timedelta(minutes=now.minute % 5 + 5,
                          seconds=now.second,
                          microseconds=now.microsecond)
print rounded
# -> 2014-04-12 00:05:00

rawDescription: python utc time minus 5 minutes

description: Python utc time minus 5 minutes


code:
import xlrd
wb = xlrd.open_workbook("file.xls")

wb.sheet_names()

sh = wb.sheet_by_index(0)

for item in sh.col(0):
    value = unicode(item.value)
    if value.startswith("cheap"):
        print value

rawDescription: Read through an unstructured xls file

description: Read through an unstructured xls file


code:
primes = []

for prime in xrange(1, 1000):
    for b in xrange(2, prime):
        if (prime % b == 0):
            break
    else:
        primes.append(prime)

print primes

rawDescription: How to append to a list only the first time a prime is encountered

description: Append to a list only the first time a prime is encountered


code:
import win32api
## If need to install pywin if not already to get win32api

## Define constants for Windows file attributes
FILE_ATTRIBUTE_READONLY = 0x01
FILE_ATTRIBUTE_HIDDEN = 0x02
FILE_ATTRIBUTE_SYSTEM = 0x04
FILE_ATTRIBUTE_DIRECTORY = 0x10
FILE_ATTRIBUTE_ARCHIVE = 0x20
FILE_ATTRIBUTE_NORMAL = 0x80
FILE_ATTRIBUTE_TEMPORARY = 0x0100

## Combine all the attributes you want using bitwise-Or (using the pipe symbol)
Attribute = FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM

filename="Your-filename-goes-here"

win32api.SetFileAttributes(filename,Attribute)

## Check that the attribute is set.
## You can also right click on the file in windows explorer and
## look under Details tab.

print win32api.GetFileAttributes(filename)

rawDescription: Python: Setting Multiple Attributes for a file (e.g. System, Hidden)