code:
iterations = 0  # переменная для подсчета итераций (используется при выводе)

# ------------------------------------------------------------------------------------
# Функция считывания условий из файла
def read_data(filename):
    try: f = open(filename, "r")
    except:
        print "\nERROR: File %s not found.\nNow try to open input.txt..." % filename
        try:
            f = open("input.txt", "r")
        except:
            print "\nERROR: File 'input.txt' not found."
            sys.exit(raw_input("Press enter to exit..."))

    return [ map(int, condition) for condition in                       # для каждой "строки(массива)" массива
                                                                        # каждый элемент превращаем в число.
                [ re.findall(r'\d+', line) for line in f.readlines()]
            ]                                                           # для каждой линии из считанного файла
                                                                        # регулярным выражением выделяем массив чисел в
                                                                        # этой строке, которые разделены пробелом.

# ------------------------------------------------------------------------------------
# Функция проверки условий
def check(tab, row, conditions):
    # Вывод матрицы на итерации с шагом 1000
    global iterations
    iterations +=1
    if  iterations % 1000000 == 0 :
        for i in range(8):
            print tab[i]
        print "   "

    #Обязательное правило №1 #top-side conditions
    # Проверка строк на соответствие верхним ограничениям

    # Проверка первой строки
    # Тут могут быть либо нули, либо ограничивающая цифра, иначе выход на перегенерацию строки
    if row == 0:
        for col in range(8):
            if (conditions[2][col] != 0):
                if (tab[0][col] != conditions[2][col]       and
                    tab[0][col] != 0                        and
                    tab[0][col] != 7
                    ):      # Грустный смайлик. Почему, ведь всё прекрасно работает?
                    return 0

    # Если в первой строке нули, то во второй должно быть верхнее ограничение, либо ноль
    if row == 1:
        for col in range(8):
            if (conditions[2][col] != 0):
                if (
                    (tab[0][col] == 0 or tab[0][col] == 7)  and
                     tab[1][col] != conditions[2][col]      and
                     tab[1][col] != 0                       and
                     tab[1][col] != 7
                    ):
                    return 0

    # Если в первой и второй строках нули, то в третьей должно быть верхнее ограничение, без вариантов
    if row == 2:
        for col in range(8):
            if (conditions[2][col] != 0):
                if (
                    (tab[0][col] == 0 or tab[0][col] == 7)  and
                    (tab[1][col] == 0 or tab[1][col] == 7)  and
                     tab[2][col] != conditions[2][col]
                    ):
                    return 0

    #Обязательное правило №2 #left-side conditions
    # Проверка строк на соответствие левым ограничениям, вызывается для каждой строки
    if (conditions[0][row] != 0): # если первое условин не нулевое. Какое первое? Левое! Первое оно у нас в файле, зачем привязывать к формату
        if (
            (tab[row][0] != conditions[0][row]      and # если на первой позиции не стоит граничное
             tab[row][1] != conditions[0][row]      and #если на второй тоже не стоит граничное
             tab[row][2] != conditions[0][row]          #если на 3-й тоже не стоит граничное
            )
            or
            (tab[row][1] == conditions[0][row]      and # вторая позиция равна условию
            (tab[row][0] != 0 and tab[row][0] != 7)     # при этом на 1-й позиции не 0 и не 7
            )
            or
            (
                tab[row][2] == conditions[0][row]   and
                (
                tab[row][0] != 0 and tab[row][0] != 7
                or
                tab[row][1] != 0 and tab[row][1] != 7
                )
            )
            ):
            return 0

    #Обязательное правило №3 #right-side conditions
    # Проверка строк на соответствие правым ограничениям, вызывается для каждой строки
    if (conditions[1][row] != 0):
        if (
            (tab[row][-1] != conditions[1][row]     and # если на первой позиции не стоит граничное
             tab[row][-2] != conditions[1][row]     and #если тут тоже не стоит граничное
             tab[row][-3] != conditions[1][row]
            )
            or
            (tab[row][-2] == conditions[1][row]     and
             tab[row][-1] != 0 and tab[row][-1] != 7
            )
            or
            (
                tab[row][-3] == conditions[1][row]      and
                (
                    tab[row][-1] != 0 and tab[row][-1] != 7
                    or
                    tab[row][-2] != 0 and tab[row][-2] != 7
                )
            )
            ):
            return 0

    #Необязательное правило #Оптимизация
    # Проверка того, что числа в нижних ограничениях не встречаются раньше 5-й строки
    if row < (len(tab) - 3):    # 8 - 3 = 5
        for i in range(len(tab)):
            if tab[row][i]==conditions[3][i]:
                return 0

    #Обязательные правила №5-6, переставлены сюда для оптимизации
    # Проверка того, что цифры в столбце не повторились и что количество пробелов не больше 2
    for j in range(0, row) :
            for h in range(0, 8):
                    if (tab[row][h] == tab[j][h] and tab[row][h] != 0 and tab[row][h] != 7) :
                            return 0
    sum = 0
    for k in range(0, 8) :
            for n in range(0, row + 1):
                    if (tab[n][k] == 0 or tab[n][k] == 7) :
                            sum += 1
                    if (sum > 2):
                            return 0
            sum = 0

    #Обязательное правило №4 #down-side conditions
    # Проверка строк на соответствие нижним ограничениям (ТОДО: исправить и проверить)
    if (row == 7):
        for col in range(len(tab)):
            if conditions[3][col] != 0 :  #если 3-е условие не равно 0. Не 3-е, нижнее ведь. Давайте не будем путать людей
                if (
                    (tab[-1][col] != conditions[3][col] and # Исправил индексы так, чтобы они были единой системы счисления
                     tab[-2][col] != conditions[3][col] and
                     tab[-3][col] != conditions[3][col]
                    )
                    or
                    (tab[-2][col] == conditions[3][col] and
                     tab[-1][col] !=0 and tab[-1][col] !=7
                    )
                    or
                    (
                        tab[-3][col] == conditions[3][col]  and
                        (
                            tab[-1][col] !=0 and tab[-1][col] !=7
                            or
                            tab[-2][col] !=0 and tab[-2][col] !=7
                        )
                    )
                    ):
                    return 0

    return 1

# ------------------------------------------------------------------------------------
# Функция генерирования строки (почти без комментариев, потому что поздно)
def generate(row):
    if (row[0] == -1):
        row[:] = range(len(row))
        return 1
    a = -1
    for j in reversed(range(len(row)-1)):
        if (row[j] < row[j+1]):
            a = j
            break
    if a == -1:
        return 0
    b = -1
    for j in reversed(range(a, len(row))):
        if (row[j] > row[a]):
            b = j
            break

    row[a], row[b] = row[b], row[a]     # Обмен значений для получения новой строки
    row[(a+1):] = reversed(row[(a+1):])
    return 1

# ------------------------------------------------------------------------------------
# Функция рекурсивного подбора строк матрицы
def rekurs(tab, row, conditions):
    while (1):
        if (generate(tab[row]) == 0):   # Если не осталось больше вариантов строк - забиваем минус единицы, выходим
            tab[row] = [-1 for i in range(len(tab))]
            return 0
        if (check(tab, row, conditions) == 1):
            if row < 7:                 # Пока не заполним таблицу полностью, спускаемся по уровням, т.е. по строкам
                if (rekurs(tab, row + 1, conditions)):
                    return 1
            else:
                return 1

## -------------------- run program -------------------
if __name__ == '__main__':
    conditions = read_data(raw_input("Input file:  "))
    tab = [ [-1 for j in range(len(conditions[0]))] for i in range( len(conditions[0]) ) ]
    print "\nSuccess. \nNow search for solutions..."
    if rekurs(tab, 0, conditions) == 0:
        print "\nThere is no solution:"
        for i in range(len(tab)): print tab[i]
    else:
        print "\nGood news:"
        for i in range(len(tab)):
            for k in range(len(tab)):
                if (tab[i][k] == 7): tab[i][k] = 0
            print tab[i]
    raw_input("Press enter to exit...")

rawDescription: Solving End view puzzle on Python

description: Solving End view puzzle on Python


code:
#!/usr/bin/python
# script to delete all keys in a Riak bucket

import json
import re
import requests
import sys

def processChunk(chunk):
    global key_count
    obj = json.loads(chunk.group(2))
    if 'keys' in obj:
        for key in obj['keys']:
            r = requests.delete(sys.argv[1] + '/' + key)
            print 'delete key', key, 'response', r.status_code
            key_count += 1

if len(sys.argv) != 2:
    print 'Usage: {0} <http://riak_host:8098/riak/bucket_name>'.format(sys.argv[0])
    print 'Set riak_host and bucket_name appropriately for your Riak cluster.'
    exit(0)

r = requests.get(sys.argv[1] + '?keys=stream')
content = ''
key_count = 0

for chunk in r.iter_content():
    if chunk:
        content += chunk

re.sub(r'(?=(^|})({.*?})(?={|$))', processChunk, content)

print 'Deleted', key_count, 'keys'

rawDescription: How can I delete a Riak bucket in Python?

description: Delete a Riak bucket in Python


code:
import random
def print_random(random_number=None):
    if random_number is None:
        random_number = 4 # chosen by fair dice roll.
                          # guaranteed to be random.
    print random_number

rawDescription: Force default reevaluation on function call


code:
from itertools import combinations

def find_sum_in_list(numbers, target, comboSize):
    results = []
    for combo in combinations(numbers, comboSize):
        if sum(combo) == target:
            results.append(combo)
    return results

if __name__ == "__main__":
    numbers = [10,20,30,40,50,60,70,80,90,100,110,120,130,140,150,160,170,180,190,200,210,220,230,240,250,260,270,280,290,300]
    total = 1200
    comboSize = 5
    print find_sum_in_list(numbers, total, comboSize)

rawDescription: How to limit Python recursive combinations?

description: Limit Python recursive combinations


code:
import re

s = "http://example.com/variable/controller/id32434242423423234?param1=321&param2=4324342"

m = re.search(r'controller/id(\d+)\?',s)
if m:
    print "Found the id:", m.group(1)

rawDescription: Python - Extract important string information


code:
from Tkinter import *

root = Tk()

def key(event):
    print "pressed", repr(event.char)

def callback(event):
    print "clicked at", event.x, event.y

canvas= Canvas(root, width=100, height=100)
canvas.bind("<Key>", key)
canvas.bind("<Button-1>", callback)
canvas.pack()

root.mainloop()

rawDescription: How to bind a click event to a Canvas in Tkinter?

description: Bind a click event to a Canvas in Tkinter


code:
from dateutil import tz
from datetime import datetime
utc_time = datetime(2010, 5, 19, 9, 16, 43, tzinfo=tz.tzutc())
jst_time = utc_time.astimezone(tz.gettz('Japan'))
print utc_time
print jst_time

rawDescription: why datetime.now() shows invalid result when executed inside django server?

description: Why datetime.now() shows invalid result when executed inside django server


code:
class Foo:
    def bar1(self):
        print 1
    def bar2(self):
        print 2

def callMethod(o, name):
    getattr(o, name)()

f = Foo()
callMethod(f, "bar1")

rawDescription: Call a Python method by name

description: Call a Python method by name


code:
def quadratic(a, b, c):
    discriminant = b**2 - 4*a*c
    if discriminant < 0:
      return []
    elif discriminant == 0:
      return [-b / (2*a)]
    else:
      root = math.sqrt(discriminant)
      return [(-b + root) / (2*a), (-b - root) / (2*a)]

print quadratic(2, 3, 2) # []
print quadratic(2, 4, 2) # [-1]
print quadratic(2, 5, 2) # [-0.5, -2.0]

rawDescription: python - returns incorrect positive #

description: Python - returns incorrect positive #


code:
import re, binascii
originals = ('123456', 'FOOBAR', ':;<=>?')
data = ' '.join(map(binascii.hexlify, originals))
print data
for pattern in (r'(?:3\d){6}', r'(3[0-9a-fA-F]){6}',
            r'(?:3[0-9a-fA-F]){6}', r'[0-9a-fA-F]{12}'):
    print repr(pattern), re.findall(pattern, data)

rawDescription: Creating a regular expression that will search for strings converted to 12 digit hex values


code:
class Foo(object):
    @property
    def spam(self):
        print 'Foo.spam called'
        return 'spam'
    @spam.setter
    def spam(self, value):
        print 'Foo.spam.setter called'
    @property
    def ham(self):
        print 'Foo.ham called'
        return 'ham'
    @ham.setter
    def ham(self, value):
        print 'Foo.ham.setter called'

class Bar(Foo):
    @Foo.spam.getter
    def spam(self):
        print 'Bar.spam override'
        return 'eggs and spam'
    @property
    def ham(self):
        print 'Bar.ham override'
        return 'eggs and ham'

Bar().spam
Bar().spam = 'foo'
Bar().ham
Bar().ham = 'foo'

rawDescription: What is the purpose of Python's property.getter?


code:
def get_difficulty():
    while True:
        chosen_difficulty = raw_input("***  Choose difficulty: Easy, Medium or Hard: ").lower()
        try:
            return {"hard": 10, "medium": 15, "easy": 20}[chosen_difficulty]
        except KeyError:
            print "***  Did you enter 'Easy', 'Medium' or 'Hard'?"
            print "***  Sorry that was passive aggressive. You obviously didn't..."

rawDescription: Python: Is it good practice to call a function within itself?


code:
import os

print "hello world"
os.system("python hello_world.py")

rawDescription: Self compiling python script?

description: Self compiling python script


code:
class dummy(object):
    def __init__(self, arg):
        super(dummy, self).__setattr__("data", arg)

    def __setattr__(self, name, value):
        if name == "data":
            raise AttributeError("Can't modify data")
        else:
            super(dummy, self).__setattr__(name, value)

a = dummy(5)
print a.data
# 5
a.data = "1"
# AttributeError: Can't modify data

rawDescription: Python - how to create immutable class member that is configurable during __init__


code:
from collections import Counter

x = ['123', '456', '789', '123']
y = ['aaa', 'aaa', 'bbb', 'ccc']

uniq = []
res = Counter()
for number, letter in zip(x, y):
    if number not in uniq:
        uniq.append(number)
        res.update(letter)

print dict(res)

rawDescription: Two lists of same length. Get unique pairs based on one of them


code:
import os
import fnmatch

def findFiles (path, filter):
    Files = []
    for root, dirs, files in os.walk(path):
        for file in fnmatch.filter(files, filter):
           Files.append(os.path.join(root, file))
    return Files

def fastq2SQlite(Files):
    for file_ in Files:
        print file_

        with open(file_, 'r') as dummy_file:

            for line in dummy_file:
                print line

rawDescription: Python: Using oswalk in first function to find files, pass name, then trying to open in second function


code:
import csv

with open('sg_cand.csv', 'rb') as csvfile:
    csvReader = csv.reader(csvfile)
    seen = set()
    for row in csvReader:
        if row[0] not in seen and row[11] != '\N':
            seen.add(row[0])
            print row[0], row[11]

rawDescription: Get first numeric value from csv where all the first column shares same value in Python 2.7


code:
import re

names = [
    'LIC. SEBASTIÁN LASTIRI',
    'ING. AGR. ROBERTO DANIEL RODRÍGUEZ',
    'C.P.N. JULIO DOMINGO BURAK',
    'INGENIERO HIDRÁULICO VÍCTOR AGUSTÍN PORRINO'
]

new_names = [re.sub("^\s+", "", i.split(".")[-1]) for i in names]

print new_names # [SEBASTIÁN LASTIRI', ROBERTO DANIEL RODRÍGUEZ', JULIO DOMINGO BURAK', 'INGENIERO HIDRÁULICO VÍCTOR AGUSTÍN PORRINO']

rawDescription: Remove prefix from name python

description: Remove prefix from name python


code:
# I named it 'mystr' because it is a bad practice to name a variable 'str'
# Doing so overrides the built-in
mystr = "Hello! My name is Barney!"
mystr.count("!")
if mystr.count("!") == 2:
    print True
# Just to explain further
help(str.count)

rawDescription: Way to check that string contains two of the same characters?


code:
word_list = ["AAgg", "aGGG", "AgaG", "gAaA"]
for idx in word_list:
    if idx.lower().count("a") == idx.lower().count("g") == 2:
        print idx

rawDescription: Given an item, how can I count the occurrences of said item in a list, and not print the item if it does not reach certain regulations?


code:
from time import sleep
MAX_TRIES = 6

# ... your other code ...

for i in xrange(MAX_TRIES):
    proc = subprocess.Popen(shell_script, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    (stdout, stderr) = proc.communicate()
    if stderr:
       print "Shell script gave some error..."
       print stderr
       sleep(0.05) # delay for 50 ms
    else:
       print stdout
       print "end" # Shell script ran fine.
       break

rawDescription: How to implement retry mechanism if the shell script execution got failed?

description: Implement retry mechanism if the shell script execution got failed


code:
for obj in collection.find():
    print obj['username']

rawDescription: Retrieve data from pymongo

description: Retrieve data from pymongo


code:
conn = boto.route53.connection.Route53Connection(aws_access_key_id = aws_access_key_id, aws_secret_access_key = aws_secret_access_key)

zone = conn.get_zone("your.zone.")

for record in zone.get_records():
  print "Type: %s, name: %s, values: %s" % (record.type, record.name, ",".join(record.resource_records))

rawDescription: BOTO ResourceRecordSets object convert to string


code:
p= subprocess.Popen(['mplayer', url], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
for line in p.stdout:
    if line.startswith('ICY Info:'):
        info = line.split(':', 1)[1].strip()
        attrs = dict(re.findall("(\w+)='([^']*)'", info))
        print 'Stream title: '+attrs.get('StreamTitle', '(none)')

rawDescription: Python: Parse stream title with mplayer

description: Python: Parse stream title with mplayer


code:
def lookup(self, username="", guess=0,verbose=0):
        guin = guess
        result_set = []
        varsearch = "(&(name=" + str(username) + ")(" + "nin" + "=" + str(guin) + "*))"
        result_id = self.l.search("", ldap.SCOPE_SUBTREE, varsearch, ["nin"])
        while True:
            try:
                result_type, result_data = self.l.result(result_id, 0, 5.0)
                if (result_data == []):
                    break
                else:
                    if result_type == ldap.RES_SEARCH_ENTRY:
                        result_set.append(result_data)
            except ldap.TIMEOUT:
                return {"name": username}
        if len(result_set) == 0:
            return self.lookup(username, guin + 1,verbose)
        else:
            if guess < 1000000:
                return self.lookup(username, guess * 10,verbose)
            else:
                if verbose==1:
                    print "Bingo!",
                return str(guess)

rawDescription: Binary search of unaccesible data field in ldap from python


code:
import random

stats = {'correct': 0, 'wrong': 0}

num_ques=int(input('Enter Number of Questions:'))
while(num_ques < 1):
   num_ques=int(input('Enter Positive Number of Questions:'))

   for i in range(0, (num_ques)):
      a=random.randint(1,100)
      b=random.randint(1,100)
      answer=int(input(str(a) + '+' + str(b) + '='))
      sum=a+b
      if (answer==sum):
        print ('Correct')
        stats['correct'] += 1
      else:
        print ('Wrong.')
        stats['wrong'] += 1

print "results: {0} correct, {1} wrong".format(stats['correct'], stats['wrong'])

rawDescription: Trying to Make a Quiz

description: Trying to Make a Quiz


code:
from twisted.trial import unittest
#^^^^^^^^^^^^^^^^^
import time

from twisted.internet import defer
from twisted.internet import reactor

class MyTest(unittest.TestCase):

    def test_simple_deferred(self):

        print "\nStarting Test"

        my_deferred = defer.Deferred()

        def print_time(dont_care):
        #              ^^^^^^^^^
            print time.time()
            self.assertTrue(False)

        my_deferred.addCallback(print_time)

        reactor.callLater(3, my_deferred.callback, None)
        #                                        ^^^^^^
        print time.time()

        return my_deferred

rawDescription: Testing with a twisted deferred

description: Testing with a twisted deferred


code:
apples = [red, green]
for type in apples:
    for item in type:
        print item

rawDescription: Sending a list of arrays to a For loop

description: Sending a list of arrays to a For loop


code:
conditionMet = False
for row in reader:
    if conditionMet == True:
        print "FA",row[0], ','.join(row[1:])
        conditionMet = False # or break if you know you only need at most one line
    if row[1:] == val:
        conditionMet = True

rawDescription: Python Excel if a condition is true print next line t+1


code:
p = re.compile(ur'[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+', re.MULTILINE | re.IGNORECASE)
test_str = r'...'
re.findall(p, test_str)

rawDescription: Extract emails from html using regex

description: Extract emails from html using regex


code:
pid = read_pidfile(pidfile)
if pid:
    try:
        os.kill(int(pid), 0)
        return pid
    except OSError, e:
        if e.errno == errno.EPERM:
            return pid
return None

rawDescription: Paster daemon won't shut down because can't read own pid file


code:
from splinter import Browser

# Define the username and password
username2 = '***'
password2 = '***'

# Choose the browser (default is Firefox)
browser2 = Browser()

# Fill in the url
browser2.visit('https://mijn.ing.nl/internetbankieren/SesamLoginServlet')

# Find the username form and fill it with the defined username
browser2.find_by_id('gebruikersnaam').first.find_by_tag('input').fill(username2)

# Find the password form and fill it with the defined password
browser2.find_by_id('wachtwoord').first.find_by_tag('input').fill(password2)

# Find the submit button and click
browser2.find_by_css('.submit').first.click()

# Print the current url
print browser2.url

# Print the current browser title
print browser2.title

# Print the current html source code
print browser2.html

rawDescription: Filling a password form with Splinter

description: Filling a password form with Splinter


code:
n = 100
numbers = range(2,100)
results = []
while len(numbers) > 0:
    results.append(numbers[0])
    numbers = [number for number in numbers if number % results[-1] != 0]
print len(results)

rawDescription: Find all the primes from 2 to n, using the Sieve of Eratosthenes


code:
#!/usr/bin/python

import subprocess
import re

cmd = "arp -a"
process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
output, errors = process.communicate()

for line in output.split("\n"):
    if line and not line.isspace():
        print "line ->", line
        regex = re.match("(?i).*?(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}).*?((?:[0-9A-F]{1,2}[:]){5}(?:[0-9A-F]{1,2}))", line)
        print "ip  ->", regex.group(1)
        print "mac ->", re.sub('(^[^:](?=:)|(?<=:)[^:](?=:)|(?<=:)[^:]$)', '0\\1', regex.group(2))

rawDescription: Regex woes with Subprocess output

description: Regex woes with Subprocess output


code:
from urlparse import urlparse, parse_qs
q = urlparse('http://sitename.com/pathname?title=moviename&url=VIDEO_URL')
qs = parse_qs(q.query)
print qs["title"] # moviename
print qs["url"] # VIDEO_URL

rawDescription: Split the title part of the URL into a separate column - Python


code:
import numpy as np
a = np.arange(24)
a = a.reshape([4,3,2])

def my_func(a):
  print "vector: " + str(a)
  return sum(a) / len(a)

np.apply_along_axis(my_func, 0, a)

rawDescription: Apply function to vectors in 3D numpy array


code:
import matplotlib.pyplot as plt
from matplotlib.widgets import SpanSelector

ax = plt.subplot(111)
ax.plot([1,2], [3,4])

def onselect(vmin, vmax):
    print vmin, vmax

span = SpanSelector(ax, onselect, 'horizontal')

span.set_visible(False)

rawDescription: Turn off the Spanselector in matplotlib

description: Turn off the Spanselector in matplotlib


code:
elem = soup.find('input',{'id':'short-link-input'})
print elem.get('value')

rawDescription: Unable to scrap data with beautiful soup in python


code:
for root, dirs, files in os.walk('/starting/path/'):
    for myFile in files:
        if myFile == "index.html":
            print os.path.join(root, myFile)

rawDescription: Does python's glob function support wildcards with variable depth?


code:
#!/usr/bin/env python

class ReadFile(object): # Classes have titlecase names and inherit from object
    def __init__(self):
        self.count = 0
        self.txt = None # Initialise the class member here

    def open(self, filename): # file is a Python built-in. Prefer 'filename'
        self.txt = open(filename, "r")

    def cnt(self):
        line = self.txt.readline() # str is a Python built-in. Prefer 'line'.
                                   # Reference the class member with 'self.'
        line = line.strip() # Remove any trailing whitespace
        while line != "end": # TODO: What happens if this line doesn't appear?
            self.count += 1
            line = self.txt.readline().strip()

    def printline(self):
        print "the number of lines = %d" % self.count

obj = ReadFile()
obj.open(raw_input("which file do you want to read? \n").strip())
obj.cnt()
obj.printline()

'''
end
'''

rawDescription: Trouble with defining global variables

description: Trouble with defining global variables


code:
def Timer(swimmer):
    myFile = open("race.txt", "r")
    lists = myFile.readlines()
    found = [l for l in lists if l.startswith(swimmer)][0]  # Gets first found swimmer
    time = found.split()[-1]  # Gets last item (eg. time) in splitted list
    myFile.close()
    return time

print Timer('jack')

rawDescription: How to check a list for a string then select the rest of that item,

description: Check a list for a string then select the rest of that item,


code:
import urllib2

@cherrypy.expose
def onSubmit(**kwargs):
  ##Do something
  ##Do something
  ##Do something

  url = "http://localhost/some_other_location/doSomethingElse?arg1=x&arg2=y"

  try:
    data = urllib2.urlopen(url).read()
  except urllib2.HTTPError, e:
    raise cherrypy.HTTPError(500, "HTTP error: %d" % e.code)
  except urllib2.URLError, e:
    raise cherrypy.HTTPError(500, "Network error: %s" % e.reason.args[1])

  ##Do something with the data

rawDescription: calling a function with cherry.py

description: Calling a function with cherry.py


code:
my_string = "
hello, how are you other code my name is joe
"
soup = BeautifulSoup(my_string, 'html')

soup.code.extract()
text = soup.p.get_text()
print text

rawDescription: BeautifulSoup Tag Removal unexpected result


code:
import re

LETTERS = 'abcdefghijklmno'

def output_letters(text):
    elements = re.finditer(r'(\*This).*?\[position=(change\()?(\d+)-(\d+)\)?\]', text)
    for element in elements:
        print element.group(0)
        letters = LETTERS[int(element.group(3)):int(element.group(4))]
        if element.group(2):
            letters = letters.replace('c','1')
        print letters

string1='*This is an inverse position [position=change(1-4)]in a long sentence\n*This is a direct position [position=2-7] in a long sentence'
output_letters(string1)

rawDescription: Extract and replace letters from a string both at the same time


code:
import collections
import re
import os

all_files_frequency = collections.Counter()

previous_dir = os.getcwd()
os.chdir('testfilefolder')
for filename in os.listdir('.'):
    with open(filename) as f:
        file_contents = f.read().lower()

    words = re.findall(r"[a-zA-Z0-9']+", file_contents) # Breaks up into words
    frequency = collections.Counter(words)              # For this file only
    all_files_frequency.update(words)                   # For all files
    print(frequency)

os.chdir(previous_dir)

print ''
print all_files_frequency

rawDescription: Python - reading files from directory file not found in subdirectory (which is there)


code:
def checkComm(old_commCount): # passed as a parameter
    server = xmlrpclib.ServerProxy(server_uri) # connect to WP server
    comments = server.wp.getComments(blog_id, server_admin, admin_pass, filters)
    new_commCount = len(comments)
    if new_commCount > old_commCount:
        print "there are new comments"
        old_commCount = new_commCount
        return old_commCount # return it so you can update it
    else:
        print "no new comments"
        return old_commCount

comm_count = 0 # initialize it here
while True:
    comm_count = checkComm(comm_count) # update it every time
    time.sleep(60)

rawDescription: how can I give a variable another value inside a function in python?

description: Give a variable another value inside a function in python


code:
import networkx as nx

g = nx.Graph([['a','b'],['a','c'],['b','c'],['d','e'],['e','f'],['d','f'],['g','h'],['g','i'],['h','i']])

interest_nodes = set(['a', 'b', 'f'])

interest_edges = []
for component in nx.connected_component_subgraphs(g):
    if len(set(component) & interest_nodes) > 0:
        interest_edges.extend(component.edges())

print interest_edges
# output
# [('a', 'c'), ('a', 'b'), ('c', 'b'), ('e', 'd'), ('e', 'f'), ('d', 'f')]

rawDescription: Loop though connected components in networkx and extract components that contain certain nodes


code:
#!/usr/bin/env python

import Queue
import threading
import urllib2
import time
import htmllib, formatter

class LinksExtractor(htmllib.HTMLParser):
    # derive new HTML parser

    def __init__(self, formatter):
        # class constructor
        htmllib.HTMLParser.__init__(self, formatter)
        # base class constructor
        self.links = []
        # create an empty list for storing hyperlinks

    def start_a(self, attrs) :  # override handler of <A ...>...</A> tags
        # process the attributes
        if len(attrs) > 0 :
            for attr in attrs :
                if attr[0] == "href":
                    # ignore all non HREF attributes
                    self.links.append(attr[1]) # save the link info in the list

    def get_links(self) :
        # return the list of extracted links
        return self.links

format = formatter.NullFormatter()
htmlparser = LinksExtractor(format)

data = open("links.html")
htmlparser.feed(data.read())
htmlparser.close()

hosts = htmlparser.links

queue = Queue.Queue()

class ThreadUrl(threading.Thread):
    """Threaded Url Grab"""
    def __init__(self, queue):
        threading.Thread.__init__(self)
        self.queue = queue

    def run(self):
        while True:
            #grabs host from queue
            host = self.queue.get()

            ####################################
            ############FIX THIS PART###########
            #VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV#

            url = urllib2.urlopen(host)
            morehtml = url.read() # your own your own with this

            #signals to queue job is done
            self.queue.task_done()

start = time.time()
def main():
    #spawn a pool of threads, and pass them queue instance
    for i in range(5):
        t = ThreadUrl(queue)
        t.setDaemon(True)
        t.start()

        #populate queue with data
    for host in hosts:
        queue.put(host)

    #wait on the queue until everything has been processed
    queue.join()

main()
print "Elapsed Time: %s" % (time.time() - start)

rawDescription: python urllib2 multi downloading

description: Python urllib2 multi downloading


code:
import xml.dom.minidom as minidom

xml = """
<root>

</root>
"""
doc = minidom.parseString(xml)                  # or minidom.parse(filename)
root = doc.getElementsByTagName('root')[0]      # or doc.documentElement
items = [n for n in root.childNodes if n.nodeType == doc.ELEMENT_NODE]

for item in items:
    print item.nodeName

rawDescription: Python xmltodict: How to preserve XML element order?


code:
buildpath = sys.argv[1]
buildpath = buildpath.replace('\\', '\\\\')
print buildpath

rawDescription: Python2.7 set a given variable to replace one backslash to two backslashes


code:
import datetime
import matplotlib.pyplot as plt
x = [datetime.date(2011,2,11),
     datetime.date(2011,3,11),
     datetime.date(2011,4,11),
     datetime.date(2011,5,11),
     datetime.date(2011,6,11),
     datetime.date(2011,7,11)]
y = [23,41,67,72,18,19]
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot_date(x, y, 'kx')

# next task is to broaden the xaxis so that it begins
# and ends at the start of a month (approximately).
xmin, xmax, ymin, ymax = ax.axis() ; print xmin, xmax, ymin, ymax
a1 = xmin - min(x).day + 1
a2 = xmax - max(x).day + 31

ax.plot_date(a1, ymin, 'ko')
ax.plot_date(a2, ymin, 'ko')
ax.axis('auto')

plt.show()

rawDescription: matplotlib 'auto dimensioning of axes' not showing all datapoints

description: Matplotlib 'auto dimensioning of axes' not showing all datapoints


code:
def incrX(i):
  while True:
    i += 1
    i %= 10
    yield i

incr = incrX(10)
print incr.next()
print incr.next()

rawDescription: Is it beneficial to replace a simple Python class with a closure?


code:
import codecs, os, re, sys
from xml.sax.saxutils import escape

fn = sys.argv[1]

ged = codecs.open(fn, encoding="cp437")
xml = codecs.open(fn+".xml", "w", "utf8")
xml.write("""<?xml version="1.0"?>\n""")
xml.write("<gedcom>")
sub = []
for s in ged:
    s = s.strip()
    m = re.match(r"(\d+) (@(\w+)@ )?(\w+)( (.*))?", s)
    if m is None:
        print "Error: unmatched line:", s
    level = int(m.group(1))
    id = m.group(3)
    tag = m.group(4)
    data = m.group(6)
    while len(sub) > level:
        xml.write("</%s>\n" % (sub[-1]))
        sub.pop()
    if level != len(sub):
        print "Error: unexpected level:", s
    sub += [tag]
    if id is not None:
        xml.write("<%s id=\"%s\">" % (tag, id))
    else:
        xml.write("<%s>" % (tag))
    if data is not None:
        m = re.match(r"@(\w+)@", data)
        if m:
            xml.write(m.group(1))
        elif tag == "NAME":
            m = re.match(r"(.*?)/(.*?)/$", data)
            if m:
                xml.write("<forename>%s</forename><surname>%s</surname>" % (escape(m.group(1).strip()), escape(m.group(2))))
            else:
                xml.write(escape(data))
        elif tag == "DATE":
            m = re.match(r"(((\d+)?\s+)?(\w+)?\s+)?(\d{3,})", data)
            if m:
                if m.group(3) is not None:
                    xml.write("<day>%s</day><month>%s</month><year>%s</year>" % (m.group(3), m.group(4), m.group(5)))
                elif m.group(4) is not None:
                    xml.write("<month>%s</month><year>%s</year>" % (m.group(4), m.group(5)))
                else:
                    xml.write("<year>%s</year>" % m.group(5))
            else:
                xml.write(escape(data))
        else:
            xml.write(escape(data))
while len(sub) > 0:
    xml.write("</%s>" % sub[-1])
    sub.pop()
xml.write("</gedcom>\n")
ged.close()
xml.close()

rawDescription: Is there a GEDCOM parser written in Python?


code:
import numpy as np

M = np.array([[1,0,0,0,2],[0,0,3,0,0],[0,0,0,0,0],[0,4,0,0,0]])

#We perform singular-value decomposition of M
U, s, V = np.linalg.svd(M)

S = np.zeros(M.shape,dtype = np.float64)

b = np.array([1,2,3,4])

m = min(M.shape)

#We generate the matrix S (Sigma) from the singular values s
S[:m,:m] = np.diag(s)

#We calculate the pseudo-inverse of S
Sp = S.copy()

for m in range(0,m):
  Sp[m,m] = 1.0/Sp[m,m] if Sp[m,m] != 0 else 0

Sp = np.transpose(Sp)

Us = np.matrix(U).getH()
Vs = np.matrix(V).getH()

print "U:\n",U
print "V:\n",V
print "S:\n",S

print "U*:\n",Us
print "V*:\n",Vs
print "Sp:\n",Sp

#We obtain the solution to M*x = b using the singular-value decomposition of the matrix
print "numpy.linalg.svd solution:",np.dot(np.dot(np.dot(Vs,Sp),Us),b)

#This will print:
#numpy.linalg.svd solution: [[ 0.2         1.          0.66666667  0.          0.4       ]]

#We compare the solution to np.linalg.lstsq
x,residuals,rank,s =  np.linalg.lstsq(M,b)

print "numpy.linalg.lstsq solution:",x
#This will print:
#numpy.linalg.lstsq solution: [ 0.2         1.          0.66666667  0.          0.4       ]

#We determine the significant (i.e. non-arbitrary) components of x

Vs_significant = Vs[np.nonzero(s)]

print "Significant variables:",np.nonzero(np.sum(np.abs(Vs_significant),axis = 0))[1]

#This will print:
#Significant variables: [[0 1 2 4]]
#(i.e. x_3 can be chosen arbitrarily without altering the result)

rawDescription: How do I associate which singular value corresponds to what entry?

description: Associate which singular value corresponds to what entry


code:
import json

# let x be a string contain the JSON encoded data
x = '{"id":"9e1ebc5d", ...}'

# convert to Python dictionary
p = json.loads(x)

# p is now a Python dictionary
print type(p) # prints   <type 'dict'>
print p['id'] # prints   9e1ebc5d

rawDescription: How do I turn the following data into a Python dict

description: Turn the following data into a Python dict


rawDescription: Checking if a website is up via Python

description: Checking if a website is up via Python


code:
def gen_num(trailing, depth, left):
    if depth < 11:
        for i in range(max(0,min(10, left))):
            gen_num(trailing*10+i, depth+1, left-i)
    elif depth == 11:
        if left < 10:
            print trailing*10+left

for i in range(1,10):
    gen_num(i, 1, 55-i)

rawDescription: How to generate a 12 digit number, but all the digits summed together must equal 55?

description: Generate a 12 digit number, but all the digits summed together must equal 55


code:
import os
import codecs

for root, dirs, files in os.walk("./"):
    for name in files:
        abs_path = os.path.normpath(root + '/' + name)
        file_name, file_ext = os.path.splitext(abs_path)
        if file_ext == '.html':
            f = codecs.open(abs_path,'r')
            print f.read()

rawDescription: reading HTML(different folders) files

description: Reading HTML(different folders) files


code: print ", ".join([entry['name'] + " is " + str(entry['age']) + " years old" for entry in mylist])

rawDescription: print the same values in a list of dicts on same line

description: Print the same values in a list of dicts on same line


code:
from time import time

time_before = time()
perform_get() # whatever way you do this
time_after = time()
time_taken = time_after-time_before

print time_taken

rawDescription: How to determine latency of a GET request, in python

description: Determine latency of a GET request, in python


rawDescription: importing assignment into modul re/expected string or buffer Python,

description: Importing assignment into modul re/expected string or buffer Python,


code:
from collections import Counter
import random

tups = [ (1,2), (3,4), (5,6), (1,2), (3,4) ]
lst = Counter(tups).most_common()
highest_count = max([i[1] for i in lst])
values = [i[0] for i in lst if i[1] == highest_count]
random.shuffle(values)
print values[0]

rawDescription: Python: Get most frequent item in list

description: Python: Get most frequent item in list


code:
c = Client()
dview = c[:]
asyncs = [dview.map_async(f, [arg]) for arg in args]
while asyncs:
    for async in asyncs[:]:
        if async.ready():
            asyncs.remove(async)
            print async.result[0]

rawDescription: Asynchronous evaluation in ipython parallel


code:
class Main(object):
    template = ""
    favorite_number = None
    least_favorite_number = None

    def add(a, b):
        return a + b

    def subtract(a, b):
        return a - b

    def multiply(a, b):
        return a * b

    def divide(a, b):
        return a / b

class Calculator(Main, View):
    template = 'calculator/index.html'
    favorite_number = 20
    least_favorite_number = 2

    def get(self, request):
        print self.add(self.favorite_number, self.least_favorite_number)
        return render(request, self.template, {})

rawDescription: Django/Python: How to call function from parent class within child class?


code:
import wx

words = ['lorem', 'ipsum', 'dolor', 'sit', 'amet', 'consectetur',
'adipisicing', 'elit', 'sed', 'do', 'eiusmod', 'tempor', 'incididunt',
'ut', 'labore', 'et', 'dolore', 'magna', 'aliqua', 'ut', 'enim', 'ad',
'minim', 'veniam', 'quis', 'nostrud', 'exercitation', 'ullamco',
'laboris', 'nisi', 'ut', 'aliquip', 'ex', 'ea', 'commodo',
'consequat', 'duis', 'aute', 'irure', 'dolor', 'in', 'reprehenderit',
'in', 'voluptate', 'velit', 'esse', 'cillum', 'dolore', 'eu',
'fugiat', 'nulla', 'pariatur', 'excepteur', 'sint', 'occaecat',
'cupidatat', 'non', 'proident', 'sunt', 'in', 'culpa', 'qui',
'officia', 'deserunt', 'mollit', 'anim', 'id', 'est', 'laborum']

class Example(wx.Frame):

    def __init__(self, *args, **kwargs):
        super(Example, self).__init__(*args, **kwargs)
        self.InitUI()
        self.Ctrls()
        i = 0
        for word in words:
            i += 1
            print " word = ",word, "  ",i
            button = wx.Button(self.panel, -1, word, size=wx.Size(70,25))
            self.wrapSizer.Add(button, 1, wx.EXPAND)
        self.Show(True)
        self.panel.Layout()

    def InitUI(self):
        self.SetSize((800, 400))
        self.SetTitle('Dynamically Flow Buttons to Next Row on Window-Resize')
        self.Centre()

    def Sizers(self):
        self.wrapSizer = wx.WrapSizer()
        self.panel.SetSizer(self.wrapSizer)

    def Ctrls(self):
        self.panel = wx.Panel(parent=self,pos=wx.Point(0,0), size=wx.Size(750,550), style=wx.TAB_TRAVERSAL)
        self.Sizers()

def main():

    ex = wx.App()
    Example(None)
    ex.MainLoop()

if __name__ == '__main__':
    main()

rawDescription: wxPython: Dynamically Flow Buttons to Next Row on Window-Resize

description: WxPython: Dynamically Flow Buttons to Next Row on Window-Resize


code:
from Tkinter import *

class QuitBtn(Frame):
    def __init__(self):
        Frame.__init__(self)

        b = Button(text = "Quit", fg = "red", command = self.quit)
        b.pack(in_=self)                                                   # Here

class HiBtn(Frame):
    def __init__(self):
        Frame.__init__(self)

        b = Button(text = "Hi there", fg = "blue", command = self.quit)
        b.pack(in_=self)                                                   # Here

class App(Frame):
    def __init__(self, master = None):
        Frame.__init__(self, master)
        self.pack()
        self.createWidgets()

    def say_hi(self):
        print "hi there, everyone!"

    def createWidgets(self):
        self.QUIT = QuitBtn().pack(side = LEFT)
        self.hi_there = HiBtn().pack(side = LEFT)

root = Tk()
app = App(master = root)
app.mainloop()
root.destroy()

rawDescription: Tkinter pack() geometry manager confusion


code:
print x
print x.decode('unicode-escape')

rawDescription: Allowing input of Unicode escapes as command line arguments


code:
totalValue = 0

for item in prices:
     totalValue += prices[item] * stock[item]

print totalValue

rawDescription: Shouldn't I have been able to do this without sum()? [Python Codeacademy]


code:
if time == '90.00':
    time = float(time)
    added = added.getText()
    if not added == '':
        added = added.replace(':', '.')
        added = added.replace('+', '')
        added = ' '.join(added.split())
        added = float(added)
        time1 = time+added
        print time1

rawDescription: Adding numbers results in strange result - e.g. "90.005.25"


code:
import time
import gc

class A:
    def __init__(self):
        self.x = 1
        self.y = 2
        self.why = 'no reason'

def time_to_append(size, append_list, item_gen):
    t0 = time.time()
    for i in xrange(0, size):
        append_list.append(item_gen())
    return time.time() - t0

def test():
    x = []
    count = 10000
    for i in xrange(0,1000):
        print len(x), time_to_append(count, x, lambda: A())

def test_nogc():
    x = []
    count = 10000
    for i in xrange(0,1000):
        gc.disable()
        print len(x), time_to_append(count, x, lambda: A())
        gc.enable()

rawDescription: Is there a way to circumvent Python list.append() becoming progressively slower in a loop as the list grows?


code:
composite_object_resource = {
        'contentType': 'text/plain',  # required
        'contentLanguage': 'en',
        'metadata': {'my-key': 'my-value'},
}
compose_req_body = {
        'sourceObjects': [
                {'name': source_object_name_1,
                 'objectPreconditions': {'ifGenerationMatch': source_generation_1}},
                {'name': source_object_name_2,
                 'objectPreconditions': {'ifGenerationMatch': source_generation_2}}],
        'destination': composite_object_resource
}
req = client.objects().compose(
        destinationBucket=bucket_name,
        destinationObject=composite_object_name,
        body=compose_req_body)
resp = req.execute()
print json.dumps(resp, indent=2)

rawDescription: How to write to cloudstorage using task chaining, The blobstore Files API did a nice job

description: Write to cloudstorage using task chaining, The blobstore Files API did a nice job


code:
for index, item in enumerate(z):
    if index != len(z)-1:
        print index

rawDescription: Python - Way to distinguish between item index in a list and item's contents in a FOR loop?


code:
video_playing = False

def welcome_loop():
    global playProcess
    while True:
        x = 1
        if not video_playing:
            print "Play Welcome Video"
            time.sleep(.5)
            playProcess=subprocess.Popen(['omxplayer','-b','Desktop/videos/loop/loop.mp4'],
                                         stdin=subprocess.PIPE,stdout=subprocess.PIPE,
                                         stderr=subprocess.PIPE,close_fds=True)
        time.sleep(25)
        x += 1

def videos():
    global video_playing
    while True:
        if GPIO.input(9):
            video_playing = True  # Set the flag
            print "Stop Welcome Video"
            time.sleep(.5)
            playProcess.stdin.write('q')
            time.sleep(.5)
            print "Play Sippycup Video"
            sippycup_video=subprocess.Popen(['omxplayer','-b','Desktop/videos/sippycup.mp4'],
                                            stdin=subprocess.PIPE,stdout=subprocess.PIPE,
                                            stderr=subprocess.PIPE,close_fds=True)
            time.sleep(30)
            sippycup_video.stdin.write('q')
            video_playing = False  # unset the flag
            time.sleep(.5)
            #welcome_loop()

    # Same pattern for the other videos.

rawDescription: How to pause a subprocess (Python 2.2.6)?

description: Pause a subprocess (Python 2.2.6)


code:
import subprocess
password = 'cGFzc3dvcmQ='.decode('base64')
path = "C:\Users\blabla.tc"
subprocess.Popen(['truectypt','/a','/p',password,'/q','/e','/v',path]).communicate()

rawDescription: How to compile a python/shell script ? (to hide informations)

description: Compile a python/shell script ? (to hide informations)


code:
from multiprocessing import Pool, Value
from time import sleep

counter = None

def init(args):
    ''' store the counter for later use '''
    global counter
    counter = args

def analyze_data(args):
    ''' increment the global counter, do something with the input '''
    global counter
    # += operation is not atomic, so we need to get a lock:
    with counter.value.get_lock():
        counter.value += 1
    print counter.value
    return args * 10

if __name__ == '__main__':
    #inputs = os.listdir(some_directory)

    #
    # initialize a cross-process counter and the input lists
    #
    counter = Value('i', 0)
    inputs = [1, 2, 3, 4]

    #
    # create the pool of workers, ensuring each one receives the counter
    # as it starts.
    #
    p = Pool(initializer = init, initargs = (counter, ))
    i = p.map_async(analyze_data, inputs, chunksize = 1)
    i.wait()
    print i.get()

rawDescription: Python multiprocessing and a shared counter


code:
from mechanize import Browser
year="2005"

br=Browser()
br.open("http://utahcritseries.com/RawResults.aspx")
br.select_form(name="aspnetForm")
control=br.form.find_control("ctl00$ContentPlaceHolder1$ddlSeries")
control.set_value_by_label((year,))
response2=br.submit()

print response2.read()

rawDescription: Python selecting a value in a combo box and HTTP POST


code:
import os, struct, xattr

# values from http://www.tuxera.com/community/ntfs-3g-advanced/extended-attributes/
attributes = ['readonly', 'hidden', 'system', 'unknown',
              'unknown', 'archive', 'unknown', 'unknown',
              'temp', 'unknown', 'unknown', 'compressed_dir',
              'offline', 'not_content_indexed' ] + ['unknown']*18

def ntfs_attr(path):
    attr = struct.unpack("i", xattr.get(path, "system.ntfs_attrib"))[0]
    for shift, attribute in enumerate(attributes):
        if (attr >> shift) & 1 == 1:
            yield attribute

def main():
    import sys
    if len(sys.argv) != 3:
        print "Usage: %s path attribute" % sys.argv[0]
        a = set(attributes)
        a.remove('unknown')
        print "where attribute is one of:", ' '.join(a)
        sys.exit(1)

    path = sys.argv[1]
    attribute = sys.argv[2]
    print "Files with %s attribute in %s:" % (attribute, path)
    for filename in os.listdir(path):
        fullname = os.path.join(path, filename)
        if attribute in ntfs_attr(fullname):
            print fullname

if __name__ == '__main__':
    main()

rawDescription: How to check for hidden files & folders on NTFS partition using python on linux?

description: Check for hidden files & folders on NTFS partition using python on linux


code:
def print_multiplication_table(n):
    a = 1
    b = 1 # won't do harm, but doesn't really need now
    while a <= n:
        b = 1 # <-- note
        while b <= n:
            print str(a) + " * " + str(b)
            b = b + 1
        a = a + 1

rawDescription: Python: what's wrong with my nested loop?


code:
from urlparse import parse_qs
from wsgiref.simple_server import make_server, demo_app

def showresult(environ, start_response):
    status = '200 OK' # HTTP Status
    headers = [('Content-type', 'application/json')] # HTTP Headers
    start_response(status, headers)
    params = parse_qs(environ['QUERY_STRING'])  #  Here you get the values in a dict!
    print params

    # The returned object is going to be printed
    return "ok"

httpd = make_server('', 8081, showresult)

# Respond to requests until process is killed
httpd.serve_forever()

rawDescription: How I get params of url in python

description: How I get params of url in python


code:
def my_os_system(cmd):
    err = os._system(cmd)
    if err != 0:
        print "Error occured when executing: %s. Exiting." % cmd
        sys.exit(-1)

os._system = os.system
os.system = my_os_system

rawDescription: wrap python os.system method

description: Wrap python os.system method


code:
for m in re.finditer(r',\s((19|20)\d\d)', text):
    print m.group(1)

rawDescription: Find comma space year but ignore comma year without space


code:
import re

def occurences(ch_searched, str_input):
    return [i.start() for i in re.finditer(ch_searched, str_input)]

def betweeners(str_input, ch_from, ch_to):
    starts = occurences(ch_from, str_input)
    ends = occurences(ch_to, str_input)
    result = []
    for start in starts:
        for end in ends:
            if start<end:
                result.append( str_input[start:end+1] )
    return result

print betweeners('KANNKAAN', "K", "N")

rawDescription: finding substring

description: Finding substring


code:
import requests
from requests_ntlm import HttpNtlmAuth

username = 'myUser'
password = 'myPswd'
url = 'https://NTLMwebsite/base.com'
nextPage = 'https://NTLMwebsite/base/next.com'

s = requests.Session()

s.auth = HttpNtlmAuth(username, password)

r1 = s.get(url)
r2 = s.get(nextPage)
print 'r1', r1
print 'r2', r2
print 'Session using same connection:', r1.connection == r2.connection

r1 = requests.get(url, auth=HTTPBasicAuth(username, password))
r2 = requests.get(nextPage, auth=HTTPBasicAuth(username, password))
print 'r1', r1
print 'r2', r2
print 'Non Session using same connection:', r1.connection == r2.connection

rawDescription: Python Requests: follow a link

description: Python Requests: follow a link


code:
inputText = "x1 y1\n x2 y2\n x3 y3\n"
print [line.split() for line in inputText.split('\n') if line]

rawDescription: How to format a string into a two column list

description: Format a string into a two column list


code:
from modulefinder import ModuleFinder
finder = ModuleFinder()
finder.run_script('bacon.py')

print 'Loaded modules:'
for name, mod in finder.modules.iteritems():
    print '%s: ' % name,
    print ','.join(mod.globalnames.keys()[:3])

print '-'*50
print 'Modules not imported:'
print '\n'.join(finder.badmodules.iterkeys())

rawDescription: How to check if all modules imported by a Python script are installed without running the script?

description: Check if all modules imported by a Python script are installed without running the script


code:
import subprocess as sp

class Player(object):
    def __init__(self, x, y, char):
        self.x = x
        self.y = y
        self.char = char

    def move(self, direction):
        """ update our position. """
        if direction.lower() == 'left':
            self.y -= 1
        elif direction.lower() == 'right':
            self.y += 1
        elif direction.lower() == 'up':
            self.x -= 1
        elif direction.lower() == 'down':
            self.x += 1

def create_board(player):
    ''' Creates a 10x10 grid of cells'''
    board = []
    for _ in range(10):
        board.append(['-']*10)
    board[player.x][player.y] = player.char
    return board

def print_board(board):
    '''Clears the screen prints or re-print all changes'''
    tmp = sp.call('clear')
    for row in board:
        print ' '.join(row)

def main():
    player = Player(9, 5, 'o')
    board = create_board(player)
    print_board(board)

    while True:
        '''Main loop'''
        choice = raw_input('What do you want to do? ')
        print_board(board)
        if choice == 'move':
            '''Moves the player. Empties the cell previously occupid,
                adds/subtracts 1 from the player location,
                and then reprints the board'''
            direction = raw_input('Which way do you want to move? ')
            if direction in ('up', 'down', 'left', 'right'):
                board[player.x][player.y] = ' '  # Erase
                player.move(direction)
                board[player.x][player.y] = player.char
                print_board(board)
        elif choice == 'attack':
            print 'There is no one to attack right now.'
        elif choice == 'die':
            player.char = '%'
            print_board(board)
            quit()

if __name__ == '__main__':
    main()

rawDescription: Getting rid of globals and creating functions


code:
user = request.user
userorgs = UserOrgConnections.objects.filter(user = user)
# at this point, you have all instances of UserOrgConnections
# for which the current user is the user value

print userorgs.values('orgs')       # as ValuesQuerySet
print [x.orgs for x in userorgs]    # as Python list

rawDescription: Django authentication: query by current user from foreign key


code:
if  ((oneScore == "positive" and twoScore > 0) or
     (oneScore == "null" and twoScore == 0) or
     (oneScore == "neutral" and twoScore == 0) or
     (oneScore == "negative" and twoScore < 0)):
    print bookID, ID, oneScore, twoScore, "TRUE"

rawDescription: Using multiple conditions for the same variable in `python`


code:
import csv
most_used_products = dict()

with open('your_csv_filename.csv', 'rb') as csvfile:
    products_reader = csv.reader(csvfile, delimiter=',')
    for client, product, str_usage in products_reader:
        usage = int(str_usage)
        if client not in most_used_products:
            most_used_products[client] = (product, usage)
        else:
            used_product, product_usage = most_used_products[client]
            if usage > product_usage:
                 most_used_products[client] = (product, usage)

for client, product_info in most_used_products.items():
    product_name, _ = product_info
    print '"%s","%s"' % (client, product_name)

rawDescription: Filter two-dimensional table to find most used product by client on large table


code:
import pandas as pd

df1 = pd.DataFrame([['B0006IYIMW',5.0],['B000A56PUO', 3.0],['B000AMLQQU', 4.0],['B000OVNMGE', 1.0]],columns=('item_id','rating'))
df2 = pd.DataFrame([['B0006IYIMW','iphone'],['B000A56PUO', 'nokia'],['B000AMLQQU', 'htc'],['B000OVNMGE', 'samsung']],columns=('item_id','class'))

df_merged = df1.merge(df2,on='item_id')

print df_merged

rawDescription: How to merge two data frames based on mutual information with python-pandas?

description: Merge two data frames based on mutual information with python-pandas


rawDescription: WxPython, Return value for function called by button


code:
# to hold your variables
holder_dict = {}

# read the file:
with open("/path/to/file.csv", 'r') as csv_read:
    for line in csv_read.readlines():
        word, score, std = line.split('\t')
        if word in holder_dict.keys():
            holder_dict[word][0] += [float(score)]
            holder_dict[word][1] += [std]
        else:
            holder_dict[word] = [[float(score)],[std]]

# get average score
for word in holder_dict.keys():
    average_score = sum(holder_dict[word][0])/len(holder_dict[word][0])
    print "average score for word: %s is %.3f" % (word, average_score)

rawDescription: Take the average for scores in a given file for Python


code:
from pexpect import spawn
import time
import datetime

KEY_UP = '\x1b[A'
KEY_DOWN = '\x1b[B'
KEY_RIGHT = '\x1b[C'
KEY_LEFT = '\x1b[D'
KEY_ESCAPE = '\x1b'
KEY_BACKSPACE = '\x7f'

child = spawn('elinks http://python.org')
print 'waiting for python.org to load'
child.expect('Python')
time.sleep(0.1)
print 'doing selenium search'
child.sendline('/advanced search')
child.sendline(KEY_UP * 2)
child.sendline('selenium')
child.sendline('')
print 'waiting for search results'
child.expect('Google Search')
time.sleep(0.1)
print 'saving html'
child.send(KEY_ESCAPE)  # bring up menu
child.send(KEY_DOWN + 's')  # select save as in menu
child.send(KEY_BACKSPACE * 100) # remove any file name already in input box
file = './saved_' + datetime.datetime.now().strftime('%H%M%S') + '.html'
child.sendline(file)
#child.interact() #uncomment to interact with elinks, good for debugging
print 'quiting'
child.sendline('q')
child.wait()

rawDescription: Is there any way to run ELinks with python-script like FireFox with Selenium webdriver with python


code:
import re

b = 'http://match.id.txt --- blablabla --- http://match2.id.txt'
matches = re.findall(r'http.*?\.id\.txt', b)
print matches  # ['http://match.id.txt', 'http://match2.id.txt']

rawDescription: regular expression http in python

description: Regular expression http in python


code:
#!/usr/bin/python

# globals
verbose = True

def get_tour(start, graph, path):
    if path==[]:
        from_node=start
    else:
        from_node=path[-1][1]

    if verbose:
        print '\nfrom_node:\t', from_node
        print 'start:\t', start
        print 'graph:\t', graph
        print 'path:\t', path

    if graph==[]:
        if start in path[-1]:
            print "Tour Found"
            return path

    else:
        edges=[node for node in graph if from_node in node]
        for edge in edges:
            to_node=[i for i in edge if i <> from_node][0]
            p=list(path)
            p.append((from_node,to_node))
            g=list(graph)
            g.remove(edge)
            path = get_tour(start, g, p)
            if path:
                return path

g=[(1,2), (1,3), (2,3)]

get_tour(1, graph=g, path=[])

rawDescription: Returning value when condition met in recursion


code:
a = [1,2]
# a = list(1,2) at address AAA

b = [a, 3]
# b = list( [REFERENCE to AAA], 3) at address BBB

c = b[:]
# c = NEW list( b[0], b[1] ) at address CCC
# c = list( [REFERENCE to AAA], 3) at address CCC

a[0] = 7
# change item at AAA, offset [0], to 7
# 'b' points to AAA, so it will see change
# 'c' points to AAA, so it will see change

b[1] = 8
# change item at BBB, offset [1], to 8
# 'a' doesn't know about this, so it doesn't care.
# 'c' doesn't point to BBB, so it doesn't see the change.

print c
# Prints CCC offset [0], which refers to the AAA list, as changed,
# then prints CCC offset [1], which is still 3.

rawDescription: When you have a multilevel list [python], how does the point of reference change in that list?


code:
l= s.split(';')
for i in l :
 if 'BOOTR' in i:
  print i.split(':')

rawDescription: find something in a string then print it in python

description: Find something in a string then print it in python


code:
def iterskip(iterator, test, n):
    """Iterate skipping values matching test, and n following values"""
    iterator = iter(iterator)
    while 1:
        value = next(iterator)
        if test(value):
            for dummy in range(n):
                next(iterator)
        else:
            yield value

def is_foo(value):
    return value == 'foo'

print list(iterskip(values, is_foo, 2))

rawDescription: Remove element, and n following elements from list


code:
dict={}
for doc in os.listdir('..'):
    doc2 = '..'
    with open (doc2, 'r') as inF:
        for line in inF:
            while no < 10:
                c = vt + (repr(no))
                if c in line:
                    numberOfElements = 0
                    if dict.has_key(c):
                        numberOfElements = dict[c]
                        numberOfElements += 1
                    else:
                        numberOfElements = 1
                    dict[c] = numberOfElements
                no += 1

for key in dict.keys():
    print key, dict[key]

rawDescription: Count the number of files in a folder that have certain strings


code:
from Tkinter import *

#Below should pack to class
class MyWindow:
    def __init__(self, wname=""):
        self.root = Tk()
        self.root.title(wname)
        self.text = Text(self.root,font=("Purisa",12))
        self.text.pack()

        self.button=Button(self.root, text ="Button", command=self.prn)
        self.button.pack()
        self.root.mainloop()

    def get_words_list(self, widget):
        """Return list of words"""
        options=widget.get(1.0, END)# get lines into string
        #Remove spaces in list of lines
        return [i.strip() for i in options.splitlines()]

    def prn(self):
        """Testing get_words_list"""
        print self.get_words_list(self.text)

if __name__ == "__main__":
    w = MyWindow("My window")

rawDescription: How to create an array of tkinter text input, where every line in text is an element in array

description: Create an array of tkinter text input, where every line in text is an element in array


code:
from Tkinter import *
import ttk, threading

class progress():
    def __init__(self, parent):
            toplevel = Toplevel(tk)
            self.progressbar = ttk.Progressbar(toplevel, orient = HORIZONTAL, mode = 'indeterminate')
            self.progressbar.pack()
            self.t = threading.Thread()
            self.t.__init__(target = self.progressbar.start, args = ())
            self.t.start()
            #if self.t.isAlive() == True:
             #       print 'worked'

    def end(self):
            if self.t.isAlive() == False:
                    self.progressbar.stop()
                    self.t.join()

def printmsg():
    print 'proof a new thread is running'

tk = Tk()
new = progress(tk)
but1 = ttk.Button(tk, text= 'stop', command= new.end)
but2 = ttk.Button(tk, text = 'test', command= printmsg)
but1.pack()
but2.pack()
tk.mainloop()

rawDescription: Python, Tkinter - ttk.Progressbar in a separate thread


code:
import sys
import socket
from time import sleep
import threading

class ConnectionThread ( threading.Thread ):
    def __init__(self):
        self.ip = raw_input ("please insert host ip: ")
        self.port = input ("please insert port to fuzz: ")
        self.header = raw_input ("please enter the header you want to fuzz, put & in the place you want to fuzz: ")
        self.packet = raw_input ("what string would you like to fuzz the header with? : ")
        self.multi = input ("in what jumps would you liike to multiply the string ? : ")
        self.process = input ("please insert number of threads: ")
        self.host = self.ip, self.port
        self.char = self.packet * self.multi
        self.a = 1

    def run ( self ):
        while self.a > 0:
            try:
                s = socket.socket( socket.AF_INET, socket.SOCK_STREAM)
                s.connect((self.host))
                self.header = self.header.replace("&", self.packet)
                s.send(self.header)
                s.settimeout(7)
                data = s.recv(4)
                if data > 0:
                    print "got awnser"
                else:
                    print "no awnser"
                sleep(0.1)
                print "Fuzzing With:", header
                self.header = self.header.replace (self.packet, "&")
                self.packet = self.char + self.packet
                s.close()
            except Exception as e:
                print e
                s.close()
                sys.exit(0)

for x in xrange ( ConnectionThread.process ):
   ConnectionThread().start()

rawDescription: python multi-threading

description: Python multi-threading


code:
l1 = [1,2,3]
l2 = [4,5,6]

newl = []
for item1, item2 in zip(reversed(l1), reversed(l2)):
    newl.append(item1)
    newl.append(item2)

print newl

rawDescription: Creating new list with values from two prior lists


code:
val="1 2 3"
for number in val:
        print number

rawDescription: Please explain Python for loops to a C++/C#/Java programmer


code:
digit_one = int(raw_input())
digit_two = int(raw_input())
digit_three= int(raw_input())
count_digit_one = 0
count_digit_two = 0
count_digit_three= 0

while digit_one > count_digit_one:
    print "Digit one could be", count_digit_one
    count_digit_one += 1

while digit_two > count_digit_two:
    print "The first two digits could be", count_digit_one, count_digit_two
    count_digit_two += 1

while digit_three> count_digit_three:
    print "The first three digits could be", count_digit_one, count_digit_two
    count_digit_three += 1
print "This is most definitely the number! {}{}{}".format(count_digit_one, count_digit_two, count_digit_three)

rawDescription: Why won't this code execute?

description: Why won't this code execute


code:
for i in range(2,6):
    t=time.time()
    n = 10**i+1
    m = int(ratio * n)
    print i,n,m

    ip = np.random.random_integers(10, size=(n,3))
    jp = np.random.random_integers(10, size=(m,3))

    chunksize=10000
    if chunksize>ip.shape[0]:
        chunksize=ip.shape[0]
    span=ip.shape[0]/chunksize
    remainder=(ip.shape[0]-span*chunksize)

    out=[]
    start=0
    for n in xrange(span):
        end=start+chunksize
        a = np.expand_dims(ip[start:end], -1) == jp.T
        b = np.where( a.all(axis=1).any(axis=1) )[0]
        out.append(b+start)
        start+=chunksize

    if remainder!=0:
        a = np.expand_dims(ip[-remainder:], -1) == jp.T
        b = np.where( a.all(axis=1).any(axis=1) )[0]
        out.append(b+end)

    end=np.sort(np.concatenate(out))
    print time.time()-t,end.shape

rawDescription: numpy missing attributes depending on array size

description: Numpy missing attributes depending on array size


code:
x = raw_input("Enter your name: ")
n = [ord(c) for c in x]

total = 0

for p in n:
    for i in range(2, p):
        if p % i == 0:
            break
    else:
        total += p

print total

rawDescription: How to perform functions on numbers in list consecutively?

description: Perform functions on numbers in list consecutively


rawDescription: How to replace all occurrences of an element in a list in python, in-place?

description: Replace all occurrences of an element in a list in python, in-place


code:
mtime = os.stat(file).st_mtime
while os.stat(file).st_mtime == mtime:
   print "File not modified"
print "The file has been modified"

rawDescription: Stop loop in Python when a file has been modified


code:
iter = xrange(3).__iter__()

iter.next() # this pops 0

for i in iter:
  print i

1
2

rawDescription: Need to get the rest of an iterator in python


code:
class_name = 'data.txt'
name = 'Jim'
score = 100
file = open(class_name , 'a')   #opens the file in 'append' mode so you don't delete all the information

line_data = name + " : " + str(score) + "\n" # data to write
file.write(line_data)
file.close()    #safely closes the file to save the information

viewscore = raw_input("Do you wish to view previous results for your class?").lower()

if viewscore == "yes".lower():
   f = open(class_name , "r")
   lines = [line for line in f if line.strip()]
   f.close()
   lines.sort()
   for line in lines:
      print line
else: # add else case to debug
   print 'no for', viewscore

rawDescription: Printing to a new line after sorting a text file


code: print len(set(item['propertyB'] for item in a if item['propertyA']=={}))

rawDescription: How to determine number of elements with a non-empty property in Python in a collection?

description: Determine number of elements with a non-empty property in Python in a collection


code:
list = [0,1] #sets the first two numbers in the fibonacci sequence to be added, as well as the list i will append the next 10 numbers

listint = list[0] #sets the list variable I want to incremented
list2int = list[1] #set the other list variable to be incremented

while len(list) < 12:       #sets my loop to stop when it has 12 numbers in it
    x = list[listint] + list[list2int]       #calculates number at index 2
    list.append(x)     #appends new number to list
    listint += 1    #here is where it is supposed to be incrementing the index
    list2int +=1
print list

rawDescription: Increment list index in a while loop

description: Increment list index in a while loop


code:
import os
print os.getcwd()

rawDescription: How to get the name of dir from where a python script is called (not exaclty where it ran)

description: Get the name of dir from where a python script is called (not exaclty where it ran)


code:
import re
data_separator_regepx     = "-|:" #theres - and : as separators in sample text
employee_separator_regexp ="^=+$"
employees      = []
with open('test.txt') as f_in:
    curr_employee = {}
    for idx,line in enumerate(f_in):
        if not idx : continue #skip first line
        line = line.strip()
        if not line: continue #skip empty lines
        if re.match(employee_separator_regexp,line):
            if curr_employee:
                employees.append(curr_employee)
                curr_employee = {}
        else:
            line = re.split(data_separator_regepx,line)
            key, value = line[0],line[1]
            curr_employee[key.strip()]=value.strip()

for employee in employees:
    print "Details of Employee: ({})".format(employee.get('Empl Name',''))
    print "Telephone Number: ({})".format(employee.get('Telephone Number',''))
    print "Designation: ({})".format(employee.get('Designation',''))

rawDescription: Split file based on multiple occurrence of delimiter


code:
def printIt(*args, **kwargs):
  print 'Splat Contents=%s' % str(args)
  print 'Double Splat Contents=%s' % str(kwargs)

lst = [1, 2, 3]
dct = { 'name': 'sanjay', 'age': 666 }
printIt(*lst, **dct) # usage

rawDescription: How to understand '*' in below python code

description: Understand '*' in below python code


code:
from intervaltree import IntervalTree

tree = IntervalTree()
tree.addi(0, 10, 5)
print tree[4]
print tree[6]

# need to chop before, as the library stores both intervals otherwise
tree.chop(5, 15)
tree.addi(5, 15, 20)
print tree[4]
print tree[6]

rawDescription: Dictionary with range as key

description: Dictionary with range as key


rawDescription: accessing python 2D array

description: Accessing python 2D array


code:
try:
    while True:
        data = ser.read(1).__repr__()
        if data:
            print "Received: %s." % data
        else:
            print "Looping."
except KeyboardInterrupt:
    print "Done."
except:
    raise
finally:
    ser.close()
    print "Closed port."

rawDescription: Echo Program in between Arduino and Python


code:
import dbus

bus = dbus.SystemBus()

manager = dbus.Interface(bus.get_object('org.bluez', '/'), 'org.bluez.Manager')

adapterPath = manager.DefaultAdapter()

adapter = dbus.Interface(bus.get_object('org.bluez', adapterPath), 'org.bluez.Adapter')

for devicePath in adapter.ListDevices():
    device = dbus.Interface(bus.get_object('org.bluez', devicePath),'org.bluez.Device')
    deviceProperties = device.GetProperties()
    print deviceProperties["Address"]

rawDescription: List nearby/discoverable bluetooth devices, including already paired, in Python, on Linux


code:
keywords = ['abc', 'def', 'ghi']

for line in f:
    if all(keyword in line for keyword in keywords):
        print line

rawDescription: Python Beginners - Searching a text file for an array of text


code:
from math import modf
def old_dist_format(distance):
    if distance < 100:
        return '%dm' % distance
    elif distance < 1000:
        return '%.0fm' % round(distance, -1)
    else:
        m, km = modf(distance / 1000.0)
        if m < 0.01:
            return '%.0fkm' % km
        else:
            return '%.1fkm' % (km + round(m, 1))

def dist_format(distance):
    rounded = float('%.2g' % distance)
    km = modf(rounded / 1000.0)
    if km[1]:
        return "%gkm" % (km[0] + km[1])
    else:
        return "%gm" % rounded

if __name__ == "__main__":
    while True:
        try:
            s = raw_input("> ")
            try:
                d = float(s)
            except ValueError:
                print "Enter number"
                continue
            print "%s\t%s" % (dist_format(d), old_dist_format(d))
        except KeyboardInterrupt:
            print
            break

rawDescription: Does the Django have a ready modules for formatting of distance on a scale?


code:
from math import log, ceil, floor

def monoSearch(low, high):
    max_power = int(floor(log(high) / log(2)))
    for power in range(3, max_power + 1):
        min_base = low ** (1.0 / power)
        max_base = high ** (1.0 / power)
        for base in range(int(ceil(min_base)), int(floor(max_base)) + 1):
            yield '%s ^ %s' % (base, power)

print '\n'.join(monoSearch(42, 1000000))

rawDescription: Find all A^x in a given range

description: Find all A^x in a given range


rawDescription: Match but not return regular expression between two matches


code:
import collections

result = collections.defaultdict(int)

with open("beast","rt") as f:
    for line in f:
        hashes = line.split()
        key = '-'.join(hashes)
        result[key] += 1

print result

rawDescription: Multiple levels of keys and values in Python


code:
import sqlite3
from datetime import datetime

db = sqlite3.connect(':memory:')

db.execute('create table log_a (timestamp, uniq_id, filesize)')
a = ['[2012-09-12 12:23:33] SOME_UNIQ_ID filesize']
for line in a:
    timestamp, uniq_id, filesize = line.rsplit(' ', 2)
    db.execute('insert into log_a values(?, ?, ?)', (timestamp, uniq_id, filesize))
db.commit()

db.execute('create table log_b (timestamp, uniq_id)')
b = ['[2012-09-12 13:23:33] SOME_UNIQ_ID']
for line in b:
    timestamp, uniq_id = line.rsplit(' ', 1)
    db.execute('insert into log_b values(?, ?)', (timestamp, uniq_id))
db.commit()

TIME_FORMAT = '[%Y-%m-%d %H:%M:%S]'
for matches in db.execute('select * from log_a join log_b using (uniq_id)'):
    log_a_ts = datetime.strptime(matches[0], TIME_FORMAT)
    log_b_ts = datetime.strptime(matches[3], TIME_FORMAT)
    print matches[1], 'has a difference of', abs(log_a_ts - log_b_ts)
    # 'SOME_UNIQ_ID has a difference of 1:00:00'
    # '1:00:00' == datetime.timedelta(0, 3600)

rawDescription: handling many huge log files with python

description: Handling many huge log files with python


code:
seen = set()
with open(filename, 'r') as f:
    for line in f:
        if line not in seen:
            print line
            seen.add(line)

rawDescription: how to sort out repeated entry from a column in python

description: Sort out repeated entry from a column in python


code:
import sys,tty,termios
class _Getch:
    def __call__(self):
            fd = sys.stdin.fileno()
            old_settings = termios.tcgetattr(fd)
            try:
                tty.setraw(sys.stdin.fileno())
                ch = sys.stdin.read(3)
            finally:
                termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
            return ch

def get():
        inkey = _Getch()
        while(1):
                k=inkey()
                if k!='':break
        if k=='\x1b[A':
                print "up"
        elif k=='\x1b[B':
                print "down"
        elif k=='\x1b[C':
                print "right"
        elif k=='\x1b[D':
                print "left"
        else:
                print "not an arrow key!"

def main():
        for i in range(0,20):
                get()

if __name__=='__main__':
        main()

rawDescription: Finding the Values of the Arrow Keys in Python: Why are they triples?


code:
from nltk.tokenize.punkt import PunktSentenceTokenizer

text = 'Rabbit say to itself "Oh dear! Oh dear! I shall be too late!"'
for start, end in PunktSentenceTokenizer().span_tokenize(text):
    length = end - start
    print buffer(text, start, length), start, length

rawDescription: Finding exact position of tokenized sentences


code:
for line in open('myfile.dat'):
   if not line.rstrip():
      continue  # skip blank lines
   if line[0] in ('-', '#'):
      continue  # skip lines with these prefixes
   line = line.replace('-sale', '')
   print line,

rawDescription: How can I parse this txt file by omitting certain undesired elements?

description: Parse this txt file by omitting certain undesired elements


code:
import random

class Human:
  def __init__(self):
    self.name = 'Human'
    self.wins = []
    self.losses = []
    self.bets = []
    self.total = 0

class Computer:
  def __init__(self):
    self.name = 'Computer'
    self.wins = []
    self.losses = []
    self.bets = []
    self.total = 0

class Game:
  def __init__(self):
    self.rolls = []
    self.currentPlayer = None

  def roll(self):
    self.rolls.append(random.randint(1, 6))

if __name__ == '__main__':
  human = Human()
  computer = Computer()
  game = Game()

  game.roll()
  print games.rolls

rawDescription: Recording a win or loss in a game of craps


code:
import sys

from PyQt4.QtGui import QApplication
from PyQt4.QtCore import QThreadPool, QObject, QRunnable, pyqtSignal

class WorkerSignals(QObject):
    result = pyqtSignal(int)

class Worker(QRunnable):
    def __init__(self, task):
        super(Worker, self).__init__()

        self.task = task
        self.signals = WorkerSignals()

    def run(self):
        print 'Sending', self.task
        self.signals.result.emit(self.task)

class Tasks(QObject):
    def __init__(self):
        super(Tasks, self).__init__()

        self.pool = QThreadPool()
        self.pool.setMaxThreadCount(1)

    def process_result(self, task):
        print 'Receiving', task

    def start(self):
        for task in range(10):
            worker = Worker(task)
            worker.signals.result.connect(self.process_result)

            self.pool.start(worker)

        self.pool.waitForDone()

if __name__ == "__main__":
    import  sys

    app = QApplication(sys.argv)
    main = Tasks()
    main.start()
    sys.exit(app.exec_())

rawDescription: How run two different threads simultaneously in pyqt


code:
import tkinter as tk
from functools import partial

def callback(key, var, *args):
    print "callback var =", key, var.get()
    ##myStrVars[key].set(var[-1])

root = tk.Tk()

for key in range(5):
    var = tk.StringVar()
    var.trace('w', partial(callback, key, var))
    tk.Entry(root, textvariable=var).pack()

root.mainloop()

rawDescription: How can I use the same callback function to trace multiple variables?

description: Use the same callback function to trace multiple variables


code:
def save_info():
    name = 'hello'
    var1 = 'other item'
    var2 = 1
    TV_SERIES_FIELDS_TO_UPDATE = ['name', 'var1', 'var2']
    for field in TV_SERIES_FIELDS_TO_UPDATE:
        print field, locals()[field]

save_info()

rawDescription: getattr in current function

description: Getattr in current function


code:
import boto.ec2
import os
import sys

ACCESS_KEY = raw_input("Enter your access key > ")
SECRET_KEY = raw_input("Enter your secret key > ")
if not ACCESS_KEY:
    sys.exit("ERROR: You did not enter anything for ACCESS KEY or SECRET KEY. Exiting...")

regions = boto.ec2.regions()
for x in regions:
    ec2_conn = boto.connect_ec2(ACCESS_KEY, SECRET_KEY, region=x)
    reservations = ec2_conn.get_all_reservations()
    for r in reservations:
        for i in r.instances:
            print r.instances
            print 'Tags: ',i.tags['Name']
            print 'Public IP Address: ',i.ip_address
            print 'Private IP address: ',i.private_ip_address
            if (i.virtualization_type == 'hvm'):
                platform = 'Windows'
            else:
                platform = 'Linux'
                print 'Platform: ',platform
            print 'State: ',i.state
            print

rawDescription: How do I loop through regions using boto with python?

description: Loop through regions using boto with python


code:
import Tkinter as tk

class application:
    def __init__(self,window):
        """ Initalize the Application """
        self.myentrybox = tk.Entry(window)
        self.myentrybox.pack()
        self.myentrybox.insert(0,"some default value")
        self.myentrybox.bind("<Return>",self.Enter)

    def Enter(self,event):
        """ Someone Pressed Enter """
        print "You entered >> %s" % (self.myentrybox.get())

root=tk.Tk()
myapp = application(root)
root.mainloop()

rawDescription: How to use entry widget in Tkinter

description: Use entry widget in Tkinter


code:
input = "1,2,3\n4,5,6\n7,8,9".splitlines()
reader=csv.reader(input)
for row in reader:
    row[2] = log(float(row[2]))
    print ','.join(map(str,row))

rawDescription: csv python questions

description: Csv python questions


code:
items = soup.find_all("div", {"class":"zg_itemWrapper"})

for item in items:
    title_elm = item.find("div", {"class":"zg_title"}).a
    title = title_elm.get_text()
    link = title_elm["href"]

    author = item.find("div", {"class": "zg_byline"}).get_text()
    price = item.find("div", {"class": "zg_price"}).get_text()

    print title, link, author, price

rawDescription: Python: Extract all childs of a <div> tag using BeautifulSoup


code:
gp = ctypes.CDLL('libgphoto2.so')
gp.gp_library_version.restype = ctypes.POINTER(ctypes.c_char_p)
a = gp.gp_library_version(0)
print a[0].value

rawDescription: How to handle array of strings (char **) in ctypes in a 64-bit environment?

description: Handle array of strings (char **) in ctypes in a 64-bit environment


code:
# Any reference properties not loaded yet
customer = Customer.get_by_id(1)
print customer.name
print customer.address

# Assuming customer.order is a ReferenceProperty, now is when it
# would be loaded from the datastore.
print customer.order.created_at

rawDescription: google datastore - does it do lazy loading?

description: Google datastore - does it do lazy loading


code:
from BeautifulSoup import BeautifulSoup

html = """
...

text

...

Don't find me!

Don't find me!

Don't error on missing href!

...

"""
soup = BeautifulSoup(html)

for h3 in soup.findAll("h3", {"class": "r"}):
  for a in h3.findAll("a", {"class": "l", "href": True}):
    print a["href"]

rawDescription: Extract URLs from specific tags in python


code:
import numpy as np
import pandas as pd
x = pd.DataFrame(np.random.randn(3,3), index=[1,2,3], columns=['A', 'B', 'C'])

locations = [(1, "A"), (1, "B"), (1, "A"), (3, "C")]

print x.get_value(1, "A")

row_labels, col_labels = zip(*locations)
print x.lookup(row_labels, col_labels)

rawDescription: Select specific index, column pairs from pandas dataframe


code:
import json
import geojson
from functools import partial
import pyproj
import shapely.geometry
import shapely.ops

# reading into two geojson objects, in a GCS (WGS84)
with open('file1.json') as geojson1:
    poly1_geojson = json.load(geojson1)

with open('file2.json') as geojson2:
    poly2_geojson = json.load(geojson2)

# pulling out the polygons
poly1 = shapely.geometry.asShape(poly1_geojson['features'][2]['geometry'])
poly2 = shapely.geometry.asShape(poly2_geojson['features'][2]['geometry'])

# checking to make sure they registered as polygons
print poly1.geom_type
print poly2.geom_type

# merging the polygons - they are feature collections, containing a point, a polyline, and a polygon - I extract the polygon
# for my purposes, they overlap, so merging produces a single polygon rather than a list of polygons
mergedPolygon = poly1.union(poly2)

# using geojson module to convert from WKT back into GeoJSON format
geojson_out = geojson.Feature(geometry=mergedPolygon, properties={})

# outputting the updated geojson file - for mapping/storage in its GCS format
with open('Merged_Polygon.json', 'w') as outfile:
    json.dump(geojson_out.geometry, outfile, indent=3, encoding="utf-8")
outfile.close()

# reprojecting the merged polygon to determine the correct area
# it is a polygon covering much of the US, and dervied form USGS data, so using Albers Equal Area
project = partial(
    pyproj.transform,
    pyproj.Proj(init='epsg:4326'),
    pyproj.Proj(init='epsg:5070'))

mergedPolygon_proj = shapely.ops.transform(project,mergedPolygon)

rawDescription: Merging two GEOJSON polygons in Python

description: Merging two GEOJSON polygons in Python


code:
lists = [a, b] # add more lists here if need be...
for idx, items in enumerate(zip(*lists)):
    unique = set(items)
    if len(unique) == 1:
        # idx = position, unique.pop() == the value
        print idx, unique.pop()

rawDescription: Find matches between many Lists with same length at the same Position


code:
while 1:
    i=input('Enter the number for which all previous shall be tested for primality: ')
    n=5
    a=[2,3]
    while n<=i:
        n=n+1
        isPrime = True
        for b in a:
            if n%b==0:
                isPrime = False
                break
        if isPrime:
            a.append(n)
            print a

rawDescription: prime number generator in python: accumulation of numbers

description: Prime number generator in python: accumulation of numbers


code:
class BuildProcess(wx.Process):

    def __init__(self, cmd, notify=None):
        wx.Process.__init__(self, notify)
        self.Redirect()
        self.cmd = cmd
        self.pid = None
        self.timer = wx.Timer(self)
        self.Bind(wx.EVT_TIMER, self.on_timer)

    def start(self):
        wx.PostEvent(self, BuildEvent(EVT_BUILD_STARTED, self))
        self.pid = wx.Execute(self.cmd, wx.EXEC_ASYNC, self)
        self.timer.Start(100)

    def on_timer(self, evt):
        stream = self.GetInputStream()
        if stream.CanRead():
            text = stream.read()
            wx.PostEvent(self, BuildEvent(EVT_BUILD_UPDATE, self, data=text))

    def OnTerminate(self, *args, **kwargs):
        print "terminating..."
        stream = self.GetInputStream()
        if stream.CanRead():
            text = stream.read()
            wx.PostEvent(self, BuildEvent(EVT_BUILD_UPDATE, self, data=text))
        if self.timer:
            self.timer.Stop()
        wx.PostEvent(self, BuildEvent(EVT_BUILD_FINISHED, self))

rawDescription: What's the best way to propagate information from my wx.Process back to my main thread?


code:
import re
pattern = re.compile("<(\d{4,5})>")

for i, line in enumerate(open('test.txt')):
    for match in re.finditer(pattern, line):
        print 'Found on line %s: %s' % (i+1, match.groups())

rawDescription: How do I search for a pattern within a text file using Python combining regex & string/file operations and store instances of the pattern?

description: Search for a pattern within a text file using Python combining regex & string/file operations and store instances of the pattern


code:
import re

caselines_index = []
cases = []
readlines = []

def read(in_file):
  global cases
  global caselines_index
  global readlines
  with open(in_file, 'r') as file:
    for line in file.readlines():
      readlines.append(line.strip())
    for line in readlines:
      case_search = re.search("case\s\".+?\"\:\s", line)
      if case_search:
        caselines_index.append(readlines.index(line))
    #print caselines_index
    caselines_index_iter = iter(caselines_index)
    int_line_index = int(next(caselines_index_iter))
    int_next_index = int(next(caselines_index_iter))
    while True:
      try:
        case_text = ' '.join(readlines[int_line_index:int_next_index]).strip()
        case = [readlines[int_line_index].strip(), case_text]
        cases.append(case)
        int_line_index = int_next_index
        int_next_index = int(next(caselines_index_iter))
      except StopIteration:
        case_text = ' '.join(readlines[int_line_index:len(readlines) - 1]).strip()
        case = [readlines[int_line_index].strip(), case_text]
        cases.append(case)
        break

def work():
  MATCH = 1
  for case_list in cases:
    details = []
    nvp_add = []
    caseline = case_list[0].strip()
    nvp = re.findall("details\(.+?\)", case_list[1].strip())

    for item in nvp:
      result_list = re.findall("(\$.+?)[\,\)]", item)

      for result in result_list:
        if "$*" not in result:
          details.append(result)

    nvp = re.findall("nvp_add\(.+?\)", case_list[1].strip())

    for item in nvp:
      result_list = re.findall("(\$.+?)[\,\)]", item)

      for result in result_list:
        if "$*" not in result:
          nvp_add.append(result)

    missing_from_details, missing_from_nvp_add = [], []
    missing_from_details = [o for o in nvp_add if o not in set(details)]
    missing_from_nvp_add = [o for o in details if o not in set(nvp_add)]
    if missing_from_nvp_add or missing_from_details:
      MATCH = 0
      print caseline + "   LINE - " + str(readlines.index(caseline) + 1)
      for mismatch in missing_from_details:
        print "Missing from details:"
        print mismatch
      for mismatch in missing_from_nvp_add:
        print "Missing from nvp_add:"
        print mismatch
      print "\n"
  if MATCH == 1:
    print "MATCH"
  else:
    print "MISMATCHES"

def main():
  in_file = "target1.txt"
  read(in_file)
  work()

if __name__=="__main__":
  main()

rawDescription: How to compare the attributes start with $ in 2 functions and display match or mismatch

description: Compare the attributes start with $ in 2 functions and display match or mismatch


code:
import random
from random import randint

name = raw_input("Hi, what is your name?\n") # Asks for name
print "Hi " +name+ " let's get started!"

score_count = 0
question_count = 0 # creates counter
while question_count <= 10: # Everything MUST BE WITHIN THIS LOOP
    # makes numbers and operator
    first_number = randint(1,10)
    second_number = randint(1,10)
    oper = random.choice("+""-""*")
    # determines the problem
    if oper == "+":
        answer = first_number + second_number
        print first_number,second_number,oper
    elif oper == "-":
        answer = first_number - second_number
        print first_number,second_number,oper
    elif oper == "*":
        answer = first_number*second_number
        print first_number, second_number, oper
    user_answer = int(raw_input("Your answer: "))
    if user_answer != answer:
        print 'Wrong answer! try again!'
        user_answer = int(raw_input('Your answer: '))
    if user_answer == answer: # exits the while loop when the correct answer is given
        if question_count < 10:
            print 'Well done! Now onto question number {0}'.format(question_count+1)
            score_count += 1
        elif question_count == 10:
            print 'Well done! You are done!'
            score_count += 1
    else:
        print 'Something is wrong.'
    question_count += 1 # updates the variable
    # GOES BACK TO THE BEGINNING UNTIL question_count IS GREATER THAN OR EQUAL TO 10
print "Your score was: {}".format(score_count)

rawDescription: python quiz validation not working

description: Python quiz validation not working


code:
class Foo(object):
    print repr(Foo)

rawDescription: When does Python create class object in memory?


code:
for fpath in glob.glob("*.py"):
    if not fpath.endswith("__init__.py"): #recall glob returns full path
        with open(fpath) as f:
             print os.path.basename(fpath)
             print "  "+"\n  ".join(re.findall("def (.*):",f.read()))

rawDescription: Getting all def functions of a file from a string containing the file name


code:
# first channel
samples_o = samples[0::2]
# second channel
samples_c = samples[1::2]

# for 3 second 24000 = 8000*3
gr_size = len(samples_o) // gr_count

lst = [lst[i:i+gr_size] for i in range(0, len(samples_o), gr_size)]

agr = []

for array in lst:
  max_el = np.argmax(array, axis=0)
  agr.append(max_el)

print np.mean(agr, axis=0) # avg max volume for first channel

rawDescription: How to get a stereo wav file of the average and maximum volume for each channel? Get the volume in an array on a per second, for example?

description: Get a stereo wav file of the average and maximum volume for each channel? Get the volume in an array on a per second, for example


code:
todo = [(0, 0)]
while todo:
    i, j = todo.pop()
    print "processing ", i, j
    if i != 3 and j != 3:
        todo.append((i, j+1))
        todo.append((i+1, j))

rawDescription: Iterative to recursion function for non-tail recursive methods


code:
import difflib

L_1 = ["Bob", "Mary", "Hans"]
L_2 = ["Bob", "Marie", "Hans"]

def similiarity(L_1, L_2):
    L_1 = set(intern(w) for w in L_1)
    L_2 = set(intern(w) for w in L_2)

    to_match = L_1.difference( L_2)
    against = L_2.difference(L_1)
    for w in to_match:
        res = difflib.get_close_matches(w, against)
        if len(res):
            against.remove( res[0] )
    return (len(L_2)-len(against)) / (len(L_1))

print similiarity(L_1,L_2)

rawDescription: Comparing lists in python by difflib modul


code:
# V is the target value, t is the tolerance
# A is the list of values
# B is the subset of A that is still below V-t
def combination_in_range(V, t, A, B=[]):
    for i,a in enumerate(A):
        if a > V+t:    # B+[a] is too large
            continue

        # B+[a] can still be a possible list
        B.append(a)

        if a >= V-t:   # Found a set that works
            print B

        # recursively try with a reduced V
        # and a shortened list A
        combination_in_range(V-a, t, A[i+1:], B)

        B.pop()        # drop [a] from possible list

A=[0.4, 2, 3, 1.4, 2.6, 6.3]
combination_in_range(5, 0.5, A)

rawDescription: Find values in list which sum to a given value


code:
import errno
import socket

size = 1024
host = 'localhost'
port = 80

def connectsocket(userHost, userPort):

    while(1):
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  # TCP socket
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        s.connect((userHost, userPort))

        command = raw_input("Command: ")

        s.send(command + '\r\n\r\n')  # Send command
        response = s.recv(size)  # Recieve output
        print response

        try:
            s.shutdown(socket.SHUT_RDWR)
        except socket.error, exc:
            # Depending on the platform, shutting down one half of the
            # connection can also close the opposite half
            if exc.errno != errno.ENOTCONN:
                raise

        s.close()

connectsocket(host, port)

rawDescription: Python re-using same socket and getting problems


code:
import math; f = math.sqrt(10)
str(f)
repr(f)
print f

rawDescription: getting not-full answer as the output of the function

description: Getting not-full answer as the output of the function


code:
for j in sorted(dic, key=int):
    print dic[j]

rawDescription: Can't seem to iterate over a sorted dictionary where the keys are number strings. How do you sort a dictioanry to iterate?


code:
class foo(object):
    def __init__(self, x):
        self.x = x
        print "hi"
    def __enter__(self):
        return self
    def __exit__(self, exc_type, exc_val, exc_tb):
        print "bye"
        del self.x

with foo(123456789) as a:
    print a.x  # This works, because a.x still exists
# bye is printed at this point
print a.x # This fails, because we deleted the x attribute in __exit__ and the with is done
# a still exists until it goes out of scope, but it's logically "dead" and empty

rawDescription: Class Instance deletion in Python

description: Class Instance deletion in Python


code:
import babel.dates
import datetime
now = datetime.datetime.now()
print babel.dates.format_date(now, 'd MMMM yyyy', locale='pl_PL')

rawDescription: Format date with month name in polish, in python


code:
import logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s [%(levelname)s] - %(message)s',
    filename='filename.txt')  # pass explicit filename here
logger = logging.get_logger()  # get the root logger
logger.warning('This should go in the file.')
print logger.handlers   # you should have one FileHandler object

rawDescription: Logging module not writing to file

description: Logging module not writing to file


code:
import urllib2
from BeautifulSoup import BeautifulSoup
# or if you're using BeautifulSoup4:
# from bs4 import BeautifulSoup

soup = BeautifulSoup(urllib2.urlopen('http://example.com').read())

for row in soup('table', {'class': 'spad'})[0].tbody('tr'):
    tds = row('td')
    print tds[0].string, tds[1].string
    # will print date and sunrise

rawDescription: Web scraping with Python

description: Web scraping with Python