code stringlengths 1 1.72M | language stringclasses 1
value |
|---|---|
#!/usr/bin/env python
import sys, os
sys.stdout=sys.stderr
def lcs(a, b):
print '-'*48, '\nFunc:', sys._getframe().f_code.co_name
nr = len(a) + 1
nc = len(b) + 1
c = [[0]*nc for i in range(nr)]
s = [['*']*nc for i in range(nr)]
for i in range(1, nr):
for j in range(1, nc):
if a[i-1] == b[j-1]:
c[i][j] = c[i-1][j-1] + 1
s[i][j] = '\\'
else:
el = c[i][j-1]
eu = c[i-1][j]
c[i][j] = el > eu and el or eu
s[i][j] = el > eu and '-' or '|'
for r in c:
print r
for r in s:
print ' '.join(r)
r = ''
i = nr - 1
j = nc - 1
while i >=1 or j >=1:
if s[i][j] == '\\':
r = a[i-1] + r
i -= 1
j -= 1
elif s[i][j] == '-':
j -= 1
else:
i -= 1
print 'lcs=', r
#lcs('aasdfuh;sadjfalskdjfc', 'acasdfhoaei;asdijfasduifha;sdifjf')
def qsort(dat):
if dat == []: return []
a = [e for e in dat[1:] if e < dat[0]]
b = [e for e in dat[1:] if e >= dat[0]]
print a, b
return qsort(a) + dat[0:1] + qsort(b)
print qsort([3,2,1])
| Python |
#!/usr/bin/env python
# @author FAN Kai (fankai@net.pku.edu.cn), Peking University
# @date Apr 24 14:59:56 CST 2009
import random
def average_sim(sim, item, group):
if not group: return 1
return sum([sim[item][x] for x in group])/float(len(group))
def kmeans(sim, group_count):
num = len(sim)
seeds = random.sample(range(0, num), group_count)
groups = [[seeds[i]] for i in range(group_count)]
for round in range(0, 10):
print groups
gsim = [[average_sim(sim, i, g) for g in groups] for i in range(num)]
#for row in gsim: print row
new_groups = [[] for g in range(group_count)]
for i in range(num):
mg = max(zip(gsim[i], range(group_count)))[1]
new_groups[mg].append(i)
if new_groups == groups: break
groups = new_groups
sim = [[1]*9 for i in range(9)]
for i in range(1, 9):
for j in range(0, i):
sim[i][j] = sim[j][i] = random.random()
#print sim
kmeans(sim, 5)
| Python |
#!/usr/bin/env python
# @author FAN Kai (fankai@net.pku.edu.cn), Peking University
# @date Apr 22 21:07:32 CST 2009
import re, sys
def html2text(page):
page = re.sub('<script[^<]*</script>', '', page)
page_text = re.sub('<[^>]*>|&[^;]*;', '', page)
return page_text
| Python |
#!/usr/bin/env python
# @author FAN Kai (fankai@net.pku.edu.cn), Peking University
# @date Jan 16 04:02:42 PM CST 2009
import os, time, cPickle
class fdb:
def __init__(self, path):
if os.path.exists(path):
f = open(path, 'rb+')
pos = int(f.read(8), 16)
f.seek(pos)
idxstr = f.read()
self.idx = cPickle.loads(idxstr)
#print self.idx
self.pos = pos
self.dat = f
else:
self.idx = {}
self.pos = 8
os.mknod(path)
self.dat = open(path, 'rb+')
self.closed = False
def __del__(self):
pass
#if not self.closed:
#self.close()
def keys(self):
return self.idx.keys()
def put(self, key, value):
#print self.pos
self.dat.seek(self.pos)
self.idx[key] = (self.dat.tell(), len(value))
self.dat.write(value)
self.pos = self.dat.tell()
def get(self, key):
if key in self.idx:
pos, len = self.idx[key]
self.dat.seek(pos)
return self.dat.read(len)
def close(self):
self.dat.seek(0)
self.dat.write('%08x'%self.pos)
idxstr = cPickle.dumps(self.idx)
self.dat.seek(self.pos)
#print self.pos
self.dat.write(idxstr)
#self.dat.truncate()
self.dat.close()
self.closed = True
if __name__ == "__main__":
import sys
#os.system('rm fdb_tmp')
db = fdb('fdb_tmp')
for i in range(10):
db.put(i, str(i))
db.close()
db = fdb('fdb_tmp')
for k in db.keys():
print k, db.get(k)
| Python |
#!/usr/bin/env python
# @author FAN Kai (fankai@net.pku.edu.cn), Peking University
# @date Jan 05 19:40:49 CST 2009
import math
def entropy(d):
e = 0
for p in d:
e -= p*math.log(p, 2)
return e
print entropy([0.5, 0.5])
print entropy([0.2, 0.8])
print entropy([0.25,0.25, 0.25, 0.25])
print entropy([0.25] * 4)
print entropy([0.05] * 20)
a=[(1,2), (3,4)]
b=[(1,3), (4,5)]
def cos(a, b):
s = 0
for i in range(len(a)):
s += a[i]*b[i]
aa = math.sqrt(sum(i*i for i in a))
bb = math.sqrt(sum(i*i for i in b))
return s / aa / bb
print cos((-1,0), (-1, 1))
print cos((-2,0), (-2, 2))
| Python |
#!/usr/bin/env python
import math
import random
nRounds = 10000
nInputs = 3
nHidden = 8
nPatterns = 4
LR_IH = 0.7
LR_HO = 0.07
trainInput = []
trainOutput = []
weightIH = []
weightHO = []
valHidden = []
output = 0
diff = 0
def calcNN(pattern):
output = 0.0
for h in range(0, nHidden):
x = 0
for i in range(0, nInputs):
x += trainInput[pattern][i] * weightIH[i][h]
# print trainInput[pattern][i], weightIH[i][h]
# print x, trainInput[pattern][i], weightIH[i][h]
valHidden[h] = 1.0 / (1 + math.exp(-x))
# print h, valHidden[h]
# print "Value Hidden ",h,"=", valHidden[h]
output += valHidden[h] * weightHO[h]
# print "Output:", output, "Expect:", trainOutput[pattern]
diff = output * (1 - output) * (trainOutput[pattern] - output)
return output - trainOutput[pattern]
def changeWeightHO(error):
for h in range(0, nHidden):
weightHO[h] -= LR_HO * error * valHidden[h]
# weightHO[h] -= LR_HO * error * (1 - output) * output * valHidden[h]
# print "weight",h,"=",weightHO[h],"error=", error
if weightHO[h] > 5: weightHO[h] = 5
if weightHO[h] < -5: weightHO[h] = -5
# print "weight",h,"=",weightHO[h],"error=", error
def changeWeightIH(pattern, error):
for h in range(0, nHidden):
# change = valHidden[h] * (1 - valHidden[h])
# change *= LR_IH * weightHO[h] * error
change = 1 - (valHidden[h] ** 2)
change *= LR_IH * error * weightHO[h]
for i in range(0, nInputs):
# print weightIH[i][h]
weightIH[i][h] -= change * trainInput[pattern][i]
# print "weight",i,h,"=",weightIH[i][h],"change=", change, error, trainInput[pattern][i]
# if weightIH[i][h] > 10: weightIH[i][h] = 10
# if weightIH[i][h] < -10: weightIH[i][h] = -10
def initWeights():
for h in range(0, nHidden):
weightHO[h] = 1.5 - h
for i in range(0, nInputs):
weightIH[i][h] = 1 - i
def initData():
for h in range(0, nHidden):
valHidden.append(0)
weightHO.append(0)
for i in range(0, nInputs):
weightIH.append([])
for h in range(0, nHidden):
weightIH[i].append(0)
nPatterns = 0
for line in open("nntrain.txt"):
t = line.split(" ")
tt = []
for i in (0, 1, 2):
tt.append(float(t[i]))
trainInput.append(tt)
trainOutput.append(float(t[3]))
nPatterns += 1
def check():
error = 0
for p in range(0, nPatterns):
e = calcNN(p)
error += e ** 2
error /= nPatterns
print "Error :", math.sqrt(error)
def main():
initData()
initWeights()
for r in range(0, nRounds):
p = random.randint(0, 3)
# p = r % 4
error = calcNN(p)
changeWeightHO(error)
changeWeightIH(p, error)
# print trainInput[p][0], trainInput[p][1], trainInput[p][2]
print "Round", r, "Error = ", error
check()
main()
| Python |
#!/usr/bin/env python
# @author FAN Kai, Peking University
# @date Dec 12 11:02:05 CST 2008
import sys, profile
nMethods = 0;
def check(index, pos):
for i in range(0, index):
if pos[i] == pos[index] or abs(pos[i]-pos[index]) == abs(i-index):
return False
return True
def found(pos):
global nMethods
nMethods += 1
print "Method", nMethods
return
for i in range(0, len(pos)):
print ' -'*pos[i],'*', '- '*(len(pos)-pos[i]-1)
def queens_rec(index, pos):
n = len(pos)
if index == n: found(pos)
else:
for i in range(0, n):
pos[index] = i
if check(index, pos):
queens_rec(index + 1, pos)
def queens_back(n):
index = 0
pos = [-1]*n
while index >= 0:
pos[index] += 1
if pos[index] == n:
pos[index] = -1
index -= 1
elif check(index, pos):
if index == n - 1: found(pos)
else: index += 1
def queens(nQueens):
#queens_rec(0, [0]*nQueens)
queens_back(nQueens)
if len(sys.argv) > 1:
queens(int(sys.argv[1]))
else:
profile.run('queens(8)')
#queens(8)
| Python |
#!/usr/bin/env python
import math
import timeit
def prime1(m):
num = 1
p = [2]
i = 3
while True:
flag = True
k = int(math.sqrt(i)) + 1
for j in p:
if i % j == 0:
flag = False
break
if j*j>i:break
if flag:
num += 1
p.append(i)
i += 1
if i > m:break
return p
def prime2(m):
pp = range(2, m+1)
p = []
while pp[0] ** 2 <= m:
p.append(pp[0])
pp = [e for e in pp if e % pp[0] != 0]
p.extend(pp)
return p
def prime3(m):
p = range(2, m+1)
for i in range(0, m):
p = [e for e in p if (e % p[i] != 0 or e == p[i])]
if (p[i] ** 2 > m): break
return p
def prime4(m):
p = range(2, m+1)
for i in range(0, m):
p = filter(lambda x: x % p[i] != 0 or x <= p[i] , p)
if (p[i] ** 2 > m): break
return p
if __name__ == '__main__':
print prime1(121)
print prime2(121)
print prime3(121)
print prime4(121)
t = timeit.Timer("primes.prime1(10000)", "import primes")
print t.repeat(3, 10)
t = timeit.Timer("primes.prime2(10000)", "import primes")
print t.repeat(3, 10)
t = timeit.Timer("primes.prime3(10000)", "import primes")
print t.repeat(3, 10)
t = timeit.Timer("primes.prime4(10000)", "import primes")
print t.repeat(3, 10)
| Python |
#!/usr/bin/env python
# @author FAN Kai (fankai@net.pku.edu.cn), Peking University
# @date Dec 29 07:23:04 CST 2008
import sys, threading, random, time, optparse, os
from socket import *
class Receiver(threading.Thread):
def __init__(self, connection):
threading.Thread.__init__(self)
self.connection = connection
def run(self):
start = time.time()
mbytes = 0
if opts.file:
fname = '%s_%f.tmp' % (opts.file, start)
f = open(fname, 'wb')
while True:
data = self.connection.recv(Receiver.buffer_size)
if not data: break
if opts.file: f.write(data)
Receiver.mbytes += len(data)/1024.0/1024.0
mbytes += len(data)/1024.0/1024.0
sender = self.connection.getpeername()
self.connection.close()
if opts.file:
f.close()
#os.remove(fname)
interval = time.time() - start
if opts.verbose:
print 'sender=%s bytes=%.2fMB speed=%.2fMB/s'\
%(sender, mbytes, mbytes/interval)
class Sender(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
start = time.time()
sock = socket(AF_INET, SOCK_STREAM)
sock.settimeout(3)
sock.connect((opts.host, opts.port))
self.mbytes = 0;
if opts.file:
f = open(opts.file, 'rb')
while True:
data = f.read(1024*1024)
if not data: break
sock.sendall(data)
self.mbytes += len(data)/1024.0/1024.0
else:
while self.mbytes < Sender.size:
bsize = random.randint(Sender.block_size/2, Sender.block_size)
sock.sendall(' ' * bsize)
self.mbytes += bsize/1024.0/1024.0
sock.close()
interval = time.time() - start
Sender.sema.release()
if opts.verbose:
print 'sent=%.2fMB speed=%.2fMB/s'%(self.mbytes, self.mbytes/interval)
class SpeedCalculator(threading.Thread):
def run(self):
time_start = time.time()
while True:
time_last = time.time()
mbytes_last = Receiver.mbytes
time.sleep(1)
mbytes = Receiver.mbytes - mbytes_last
interval = time.time() - time_last
if opts.verbose and mbytes > 0:
print 'time=%.2f peers=%d bytes=%.2fMB speed=%.2fMB/s'\
%(time.time() - time_start, threading.activeCount()-2,
Receiver.mbytes, mbytes/interval)
def start_server():
Receiver.mbytes = 0
tsc = SpeedCalculator()
tsc.setDaemon(True)
tsc.start()
ss = socket(AF_INET, SOCK_STREAM)
ss.bind((opts.host, opts.port))
ss.listen(5)
while True:
connection, address = ss.accept()
ts = Receiver(connection)
ts.start()
def start_client():
start = time.time()
threads = []
for i in range(Sender.thread):
Sender.sema.acquire()
t = Sender()
t.start()
threads.append(t)
mbytes = 0
for i in range(Sender.thread):
threads[i].join()
mbytes += threads[i].mbytes
span = time.time() - start
print 'server=%s thread=%d block=%dB bytes=%.2fMB speed=%.2fMB/s'\
%((opts.host, opts.port), Sender.thread, Sender.block_size, mbytes, mbytes/span)
parser = optparse.OptionParser(description='Test efficiency of tcp transmission.')
parser.add_option('-v', '--verbose', action='store_true', default=False,
help='show more information when running')
parser.add_option('-s', '--server', action='store_true', dest='server', default=False,
help='start as server')
parser.add_option('-c', '--client', action='store_true', dest='client', default=False,
help='start as client')
parser.add_option('-a', '--host', default='127.0.0.1',
help='server host')
parser.add_option('-p', '--port', type=int, default=22345,
help='server port')
parser.add_option('-u', '--buffer', metavar='SIZE', default='1024*1024',
help='size of buffer server use to receive data')
parser.add_option('-b', '--block', metavar='SIZE', default='1024*1024',
help='max size of each transmission, the default value is 1MB')
parser.add_option('-n', '--size', default='8',
help='data size in MB, the default value is 8MB')
parser.add_option('-f', '--file', default='',
help='read/write data from/to FILE')
parser.add_option('-t', '--thread', metavar='NUM', type='int', default=1,
help='number of threads client starts')
parser.add_option('-k', '--concurrent', metavar='NUM', type='int', default=1,
help='max number of concurrent client threads')
opts, args = parser.parse_args()
if opts.server:
Receiver.buffer_size = eval(opts.buffer)
start_server()
elif opts.client:
Sender.sema = threading.Semaphore(opts.concurrent)
Sender.block_size = eval(opts.block)
Sender.size = eval(opts.size)
Sender.thread = opts.thread
start_client()
else:
parser.print_help()
| Python |
#!/usr/bin/env python
import Queue, threading, sys
from threading import Thread
import time,urllib
# working thread
class Worker(Thread):
worker_count = 0
def __init__(self, workQueue, resultQueue, timeout = 0, **kwds):
Thread.__init__(self, **kwds)
self.id = Worker.worker_count
Worker.worker_count += 1
self.setDaemon(True)
self.workQueue = workQueue
self.resultQueue = resultQueue
self.timeout = timeout
self.count = 0
def run(self):
''' the get-some-work, do-some-work main loop of worker threads '''
while True:
try:
callable, args, kwds = self.workQueue.get(timeout=self.timeout)
res = callable(*args, **kwds)
print "worker[%2d %d]: %s" % (self.id, self.count, str(res))
self.count += 1
self.resultQueue.put(res)
except Queue.Empty:
break
except :
print 'worker[%2d]' % self.id, sys.exc_info()[:2]
class WorkerManager:
def __init__(self, num_of_workers=10, timeout = 1):
self.workQueue = Queue.Queue()
self.resultQueue = Queue.Queue()
self.workers = []
self.timeout = timeout
self._recruitThreads(num_of_workers)
def _recruitThreads(self, num_of_workers):
for i in range(num_of_workers):
worker = Worker(self.workQueue, self.resultQueue, self.timeout)
self.workers.append(worker)
def start(self):
for w in self.workers:
w.start()
def wait_for_complete(self):
# ...then, wait for each of them to terminate:
while len(self.workers):
worker = self.workers.pop()
worker.join()
if worker.isAlive() and not self.workQueue.empty():
self.workers.append(worker)
print "All jobs are are completed."
def add_job(self, callable, *args, **kwds):
self.workQueue.put((callable, args, kwds))
def get_result(self, *args, **kwds):
return self.resultQueue.get(*args, **kwds)
def test_job(id, sleep = 0.001):
try:
urllib.urlopen('http://localhost/html').read()
except:
print '[%4d]' % id, sys.exc_info()[:2]
return id
def test():
import socket
socket.setdefaulttimeout(10)
print 'start testing'
wm = WorkerManager(10)
for i in range(500):
wm.add_job(test_job, i, i*0.001)
wm.start()
wm.wait_for_complete()
print 'end testing'
if __name__ == '__main__':
test()
| Python |
#!/usr/bin/env python
print "Hello, world!"
from time import time
begin = time()
data = []
for line in open("D:\data.txt", "r"):
tmp = []
for x in line.split(","):
tmp.append(float(x))
data.append(tmp)
dimension = len(data[0]) - 1
print "number of training data:", len(data)
print "data dimemsion:", dimension
for line in open("D:\test.txt", "r"):
test = line.split(",")
ans = 0
for d in data:
dis = 0
for i in range(0, dimension):
dis += (float(test[i])-d[i+1])**2
if dis == 0: dis = 1
ans += d[0] / dis
if ans > 0: print "positive"
else: print "negative"
print "cost :", time() - begin, "s"
| Python |
#!/usr/bin/env python
# @author FAN Kai (fankai@net.pku.edu.cn), Peking University
# @date Dec 31 04:43:12 PM CST 2008
import os, time
import sys
def test_local():
os.system('pkill -f "python.*tcp.py"')
for i in range(6, 25, 2):
scmd = './tcp.py -s -u %d -p 12345 &' % 2**i
print scmd
os.system(scmd)
time.sleep(1)
for j in range(6, 25, 2):
ccmd = './tcp.py -c -b %d -n %d -t 1 -a 127.0.0.1 -p 12345' % (2**j, 2**(24-j))
#print ccmd
os.system(ccmd)
os.system('pkill -f "python.*tcp.py"')
def test():
for j in range(4, 18):
ccmd = './tcp.py -b %d -n %d -t 1 -a %s %s' % (2**j, 2**(24-j), sys.argv[1], sys.argv[2])
#print ccmd
os.system(ccmd)
test_local()
| Python |
#!/usr/bin/env python
import time
class Timer:
"A Timer like boost::timer"
cnt = 0
def __init__(self):self.restart();Timer.cnt += 1
def __repr__(self):return self.t
def __str__(self):return str(self.t)
def __private(self):print "private func %d" % self.cnt
def public(self):self.__private()
@staticmethod
def static():print 'static method %d' % Timer.cnt
#@classmethod
#def cm():print 'class method %d' % Timer.cnt
def restart(self):
self.t = time.clock()
def elapsed(self):
return time.clock() - self.t
if __name__ == '__main__':
print Timer.cnt
t = Timer();
print Timer.cnt
print t.cnt
print t.__doc__
print t.elapsed()
time.sleep(.1)
print t.elapsed()
t.restart()
time.sleep(.1)
print t.elapsed()
print t
t.public()
print dir(t)
print t.t
t.static()
Timer.static()
#Timer.cm()
tt = Timer()
print Timer.cnt, tt.cnt
| Python |
#!/usr/bin/env python
from time import *
from heapq import *
import math
def initData():
data = []
for line in open("D:\data.txt", "r"):
tmp = []
for x in line.split(","):
tmp.append(float(x))
data.append(tmp)
print "Number of training data:", len(data)
return data
def testData(k, data):
e = 0
s = 0
for test in data:
ans = 0
neighbors = []
for d in data:
tmp = [0, 0]
dis = 0
for i in range(0, dimension):
dis += ((test[i]-d[i])*ss[i])**2
if dis == 0: continue
tmp[0] = math.sqrt(dis)
tmp[1] = d[dimension] - 0.5
neighbors.append(tuple(tmp))
nn = nsmallest(k, neighbors)
for x in nn:
ans += x[1]/x[0]
# print ans, nn
if ans > 0: ans = 1
else: ans = 0
s += 1
if int(test[dimension]) != ans:
e += 1
# print e, s, test[dimension], ans
return e
dimension = 57
begin = time()
data = initData()
ss = []
for i in range(0, dimension):
ss.append(1)
for x in range(0, dimension):
ss[x] = 0.1
error = testData(20, data)
for i in range(0, 12):
ss[x] *= 1.5
e = testData(20, data)
print x, i, ss[x], e, error
if e > error:break
print "Cost", time()-begin, "seconds"
| Python |
#!/usr/bin/env python
print "Hello, world!"
from time import time
begin = time()
data = []
for line in open("D:\data.txt", "r"):
tmp = []
for x in line.split(","):
tmp.append(float(x))
data.append(tmp)
dimension = len(data[0]) - 1
print "number of training data:", len(data)
print "data dimemsion:", dimension
for line in open("D:\test.txt", "r"):
test = line.split(",")
ans = 0
for d in data:
dis = 0
for i in range(0, dimension):
dis += (float(test[i])-d[i+1])**2
if dis == 0: dis = 1
ans += d[0] / dis
if ans > 0: print "positive"
else: print "negative"
print "cost :", time() - begin, "s"
| Python |
#!/usr/bin/env python
import Queue, threading, sys
from threading import Thread
import time,urllib
# working thread
class Worker(Thread):
worker_count = 0
def __init__(self, workQueue, resultQueue, timeout = 0, **kwds):
Thread.__init__(self, **kwds)
self.id = Worker.worker_count
Worker.worker_count += 1
self.setDaemon(True)
self.workQueue = workQueue
self.resultQueue = resultQueue
self.timeout = timeout
self.count = 0
def run(self):
''' the get-some-work, do-some-work main loop of worker threads '''
while True:
try:
callable, args, kwds = self.workQueue.get(timeout=self.timeout)
res = callable(*args, **kwds)
print "worker[%2d %d]: %s" % (self.id, self.count, str(res))
self.count += 1
self.resultQueue.put(res)
except Queue.Empty:
break
except :
print 'worker[%2d]' % self.id, sys.exc_info()[:2]
class WorkerManager:
def __init__(self, num_of_workers=10, timeout = 1):
self.workQueue = Queue.Queue()
self.resultQueue = Queue.Queue()
self.workers = []
self.timeout = timeout
self._recruitThreads(num_of_workers)
def _recruitThreads(self, num_of_workers):
for i in range(num_of_workers):
worker = Worker(self.workQueue, self.resultQueue, self.timeout)
self.workers.append(worker)
def start(self):
for w in self.workers:
w.start()
def wait_for_complete(self):
# ...then, wait for each of them to terminate:
while len(self.workers):
worker = self.workers.pop()
worker.join()
if worker.isAlive() and not self.workQueue.empty():
self.workers.append(worker)
print "All jobs are are completed."
def add_job(self, callable, *args, **kwds):
self.workQueue.put((callable, args, kwds))
def get_result(self, *args, **kwds):
return self.resultQueue.get(*args, **kwds)
def test_job(id, sleep = 0.001):
try:
urllib.urlopen('http://localhost/html').read()
except:
print '[%4d]' % id, sys.exc_info()[:2]
return id
def test():
import socket
socket.setdefaulttimeout(10)
print 'start testing'
wm = WorkerManager(10)
for i in range(500):
wm.add_job(test_job, i, i*0.001)
wm.start()
wm.wait_for_complete()
print 'end testing'
if __name__ == '__main__':
test()
| Python |
#!/usr/bin/env python
# @author FAN Kai (fankai@net.pku.edu.cn), Peking University
# @date Dec 29 07:23:04 CST 2008
import sys, threading, random, time, optparse, os
from socket import *
class Receiver(threading.Thread):
def __init__(self, connection):
threading.Thread.__init__(self)
self.connection = connection
def run(self):
start = time.time()
mbytes = 0
if opts.file:
fname = '%s_%f.tmp' % (opts.file, start)
f = open(fname, 'wb')
while True:
data = self.connection.recv(Receiver.buffer_size)
if not data: break
if opts.file: f.write(data)
Receiver.mbytes += len(data)/1024.0/1024.0
mbytes += len(data)/1024.0/1024.0
sender = self.connection.getpeername()
self.connection.close()
if opts.file:
f.close()
#os.remove(fname)
interval = time.time() - start
if opts.verbose:
print 'sender=%s bytes=%.2fMB speed=%.2fMB/s'\
%(sender, mbytes, mbytes/interval)
class Sender(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
start = time.time()
sock = socket(AF_INET, SOCK_STREAM)
sock.settimeout(3)
sock.connect((opts.host, opts.port))
self.mbytes = 0;
if opts.file:
f = open(opts.file, 'rb')
while True:
data = f.read(1024*1024)
if not data: break
sock.sendall(data)
self.mbytes += len(data)/1024.0/1024.0
else:
while self.mbytes < Sender.size:
bsize = random.randint(Sender.block_size/2, Sender.block_size)
sock.sendall(' ' * bsize)
self.mbytes += bsize/1024.0/1024.0
sock.close()
interval = time.time() - start
Sender.sema.release()
if opts.verbose:
print 'sent=%.2fMB speed=%.2fMB/s'%(self.mbytes, self.mbytes/interval)
class SpeedCalculator(threading.Thread):
def run(self):
time_start = time.time()
while True:
time_last = time.time()
mbytes_last = Receiver.mbytes
time.sleep(1)
mbytes = Receiver.mbytes - mbytes_last
interval = time.time() - time_last
if opts.verbose and mbytes > 0:
print 'time=%.2f peers=%d bytes=%.2fMB speed=%.2fMB/s'\
%(time.time() - time_start, threading.activeCount()-2,
Receiver.mbytes, mbytes/interval)
def start_server():
Receiver.mbytes = 0
tsc = SpeedCalculator()
tsc.setDaemon(True)
tsc.start()
ss = socket(AF_INET, SOCK_STREAM)
ss.bind((opts.host, opts.port))
ss.listen(5)
while True:
connection, address = ss.accept()
ts = Receiver(connection)
ts.start()
def start_client():
start = time.time()
threads = []
for i in range(Sender.thread):
Sender.sema.acquire()
t = Sender()
t.start()
threads.append(t)
mbytes = 0
for i in range(Sender.thread):
threads[i].join()
mbytes += threads[i].mbytes
span = time.time() - start
print 'server=%s thread=%d block=%dB bytes=%.2fMB speed=%.2fMB/s'\
%((opts.host, opts.port), Sender.thread, Sender.block_size, mbytes, mbytes/span)
parser = optparse.OptionParser(description='Test efficiency of tcp transmission.')
parser.add_option('-v', '--verbose', action='store_true', default=False,
help='show more information when running')
parser.add_option('-s', '--server', action='store_true', dest='server', default=False,
help='start as server')
parser.add_option('-c', '--client', action='store_true', dest='client', default=False,
help='start as client')
parser.add_option('-a', '--host', default='127.0.0.1',
help='server host')
parser.add_option('-p', '--port', type=int, default=22345,
help='server port')
parser.add_option('-u', '--buffer', metavar='SIZE', default='1024*1024',
help='size of buffer server use to receive data')
parser.add_option('-b', '--block', metavar='SIZE', default='1024*1024',
help='max size of each transmission, the default value is 1MB')
parser.add_option('-n', '--size', default='8',
help='data size in MB, the default value is 8MB')
parser.add_option('-f', '--file', default='',
help='read/write data from/to FILE')
parser.add_option('-t', '--thread', metavar='NUM', type='int', default=1,
help='number of threads client starts')
parser.add_option('-k', '--concurrent', metavar='NUM', type='int', default=1,
help='max number of concurrent client threads')
opts, args = parser.parse_args()
if opts.server:
Receiver.buffer_size = eval(opts.buffer)
start_server()
elif opts.client:
Sender.sema = threading.Semaphore(opts.concurrent)
Sender.block_size = eval(opts.block)
Sender.size = eval(opts.size)
Sender.thread = opts.thread
start_client()
else:
parser.print_help()
| Python |
#!/usr/bin/env python
import time
class Timer:
"A Timer like boost::timer"
cnt = 0
def __init__(self):self.restart();Timer.cnt += 1
def __repr__(self):return self.t
def __str__(self):return str(self.t)
def __private(self):print "private func %d" % self.cnt
def public(self):self.__private()
@staticmethod
def static():print 'static method %d' % Timer.cnt
#@classmethod
#def cm():print 'class method %d' % Timer.cnt
def restart(self):
self.t = time.clock()
def elapsed(self):
return time.clock() - self.t
if __name__ == '__main__':
print Timer.cnt
t = Timer();
print Timer.cnt
print t.cnt
print t.__doc__
print t.elapsed()
time.sleep(.1)
print t.elapsed()
t.restart()
time.sleep(.1)
print t.elapsed()
print t
t.public()
print dir(t)
print t.t
t.static()
Timer.static()
#Timer.cm()
tt = Timer()
print Timer.cnt, tt.cnt
| Python |
def gcd(a, b):
if a > b:
a, b = b, a
if b % a == 0:
return a
return gcd(b % a, a)
p = int(raw_input("Input tow primes:"))
q = int(raw_input())
n = p * q
s = (p-1) * (q-1)
for e in range(2, n):
if gcd(e, s) == 1:break
for d in range(2, n):
if e * d % s == 1:break
print "p q n s e d\n", p, q, n, s, e, d
while True:
m = int(raw_input())
if m == 0: break
c = m ** e % n
print "After encrypt:", c
print "After decrypt:", c ** d %n
| Python |
#!/usr/bin/env python
# @author FAN Kai, Peking University
# @date Dec 12 11:02:05 CST 2008
import sys, profile
nMethods = 0;
def check(index, pos):
for i in range(0, index):
if pos[i] == pos[index] or abs(pos[i]-pos[index]) == abs(i-index):
return False
return True
def found(pos):
global nMethods
nMethods += 1
print "Method", nMethods
return
for i in range(0, len(pos)):
print ' -'*pos[i],'*', '- '*(len(pos)-pos[i]-1)
def queens_rec(index, pos):
n = len(pos)
if index == n: found(pos)
else:
for i in range(0, n):
pos[index] = i
if check(index, pos):
queens_rec(index + 1, pos)
def queens_back(n):
index = 0
pos = [-1]*n
while index >= 0:
pos[index] += 1
if pos[index] == n:
pos[index] = -1
index -= 1
elif check(index, pos):
if index == n - 1: found(pos)
else: index += 1
def queens(nQueens):
#queens_rec(0, [0]*nQueens)
queens_back(nQueens)
if len(sys.argv) > 1:
queens(int(sys.argv[1]))
else:
profile.run('queens(8)')
#queens(8)
| Python |
#!/usr/bin/env python
# @author FAN Kai (fankai@net.pku.edu.cn), Peking University
# @date Dec 31 04:43:12 PM CST 2008
import os, time
import sys
def test_local():
os.system('pkill -f "python.*tcp.py"')
for i in range(6, 25, 2):
scmd = './tcp.py -s -u %d -p 12345 &' % 2**i
print scmd
os.system(scmd)
time.sleep(1)
for j in range(6, 25, 2):
ccmd = './tcp.py -c -b %d -n %d -t 1 -a 127.0.0.1 -p 12345' % (2**j, 2**(24-j))
#print ccmd
os.system(ccmd)
os.system('pkill -f "python.*tcp.py"')
def test():
for j in range(4, 18):
ccmd = './tcp.py -b %d -n %d -t 1 -a %s %s' % (2**j, 2**(24-j), sys.argv[1], sys.argv[2])
#print ccmd
os.system(ccmd)
test_local()
| Python |
#!/usr/bin/env python
import math
import random
nRounds = 10000
nInputs = 3
nHidden = 8
nPatterns = 4
LR_IH = 0.7
LR_HO = 0.07
trainInput = []
trainOutput = []
weightIH = []
weightHO = []
valHidden = []
output = 0
diff = 0
def calcNN(pattern):
output = 0.0
for h in range(0, nHidden):
x = 0
for i in range(0, nInputs):
x += trainInput[pattern][i] * weightIH[i][h]
# print trainInput[pattern][i], weightIH[i][h]
# print x, trainInput[pattern][i], weightIH[i][h]
valHidden[h] = 1.0 / (1 + math.exp(-x))
# print h, valHidden[h]
# print "Value Hidden ",h,"=", valHidden[h]
output += valHidden[h] * weightHO[h]
# print "Output:", output, "Expect:", trainOutput[pattern]
diff = output * (1 - output) * (trainOutput[pattern] - output)
return output - trainOutput[pattern]
def changeWeightHO(error):
for h in range(0, nHidden):
weightHO[h] -= LR_HO * error * valHidden[h]
# weightHO[h] -= LR_HO * error * (1 - output) * output * valHidden[h]
# print "weight",h,"=",weightHO[h],"error=", error
if weightHO[h] > 5: weightHO[h] = 5
if weightHO[h] < -5: weightHO[h] = -5
# print "weight",h,"=",weightHO[h],"error=", error
def changeWeightIH(pattern, error):
for h in range(0, nHidden):
# change = valHidden[h] * (1 - valHidden[h])
# change *= LR_IH * weightHO[h] * error
change = 1 - (valHidden[h] ** 2)
change *= LR_IH * error * weightHO[h]
for i in range(0, nInputs):
# print weightIH[i][h]
weightIH[i][h] -= change * trainInput[pattern][i]
# print "weight",i,h,"=",weightIH[i][h],"change=", change, error, trainInput[pattern][i]
# if weightIH[i][h] > 10: weightIH[i][h] = 10
# if weightIH[i][h] < -10: weightIH[i][h] = -10
def initWeights():
for h in range(0, nHidden):
weightHO[h] = 1.5 - h
for i in range(0, nInputs):
weightIH[i][h] = 1 - i
def initData():
for h in range(0, nHidden):
valHidden.append(0)
weightHO.append(0)
for i in range(0, nInputs):
weightIH.append([])
for h in range(0, nHidden):
weightIH[i].append(0)
nPatterns = 0
for line in open("nntrain.txt"):
t = line.split(" ")
tt = []
for i in (0, 1, 2):
tt.append(float(t[i]))
trainInput.append(tt)
trainOutput.append(float(t[3]))
nPatterns += 1
def check():
error = 0
for p in range(0, nPatterns):
e = calcNN(p)
error += e ** 2
error /= nPatterns
print "Error :", math.sqrt(error)
def main():
initData()
initWeights()
for r in range(0, nRounds):
p = random.randint(0, 3)
# p = r % 4
error = calcNN(p)
changeWeightHO(error)
changeWeightIH(p, error)
# print trainInput[p][0], trainInput[p][1], trainInput[p][2]
print "Round", r, "Error = ", error
check()
main()
| Python |
#!/usr/bin/env python
import math
import timeit
def prime1(m):
num = 1
p = [2]
i = 3
while True:
flag = True
k = int(math.sqrt(i)) + 1
for j in p:
if i % j == 0:
flag = False
break
if j*j>i:break
if flag:
num += 1
p.append(i)
i += 1
if i > m:break
return p
def prime2(m):
pp = range(2, m+1)
p = []
while pp[0] ** 2 <= m:
p.append(pp[0])
pp = [e for e in pp if e % pp[0] != 0]
p.extend(pp)
return p
def prime3(m):
p = range(2, m+1)
for i in range(0, m):
p = [e for e in p if (e % p[i] != 0 or e == p[i])]
if (p[i] ** 2 > m): break
return p
def prime4(m):
p = range(2, m+1)
for i in range(0, m):
p = filter(lambda x: x % p[i] != 0 or x <= p[i] , p)
if (p[i] ** 2 > m): break
return p
if __name__ == '__main__':
print prime1(121)
print prime2(121)
print prime3(121)
print prime4(121)
t = timeit.Timer("primes.prime1(10000)", "import primes")
print t.repeat(3, 10)
t = timeit.Timer("primes.prime2(10000)", "import primes")
print t.repeat(3, 10)
t = timeit.Timer("primes.prime3(10000)", "import primes")
print t.repeat(3, 10)
t = timeit.Timer("primes.prime4(10000)", "import primes")
print t.repeat(3, 10)
| Python |
#!/usr/bin/env python
from time import *
from heapq import *
import math
def initData():
data = []
for line in open("D:\data.txt", "r"):
tmp = []
for x in line.split(","):
tmp.append(float(x))
data.append(tmp)
print "Number of training data:", len(data)
return data
def testData(k, data):
e = 0
s = 0
for test in data:
ans = 0
neighbors = []
for d in data:
tmp = [0, 0]
dis = 0
for i in range(0, dimension):
dis += ((test[i]-d[i])*ss[i])**2
if dis == 0: continue
tmp[0] = math.sqrt(dis)
tmp[1] = d[dimension] - 0.5
neighbors.append(tuple(tmp))
nn = nsmallest(k, neighbors)
for x in nn:
ans += x[1]/x[0]
# print ans, nn
if ans > 0: ans = 1
else: ans = 0
s += 1
if int(test[dimension]) != ans:
e += 1
# print e, s, test[dimension], ans
return e
dimension = 57
begin = time()
data = initData()
ss = []
for i in range(0, dimension):
ss.append(1)
for x in range(0, dimension):
ss[x] = 0.1
error = testData(20, data)
for i in range(0, 12):
ss[x] *= 1.5
e = testData(20, data)
print x, i, ss[x], e, error
if e > error:break
print "Cost", time()-begin, "seconds"
| Python |
#!/usr/bin/env python
# @author FAN Kai, Peking University
# @date Dec 24 06:14:26 CST 2008
import os, time, sys
if len(sys.argv) < 2:
print 'Usage: %s [taskfile]' % sys.argv[0]
sys.exit(1)
task_file = sys.argv[1]
output_file = task_file + '.out'
while True:
if not os.path.exists(task_file):
os.mknod(task_file)
lines = open(task_file).readlines()
for i in range(len(lines)-1, 0, -1):
if lines[i][:4] == 'Done':
lines = lines[i+1:]
break
for line in lines:
for task in line.split(';'):
task = task.strip() + ' >>%s 2>&1 &' % output_file
os.system(task)
cmd = '''echo 'Done "%s"' at %s. >>%s''' % (task, time.asctime(), task_file)
os.system(cmd)
try:
time.sleep(1)
except:
break
| Python |
#!/usr/bin/env python
# @author FAN Kai, Peking University
# @date Dec 22 06:31:00 CST 2008
#task {'taskid':taskid, 'ip':ip, 'pid':pid, 'tid':tid, 'ts':ts, 'te':te, 'cid':chunkID,
# 'jobid':jobid, 'part':partition}
#job {taskid:task, ...}
import re, shelve
head_pat = '[\d-]+ (?P<time>..:..:..) \w+ - (?P<src>\w+\((?P<id>\d+)\):) '
jobid_pat = 'jobId = (?P<jobid>\d+)'
taskid_pat = 'taskId = (?P<taskid>\d+)'
def get_time(line):
mp = re.match('200.-..-.. (?P<h>..):(?P<m>..):(?P<s>..)', line)
if mp:
h = int(mp.group('h'))
m = int(mp.group('m'))
s = int(mp.group('s'))
#print h, m, s, h*3600+m*60+s
return h*3600+m*60+s
def match_get_task(line):
pat = '%sGet (?P<type>\w+) task, %s %s' % (head_pat, jobid_pat, taskid_pat)
mp = re.search(pat, line)
if not mp: return
id = mp.group('taskid')
taskdb.setdefault(id, {})
taskdb[id]['taskid'] = mp.group('taskid')
taskdb[id]['jobid'] = mp.group('jobid')
taskdb[id]['type'] = mp.group('type')
taskdb[id]['start_time'] = mp.group('time')
def match_complete_task(line):
pat = '%sComplete task, %s %s' % (head_pat, jobid_pat, taskid_pat)
mp = re.search(pat, line)
if not mp: return
id = mp.group('taskid')
taskdb.setdefault(id, {})
taskdb[id]['taskid'] = mp.group('taskid')
taskdb[id]['jobid'] = mp.group('jobid')
taskdb[id]['comp_time'] = mp.group('time')
def match_trans_begin(line):
pat = head_pat + 'Transfer (?P<file>[/\w]+) to (?P<addr>[\d\.:]+) sockfd = (?P<fd>\d+)'
#pat = head_pat + 'Transfer (?P<file>[/\w]+) to (?P<addr>[\d\.:]+) sockfd = (?P<fd>\d+) id = (?P<id>\d+)'
mp = re.search(pat, line)
if not mp: return
print id, line
id = mp.group('fd')
transdb[id] = {}
transdb[id]['file'] = mp.group('file')
transdb[id]['fd'] = mp.group('fd')
transdb[id]['addr'] = mp.group('addr')
transdb[id]['start_time'] = mp.group('time')
def match_trans_end(line):
pat = head_pat + 'Transfer (?P<size>\d+) bytes for (?P<file>[/\w]+) in (?P<cost_time>\d+) seconds.'
mp = re.search(pat, line)
if not mp: return
id = mp.group('id')
print id, line
transdb.setdefault(id, {})
transdb[id]['size'] = mp.group('size')
transdb[id]['cost_time'] = mp.group('cost_time')
transdb[id]['comp_time'] = mp.group('time')
print mp.group('cost_time')
def match_thread_start(line):
pat = head_pat +'Start thread (?P<tid>\d+) for (?P<type>\w+) (?P<id>\d+)'
mp = re.search(pat, line)
if not mp: return
tid = m.group('tid')
assert tid not in threaddb
threaddb[tid] = {}
threaddb[tid]['type'] = m.group('type')
threaddb[tid]['id'] = m.group('id')
taskdb = shelve.open('taskdb', flag='n', writeback=True)
transdb = shelve.open('transdb', flag='n', writeback=True)
threaddb = shelve.open('threaddb', flag='n', writeback=True)
for line in open('log').read().split('\n'):
match_get_task(line)
match_complete_task(line)
match_trans_begin(line)
match_trans_end(line)
print len(transdb)
print len(taskdb)
| Python |
#!/usr/bin/env python
# @author FAN Kai (fankai@pku.edu.cn), Peking University
# @date Dec 25 06:57:37 CST 2008
import re, shelve, time, sys
log_pattern = '(?P<time>[\d-]+ ..:..:..) \w+ - (?P<src>\w+): (?P<event>\w+) (?P<stats>.+=.+)'
fields = 'type id start end complete abandon job task transid addr retry'.split()
def parse_stats(line):
entry = {}
for stat in line.split(' '):
if '=' not in stat: continue
k = stat.split('=')[0]
v = stat.split('=')[1]
entry[k] = v
return entry
def proc(logfile='worker1/mapred_worker.log'):
for line in open(logfile).read().split('\n'):
mp = re.match(log_pattern, line)
if not mp: continue
ts = mp.group('time')
#tt = time.mktime(time.strptime(t, "%Y-%m-%d %H:%M:%S"))
src = mp.group('src')
event = mp.group('event')
stats = parse_stats(mp.group('stats'))
if event not in events:
events.add(event)
taskid = stats.get('task', None)
jobid = stats.get('job', None)
type = stats.get('type', None)
id = stats.get('id', None)
id = stats.get('id', None)
if event == 'GetTask':
task = stats
task['start'] = ts
tasks[taskid] = task
elif event == 'AbandonTask':
task = tasks[taskid]
task['abandon'] = ts
task['retry'] = stats['retry']
elif event == 'CompleteTask':
task = tasks[taskid]
task['complete'] = ts
elif event == 'StartThread':
thread = stats
thread['start'] = ts
threads[id] = thread
elif event == 'FinishThread':
thread = threads[id]
thread['complete'] = ts
def display(db):
for item in db.values():
for f in fields:
if f in item.keys():
print '%s=%s\t' % (f, item[f]),
print
tasks = {}
threads = {}
events = set()
def proc_dir(dir):
global tasks, threads, events
tasks = {}
threads = {}
events = set()
proc(dir + '/mapred_worker.log')
print 'Dir: ' + dir
print 'Tasks:'
display(tasks)
print 'Threads:'
display(threads)
print
if len(sys.argv) > 1:
proc_dir(sys.argv[1])
else:
proc_dir('worker1')
proc_dir('worker2')
proc_dir('worker3')
| Python |
#!/usr/bin/env python
# @author FAN Kai, Peking University
# @date Dec 24 06:14:26 CST 2008
import os, time, sys
if len(sys.argv) < 2:
print 'Usage: %s [taskfile]' % sys.argv[0]
sys.exit(1)
task_file = sys.argv[1]
output_file = task_file + '.out'
while True:
if not os.path.exists(task_file):
os.mknod(task_file)
lines = open(task_file).readlines()
for i in range(len(lines)-1, 0, -1):
if lines[i][:4] == 'Done':
lines = lines[i+1:]
break
for line in lines:
for task in line.split(';'):
task = task.strip() + ' >>%s 2>&1 &' % output_file
os.system(task)
cmd = '''echo 'Done "%s"' at %s. >>%s''' % (task, time.asctime(), task_file)
os.system(cmd)
try:
time.sleep(1)
except:
break
| Python |
#!/usr/bin/env python
# @author FAN Kai (fankai@pku.edu.cn), Peking University
# @date Dec 25 06:57:37 CST 2008
import re, shelve, time, sys
log_pattern = '(?P<time>[\d-]+ ..:..:..) \w+ - (?P<src>\w+): (?P<event>\w+) (?P<stats>.+=.+)'
fields = 'type id start end complete abandon job task transid addr retry'.split()
def parse_stats(line):
entry = {}
for stat in line.split(' '):
if '=' not in stat: continue
k = stat.split('=')[0]
v = stat.split('=')[1]
entry[k] = v
return entry
def proc(logfile='worker1/mapred_worker.log'):
for line in open(logfile).read().split('\n'):
mp = re.match(log_pattern, line)
if not mp: continue
ts = mp.group('time')
#tt = time.mktime(time.strptime(t, "%Y-%m-%d %H:%M:%S"))
src = mp.group('src')
event = mp.group('event')
stats = parse_stats(mp.group('stats'))
if event not in events:
events.add(event)
taskid = stats.get('task', None)
jobid = stats.get('job', None)
type = stats.get('type', None)
id = stats.get('id', None)
id = stats.get('id', None)
if event == 'GetTask':
task = stats
task['start'] = ts
tasks[taskid] = task
elif event == 'AbandonTask':
task = tasks[taskid]
task['abandon'] = ts
task['retry'] = stats['retry']
elif event == 'CompleteTask':
task = tasks[taskid]
task['complete'] = ts
elif event == 'StartThread':
thread = stats
thread['start'] = ts
threads[id] = thread
elif event == 'FinishThread':
thread = threads[id]
thread['complete'] = ts
def display(db):
for item in db.values():
for f in fields:
if f in item.keys():
print '%s=%s\t' % (f, item[f]),
print
tasks = {}
threads = {}
events = set()
def proc_dir(dir):
global tasks, threads, events
tasks = {}
threads = {}
events = set()
proc(dir + '/mapred_worker.log')
print 'Dir: ' + dir
print 'Tasks:'
display(tasks)
print 'Threads:'
display(threads)
print
if len(sys.argv) > 1:
proc_dir(sys.argv[1])
else:
proc_dir('worker1')
proc_dir('worker2')
proc_dir('worker3')
| Python |
#!/usr/bin/env python
# @author FAN Kai, Peking University
# @date Dec 22 06:31:00 CST 2008
#task {'taskid':taskid, 'ip':ip, 'pid':pid, 'tid':tid, 'ts':ts, 'te':te, 'cid':chunkID,
# 'jobid':jobid, 'part':partition}
#job {taskid:task, ...}
import re, shelve
head_pat = '[\d-]+ (?P<time>..:..:..) \w+ - (?P<src>\w+\((?P<id>\d+)\):) '
jobid_pat = 'jobId = (?P<jobid>\d+)'
taskid_pat = 'taskId = (?P<taskid>\d+)'
def get_time(line):
mp = re.match('200.-..-.. (?P<h>..):(?P<m>..):(?P<s>..)', line)
if mp:
h = int(mp.group('h'))
m = int(mp.group('m'))
s = int(mp.group('s'))
#print h, m, s, h*3600+m*60+s
return h*3600+m*60+s
def match_get_task(line):
pat = '%sGet (?P<type>\w+) task, %s %s' % (head_pat, jobid_pat, taskid_pat)
mp = re.search(pat, line)
if not mp: return
id = mp.group('taskid')
taskdb.setdefault(id, {})
taskdb[id]['taskid'] = mp.group('taskid')
taskdb[id]['jobid'] = mp.group('jobid')
taskdb[id]['type'] = mp.group('type')
taskdb[id]['start_time'] = mp.group('time')
def match_complete_task(line):
pat = '%sComplete task, %s %s' % (head_pat, jobid_pat, taskid_pat)
mp = re.search(pat, line)
if not mp: return
id = mp.group('taskid')
taskdb.setdefault(id, {})
taskdb[id]['taskid'] = mp.group('taskid')
taskdb[id]['jobid'] = mp.group('jobid')
taskdb[id]['comp_time'] = mp.group('time')
def match_trans_begin(line):
pat = head_pat + 'Transfer (?P<file>[/\w]+) to (?P<addr>[\d\.:]+) sockfd = (?P<fd>\d+)'
#pat = head_pat + 'Transfer (?P<file>[/\w]+) to (?P<addr>[\d\.:]+) sockfd = (?P<fd>\d+) id = (?P<id>\d+)'
mp = re.search(pat, line)
if not mp: return
print id, line
id = mp.group('fd')
transdb[id] = {}
transdb[id]['file'] = mp.group('file')
transdb[id]['fd'] = mp.group('fd')
transdb[id]['addr'] = mp.group('addr')
transdb[id]['start_time'] = mp.group('time')
def match_trans_end(line):
pat = head_pat + 'Transfer (?P<size>\d+) bytes for (?P<file>[/\w]+) in (?P<cost_time>\d+) seconds.'
mp = re.search(pat, line)
if not mp: return
id = mp.group('id')
print id, line
transdb.setdefault(id, {})
transdb[id]['size'] = mp.group('size')
transdb[id]['cost_time'] = mp.group('cost_time')
transdb[id]['comp_time'] = mp.group('time')
print mp.group('cost_time')
def match_thread_start(line):
pat = head_pat +'Start thread (?P<tid>\d+) for (?P<type>\w+) (?P<id>\d+)'
mp = re.search(pat, line)
if not mp: return
tid = m.group('tid')
assert tid not in threaddb
threaddb[tid] = {}
threaddb[tid]['type'] = m.group('type')
threaddb[tid]['id'] = m.group('id')
taskdb = shelve.open('taskdb', flag='n', writeback=True)
transdb = shelve.open('transdb', flag='n', writeback=True)
threaddb = shelve.open('threaddb', flag='n', writeback=True)
for line in open('log').read().split('\n'):
match_get_task(line)
match_complete_task(line)
match_trans_begin(line)
match_trans_end(line)
print len(transdb)
print len(taskdb)
| Python |
db = []
item_count = {}
cnt = 0
def grow(itemsets):
r = []
i = 0
j = 1
while i < len(itemsets):
while j < len(itemsets) and itemsets[i][:-1] == itemsets[j][:-1]:
j += 1
for p in range(i, j):
for q in range(p+1, j):
r.append(itemsets[p]+itemsets[q][-1:])
i = j
return r
def contain(seta, setb):
i,j = 1, 0
while j < len(setb):
if i == len(seta): return False
if seta[i] > setb[j]: return False
elif seta[i] < setb[j]: i+=1
else: i, j = i+1, j+1
return True
def check(candidates):
r = []
candidates = map(tuple, candidates)
cnt = {}
for c in candidates: cnt[c] = 0
for transaction in db:
# print transaction
for candidate in candidates:
# print transaction, candidate, contain(transaction, candidate)
if cnt[candidate] < threshold and contain(transaction, candidate):
cnt[candidate] += 1
if cnt[candidate] >= threshold:
r.append(candidate)
print candidate
return r
import time
print time.asctime()
for line in open("f:/data/nausea.dat"):
parts = line.split()
db.append(parts[:1]+sorted(parts[1:]))
for item in db[-1][1:]:
# print item
item_count.setdefault(item, 0)
item_count[item] += 1
cnt += 1
threshold = 600
fitems = [item for item in item_count if item_count[item] >= threshold]
print len(db)
print len(fitems)
fitemsets = [[item] for item in sorted(fitems)]
print fitemsets
while len(fitemsets) > 0:
candidates = grow(fitemsets)
fitemsets = check(candidates)
print len(candidates), len(fitemsets), fitemsets
print time.asctime()
print contain(['f', 1,2, 3], [1,2,3])
| Python |
#!/usr/bin/env python
import sys, os
def echo_exe(cmd):
print cmd
os.system(cmd)
def create_links():
conf_path = os.path.abspath('.')
if not os.path.exists(conf_path):
print 'Please execute in fklab dir.'
sys.exit(1)
echo_exe('ln -sf %s/bashrc ~/.bashrc' % conf_path)
echo_exe('ln -sf %s/_emacs ~/.emacs' % conf_path)
echo_exe('ln -sf %s/vimrc ~/.vimrc' % conf_path)
echo_exe('ln -sf %s/vim ~/.vim' % conf_path)
# echo_exe('ln -sf %s/bashrc.root /root/.bashrc' % conf_path)
# echo_exe('ln -sf %s/vimrc /root/.vimrc' % conf_path)
# echo_exe('ln -sf %s/vim /root/.vim' % conf_path)
sys.stdout.flush()
def check_links():
os.system('echo Checking ...')
os.system('ls -l --color=auto ~/.bashrc')
os.system('ls -l --color=auto ~/.emacs')
os.system('ls -l --color=auto ~/.vimrc')
os.system('ls -l --color=auto ~/.vim')
# os.system('ls -l --color=auto /root/.bashrc')
#os.system('ls -l --color=auto /root/.vimrc')
#os.system('ls -l --color=auto /root/.vim')
if __name__ == '__main__':
# if not os.getuid() == 0:
# print 'Require root privilege.'
# sys.exit(1)
print 'Initializing environment ...'
create_links()
check_links()
print 'Initialized environment.'
| Python |
#!/usr/bin/env python
import sys, os
def echo_exe(cmd):
print cmd
os.system(cmd)
def create_links():
conf_path = os.path.abspath('.')
if not os.path.exists(conf_path):
print 'Please execute in fklab dir.'
sys.exit(1)
echo_exe('ln -sf %s/bashrc ~/.bashrc' % conf_path)
echo_exe('ln -sf %s/_emacs ~/.emacs' % conf_path)
echo_exe('ln -sf %s/vimrc ~/.vimrc' % conf_path)
echo_exe('ln -sf %s/vim ~/.vim' % conf_path)
# echo_exe('ln -sf %s/bashrc.root /root/.bashrc' % conf_path)
# echo_exe('ln -sf %s/vimrc /root/.vimrc' % conf_path)
# echo_exe('ln -sf %s/vim /root/.vim' % conf_path)
sys.stdout.flush()
def check_links():
os.system('echo Checking ...')
os.system('ls -l --color=auto ~/.bashrc')
os.system('ls -l --color=auto ~/.emacs')
os.system('ls -l --color=auto ~/.vimrc')
os.system('ls -l --color=auto ~/.vim')
# os.system('ls -l --color=auto /root/.bashrc')
#os.system('ls -l --color=auto /root/.vimrc')
#os.system('ls -l --color=auto /root/.vim')
if __name__ == '__main__':
# if not os.getuid() == 0:
# print 'Require root privilege.'
# sys.exit(1)
print 'Initializing environment ...'
create_links()
check_links()
print 'Initialized environment.'
| Python |
#!/usr/bin/env python
# @author FAN Kai (fankai@net.pku.edu.cn), Peking University
# @date |DATE|
import optparse
parser = optparse.OptionParser(usage="%prog [options] [args]")
parser.add_option('-v', '--verbose', action='store_true', dest='verbose', default=False, help='make lots of noise')
options, args = parser.parse_args()
|CURSOR|
| Python |
#!/usr/bin/env python
# @author FAN Kai (fankai@net.pku.edu.cn), Peking University
# @date |DATE|
import optparse
parser = optparse.OptionParser(usage="%prog [options] [args]")
parser.add_option('-v', '--verbose', action='store_true', dest='verbose', default=False, help='make lots of noise')
options, args = parser.parse_args()
|CURSOR|
| Python |
#!/usr/bin/env python
####
# Version: 0.2.0
# - UTF-8 filenames are now allowed (Eli Golovinsky)<br/>
# - File object is no more mandatory, Object only needs to have seek() read() attributes (Eli Golovinsky)<br/>
#
# Version: 0.1.0
# - upload is now done with chunks (Adam Ambrose)
#
# Version: older
# THANKS TO:
# bug fix: kosh @T aesaeion.com
# HTTPS support : Ryan Grow <ryangrow @T yahoo.com>
# Copyright (C) 2004,2005,2006 Fabien SEISEN
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# you can contact me at: <fabien@seisen.org>
# http://fabien.seisen.org/python/
#
# Also modified by Adam Ambrose (aambrose @T pacbell.net) to write data in
# chunks (hardcoded to CHUNK_SIZE for now), so the entire contents of the file
# don't need to be kept in memory.
#
"""
enable to upload files using multipart/form-data
idea from:
upload files in python:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146306
timeoutsocket.py: overriding Python socket API:
http://www.timo-tasi.org/python/timeoutsocket.py
http://mail.python.org/pipermail/python-announce-list/2001-December/001095.html
import urllib2_files
import urllib2
u = urllib2.urlopen('http://site.com/path' [, data])
data can be a mapping object or a sequence of two-elements tuples
(like in original urllib2.urlopen())
varname still need to be a string and
value can be string of a file object
eg:
((varname, value),
(varname2, value),
)
or
{ name: value,
name2: value2
}
"""
import os
import socket
import sys
import stat
import mimetypes
import mimetools
import httplib
import urllib
import urllib2
CHUNK_SIZE = 65536
def get_content_type(filename):
return mimetypes.guess_type(filename)[0] or 'application/octet-stream'
# if sock is None, juste return the estimate size
def send_data(v_vars, v_files, boundary, sock=None):
l = 0
for (k, v) in v_vars:
buffer=''
buffer += '--%s\r\n' % boundary
buffer += 'Content-Disposition: form-data; name="%s"\r\n' % k
buffer += '\r\n'
buffer += v + '\r\n'
if sock:
sock.send(buffer)
l += len(buffer)
for (k, v) in v_files:
fd = v
file_size = os.fstat(fd.fileno())[stat.ST_SIZE]
name = fd.name.split('/')[-1]
if isinstance(name, unicode):
name = name.encode('UTF-8')
buffer=''
buffer += '--%s\r\n' % boundary
buffer += 'Content-Disposition: form-data; name="%s"; filename="%s"\r\n' \
% (k, name)
buffer += 'Content-Type: %s\r\n' % get_content_type(name)
buffer += 'Content-Length: %s\r\n' % file_size
buffer += '\r\n'
l += len(buffer)
if sock:
sock.send(buffer)
if hasattr(fd, 'seek'):
fd.seek(0)
while True:
chunk = fd.read(CHUNK_SIZE)
if not chunk: break
sock.send(chunk)
l += file_size
buffer='\r\n'
buffer += '--%s--\r\n' % boundary
buffer += '\r\n'
if sock:
sock.send(buffer)
l += len(buffer)
return l
# mainly a copy of HTTPHandler from urllib2
class newHTTPHandler(urllib2.BaseHandler):
def http_open(self, req):
return self.do_open(httplib.HTTP, req)
def do_open(self, http_class, req):
data = req.get_data()
v_files=[]
v_vars=[]
# mapping object (dict)
if req.has_data() and type(data) != str:
if hasattr(data, 'items'):
data = data.items()
else:
try:
if len(data) and not isinstance(data[0], tuple):
raise TypeError
except TypeError:
ty, va, tb = sys.exc_info()
raise TypeError, "not a valid non-string sequence or mapping object", tb
for (k, v) in data:
if hasattr(v, 'read'):
v_files.append((k, v))
else:
v_vars.append( (k, v) )
# no file ? convert to string
if len(v_vars) > 0 and len(v_files) == 0:
data = urllib.urlencode(v_vars)
v_files=[]
v_vars=[]
host = req.get_host()
if not host:
raise urllib2.URLError('no host given')
h = http_class(host) # will parse host:port
if req.has_data():
h.putrequest('POST', req.get_selector())
if not 'Content-type' in req.headers:
if len(v_files) > 0:
boundary = mimetools.choose_boundary()
l = send_data(v_vars, v_files, boundary)
h.putheader('Content-Type',
'multipart/form-data; boundary=%s' % boundary)
h.putheader('Content-length', str(l))
else:
h.putheader('Content-type',
'application/x-www-form-urlencoded')
if not 'Content-length' in req.headers:
h.putheader('Content-length', '%d' % len(data))
else:
h.putrequest('GET', req.get_selector())
scheme, sel = urllib.splittype(req.get_selector())
sel_host, sel_path = urllib.splithost(sel)
h.putheader('Host', sel_host or host)
for name, value in self.parent.addheaders:
name = name.capitalize()
if name not in req.headers:
h.putheader(name, value)
for k, v in req.headers.items():
h.putheader(k, v)
# httplib will attempt to connect() here. be prepared
# to convert a socket error to a URLError.
try:
h.endheaders()
except socket.error, err:
raise urllib2.URLError(err)
if req.has_data():
if len(v_files) >0:
l = send_data(v_vars, v_files, boundary, h)
elif len(v_vars) > 0:
# if data is passed as dict ...
data = urllib.urlencode(v_vars)
h.send(data)
else:
# "normal" urllib2.urlopen()
h.send(data)
code, msg, hdrs = h.getreply()
fp = h.getfile()
if code == 200:
resp = urllib.addinfourl(fp, hdrs, req.get_full_url())
resp.code = code
resp.msg = msg
return resp
else:
return self.parent.error('http', req, fp, code, msg, hdrs)
urllib2._old_HTTPHandler = urllib2.HTTPHandler
urllib2.HTTPHandler = newHTTPHandler
class newHTTPSHandler(newHTTPHandler):
def https_open(self, req):
return self.do_open(httplib.HTTPS, req)
urllib2.HTTPSHandler = newHTTPSHandler
def upload(filename):
fd = open(filename, 'r')
url = "http://fankaicn.appspot.com/store"
data = { 'ufile' : fd, }
# u = urllib2.urlopen(url, data)
req = urllib2.Request(url, data, {})
try:
u = urllib2.urlopen(req)
except urllib2.HTTPError, errobj:
print "HTTPError:", errobj.code
else:
buf = u.read()
print "OK"
if __name__ == '__main__':
import sys
sys.stdout = sys.stderr
for f in sys.argv[1:]:
print "Uploading %s ..."%f,
upload(f)
| Python |
#!/usr/bin/env python
# @author FAN Kai (fankai@net.pku.edu.cn), Peking University
# @date Dec 26 10:34:01 CST 2008
import sys, os, time, getopt
usage='''Usage: repeat [INTERVAL] [COUNT] [COMMAND]
Repeat COMMAND every INTERVAL seconds up to COUNT times. '''
opts, args = getopt.getopt(sys.argv[1:], 'h')
if '-h' in dict(opts) or len(args) < 3:
print usage
sys.exit(0)
interval = int(args[0])
count = int(args[1])
cmd = ' '.join(args[2:])
try:
while count != 0:
os.system('date')
os.system(cmd)
count -= 1
time.sleep(interval)
except KeyboardInterrupt:
pass
| Python |
#!/usr/bin/env python
# @author FAN Kai, Peking University
# @date Dec 22 12:22:58 CST 2008
import re, os, time, shelve, sys, ConfigParser
def filter(cmd):
''' Filter unwanted commands. '''
for pat in filter.patterns:
if re.search(pat, cmd):
return False
return True
def sample_sys_status():
''' Sample current status of the global system. '''
try:
stats = {}
for line in open('/proc/meminfo'):
if ':' not in line: continue
words = line.split(':')
stats[words[0]] = words[1].split()[0]
for line in open('/proc/net/dev').readlines()[2:]:
if ':' not in line: continue
face = line.split(':')[0].strip()
words = line.split(':')[1].split()
stats[face + ':RB'] = words[0]
stats[face + ':RP'] = words[1]
stats[face + ':TB'] = words[8]
stats[face + ':TP'] = words[9]
for line in open('/proc/diskstats'):
words = line.split()
if len(words) < 11: continue
stats[words[2] + ':R'] = words[3]
stats[words[2] + ':RS'] = words[5]
stats[words[2] + ':RT'] = words[6]
stats[words[2] + ':W'] = words[7]
stats[words[2] + ':WS'] = words[9]
stats[words[2] + ':WT'] = words[10]
for line in open('/proc/stat'):
words = line.split()
if len(words) < 2: continue
stats[words[0]] = words[1]
stats['PR'] = stats['procs_running']
stats['loadavg'] = open('/proc/loadavg').read().split()[0]
sys_status = []
for f in sys_status_fields:
name, w = parse_field(f)
if name in stats:
sys_status.append(stats[name])
else:
sys_status.append('null')
return sys_status
except IOError:
return [0]*len(sys_status_fields)
def sample_proc_status(pdir):
''' Sample current status of process. '''
stats = {}
for line in open(pdir + '/status'):
key = line.split(':')[0]
value = line.split(':')[1].split()
if value: stats[key] = value[0]
stats['threads'] = ' '.join(os.listdir(pdir + '/task'))
stats['Command'] = open(pdir + '/cmdline').read()
proc_status = []
for f in proc_status_fields:
name, w = parse_field(f)
if name in stats:
proc_status.append(stats[name])
else:
proc_status.append('null')
return proc_status
def make_sample():
''' Sample current status of system.
Sample format:
[sys_status, proc1_info, proc2_info, ...] '''
sample = [sample_sys_status()]
for pdir in os.listdir('/proc'):
if not re.match('\d+', pdir): continue
cmd = open('/proc/' + pdir + '/cmdline').read()
if filter(cmd): continue
pinfo = sample_proc_status('/proc/' + pdir)
sample.append(pinfo)
return sample
def monitor():
''' Monitor the system. '''
while True:
conf.read(conf_files)
filter.patterns = conf.get('monitor', 'patterns').split(',')
sample_interval = conf.getfloat('monitor', 'sample_interval')
sampledb = shelve.open(dbfile)
sampledb[str(time.time())] = make_sample()
sampledb.close()
time.sleep(60 * sample_interval)
def get_samples(start, num, interval):
''' Get samples from db. '''
sampledb = shelve.open(dbfile)
keys = sampledb.keys()
keys.sort()
times = []
samples = []
print 'Got sample indexes:',
for i in range(start, start + num * interval, interval):
if i >= len(keys) or i < -len(keys): continue
print i,
times.append(keys[i])
samples.append(sampledb[keys[i]])
print
sampledb.close()
return times, samples
def parse_field(field):
name = field.split('#')[0].strip()
if len(field.split('#')) > 1:
width = int(field.split('#')[1])
else:
width = len(name)
return name, width
def format_title(fields):
''' Generate table title. '''
parts = []
for field in fields:
name, width = parse_field(field)
parts.append(name.ljust(width))
return 'Time |' + '|'.join(parts)
def format_status(fields, t, info):
''' Generate table row. '''
parts = []
timestr = time.strftime('%H:%M |', time.localtime(float(t)))
for i in range(len(fields)):
name, width = parse_field(fields[i])
parts.append(info[i].ljust(width))
return timestr + '|'.join(parts)
examples = '''Examples:
monitor.py -m -c ~/monitor.ini
Start monitoring with config in ~/monitor.ini.
monitor.py -l -c ~/monitor.ini
Show sample lists with config in ~/monitor.ini.
monitor.py -s 100
Show the 100th sample.
monitor.py -g -s -100 -n 100
Show global system information of the latest 100 samples.
monitor.py -p 12345 -s 10 -n 10 -i 10
Show information for process 12345 in sample 10, 20, ..., 100.
'''.replace('monitor.py', os.path.basename(sys.argv[0]))
import optparse
parser = optparse.OptionParser(description='Monitor the system or display monitored information.')
parser.add_option('-e', '--example', action='store_true', default=False,
help='show usage examples')
parser.add_option('-m', '--deamon', action='store_true', default=False,
help='start monitoring deamon')
parser.add_option('-c', '--conf', metavar='FILE', default='monitor.ini',
help='speicify configuration file')
parser.add_option('-l', '--list', action='store_true', default=False,
help='list all monitored samples')
parser.add_option('-s', '--start', type='int', default=-1,
help='first sample to process')
parser.add_option('-n', '--count', type='int', default=1,
help='samples count')
parser.add_option('-i', '--interval', type='int', default=-1,
help='sample interval')
parser.add_option('-p', '--pid', type='int', default='-1',
help='only display information of process with this pid')
parser.add_option('-g', '--globalonly', action='store_true', default=False,
help='only display global system information')
(opts, args) = parser.parse_args()
if opts.example:
print examples
sys.exit(0)
# Load configuration.
conf = ConfigParser.ConfigParser()
conf_files=[os.path.expanduser('~/.monitor.ini'), 'monitor.ini', opts.conf]
conf.read(conf_files)
dbfile = os.path.expanduser(conf.get('monitor', 'dbfile'))
sys_status_fields = conf.get('monitor', 'sys_status_fields').split(',')
proc_status_fields = conf.get('monitor', 'proc_status_fields').split(',')
# Begin monitoring.
if opts.deamon:
monitor()
# List samples.
if opts.list:
keys = shelve.open(dbfile).keys()
keys.sort()
interval = len(keys)>60 and 60 or 1
for i in range(0, len(keys), interval):
print 'sample %d:\t' % i, time.asctime(time.localtime(float(keys[i])))
sys.exit(0)
# Get samples from sampledb.
times, samples = get_samples(opts.start, opts.count, opts.interval)
if len(times) == 0: sys.exit(1)
# Display system information.
if opts.pid == -1:
print 'System Info(memory stats in KB):'
print format_title(sys_status_fields)
for t, sample in zip(times, samples):
print format_status(sys_status_fields, t, sample[0])
print
if not opts.globalonly:
print 'Processes(memory stats in KB):'
print format_title(proc_status_fields)
for t, sample in zip(times, samples):
for i in range(1, len(sample)):
pinfo = sample[i]
if opts.pid != -1 and pinfo[0] != opts.pid: continue
row = format_status(proc_status_fields, t, pinfo)
print row
| Python |
#!/usr/bin/env python
# @author FAN Kai (fankai@net.pku.edu.cn), Peking University
# @date Jun 12 04:30:52 PM CST 2009
import urllib, re
def gget(filename, page):
pat = "\?action=download&id=\d+&file=%s"%filename
m = re.search(pat, page)
if m:
content = urllib.urlopen(url+m.group(0)).read()
open(filename, 'wb'). write(content)
print 'ok'
else:
print 'not found'
if __name__ == "__main__":
import sys
sys.stdout = sys.stderr
url = "http://fankaicn.appspot.com/store"
f = urllib.urlopen(url)
page = f.read()
for f in sys.argv[1:]:
print "downloading %s ..."%f,
gget(f, page)
| Python |
#!/usr/bin/env python
import getopt, sys, os, time, random, shutil
usage='Usage: del [FILE] ...\nMove the FILE(s) to trash directory.'
trash_path = os.path.expanduser('~/.trash')
opts, args = getopt.getopt(sys.argv[1:], 'h')
if '-h' in dict(opts):
print usage
sys.exit(0)
if not os.path.isdir(trash_path):
print 'Initializing ~/.trash directory ...'
os.mkdir(trash_path)
timestamp = time.strftime(".%y-%m-%d-%H%M%S", time.localtime())
for file in args:
if (not os.path.exists(file)):
print file, "not exists"
continue
src = os.path.abspath(file)
dst = trash_path + '/' + os.path.basename(src) + timestamp
print "deleting %s ..." % file
#os.rename(src, dst)
shutil.move(src, dst)
| Python |
#!/usr/bin/env python
import getopt, sys, os, time, random, shutil
usage='Usage: del [FILE] ...\nMove the FILE(s) to trash directory.'
trash_path = os.path.expanduser('~/.trash')
opts, args = getopt.getopt(sys.argv[1:], 'h')
if '-h' in dict(opts):
print usage
sys.exit(0)
if not os.path.isdir(trash_path):
print 'Initializing ~/.trash directory ...'
os.mkdir(trash_path)
timestamp = time.strftime(".%y-%m-%d-%H%M%S", time.localtime())
for file in args:
if (not os.path.exists(file)):
print file, "not exists"
continue
src = os.path.abspath(file)
dst = trash_path + '/' + os.path.basename(src) + timestamp
print "deleting %s ..." % file
#os.rename(src, dst)
shutil.move(src, dst)
| Python |
#!/usr/bin/env python
####
# Version: 0.2.0
# - UTF-8 filenames are now allowed (Eli Golovinsky)<br/>
# - File object is no more mandatory, Object only needs to have seek() read() attributes (Eli Golovinsky)<br/>
#
# Version: 0.1.0
# - upload is now done with chunks (Adam Ambrose)
#
# Version: older
# THANKS TO:
# bug fix: kosh @T aesaeion.com
# HTTPS support : Ryan Grow <ryangrow @T yahoo.com>
# Copyright (C) 2004,2005,2006 Fabien SEISEN
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# you can contact me at: <fabien@seisen.org>
# http://fabien.seisen.org/python/
#
# Also modified by Adam Ambrose (aambrose @T pacbell.net) to write data in
# chunks (hardcoded to CHUNK_SIZE for now), so the entire contents of the file
# don't need to be kept in memory.
#
"""
enable to upload files using multipart/form-data
idea from:
upload files in python:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146306
timeoutsocket.py: overriding Python socket API:
http://www.timo-tasi.org/python/timeoutsocket.py
http://mail.python.org/pipermail/python-announce-list/2001-December/001095.html
import urllib2_files
import urllib2
u = urllib2.urlopen('http://site.com/path' [, data])
data can be a mapping object or a sequence of two-elements tuples
(like in original urllib2.urlopen())
varname still need to be a string and
value can be string of a file object
eg:
((varname, value),
(varname2, value),
)
or
{ name: value,
name2: value2
}
"""
import os
import socket
import sys
import stat
import mimetypes
import mimetools
import httplib
import urllib
import urllib2
CHUNK_SIZE = 65536
def get_content_type(filename):
return mimetypes.guess_type(filename)[0] or 'application/octet-stream'
# if sock is None, juste return the estimate size
def send_data(v_vars, v_files, boundary, sock=None):
l = 0
for (k, v) in v_vars:
buffer=''
buffer += '--%s\r\n' % boundary
buffer += 'Content-Disposition: form-data; name="%s"\r\n' % k
buffer += '\r\n'
buffer += v + '\r\n'
if sock:
sock.send(buffer)
l += len(buffer)
for (k, v) in v_files:
fd = v
file_size = os.fstat(fd.fileno())[stat.ST_SIZE]
name = fd.name.split('/')[-1]
if isinstance(name, unicode):
name = name.encode('UTF-8')
buffer=''
buffer += '--%s\r\n' % boundary
buffer += 'Content-Disposition: form-data; name="%s"; filename="%s"\r\n' \
% (k, name)
buffer += 'Content-Type: %s\r\n' % get_content_type(name)
buffer += 'Content-Length: %s\r\n' % file_size
buffer += '\r\n'
l += len(buffer)
if sock:
sock.send(buffer)
if hasattr(fd, 'seek'):
fd.seek(0)
while True:
chunk = fd.read(CHUNK_SIZE)
if not chunk: break
sock.send(chunk)
l += file_size
buffer='\r\n'
buffer += '--%s--\r\n' % boundary
buffer += '\r\n'
if sock:
sock.send(buffer)
l += len(buffer)
return l
# mainly a copy of HTTPHandler from urllib2
class newHTTPHandler(urllib2.BaseHandler):
def http_open(self, req):
return self.do_open(httplib.HTTP, req)
def do_open(self, http_class, req):
data = req.get_data()
v_files=[]
v_vars=[]
# mapping object (dict)
if req.has_data() and type(data) != str:
if hasattr(data, 'items'):
data = data.items()
else:
try:
if len(data) and not isinstance(data[0], tuple):
raise TypeError
except TypeError:
ty, va, tb = sys.exc_info()
raise TypeError, "not a valid non-string sequence or mapping object", tb
for (k, v) in data:
if hasattr(v, 'read'):
v_files.append((k, v))
else:
v_vars.append( (k, v) )
# no file ? convert to string
if len(v_vars) > 0 and len(v_files) == 0:
data = urllib.urlencode(v_vars)
v_files=[]
v_vars=[]
host = req.get_host()
if not host:
raise urllib2.URLError('no host given')
h = http_class(host) # will parse host:port
if req.has_data():
h.putrequest('POST', req.get_selector())
if not 'Content-type' in req.headers:
if len(v_files) > 0:
boundary = mimetools.choose_boundary()
l = send_data(v_vars, v_files, boundary)
h.putheader('Content-Type',
'multipart/form-data; boundary=%s' % boundary)
h.putheader('Content-length', str(l))
else:
h.putheader('Content-type',
'application/x-www-form-urlencoded')
if not 'Content-length' in req.headers:
h.putheader('Content-length', '%d' % len(data))
else:
h.putrequest('GET', req.get_selector())
scheme, sel = urllib.splittype(req.get_selector())
sel_host, sel_path = urllib.splithost(sel)
h.putheader('Host', sel_host or host)
for name, value in self.parent.addheaders:
name = name.capitalize()
if name not in req.headers:
h.putheader(name, value)
for k, v in req.headers.items():
h.putheader(k, v)
# httplib will attempt to connect() here. be prepared
# to convert a socket error to a URLError.
try:
h.endheaders()
except socket.error, err:
raise urllib2.URLError(err)
if req.has_data():
if len(v_files) >0:
l = send_data(v_vars, v_files, boundary, h)
elif len(v_vars) > 0:
# if data is passed as dict ...
data = urllib.urlencode(v_vars)
h.send(data)
else:
# "normal" urllib2.urlopen()
h.send(data)
code, msg, hdrs = h.getreply()
fp = h.getfile()
if code == 200:
resp = urllib.addinfourl(fp, hdrs, req.get_full_url())
resp.code = code
resp.msg = msg
return resp
else:
return self.parent.error('http', req, fp, code, msg, hdrs)
urllib2._old_HTTPHandler = urllib2.HTTPHandler
urllib2.HTTPHandler = newHTTPHandler
class newHTTPSHandler(newHTTPHandler):
def https_open(self, req):
return self.do_open(httplib.HTTPS, req)
urllib2.HTTPSHandler = newHTTPSHandler
def upload(filename):
fd = open(filename, 'r')
url = "http://fankaicn.appspot.com/store"
data = { 'ufile' : fd, }
# u = urllib2.urlopen(url, data)
req = urllib2.Request(url, data, {})
try:
u = urllib2.urlopen(req)
except urllib2.HTTPError, errobj:
print "HTTPError:", errobj.code
else:
buf = u.read()
print "OK"
if __name__ == '__main__':
import sys
sys.stdout = sys.stderr
for f in sys.argv[1:]:
print "Uploading %s ..."%f,
upload(f)
| Python |
#!/usr/bin/env python
# @author FAN Kai, Peking University
# @date Dec 22 12:22:58 CST 2008
import re, os, time, shelve, sys, ConfigParser
def filter(cmd):
''' Filter unwanted commands. '''
for pat in filter.patterns:
if re.search(pat, cmd):
return False
return True
def sample_sys_status():
''' Sample current status of the global system. '''
try:
stats = {}
for line in open('/proc/meminfo'):
if ':' not in line: continue
words = line.split(':')
stats[words[0]] = words[1].split()[0]
for line in open('/proc/net/dev').readlines()[2:]:
if ':' not in line: continue
face = line.split(':')[0].strip()
words = line.split(':')[1].split()
stats[face + ':RB'] = words[0]
stats[face + ':RP'] = words[1]
stats[face + ':TB'] = words[8]
stats[face + ':TP'] = words[9]
for line in open('/proc/diskstats'):
words = line.split()
if len(words) < 11: continue
stats[words[2] + ':R'] = words[3]
stats[words[2] + ':RS'] = words[5]
stats[words[2] + ':RT'] = words[6]
stats[words[2] + ':W'] = words[7]
stats[words[2] + ':WS'] = words[9]
stats[words[2] + ':WT'] = words[10]
for line in open('/proc/stat'):
words = line.split()
if len(words) < 2: continue
stats[words[0]] = words[1]
stats['PR'] = stats['procs_running']
stats['loadavg'] = open('/proc/loadavg').read().split()[0]
sys_status = []
for f in sys_status_fields:
name, w = parse_field(f)
if name in stats:
sys_status.append(stats[name])
else:
sys_status.append('null')
return sys_status
except IOError:
return [0]*len(sys_status_fields)
def sample_proc_status(pdir):
''' Sample current status of process. '''
stats = {}
for line in open(pdir + '/status'):
key = line.split(':')[0]
value = line.split(':')[1].split()
if value: stats[key] = value[0]
stats['threads'] = ' '.join(os.listdir(pdir + '/task'))
stats['Command'] = open(pdir + '/cmdline').read()
proc_status = []
for f in proc_status_fields:
name, w = parse_field(f)
if name in stats:
proc_status.append(stats[name])
else:
proc_status.append('null')
return proc_status
def make_sample():
''' Sample current status of system.
Sample format:
[sys_status, proc1_info, proc2_info, ...] '''
sample = [sample_sys_status()]
for pdir in os.listdir('/proc'):
if not re.match('\d+', pdir): continue
cmd = open('/proc/' + pdir + '/cmdline').read()
if filter(cmd): continue
pinfo = sample_proc_status('/proc/' + pdir)
sample.append(pinfo)
return sample
def monitor():
''' Monitor the system. '''
while True:
conf.read(conf_files)
filter.patterns = conf.get('monitor', 'patterns').split(',')
sample_interval = conf.getfloat('monitor', 'sample_interval')
sampledb = shelve.open(dbfile)
sampledb[str(time.time())] = make_sample()
sampledb.close()
time.sleep(60 * sample_interval)
def get_samples(start, num, interval):
''' Get samples from db. '''
sampledb = shelve.open(dbfile)
keys = sampledb.keys()
keys.sort()
times = []
samples = []
print 'Got sample indexes:',
for i in range(start, start + num * interval, interval):
if i >= len(keys) or i < -len(keys): continue
print i,
times.append(keys[i])
samples.append(sampledb[keys[i]])
print
sampledb.close()
return times, samples
def parse_field(field):
name = field.split('#')[0].strip()
if len(field.split('#')) > 1:
width = int(field.split('#')[1])
else:
width = len(name)
return name, width
def format_title(fields):
''' Generate table title. '''
parts = []
for field in fields:
name, width = parse_field(field)
parts.append(name.ljust(width))
return 'Time |' + '|'.join(parts)
def format_status(fields, t, info):
''' Generate table row. '''
parts = []
timestr = time.strftime('%H:%M |', time.localtime(float(t)))
for i in range(len(fields)):
name, width = parse_field(fields[i])
parts.append(info[i].ljust(width))
return timestr + '|'.join(parts)
examples = '''Examples:
monitor.py -m -c ~/monitor.ini
Start monitoring with config in ~/monitor.ini.
monitor.py -l -c ~/monitor.ini
Show sample lists with config in ~/monitor.ini.
monitor.py -s 100
Show the 100th sample.
monitor.py -g -s -100 -n 100
Show global system information of the latest 100 samples.
monitor.py -p 12345 -s 10 -n 10 -i 10
Show information for process 12345 in sample 10, 20, ..., 100.
'''.replace('monitor.py', os.path.basename(sys.argv[0]))
import optparse
parser = optparse.OptionParser(description='Monitor the system or display monitored information.')
parser.add_option('-e', '--example', action='store_true', default=False,
help='show usage examples')
parser.add_option('-m', '--deamon', action='store_true', default=False,
help='start monitoring deamon')
parser.add_option('-c', '--conf', metavar='FILE', default='monitor.ini',
help='speicify configuration file')
parser.add_option('-l', '--list', action='store_true', default=False,
help='list all monitored samples')
parser.add_option('-s', '--start', type='int', default=-1,
help='first sample to process')
parser.add_option('-n', '--count', type='int', default=1,
help='samples count')
parser.add_option('-i', '--interval', type='int', default=-1,
help='sample interval')
parser.add_option('-p', '--pid', type='int', default='-1',
help='only display information of process with this pid')
parser.add_option('-g', '--globalonly', action='store_true', default=False,
help='only display global system information')
(opts, args) = parser.parse_args()
if opts.example:
print examples
sys.exit(0)
# Load configuration.
conf = ConfigParser.ConfigParser()
conf_files=[os.path.expanduser('~/.monitor.ini'), 'monitor.ini', opts.conf]
conf.read(conf_files)
dbfile = os.path.expanduser(conf.get('monitor', 'dbfile'))
sys_status_fields = conf.get('monitor', 'sys_status_fields').split(',')
proc_status_fields = conf.get('monitor', 'proc_status_fields').split(',')
# Begin monitoring.
if opts.deamon:
monitor()
# List samples.
if opts.list:
keys = shelve.open(dbfile).keys()
keys.sort()
interval = len(keys)>60 and 60 or 1
for i in range(0, len(keys), interval):
print 'sample %d:\t' % i, time.asctime(time.localtime(float(keys[i])))
sys.exit(0)
# Get samples from sampledb.
times, samples = get_samples(opts.start, opts.count, opts.interval)
if len(times) == 0: sys.exit(1)
# Display system information.
if opts.pid == -1:
print 'System Info(memory stats in KB):'
print format_title(sys_status_fields)
for t, sample in zip(times, samples):
print format_status(sys_status_fields, t, sample[0])
print
if not opts.globalonly:
print 'Processes(memory stats in KB):'
print format_title(proc_status_fields)
for t, sample in zip(times, samples):
for i in range(1, len(sample)):
pinfo = sample[i]
if opts.pid != -1 and pinfo[0] != opts.pid: continue
row = format_status(proc_status_fields, t, pinfo)
print row
| Python |
#!/usr/bin/env python
# @author FAN Kai (fankai@net.pku.edu.cn), Peking University
# @date Jun 12 04:30:52 PM CST 2009
import urllib, re
def gget(filename, page):
pat = "\?action=download&id=\d+&file=%s"%filename
m = re.search(pat, page)
if m:
content = urllib.urlopen(url+m.group(0)).read()
open(filename, 'wb'). write(content)
print 'ok'
else:
print 'not found'
if __name__ == "__main__":
import sys
sys.stdout = sys.stderr
url = "http://fankaicn.appspot.com/store"
f = urllib.urlopen(url)
page = f.read()
for f in sys.argv[1:]:
print "downloading %s ..."%f,
gget(f, page)
| Python |
#!/usr/bin/env python
# @author FAN Kai (fankai@net.pku.edu.cn), Peking University
# @date Dec 26 10:34:01 CST 2008
import sys, os, time, getopt
usage='''Usage: repeat [INTERVAL] [COUNT] [COMMAND]
Repeat COMMAND every INTERVAL seconds up to COUNT times. '''
opts, args = getopt.getopt(sys.argv[1:], 'h')
if '-h' in dict(opts) or len(args) < 3:
print usage
sys.exit(0)
interval = int(args[0])
count = int(args[1])
cmd = ' '.join(args[2:])
try:
while count != 0:
os.system('date')
os.system(cmd)
count -= 1
time.sleep(interval)
except KeyboardInterrupt:
pass
| Python |
import cgi
import datetime
import urllib
import webapp2
from google.appengine.ext import db
from google.appengine.api import users
class NoteEntry(db.Model):
date = db.DateTimeProperty(auto_now_add=True)
content = db.StringProperty(multiline=True)
def notekey():
return db.Key.from_path('user', str(users.get_current_user()))
class MainPage(webapp2.RequestHandler):
def get(self):
self.response.out.write('<html><body>')
self.response.out.write("""
<form action="/note" method="post">
<div><textarea name="content" rows="3" cols="40"></textarea></div>
<div><input type="submit" value="Note"></div>
</form>
<hr>""")
entries = db.GqlQuery("SELECT * "
"FROM NoteEntry "
"WHERE ANCESTOR IS :1 "
"ORDER BY date DESC",
db.Key.from_path('user', str(users.get_current_user())))
for entry in entries:
self.response.out.write('<b>%s</b> ' % str(entry.date)[:19])
self.response.out.write(cgi.escape(entry.content))
self.response.out.write('<br/>\n')
self.response.out.write("""
</body>
</html>""")
def post(self):
entry = NoteEntry(parent=notekey())
entry.content = self.request.get('content')
entry.put()
self.redirect('/note')
app = webapp2.WSGIApplication([('/', MainPage),
('/note', MainPage)],
debug=True)
| Python |
#!/usr/bin/python2
import fileinput
import re
collapsed = {}
def remember_stack (stack, count):
global collapsed
if stack in collapsed.keys():
collapsed[stack] = int(collapsed[stack]) + int(count)
else:
collapsed[stack] = int(count)
def matches (rexp, line):
match = re.search(rexp, line)
if match is not None:
return True
return False
stack = []
for line in fileinput.input():
line = line.rstrip()
match = re.match(r'^\s*(\d+)+$', line) # search?
if match is not None:
remember_stack(";".join(stack), match.group(1))
del stack[:]
continue
if matches("^\s*$", line):
continue
line = re.sub(r'^\s*','', line)
line = re.sub(r'\+[^+]*$', '', line)
line = re.sub(r'.* : ', '', line)
if line == "": # not line?
line = "-"
stack = [line] + stack
for k in sorted(collapsed.keys()):
print k, collapsed[k]
| Python |
#!/usr/bin/python2
import fileinput
import re
collapsed = {}
def remember_stack (stack, count):
global collapsed
if stack in collapsed.keys():
collapsed[stack] = int(collapsed[stack]) + int(count)
else:
collapsed[stack] = int(count)
def matches (rexp, line):
match = re.search(rexp, line)
if match is not None:
return True
return False
stack = []
for line in fileinput.input():
if matches("^#", line):
continue
line = line.rstrip()
if matches("^$", line):
if len(stack) != 0:
remember_stack(";".join(stack), 1)
del stack[:]
continue
# Note the details skipped below, and customize as desired
if matches(":.*:", line):
continue # skip summary lines
match = re.match("\s*\w+ (\w+) (\S+)", line)
if match is not None:
(func, mod) = (match.group(1), match.group(2))
if matches("\(", func):
continue # skip process names
if not matches("kernel", mod):
continue # skip non-kernel
stack = [func] + stack
for k in sorted(collapsed.keys()):
print k, collapsed[k]
| Python |
#!/usr/bin/python2
import argparse
import fileinput
import re
import sys
import random
from pprint import pprint
# tunables
timemax = None # (override the) sum of the counts
parser = argparse.ArgumentParser()
parser.add_argument("-f", "--fonttype", help="font type (default \"Verdana\")", action="store", default="Verdana")
parser.add_argument("-w", "--width", help="width of image (default 1200)", action="store", default=1200)
parser.add_argument("-H", "--height", help="height of each frame (default 16)", action="store", default=16)
parser.add_argument("-s", "--fontsize", help="font size (default 12)", action="store", default=12)
parser.add_argument("-i", "--fontwidth", help="font width (default 0.55)", action="store", default=0.55)
parser.add_argument("-m", "--minwidth", help="omit smaller functions (default 0.1 pixels)", action="store", default=0.1)
parser.add_argument("-t", "--titletext", help="change title text", action="store", default="Flame Graph")
parser.add_argument("-n", "--nametype", help="name type label (default \"Function:\")", action="store", default="Function:")
parser.add_argument("-c", "--countname", help="count type label (default \"samples\")", action="store", default="samples")
parser.add_argument("-a", "--nameattrfile", help="file holding function attributes", action="store", default="")
parser.add_argument("-o", "--factor", help="factor to scale counts by", action="store", default=1)
args = parser.parse_args()
fonttype = args.fonttype
imagewidth = args.width
frameheight = args.height
fontsize = args.fontsize
fontwidth = args.fontwidth
minwidth = args.minwidth
titletext = args.titletext
nametype = args.nametype
countname = args.countname
nameattrfile = args.nameattrfile
factor = args.factor
# internals
ypad1 = fontsize * 4 # pad top, include title
ypad2 = fontsize * 2 + 10 # pad bottom, include labels
xpad = 10 # pad lefm and right
depthmax = 0
Events = None
nameattr = {}
if nameattrfile != "":
# The name-attribute file format is a function name followed by a tab then
# a sequence of tab separated name=value pairs.
for line in open(nameattrfile):
line = line.rstrip()
(funcname, attrstr) = line.strip()
if attrstr == "":
print "Invalid format in", nameattrfile
exit(1)
nameattr[funcname] = [l.strip('\t') for l in line.strip('=')[:2]] # XXX
class SVG:
svgstring = ""
def __init__(self):
pass
def header(self, w, h):
self.svgstring += '<?xml version="1.0" standalone="no"?>'\
'<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">'\
'<svg version="1.1" width="' + str(w) + '" height="' + str(h) + '" onload="init(evt)" viewBox="0 0 ' + str(w) + ' ' + str(h) + '" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">'
def include(self, content):
self.svgstring += str(content)
def colorAllocate(self, r, g, b):
return 'rgb(' + str(r) + ',' + str(g) + ',' + str(b) + ')'
def group_start(self, attr):
g_attr = []
for (key, value) in attr.iteritems():
if key != "title":
g_attr.append('%s="%s"' % (key, value))
if "g_extra" in attr.keys():
g_attr.append(attr["g_extra"])
self.svgstring += "<g %s>\n" % ' '.join(g_attr)
if "title" in attr.keys():
self.svgstring += "<title>%s</title>" % attr["title"] # should be first element within g container
if "href" in attr.keys():
a_attr = "xlink:href=\"%s\"" % attr["href"]
# default target=_top else links will open within SVG <object>
if "target" in attr.keys():
a_attr.append("target=\"%s\"" % attr["target"])
else:
a_attr.append("target=\"_top\"")
if "a_extra" in attr.keys():
a_attr.append(attr["a_extra"])
self.svgstring += "<a %s>" % ' '.join(a_attr)
def group_end(self, attr):
if "href" in attr.keys():
self.svgstring += "</a>\n"
self.svgstring += "</g>\n"
def filledRectangle(self, x1, y1, x2, y2, fill, extra):
x1 = "%0.1f" % x1
x2 = "%0.1f" % x2
w = ("%0.1f" % (float(x2) - float(x1)))
h = ("%0.1f" % (float(y2) - float(y1)))
if extra == None:
extra = ""
self.svgstring += '<rect x="' + str(x1) + '" y="' + str(y1) + '" width="' + str(w) + '" height="' + str(h) + '" fill="' + str(fill) + '" ' + str(extra) + '/>\n'
def stringTTF(self, color, font, size, angle, x, y, st, loc, extra):
if loc == None:
loc = "left"
if extra == None:
extra = ""
self.svgstring += '<text text-anchor="' + str(loc) + '" x="' + str(x) + '" y="' + str(y) + '" font-size="' + str(size) + '" font-family="' + str(font) + '" fill="' + str(color) + '" ' + str(extra) + '>' + str(st) + '</text>\n'
def svg(self):
return self.svgstring + "</svg>\n"
def color(ty):
if ty == "hot":
r = 205 + int(random.randrange(0,50))
g = 0 + int(random.randrange(0,230))
b = 0 + int(random.randrange(0,55))
return "rgb(" + str(r) + "," + str(g) + "," + str(b) + ")"
return "rgb(0,0,0)"
Node = {}
Tmp = {}
def flow(last, this, v):
global Node
global Tmp
len_a = len(last) - 1
len_b = len(this) - 1
i = 0
while i <= len_a:
if i > len_b:
break
if last[i] != this[i]:
break
i += 1
len_same = i
i = len_a
while i >= len_same:
k = str(last[i]) + ";" + str(i)
# a unique ID is constructed from "func;depth;etime";
# func-depth isn't unique, it may be repeated later.
Node[str(k) + ";" + str(v)] = {}
Node[str(k) + ";" + str(v)]["stime"] = Tmp[k]["stime"]
del Tmp[str(k)]["stime"]
del Tmp[str(k)]
i -= 1
i = len_same
while i <= len_b:
k = this[i] + ";" + str(i)
Tmp[k] = {}
Tmp[k]["stime"] = v
i += 1
return this
last = []
time = 0
ignored = 0
Data = fileinput.input()
for line in sorted(Data):
line = line.rstrip()
match = re.match(r"^(.*)\s+(\d+(?:\.\d*)?)$", str(line))
if match is not None:
(stack, samples) = (match.group(1), match.group(2))
else:
(stack, samples) = (None, None)
if samples == None:
ignored += 1
continue
stack = stack.replace('(', '<')
stack = stack.replace(')', '>')
splitted = stack.split(';')
if splitted == ['']:
splitted = []
last = flow(last, [''] + splitted, time)
time += int(samples)
flow(last, [], time)
if ignored > 0:
print >> sys.stderr, "Ignored %d lines with invalid format\n" % ignored
if time == 0:
print "ERROR: No stack counts found\n"
exit(1)
if timemax != None:
if timemax < time:
if timemax/time > 0.02: # only warn is significant (e.g., not rounding etc)
print "Specified --total %d is less than actual total %d, so ignored\n" % (timemax, time)
timemax = None
if timemax == None:
timemax = time
widthpertime = float(imagewidth - 2 * xpad) / float(timemax)
minwidth_time = minwidth / widthpertime
# prune blocks that are too narrow and determine max depth
for (id, node) in Node.iteritems():
(func, depth, etime) = id.split(';')
stime = node["stime"]
if stime == None:
print "missing start for %s" % str(id)
if (float(etime) - float(stime)) < float(minwidth_time):
del Node[id]
continue
if int(depth) > int(depthmax):
depthmax = int(depth)
# Draw canvas
imageheight = (float(depthmax) * float(frameheight)) + float(ypad1) + float(ypad2)
im = SVG()
im.header(imagewidth, imageheight)
inc = """<defs >
<linearGradient id="background" y1="0" y2="1" x1="0" x2="0" >
<stop stop-color="#eeeeee" offset="5%" />
<stop stop-color="#eeeeb0" offset="95%" />
</linearGradient>
</defs>
<style type="text/css">
.func_g:hover { stroke:black; stroke-width:0.5; }
</style>
<script type="text/ecmascript">
<![CDATA[
var details;
function init(evt) { details = document.getElementById("details").firstChild; }
function s(info) { details.nodeValue = " """ + str(nametype) + """ " + info; }
function c() { details.nodeValue = ' '; }
]]>
</script>"""
im.include(inc);
im.filledRectangle(0, 0, float(imagewidth), float(imageheight), 'url(#background)', "")
(white, black, vvdgrey, vdgrey) = (
im.colorAllocate(255, 255, 255),
im.colorAllocate(0, 0, 0),
im.colorAllocate(40, 40, 40),
im.colorAllocate(160, 160, 160),
)
im.stringTTF(black, fonttype, fontsize + 5, 0.0, int(imagewidth / 2), fontsize * 2, titletext, "middle", "")
im.stringTTF(black, fonttype, fontsize, 0.0, xpad, imageheight - (ypad2 / 2), " ", "", 'id="details"')
# Draw frames
nameattr = {}
for (id, node) in Node.iteritems():
(func, depth, etime) = id.split(';')
stime = node["stime"]
if func == "" and depth == 0:
etime = timemax
x1 = float(xpad) + float(stime) * float(widthpertime)
x2 = float(xpad) + float(etime) * float(widthpertime)
y1 = float(imageheight) - float(ypad2) - (float(depth) + 1) * float(frameheight) + 1
y2 = float(imageheight) - float(ypad2) - float(depth) * float(frameheight)
samples = (float(etime) - float(stime)) * float(factor)
samples_txt = samples # add commas per perlfaq5
rx = re.compile(r'(^[-+]?\d+?(?=((?:\d{3})+)(?!\d))|\G\d{3}(?=\d))')
samples_txt = rx.sub(r'\g<1>,', str(samples_txt))
if (func == "") and (depth == 0):
info = "all (" + samples_txt + " " + countname + ", 100%)"
else:
pct = "%.2f" % ((100 * samples) / (timemax * factor))
escaped_func = func
escaped_func = re.sub("&", "&", escaped_func)
escaped_func = re.sub("<", "<", escaped_func)
escaped_func = re.sub(">", ">", escaped_func)
info = escaped_func + " (" + samples_txt + " " + countname + ", " + pct + "%)"
if func not in nameattr.keys():
nameattr[func] = {}
if "class" not in nameattr[func].keys():
nameattr[func]["class"] = "func_g"
if "onmouseover" not in nameattr[func].keys():
nameattr[func]["onmouseover"] = "s('" + info + "')"
if "onmouseout" not in nameattr[func].keys():
nameattr[func]["onmouseout"] = "c()"
if "title" not in nameattr[func].keys():
nameattr[func]["title"] = info
im.group_start(nameattr[func])
im.filledRectangle(float(x1), float(y1), float(x2), float(y2), color("hot"), 'rx="2" ry="2"')
chars = int((x2 - x1) / (fontsize * fontwidth))
if chars >= 3: # print something only if there is room for 3 characters
text = func[:chars]
if chars < len(func):
tex = list(text)[:-3]
text = ''.join(tex) + ".."
text = re.sub("&", "&", text)
text = re.sub("<", "<", text)
text = re.sub(">", ">", text)
im.stringTTF(black, fonttype, fontsize, 0.0, x1 + 3, 3 + (y1 + y2) / 2, text, None, None)
im.group_end(nameattr[func])
print im.svg()
| Python |
# -*- coding: utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf8')
import string
import cgi
import urllib
from sgmllib import SGMLParser, SGMLParseError
from google.appengine.api import urlfetch
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
appmainurl = u"http://mapps.renren.com"
loginurl = u"http://3g.renren.com/login.do?fx=0&autoLogin=true"
proxyurl = u""
form_fields = {
# "uid": u"",
# "url": u"",
"origURL": u"/home.do",
"email": u"",
"password": u"",
"login": u""
}
form_fields_get = {
"uid": u"",
"url": u"",
}
retrymax = 20
class PageHTMLParser(SGMLParser):
def __init__(self):
SGMLParser.__init__(self)
self.links = []
self.datasets = []
self.matchcheck = 0
self.eigentag = ''
self.eigenname = ''
self.eigendata = ''
self.dupcounter = 0
def handle_data(self, text):
txt = text.strip()
if txt.find(self.eigendata) != -1:
self.matchcheck = 1
self.datasets.append(txt)
def start_a(self, attr):
self.links += [v for k, v in attr if k == "href"]
def end_a(self):
if self.matchcheck == 1:
self.matchcheck = 0
else:
self.links.pop()
self.dupcounter += 1
class HTMLInputParser(SGMLParser):
def __init__(self):
SGMLParser.__init__(self)
self.linksnames = []
self.linksvalues = []
self.pairs = 0
def start_input(self, attr):
self.linksnames += [v for k, v in attr if k == 'name']
self.linksvalues += [v for k, v in attr if k == 'value']
self.pairs += 1
useremail = u''
userpasswords = u''
useruid = u'1'
class SetAcount(webapp.RequestHandler):
def ReapPlants(self, loginuser, passwords, helper = ''):
# self.response.out.write(u'<html><meta http-equiv="content-type" content="text/html; charset=UTF-8"><body><pre>你输入的用户名是:<br />')
# self.response.out.write(loginuser.decode('utf-8'))
# self.response.out.write(u'<br />你输入的密码是:<br />')
# self.response.out.write(passwords.decode('utf-8'))
# self.response.out.write(u'<br />')
# self.response.out.write(u'</pre>')
# form_fields['uid'] = useruid.encode('utf-8')
# form_fields['url'] = loginurl.encode('utf-8')
form_fields['login'] = u'登录'
form_fields['password'] = passwords
form_fields['email'] = loginuser
form_data = urllib.urlencode(form_fields)
result = urlfetch.fetch(url=loginurl, payload=form_data, method=urlfetch.POST, headers={'Content-Type': 'application/x-www-form-urlencoded','User-Agent':'Mozilla/5.0 (SymbianOS/9.4; Series60/5.0 Nokia5800 XpressMusic-1/50.0.5; Profile/MIDP-2.1 Configuration/CLDC-1.1; en-us) AppleWebKit/525 (KHTML, like Gecko) WicKed/7.1.123'}, allow_truncated=True)
success = 0
retrycounter = 0
while (success == 0 or success == 1) and retrycounter < retrymax and result.content.find('帐号和密码不匹配') != -1:
try:
retrycounter += 1
result = urlfetch.fetch(url=loginurl, payload=form_data, method=urlfetch.POST, headers={'Content-Type': 'application/x-www-form-urlencoded'}, allow_truncated=True, deadline=30)
except:
success = 1
if success == 0:
success = 2
else:
success = 0
if success != 2:
self.response.out.write(success)
# return
# self.response.out.write(result.content.decode('utf-8'))
hp = PageHTMLParser()
hp.eigentag = 'a'
hp.eigenname = 'href'
hp.eigendata = '应用'
hp.feed(result.content)
hp.close
# self.response.out.write(hp.links)
# inurl = proxyurl + 'uid=' + useruid + '&url=' + hp.links[0];
success = 0
retrycounter = 0
while (success == 0 or success == 1) and retrycounter < retrymax:
try:
retrycounter += 1
result = urlfetch.fetch(url=hp.links[0], payload=[], method=urlfetch.GET, allow_truncated=True, deadline=30)
except:
success = 1
if success == 0:
success = 2
else:
success = 0
if success != 2:
self.response.out.write(success)
# return
# self.response.out.write(result.content.decode('utf-8'))
hp = PageHTMLParser()
hp.eigentag = 'a'
hp.eigenname = 'href'
hp.eigendata = '人人农场'
hp.feed(result.content)
hp.close
# form_fields_get['url'] = hp.links[0].encode('utf-8')
# form_data = urllib.urlencode(form_fields_get)
success = 0
retrycounter = 0
while (success == 0 or success == 1) and retrycounter < retrymax:
try:
retrycounter += 1
result = urlfetch.fetch(url=hp.links[0], payload=[], method=urlfetch.GET, allow_truncated=True, deadline=30)
except:
success = 1
if success == 0:
success = 2
else:
success = 0
if success != 2:
self.response.out.write(success)
# return
# self.response.out.write(result.content.decode('utf-8'))
if result.content.find('第三方应用\"人人农场\"发生错误') != -1:
self.response.out.write(result.content.decode('utf-8'))
return
cropurl = appmainurl + result.content[result.content.find('/rr_farm/farm/action/wap,myCropAction'):result.content.find('\">【农田】')]
treeurl = appmainurl + result.content[result.content.find('/rr_farm/farm/action/wap,myTreeAction'):result.content.find('\">【果树】')]
animalurl = appmainurl + result.content[result.content.find('/rr_farm/farm/action/wap,myAnimalAction'):result.content.find('\">【畜牧】')]
machineurl = appmainurl + result.content[result.content.find('/rr_farm/farm/action/wap,myMachineAction'):result.content.find('\">【机械】')]
friendurl = appmainurl + result.content[result.content.find('/rr_farm/farm/action/wap,myFriendsListAction'):result.content.find('\">【好友农场】')]
if result.content.find('【农田】★') != -1:
resultcrop = urlfetch.fetch(url=proxyurl + cropurl, payload=[], method=urlfetch.GET, allow_truncated=True, deadline=30)
if resultcrop.content.find('收获全部农产品') != -1:
reapallcropurl = appmainurl + resultcrop.content[resultcrop.content.find('/rr_farm/farm/action/wap,reapAllAction'):resultcrop.content.find('\">收获全部农产品')]
urlfetch.fetch(url=proxyurl + reapallcropurl, payload=[], method=urlfetch.GET, allow_truncated=True, deadline=30)
# self.response.out.write(result.content.decode('utf-8'))
if result.content.find('【果树】★') != -1:
resulttree = urlfetch.fetch(url=proxyurl + treeurl, payload=[], method=urlfetch.GET, allow_truncated=True, deadline=30)
if resulttree.content.find('收获全部果树产品') != -1:
reapalltreeurl = appmainurl + resulttree.content[resulttree.content.find('/rr_farm/farm/action/wap,reapAllAction'):resulttree.content.find('\">收获全部果树产品')]
urlfetch.fetch(url=proxyurl + reapalltreeurl, payload=[], method=urlfetch.GET, allow_truncated=True, deadline=30)
# self.response.out.write(result.content.decode('utf-8'))
if result.content.find('【畜牧】★') != -1:
resultanimal = urlfetch.fetch(url=proxyurl + animalurl, payload=[], method=urlfetch.GET, allow_truncated=True, deadline=30)
resultanimal2 = urlfetch.fetch(url=proxyurl + animalurl + "&curpage=1", payload=[], method=urlfetch.GET, allow_truncated=True, deadline=30)
if resultanimal.content.find('收获全部畜牧产品') != -1:
reapallanimalurl = appmainurl + resultanimal.content[resultanimal.content.find('/rr_farm/farm/action/wap,reapAllAction'):resultanimal.content.find('\">收获全部畜牧产品')]
reapallresult = urlfetch.fetch(url=proxyurl + reapallanimalurl, payload=[], method=urlfetch.GET, allow_truncated=True, deadline=30)
# self.response.out.write(reapallresult.content.decode('utf-8'))
if helper == '':
if resultanimal.content.find('喂食') != -1:
animalresultstr = resultanimal.content[resultanimal.content.find('/rr_farm/farm/action/wap,feedAction'):]
feedurls = []
# self.response.out.write(helperanimalresultstr)
while animalresultstr.find('喂食') != -1:
feedurls.append(appmainurl + animalresultstr[animalresultstr.find('/rr_farm/farm/action/wap,feedAction'):animalresultstr.find('\" class=\"blue\">喂食')])
animalresultstr = animalresultstr[animalresultstr.find('喂食'):]
animalresultstr = animalresultstr[animalresultstr.find('食'):]
for j in range(0, len(feedurls)):
feedurl = feedurls[j]
feedpage = urlfetch.fetch(url=feedurl, payload=[], method=urlfetch.GET, allow_truncated=True, deadline=30)
feedposturl = appmainurl + feedpage.content[feedpage.content.find('/rr_farm/farm/action/wap,feedAction'):feedpage.content.find('\"><input type=\"hidden\" name=\"sid\"')]
leftstr = feedpage.content[feedpage.content.find('【仓库剩余】 '):]
leftstr = leftstr[leftstr.find(';') + 1:leftstr.find('<br/>')]
left = int(leftstr)
# self.response.out.write(leftstr)
hp = HTMLInputParser()
hp.feed(feedpage.content)
hp.close
feedform = {}
for i in range(0, hp.pairs):
feedform[hp.linksnames[i]] = hp.linksvalues[i].encode('utf-8')
feednum = int(feedform['pc'])
# self.response.out.write(feednum)
if left < feednum:
continue
if feedform.has_key('submit1'):
pass
else:
feedform['submit1'] = u'确 定'.encode('utf-8')
feedform_data = urllib.urlencode(feedform)
self.response.out.write(feedform)
self.response.out.write('<br />')
self.response.out.write(feedposturl)
self.response.out.write('<br />')
self.response.out.write('<br />')
self.response.out.write(hp.linksnames)
self.response.out.write('<br />')
self.response.out.write(hp.linksvalues)
feedresult = urlfetch.fetch(url=feedposturl, payload=feedform_data, method=urlfetch.POST, headers={'Content-Type': 'application/x-www-form-urlencoded'}, allow_truncated=True, deadline=30)
self.response.out.write(feedresult.content)
if resultanimal2.content.find('喂食') != -1:
animalresultstr = resultanimal2.content[resultanimal.content.find('/rr_farm/farm/action/wap,feedAction'):]
feedurls = []
# self.response.out.write(helperanimalresultstr)
while animalresultstr.find('喂食') != -1:
feedurls.append(appmainurl + animalresultstr[animalresultstr.find('/rr_farm/farm/action/wap,feedAction'):animalresultstr.find('\" class=\"blue\">喂食')])
animalresultstr = animalresultstr[animalresultstr.find('喂食'):]
animalresultstr = animalresultstr[animalresultstr.find('食'):]
for j in range(0, len(feedurls)):
feedurl = feedurls[j]
feedpage = urlfetch.fetch(url=feedurl, payload=[], method=urlfetch.GET, allow_truncated=True, deadline=30)
feedposturl = appmainurl + feedpage.content[feedpage.content.find('/rr_farm/farm/action/wap,feedAction'):feedpage.content.find('\"><input type=\"hidden\" name=\"sid\"')]
leftstr = feedpage.content[feedpage.content.find('【仓库剩余】 '):]
leftstr = leftstr[leftstr.find(';') + 1:leftstr.find('<br/>')]
left = int(leftstr)
# self.response.out.write(leftstr)
hp = HTMLInputParser()
hp.feed(feedpage.content)
hp.close
feedform = {}
for i in range(0, hp.pairs):
feedform[hp.linksnames[i]] = hp.linksvalues[i].encode('utf-8')
feednum = int(feedform['pc'])
# self.response.out.write(feednum)
if left < feednum:
continue
if feedform.has_key('submit1'):
pass
else:
feedform['submit1'] = u'确 定'.encode('utf-8')
feedform_data = urllib.urlencode(feedform)
self.response.out.write(feedform)
self.response.out.write('<br />')
self.response.out.write(feedposturl)
self.response.out.write('<br />')
self.response.out.write('<br />')
self.response.out.write(hp.linksnames)
self.response.out.write('<br />')
self.response.out.write(hp.linksvalues)
feedresult = urlfetch.fetch(url=feedposturl, payload=feedform_data, method=urlfetch.POST, headers={'Content-Type': 'application/x-www-form-urlencoded'}, allow_truncated=True, deadline=30)
self.response.out.write(feedresult.content)
if result.content.find('【机械】★') != -1:
resultmachine = urlfetch.fetch(url=proxyurl + machineurl, payload=[], method=urlfetch.GET, allow_truncated=True, deadline=30)
resultmachine2 = urlfetch.fetch(url=proxyurl + machineurl + "&curpage=1", payload=[], method=urlfetch.GET, allow_truncated=True, deadline=30)
if resultmachine.content.find('收获全部加工产品') != -1:
reapallmachineurl = appmainurl + resultmachine.content[resultmachine.content.find('/rr_farm/farm/action/wap,reapAllAction'):resultmachine.content.find('\">收获全部加工产品')]
reapallresult = urlfetch.fetch(url=proxyurl + reapallmachineurl, payload=[], method=urlfetch.GET, allow_truncated=True, deadline=30)
# self.response.out.write(reapallresult.content.decode('utf-8'))
if helper == '':
if resultmachine.content.find('添加') != -1:
machineresultstr = resultmachine.content[resultmachine.content.find('/rr_farm/farm/action/wap,feedAction'):]
feedurls = []
while machineresultstr.find('添加') != -1:
if machineresultstr.find('\" class=\"blue\">添加') != -1:
urltmp = appmainurl + machineresultstr[machineresultstr.find('/rr_farm/farm/action/wap,feedAction'):machineresultstr.find('\" class=\"blue\">添加')]
else:
urltmp = appmainurl + machineresultstr[machineresultstr.find('/rr_farm/farm/action/wap,feedAction'):machineresultstr.find('\">添加')]
feedurls.append(urltmp)
machineresultstr = machineresultstr[machineresultstr.find('添加'):]
machineresultstr = machineresultstr[machineresultstr.find('加'):]
# self.response.out.write(feedurls)
for j in range(0, len(feedurls)):
feedurl = feedurls[j]
feedpage = urlfetch.fetch(url=feedurl, payload=[], method=urlfetch.GET, allow_truncated=True, deadline=30)
feedposturl = appmainurl + feedpage.content[feedpage.content.find('/rr_farm/farm/action/wap,feedAction'):feedpage.content.find('\"><input type=\"hidden\" name=\"sid\"')]
leftstr = feedpage.content[feedpage.content.find('【仓库剩余】 '):]
leftstr = leftstr[leftstr.find(';') + 1:leftstr.find('<br/>')]
# self.response.out.write(feedpage.content)
# self.response.out.write('<br />')
# self.response.out.write('leftstr')
left = int(leftstr)
hp = HTMLInputParser()
hp.feed(feedpage.content)
hp.close
feedform = {}
for i in range(0, hp.pairs):
feedform[hp.linksnames[i]] = hp.linksvalues[i].encode('utf-8')
feednum = int(feedform['pc'])
# self.response.out.write(feednum)
if left < feednum:
continue
if feedform.has_key('submit1'):
pass
else:
feedform['submit1'] = u'确 定'.encode('utf-8')
feedform_data = urllib.urlencode(feedform)
feedresult = urlfetch.fetch(url=feedposturl, payload=feedform_data, method=urlfetch.POST, headers={'Content-Type': 'application/x-www-form-urlencoded'}, allow_truncated=True, deadline=30)
self.response.out.write(feedresult.content)
if resultmachine2.content.find('添加') != -1:
machineresultstr = resultmachine2.content[resultmachine.content.find('/rr_farm/farm/action/wap,feedAction'):]
feedurls = []
while machineresultstr.find('添加') != -1:
if machineresultstr.find('\" class=\"blue\">添加') != -1:
urltmp = appmainurl + machineresultstr[machineresultstr.find('/rr_farm/farm/action/wap,feedAction'):machineresultstr.find('\" class=\"blue\">添加')]
else:
urltmp = appmainurl + machineresultstr[machineresultstr.find('/rr_farm/farm/action/wap,feedAction'):machineresultstr.find('\">添加')]
feedurls.append(urltmp)
machineresultstr = machineresultstr[machineresultstr.find('添加'):]
machineresultstr = machineresultstr[machineresultstr.find('加'):]
# self.response.out.write(feedurls)
for j in range(0, len(feedurls)):
feedurl = feedurls[j]
feedpage = urlfetch.fetch(url=feedurl, payload=[], method=urlfetch.GET, allow_truncated=True, deadline=30)
feedposturl = appmainurl + feedpage.content[feedpage.content.find('/rr_farm/farm/action/wap,feedAction'):feedpage.content.find('\"><input type=\"hidden\" name=\"sid\"')]
leftstr = feedpage.content[feedpage.content.find('【仓库剩余】 '):]
leftstr = leftstr[leftstr.find(';') + 1:leftstr.find('<br/>')]
# self.response.out.write(feedpage.content)
# self.response.out.write('<br />')
# self.response.out.write('leftstr')
left = int(leftstr)
hp = HTMLInputParser()
hp.feed(feedpage.content)
hp.close
feedform = {}
for i in range(0, hp.pairs):
feedform[hp.linksnames[i]] = hp.linksvalues[i].encode('utf-8')
feednum = int(feedform['pc'])
# self.response.out.write(feednum)
if left < feednum:
continue
if feedform.has_key('submit1'):
pass
else:
feedform['submit1'] = u'确 定'.encode('utf-8')
feedform_data = urllib.urlencode(feedform)
feedresult = urlfetch.fetch(url=feedposturl, payload=feedform_data, method=urlfetch.POST, headers={'Content-Type': 'application/x-www-form-urlencoded'}, allow_truncated=True, deadline=30)
self.response.out.write(feedresult.content)
def get(self):
if cgi.escape(self.request.get('email')) != "":
useremail = cgi.escape(self.request.get('email'))
useremail = useremail.decode("utf-8")
else:
return
if cgi.escape(self.request.get('pwd')) != "":
userpasswords = cgi.escape(self.request.get('pwd'))
userpasswords = userpasswords.decode("utf-8")
else:
return
self.ReapPlants(useremail, userpasswords)
# useremail = u'flamepjlh@126.com'
# userpasswords = u'flamehjhj'
# self.ReapPlants(useremail, userpasswords)
# useremail = u'flamepjlh@163.com'
# userpasswords = u'flamehjhj'
# self.ReapPlants(useremail, userpasswords)
application = webapp.WSGIApplication(
[('/feedself', SetAcount)],
debug=True)
def main():
run_wsgi_app(application)
if __name__ == "__main__":
main() | Python |
import string
import cgi
import urllib
from sgmllib import SGMLParser, SGMLParseError
from google.appengine.api import urlfetch
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
appmainurltmp = u'https://mail.qq.com/cgi-bin/loginpage'
appmainurl = u"http://m.mail.qq.com"
loginurl = u''
redirectedurl = u"http://w1.mail.qq.com/cgi-bin/today"
proxyurl = u""
form_fields = {
"f": u"xhtml".encode('utf-8'),
"reirecturl": u"cgi-bin/today".encode('utf-8'),
"uin": u"".encode('utf-8'),
"aliastype": u"qq.com".encode('utf-8'),
"pwd": u"".encode('utf-8'),
"mss": u"1".encode('utf-8'),
"btlogin": u"登录".encode('utf-8'),
# "autologin" : u"y".encode('utf-8')
}
form_fields_get = {
"uid": u"",
"url": u"",
}
class PageHTMLParser(SGMLParser):
def __init__(self):
SGMLParser.__init__(self)
self.links = []
self.datasets = []
self.matchcheck = 0
self.eigentag = ''
self.eigenname = ''
self.eigendata = ''
self.dupcounter = 0
def handle_data(self, text):
txt = text.strip()
if txt.find(self.eigendata) != -1:
self.matchcheck = 1
self.datasets.append(txt)
def start_a(self, attr):
self.links += [v for k, v in attr if k == "href"]
def end_a(self):
if self.matchcheck == 1:
self.matchcheck = 0
else:
self.links.pop()
self.dupcounter += 1
class HTMLformTagParser(SGMLParser):
def __init__(self):
SGMLParser.__init__(self)
self.links = []
self.eigenname = ''
def start_form(self, attr):
self.links += [v for k, v in attr if k == self.eigenname]
class HTMLgoTagParser(SGMLParser):
def __init__(self):
SGMLParser.__init__(self)
self.links = []
self.eigenname = ''
def start_go(self, attr):
self.links += [v for k, v in attr if k == self.eigenname]
useremail = u''
userpasswords = u''
useruid = u'1'
class SetAcount(webapp.RequestHandler):
def RenewFiles(self, loginuser, passwords):
# self.response.out.write(u'<html><meta http-equiv="content-type" content="text/html; charset=UTF-8"><body><pre>你输入的用户名是:<br />')
# self.response.out.write(loginuser.decode('utf-8'))
# self.response.out.write(u'<br />你输入的密码是:<br />')
# self.response.out.write(passwords.decode('utf-8'))
# self.response.out.write(u'<br />')
# self.response.out.write(u'</pre>')
form_fields['uin'] = loginuser.encode('utf-8')
form_fields['pwd'] = passwords.encode('utf-8')
form_data = urllib.urlencode(form_fields)
# result = urlfetch.fetch(url=appmainurltmp , method=urlfetch.GET, allow_truncated=True, deadline=30)
result = urlfetch.fetch(url=appmainurl , method=urlfetch.GET, headers={'Content-Type': 'application/x-www-form-urlencoded','User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8'}, allow_truncated=True, deadline=30)
# self.response.out.write('<!--')
# self.response.out.write(result.content.decode("utf-8"))
# self.response.out.write(result.headers)
# self.response.out.write('-->')
if result.content.find('小Q报时') == -1:
return
hp = HTMLformTagParser()
hp.eigenname = u'action'
hp.feed(result.content)
hp.close
if(len(hp.links) != 0):
loginurl = hp.links[0]
else:
loginurltmp = result.content[result.content.find('<go href=\"'):]
loginurl = loginurltmp[loginurltmp.find('http://w'):loginurltmp.find('\" method')]
result = urlfetch.fetch(url=loginurl, payload=form_data, method=urlfetch.POST, headers={'Content-Type': 'application/x-www-form-urlencoded', 'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8'}, deadline=30)
self.response.out.write('<!--\r\n')
self.response.out.write(loginurl.decode('utf-8'))
self.response.out.write('<br />\r\n')
result = urlfetch.fetch(url=loginurl, payload=[], method=urlfetch.GET, headers={'Content-Type': 'text/vnd.wap.wml', 'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8'}, deadline=30)
try:
self.response.out.write(result.content.decode("utf-8"))
except:
# self.response.out.write(result.content.decode("gb2312"))
self.response.out.write(result.content[result.content.find('secpp='):].decode("gb2312"))
return
urlss = result.content[result.content.find('/cgi-bin/loginpage?'):result.content.find('secpp=')].decode("gb2312")
urlss = urlss + 'secpp='
while urlss.find('\"+\"') != -1:
urlss = urlss[:urlss.find('\"+\"')] + urlss[urlss.find('\"+\"')+3:]
urlss = loginurl[:loginurl.find('/cgi-bin')] + urlss
self.response.out.write(urlss)
result = urlfetch.fetch(url=urlss, payload=[], method=urlfetch.GET, headers={'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8'}, deadline=30)
self.response.out.write('<br />\r\n')
self.response.out.write(result.content.decode('utf-8'))
self.response.out.write('<br />\r\n')
self.response.out.write('-->\r\n')
return
if result.content.find('标准版') != -1:
hp = HTMLformTagParser()
hp.eigenname = u'action'
hp.feed(result.content)
hp.close
if(len(hp.links) != 0):
loginurl = hp.links[0]
else:
loginurltmp = result.content[result.content.find('<go href=\"'):]
loginurl = loginurltmp[loginurltmp.find('http://w'):loginurltmp.find('\" method')]
result = urlfetch.fetch(url=loginurl, payload=form_data, method=urlfetch.POST, headers={'Content-Type': 'application/x-www-form-urlencoded', 'User-Agent': 'Mozilla/5.0 (SymbianOS/9.4; U; Series60/5.0 Nokia5800d-1/21.0.025; Profile/MIDP-2.1 Configuration/CLDC-1.1 ) AppleWebKit/413 (KHTML, like Gecko) Safari/413'}, deadline=30)
# self.response.out.write(result.headers)
self.response.out.write('<!--')
self.response.out.write(result.content.decode('utf-8'))
self.response.out.write('-->')
return
if result.content.find('登录中') == -1:
redirectedurltmp = result.content[result.content.find('src = [\"'):]
self.response.out.write(redirectedurltmp)
self.response.out.write('<br />')
redirectedurl = redirectedurltmp[redirectedurltmp.find('http://'):redirectedurltmp.find('screentype=wap')]
sidstr = redirectedurl[redirectedurl.find('sid='):redirectedurl.find(',4&screentype=')]
redirectedurl = redirectedurl[:redirectedurl.find('getinvestigate')] + 'today?' + sidstr + '&first=1'
else:
redirectedurl = result.content[result.content.find('/cgi-bin/today?'):result.content.find('\">首页')]
redirectedurl = loginurl[:loginurl.find('/cgi-bin')] + redirectedurl
self.response.out.write('<!--')
self.response.out.write(result.headers)
self.response.out.write(redirectedurl)
result = urlfetch.fetch(url=redirectedurl,payload=[], method=urlfetch.GET, headers={'User-Agent': 'Mozilla/5.0 (SymbianOS/9.4; U; Series60/5.0 Nokia5800d-1/21.0.025; Profile/MIDP-2.1 Configuration/CLDC-1.1 ) AppleWebKit/413 (KHTML, like Gecko) Safari/413'}, allow_truncated=True, deadline=30)
# self.response.out.write(result.content.decode('utf-8'))
self.response.out.write('-->')
return
hp = PageHTMLParser()
hp.eigentag = 'a'
hp.eigenname = 'href'
hp.eigendata = '中转站'
hp.feed(result.content)
hp.close
# inurl = proxyurl + 'uid=' + useruid + '&url=' + hp.links[0];
ftnurl = loginurl[:loginurl.find('/cgi-bin')] + hp.links[0] + '0'
# self.response.out.write(ftnurl)
result = urlfetch.fetch(url=ftnurl, payload=[], method=urlfetch.GET, allow_truncated=True, deadline=30)
# self.response.out.write(result.content.decode('utf-8'))
hp = PageHTMLParser()
hp.eigentag = 'a'
hp.eigenname = 'href'
hp.eigendata = '续期'
hp.feed(result.content)
hp.close
for i in range(0, len(hp.links) - 1):
ftnurlextent = loginurl[:loginurl.find('/cgi-bin')] + hp.links[i]
result = urlfetch.fetch(url=ftnurlextent, payload=[], method=urlfetch.GET, allow_truncated=True, deadline=30)
self.response.out.write(result.content.decode('utf-8'))
return
def get(self):
useremail = u'253308567'
userpasswords = u'flame106'
self.RenewFiles(useremail, userpasswords)
application = webapp.WSGIApplication(
[('/qqfarn', SetAcount)],
debug=True)
def main():
run_wsgi_app(application)
if __name__ == "__main__":
main() | Python |
# -*- coding: utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf8')
import string
import cgi
from google.appengine.api import urlfetch
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
url01 = u"http://ggfw.tk"
url02 = u"http://eehu.tk"
url03 = u"http://gango.tk"
url04 = u"http://guid.tk"
url05 = u"http://heju.tk"
url06 = u"http://juhe.tk"
url07 = u"http://samue.tk"
url08 = u"http://twithere.tk"
url09 = u"http://twitmsg.tk"
url10 = u"http://yamiede.tk"
url11 = u"http://yeehu.tk"
url12 = u"http://backoff.tk"
url13 = u"http://efttt.tk"
url14 = u"http://peta.tk"
url15 = u"http://qcomm.tk"
url16 = u"http://samue.tk"
url17 = u"http://sheldon.tk"
class DomainAccess(webapp.RequestHandler):
def get(self):
urlfetch.fetch(url=url01, payload=[], method=urlfetch.GET, headers={'Content-Type': 'application/x-www-form-urlencoded'}, allow_truncated=True, deadline=30)
urlfetch.fetch(url=url02, payload=[], method=urlfetch.GET, headers={'Content-Type': 'application/x-www-form-urlencoded'}, allow_truncated=True, deadline=30)
urlfetch.fetch(url=url03, payload=[], method=urlfetch.GET, headers={'Content-Type': 'application/x-www-form-urlencoded'}, allow_truncated=True, deadline=30)
urlfetch.fetch(url=url04, payload=[], method=urlfetch.GET, headers={'Content-Type': 'application/x-www-form-urlencoded'}, allow_truncated=True, deadline=30)
urlfetch.fetch(url=url05, payload=[], method=urlfetch.GET, headers={'Content-Type': 'application/x-www-form-urlencoded'}, allow_truncated=True, deadline=30)
urlfetch.fetch(url=url06, payload=[], method=urlfetch.GET, headers={'Content-Type': 'application/x-www-form-urlencoded'}, allow_truncated=True, deadline=30)
urlfetch.fetch(url=url07, payload=[], method=urlfetch.GET, headers={'Content-Type': 'application/x-www-form-urlencoded'}, allow_truncated=True, deadline=30)
urlfetch.fetch(url=url08, payload=[], method=urlfetch.GET, headers={'Content-Type': 'application/x-www-form-urlencoded'}, allow_truncated=True, deadline=30)
result = urlfetch.fetch(url=url09, payload=[], method=urlfetch.GET, headers={'Content-Type': 'application/x-www-form-urlencoded'}, allow_truncated=True, deadline=30)
urlfetch.fetch(url=url10, payload=[], method=urlfetch.GET, headers={'Content-Type': 'application/x-www-form-urlencoded'}, allow_truncated=True, deadline=30)
urlfetch.fetch(url=url11, payload=[], method=urlfetch.GET, headers={'Content-Type': 'application/x-www-form-urlencoded'}, allow_truncated=True, deadline=30)
urlfetch.fetch(url=url12, payload=[], method=urlfetch.GET, headers={'Content-Type': 'application/x-www-form-urlencoded'}, allow_truncated=True, deadline=30)
urlfetch.fetch(url=url13, payload=[], method=urlfetch.GET, headers={'Content-Type': 'application/x-www-form-urlencoded'}, allow_truncated=True, deadline=30)
urlfetch.fetch(url=url14, payload=[], method=urlfetch.GET, headers={'Content-Type': 'application/x-www-form-urlencoded'}, allow_truncated=True, deadline=30)
urlfetch.fetch(url=url15, payload=[], method=urlfetch.GET, headers={'Content-Type': 'application/x-www-form-urlencoded'}, allow_truncated=True, deadline=30)
urlfetch.fetch(url=url16, payload=[], method=urlfetch.GET, headers={'Content-Type': 'application/x-www-form-urlencoded'}, allow_truncated=True, deadline=30)
urlfetch.fetch(url=url17, payload=[], method=urlfetch.GET, headers={'Content-Type': 'application/x-www-form-urlencoded'}, allow_truncated=True, deadline=30)
#urlfetch.fetch(url=url18, payload=[], method=urlfetch.GET, headers={'Content-Type': 'application/x-www-form-urlencoded'}, allow_truncated=True, deadline=30)
#urlfetch.fetch(url=url19, payload=[], method=urlfetch.GET, headers={'Content-Type': 'application/x-www-form-urlencoded'}, allow_truncated=True, deadline=30)
#urlfetch.fetch(url=url20, payload=[], method=urlfetch.GET, headers={'Content-Type': 'application/x-www-form-urlencoded'}, allow_truncated=True, deadline=30)
self.response.out.write(result.content.decode('utf-8'))
application = webapp.WSGIApplication(
[('/domain', DomainAccess)],
debug=True)
def main():
run_wsgi_app(application)
if __name__ == "__main__":
main() | Python |
import string
import cgi
from google.appengine.api import urlfetch
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
contentdecode = """document.write(decode64(\"W0F1dG9Qcm94eSAwLjIuOV0KISBDaGVja3N1bTogTEk3V1VsZkVUYVk4eFlhSFBTQkxKUQohIEV4cGlyZXM6IDZoCiEgTGFzdCBNb2RpZmllZDogV2VkLCAxMSBNYXkgMjAxMSAwMjo1NTozNiArMDgwMAohICAgICAtLS0taHR0cDovL2F1dG9wcm94eS1nZndsaXN0Lmdvb2dsZWNvZGUuY29tLwoKIS0tLS0tLS0tLS0tLS0tLS0tLS0tTnVtLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLQouMHJ6LnR3Cnx8MHRvMjU1LmNvbQoxLWFwcGxlLmNvbS50dwp8fDEtYXBwbGUuY29tLnR3Ci4xMmJldC5jb20KfHwxMmJldC5jb20KMTQxaG9uZ2tvbmcuY29tL2ZvcnVtCnQuMTZjbGFzcy5jbgoxNzNuZy5jb20KfHwxNzNuZy5jb20KLjE3ZS5vcmcKfGh0dHA6Ly8xN2Uub3JnLwoxOTg0YmJzLmNvbQp8fDE5ODRiYnMuY29tCnx8MTk4NGJsb2cuY29tCi4xOTg0YmJzLm9yZwp8fDE5ODRiYnMub3JnCi4x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equestHandler):
def get(self):
self.response.headers['Content-Type'] = 'text/html'
if cgi.escape(self.request.get('proxy')) != "":
proxytype = cgi.escape(self.request.get('proxy'))
else:
proxytype = "free-gate"
url = "http://autoproxy2pac.appspot.com/pac/"
url = url + proxytype
result = urlfetch.fetch(url)
if result.status_code == 200:
self.response.out.write('<html>\r\n')
self.response.out.write('<head>\r\n')
self.response.out.write('</head>\r\n')
self.response.out.write('<body>\r\n')
self.response.out.write('<script type="text/javascript">\r\n')
indexstr = result.content.find(search,startpos)
self.response.out.write(result.content[:indexstr] + '\r\n')
#self.response.out.write('document.write(' + result.content[indexstr + 5:] + '\r\n')
self.response.out.write(contentdecode + '\r\n')
self.response.out.write('</script>\r\n')
self.response.out.write('</body>\r\n')
self.response.out.write('</html>\r\n')
application = webapp.WSGIApplication(
[('/getpac', MainPage)],
debug=True)
def main():
run_wsgi_app(application)
if __name__ == "__main__":
main() | Python |
# -*- coding: utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf8')
import string
import cgi
import urllib
from sgmllib import SGMLParser, SGMLParseError
from google.appengine.api import urlfetch
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
appmainurl = "http://mapps.renren.com"
loginurl = "http://3g.renren.com/login.do?fx=0&autoLogin=true"
proxyurl = u""
form_fields = {
# "origURL": u"/home.do",
# "login": u"",
"email": u"",
"password": u""
}
form_fields_get = {
"uid": u"",
"url": u"",
}
retrymax = 20
class PageHTMLParser(SGMLParser):
def __init__(self):
SGMLParser.__init__(self)
self.links = []
self.datasets = []
self.matchcheck = 0
self.eigentag = ''
self.eigenname = ''
self.eigendata = ''
self.dupcounter = 0
def handle_data(self, text):
txt = text.strip()
if txt.find(self.eigendata) != -1:
self.matchcheck = 1
self.datasets.append(txt)
def start_a(self, attr):
self.links += [v for k, v in attr if k == "href"]
def end_a(self):
if self.matchcheck == 1:
self.matchcheck = 0
else:
self.links.pop()
self.dupcounter += 1
class HTMLInputParser(SGMLParser):
def __init__(self):
SGMLParser.__init__(self)
self.linksnames = []
self.linksvalues = []
self.pairs = 0
def start_input(self, attr):
self.linksnames += [v for k, v in attr if k == 'name']
self.linksvalues += [v for k, v in attr if k == 'value']
self.pairs += 1
useremail = u''
userpasswords = u''
useruid = u'1'
class SetAcount(webapp.RequestHandler):
def ReapPlants(self, loginuser, passwords, helper = ''):
# self.response.out.write(u'<html><meta http-equiv="content-type" content="text/html; charset=UTF-8"><body><pre>你输入的用户名是:<br />')
# self.response.out.write(loginuser.decode('utf-8'))
# self.response.out.write(u'<br />你输入的密码是:<br />')
# self.response.out.write(passwords.decode('utf-8'))
# self.response.out.write(u'<br />')
# self.response.out.write(u'</pre>')
# form_fields['uid'] = useruid.encode('utf-8')
# form_fields['url'] = loginurl.encode('utf-8')
# form_fields['origURL'] = u'/home.do'
form_fields['email'] = loginuser.encode('utf-8')
form_fields['password'] = passwords.encode('utf-8')
# form_fields['login'] = u'登录'
form_data = urllib.urlencode(form_fields)
form_data = form_data[form_data.find('email'):] + u'&' + form_data[form_data.find('password'):form_data.find('&')]
# result = urlfetch.fetch(url='http://3g.renren.com/', payload=None, method=urlfetch.GET, headers={'Content-Type': 'application/x-www-form-urlencoded','User-Agent':'Mozilla/5.0 (Windows; U; Windows NT 5.2; zh-CN; rv:1.9.2.9) Gecko/20100824 Firefox/3.6.9 ( .NET CLR 3.5.30729)'},follow_redirects = True)
# self.response.out.write(result.content.decode('utf-8'))
# return
form_data = u'origURL=%2Fhome.do&'+ form_data + u'&login=%E7%99%BB%E5%BD%95'
self.response.out.write(form_data)
result = urlfetch.fetch(url=u'http://peta.tk/reap/reap.php', payload=form_data, method=urlfetch.POST, headers={'Content-Type': 'application/x-www-form-urlencoded','User-Agent':'Mozilla/5.0 (SymbianOS/9.4; Series60/5.0 Nokia5800 XpressMusic-1/50.0.5; Profile/MIDP-2.1 Configuration/CLDC-1.1; zh-CN) AppleWebKit/525 (KHTML, like Gecko) WicKed/7.1.123'},follow_redirects = True)
self.response.out.write(result.content.decode('utf-8'))
# return
success = 0
retrycounter = 0
while (success == 0 or success == 1) and retrycounter < retrymax and result.content.find('帐号和密码不匹配') != -1:
if result.content.find('帐号和密码不匹配') != -1:
success = 0
form_data = urllib.urlencode(form_fields)
form_data = form_data[form_data.find('email'):] + u'&' + form_data[form_data.find('password'):form_data.find('&')]
form_data = u'origURL=&'+ form_data + u'&login=%E7%99%BB%E5%BD%95'
try:
retrycounter += 1
result = urlfetch.fetch(url=u'http://peta.tk/reap/reap.php', payload=form_data, method=urlfetch.POST, headers={'Content-Type': 'application/x-www-form-urlencoded','User-Agent':'Mozilla/5.0 (Windows; U; Windows NT 5.2; zh-CN; rv:1.9.2.9) Gecko/20100824 Firefox/3.6.9 ( .NET CLR 3.5.30729)'}, allow_truncated=True, deadline=30,follow_redirects = True)
self.response.out.write(form_data)
except:
success = 1
if success == 0:
success = 2
else:
success = 0
if success != 2:
self.response.out.write(success)
# return
self.response.out.write(result.content.decode('utf-8'))
# return
hp = PageHTMLParser()
hp.eigentag = 'a'
hp.eigenname = 'href'
hp.eigendata = '应用'
hp.feed(result.content)
hp.close
self.response.out.write(hp.links)
# inurl = proxyurl + 'uid=' + useruid + '&url=' + hp.links[0];
success = 0
retrycounter = 0
while (success == 0 or success == 1) and retrycounter < retrymax:
try:
retrycounter += 1
result = urlfetch.fetch(url=hp.links[0], payload=[], method=urlfetch.GET, allow_truncated=True, deadline=30)
except:
success = 1
if success == 0:
success = 2
else:
success = 0
if success != 2:
self.response.out.write(success)
self.response.out.write(result.content.decode('utf-8'))
# return
hp = PageHTMLParser()
hp.eigentag = 'a'
hp.eigenname = 'href'
hp.eigendata = '人人农场'
hp.feed(result.content)
hp.close
# form_fields_get['url'] = hp.links[0].encode('utf-8')
# form_data = urllib.urlencode(form_fields_get)
success = 0
retrycounter = 0
while (success == 0 or success == 1) and retrycounter < retrymax:
try:
retrycounter += 1
result = urlfetch.fetch(url=hp.links[0], payload=[], method=urlfetch.GET, allow_truncated=True, deadline=30)
except:
success = 1
if success == 0:
success = 2
else:
success = 0
if success != 2:
self.response.out.write(success)
self.response.out.write(result.content.decode('utf-8'))
# return
if result.content.find('第三方应用\"人人农场\"发生错误') != -1:
self.response.out.write(result.content.decode('utf-8'))
return
if result.content.find('/rr_farm/farm/action/wap,indexAction.php?&svv=1') != -1:
svvurl = appmainurl + result.content[result.content.find('/rr_farm/farm/action/wap,indexAction.php?&svv=1'):result.content.find('\">简版')]
result = urlfetch.fetch(url=proxyurl + svvurl, payload=[], method=urlfetch.GET, allow_truncated=True, deadline=30)
cropurl = appmainurl + result.content[result.content.find('/rr_farm/farm/action/wap,myCropAction'):result.content.find('\">【农田】')]
treeurl = appmainurl + result.content[result.content.find('/rr_farm/farm/action/wap,myTreeAction'):result.content.find('\">【果树】')]
animalurl = appmainurl + result.content[result.content.find('/rr_farm/farm/action/wap,myAnimalAction'):result.content.find('\">【畜牧】')]
machineurl = appmainurl + result.content[result.content.find('/rr_farm/farm/action/wap,myMachineAction'):result.content.find('\">【机械】')]
friendurl = appmainurl + result.content[result.content.find('/rr_farm/farm/action/wap,myFriendsListAction'):result.content.find('\">【好友农场】')]
self.response.out.write(cropurl)
self.response.out.write(u"<br />")
# return
if result.content.find('【农田】★') != -1:
resultcrop = urlfetch.fetch(url=proxyurl + cropurl, payload=[], method=urlfetch.GET, allow_truncated=True, deadline=30)
if resultcrop.content.find('收获全部农产品') != -1:
reapallcropurl = appmainurl + resultcrop.content[resultcrop.content.find('/rr_farm/farm/action/wap,reapAllAction'):resultcrop.content.find('\">收获全部农产品')]
urlfetch.fetch(url=proxyurl + reapallcropurl, payload=[], method=urlfetch.GET, allow_truncated=True, deadline=30)
# self.response.out.write(result.content.decode('utf-8'))
if result.content.find('【果树】★') != -1:
resulttree = urlfetch.fetch(url=proxyurl + treeurl, payload=[], method=urlfetch.GET, allow_truncated=True, deadline=30)
if resulttree.content.find('收获全部果树产品') != -1:
reapalltreeurl = appmainurl + resulttree.content[resulttree.content.find('/rr_farm/farm/action/wap,reapAllAction'):resulttree.content.find('\">收获全部果树产品')]
urlfetch.fetch(url=proxyurl + reapalltreeurl, payload=[], method=urlfetch.GET, allow_truncated=True, deadline=30)
# self.response.out.write(result.content.decode('utf-8'))
if result.content.find('【畜牧】★') != -1:
resultanimal = urlfetch.fetch(url=proxyurl + animalurl, payload=[], method=urlfetch.GET, allow_truncated=True, deadline=30)
if resultanimal.content.find('收获全部畜牧产品') != -1:
reapallanimalurl = appmainurl + resultanimal.content[resultanimal.content.find('/rr_farm/farm/action/wap,reapAllAction'):resultanimal.content.find('\">收获全部畜牧产品')]
reapallresult = urlfetch.fetch(url=proxyurl + reapallanimalurl, payload=[], method=urlfetch.GET, allow_truncated=True, deadline=30)
# self.response.out.write(reapallresult.content.decode('utf-8'))
if helper == '':
if resultanimal.content.find('喂食') != -1:
animalresultstr = resultanimal.content[resultanimal.content.find('/rr_farm/farm/action/wap,feedAction'):]
feedurls = []
# self.response.out.write(helperanimalresultstr)
while animalresultstr.find('喂食') != -1:
feedurls.append(appmainurl + animalresultstr[animalresultstr.find('/rr_farm/farm/action/wap,feedAction'):animalresultstr.find('\" class=\"blue\">喂食')])
animalresultstr = animalresultstr[animalresultstr.find('喂食'):]
animalresultstr = animalresultstr[animalresultstr.find('食'):]
for j in range(0, len(feedurls)):
feedurl = feedurls[j]
feedpage = urlfetch.fetch(url=feedurl, payload=[], method=urlfetch.GET, allow_truncated=True, deadline=30)
feedposturl = appmainurl + feedpage.content[feedpage.content.find('/rr_farm/farm/action/wap,feedAction'):feedpage.content.find('\"><input type=\"hidden\" name=\"sid\"')]
leftstr = feedpage.content[feedpage.content.find('【仓库剩余】 '):]
leftstr = leftstr[leftstr.find(';') + 1:leftstr.find('<br/>')]
left = int(leftstr)
# self.response.out.write(leftstr)
hp = HTMLInputParser()
hp.feed(feedpage.content)
hp.close
feedform = {}
for i in range(0, hp.pairs):
feedform[hp.linksnames[i]] = hp.linksvalues[i].encode('utf-8')
feednum = int(feedform['pc'])
# self.response.out.write(feednum)
if left < feednum:
continue
if feedform.has_key('submit1'):
pass
else:
feedform['submit1'] = u'确 定'.encode('utf-8')
feedform_data = urllib.urlencode(feedform)
self.response.out.write(feedform)
self.response.out.write('<br />')
self.response.out.write(feedposturl)
self.response.out.write('<br />')
self.response.out.write('<br />')
self.response.out.write(hp.linksnames)
self.response.out.write('<br />')
self.response.out.write(hp.linksvalues)
feedresult = urlfetch.fetch(url=feedposturl, payload=feedform_data, method=urlfetch.POST, headers={'Content-Type': 'application/x-www-form-urlencoded'}, allow_truncated=True, deadline=30)
self.response.out.write(feedresult.content)
if result.content.find('【机械】★') != -1:
resultmachine = urlfetch.fetch(url=proxyurl + machineurl, payload=[], method=urlfetch.GET, allow_truncated=True, deadline=30)
if resultmachine.content.find('收获全部加工产品') != -1:
reapallmachineurl = appmainurl + resultmachine.content[resultmachine.content.find('/rr_farm/farm/action/wap,reapAllAction'):resultmachine.content.find('\">收获全部加工产品')]
reapallresult = urlfetch.fetch(url=proxyurl + reapallmachineurl, payload=[], method=urlfetch.GET, allow_truncated=True, deadline=30)
# self.response.out.write(reapallresult.content.decode('utf-8'))
if helper == '':
if resultmachine.content.find('添加') != -1:
machineresultstr = resultmachine.content[resultmachine.content.find('/rr_farm/farm/action/wap,feedAction'):]
feedurls = []
while machineresultstr.find('添加') != -1:
if machineresultstr.find('\" class=\"blue\">添加') != -1:
urltmp = appmainurl + machineresultstr[machineresultstr.find('/rr_farm/farm/action/wap,feedAction'):machineresultstr.find('\" class=\"blue\">添加')]
else:
urltmp = appmainurl + machineresultstr[machineresultstr.find('/rr_farm/farm/action/wap,feedAction'):machineresultstr.find('\">添加')]
feedurls.append(urltmp)
machineresultstr = machineresultstr[machineresultstr.find('添加'):]
machineresultstr = machineresultstr[machineresultstr.find('加'):]
# self.response.out.write(feedurls)
for j in range(0, len(feedurls)):
feedurl = feedurls[j]
feedpage = urlfetch.fetch(url=feedurl, payload=[], method=urlfetch.GET, allow_truncated=True, deadline=30)
feedposturl = appmainurl + feedpage.content[feedpage.content.find('/rr_farm/farm/action/wap,feedAction'):feedpage.content.find('\"><input type=\"hidden\" name=\"sid\"')]
leftstr = feedpage.content[feedpage.content.find('【仓库剩余】 '):]
leftstr = leftstr[leftstr.find(';') + 1:leftstr.find('<br/>')]
# self.response.out.write(feedpage.content)
# self.response.out.write('<br />')
# self.response.out.write('leftstr')
left = int(leftstr)
hp = HTMLInputParser()
hp.feed(feedpage.content)
hp.close
feedform = {}
for i in range(0, hp.pairs):
feedform[hp.linksnames[i]] = hp.linksvalues[i].encode('utf-8')
feednum = int(feedform['pc'])
# self.response.out.write(feednum)
if left < feednum:
continue
if feedform.has_key('submit1'):
pass
else:
feedform['submit1'] = u'确 定'.encode('utf-8')
feedform_data = urllib.urlencode(feedform)
feedresult = urlfetch.fetch(url=feedposturl, payload=feedform_data, method=urlfetch.POST, headers={'Content-Type': 'application/x-www-form-urlencoded'}, allow_truncated=True, deadline=30)
self.response.out.write(feedresult.content)
if helper != '':
result = urlfetch.fetch(url=friendurl, payload=[], method=urlfetch.GET, allow_truncated=True, deadline=30)
judgestr = result.content[result.content.find('/rr_farm/farm/action/wap,friendsFarmAction.php?fid='.encode('utf-8') + helper.encode('utf-8')):]
judgestr = judgestr[:judgestr.find('<a href'.encode('utf-8'))]
# self.response.out.write(result.content.decode('utf-8'))
# self.response.out.write(judgestr.decode('utf-8'))
# self.response.out.write('<br />')
if judgestr.find('可采摘或可喂食') != -1:
helperurl = appmainurl + judgestr[:judgestr.find('\" class=\"blue\"')]
helperresult = urlfetch.fetch(url=helperurl, payload=[], method=urlfetch.GET, allow_truncated=True, deadline=30)
# self.response.out.write(helperresult.content.decode('utf-8'))
if helperresult.content.find('【畜牧】★') != -1:
helperanimalurl = appmainurl + helperresult.content[helperresult.content.find('/rr_farm/farm/action/wap,friendAnimalAction'):helperresult.content.find('\">【畜牧】')]
helperanimalresult = urlfetch.fetch(url=helperanimalurl, payload=[], method=urlfetch.GET, allow_truncated=True, deadline=30)
helperanimalresult2 = urlfetch.fetch(url=helperanimalurl + "&curpage=1", payload=[], method=urlfetch.GET, allow_truncated=True, deadline=30)
if helperanimalresult.content.find('喂食') != -1:
helperanimalresultstr = helperanimalresult.content[helperanimalresult.content.find('/rr_farm/farm/action/wap,feedFriendAction'):]
feedurls = []
# self.response.out.write(helperanimalresultstr)
while helperanimalresultstr.find('喂食') != -1:
feedurls.append(appmainurl + helperanimalresultstr[helperanimalresultstr.find('/rr_farm/farm/action/wap,feedFriendAction'):helperanimalresultstr.find('\" class=\"blue\">喂食')])
helperanimalresultstr = helperanimalresultstr[helperanimalresultstr.find('喂食'):]
helperanimalresultstr = helperanimalresultstr[helperanimalresultstr.find('食'):]
# self.response.out.write('<!--')
# self.response.out.write(helperanimalresultstr)
# self.response.out.write('--><br /><br />')
# self.response.out.write(feedurls)
for j in range(0, len(feedurls)):
feedurl = feedurls[j]
feedpage = urlfetch.fetch(url=feedurl, payload=[], method=urlfetch.GET, allow_truncated=True, deadline=30)
feedposturl = appmainurl + feedpage.content[feedpage.content.find('/rr_farm/farm/action/wap,feedFriendAction'):feedpage.content.find('\"><input type=\"hidden\" name=\"sid\"')]
leftstr = feedpage.content[feedpage.content.find('【仓库剩余】 '):]
leftstr = leftstr[leftstr.find(';') + 1:leftstr.find('<br/>')]
left = int(leftstr)
# self.response.out.write(leftstr)
hp = HTMLInputParser()
hp.feed(feedpage.content)
hp.close
feedform = {}
for i in range(0, hp.pairs):
feedform[hp.linksnames[i]] = hp.linksvalues[i]
feednum = int(feedform['pc'])
# self.response.out.write(feednum)
if left < feednum:
continue
feedform_data = urllib.urlencode(feedform)
feedresult = urlfetch.fetch(url=feedposturl, payload=feedform_data, method=urlfetch.POST, headers={'Content-Type': 'application/x-www-form-urlencoded'}, allow_truncated=True, deadline=30)
self.response.out.write(feedresult.content)
# self.response.out.write(helperanimalresult.content.decode('utf-8'))
if helperanimalresult2.content.find('喂食') != -1:
helperanimalresultstr = helperanimalresult2.content[helperanimalresult.content.find('/rr_farm/farm/action/wap,feedFriendAction'):]
feedurls = []
# self.response.out.write(helperanimalresultstr)
while helperanimalresultstr.find('喂食') != -1:
feedurls.append(appmainurl + helperanimalresultstr[helperanimalresultstr.find('/rr_farm/farm/action/wap,feedFriendAction'):helperanimalresultstr.find('\" class=\"blue\">喂食')])
helperanimalresultstr = helperanimalresultstr[helperanimalresultstr.find('喂食'):]
helperanimalresultstr = helperanimalresultstr[helperanimalresultstr.find('食'):]
# self.response.out.write('<!--')
# self.response.out.write(helperanimalresultstr)
# self.response.out.write('--><br /><br />')
# self.response.out.write(feedurls)
for j in range(0, len(feedurls)):
feedurl = feedurls[j]
feedpage = urlfetch.fetch(url=feedurl, payload=[], method=urlfetch.GET, allow_truncated=True, deadline=30)
feedposturl = appmainurl + feedpage.content[feedpage.content.find('/rr_farm/farm/action/wap,feedFriendAction'):feedpage.content.find('\"><input type=\"hidden\" name=\"sid\"')]
leftstr = feedpage.content[feedpage.content.find('【仓库剩余】 '):]
leftstr = leftstr[leftstr.find(';') + 1:leftstr.find('<br/>')]
left = int(leftstr)
# self.response.out.write(leftstr)
hp = HTMLInputParser()
hp.feed(feedpage.content)
hp.close
feedform = {}
for i in range(0, hp.pairs):
feedform[hp.linksnames[i]] = hp.linksvalues[i]
feednum = int(feedform['pc'])
# self.response.out.write(feednum)
if left < feednum:
continue
feedform_data = urllib.urlencode(feedform)
feedresult = urlfetch.fetch(url=feedposturl, payload=feedform_data, method=urlfetch.POST, headers={'Content-Type': 'application/x-www-form-urlencoded'}, allow_truncated=True, deadline=30)
self.response.out.write(feedresult.content)
# self.response.out.write(helperanimalresult.content.decode('utf-8'))
if helperresult.content.find('【机械】★') != -1:
helpermachineurl = appmainurl + helperresult.content[helperresult.content.find('/rr_farm/farm/action/wap,friendMachineAction'):helperresult.content.find('\">【机械】')]
helpermachineresult = urlfetch.fetch(url=helpermachineurl, payload=[], method=urlfetch.GET, allow_truncated=True, deadline=30)
helpermachineresult2 = urlfetch.fetch(url=helpermachineurl + "&curpage=1", payload=[], method=urlfetch.GET, allow_truncated=True, deadline=30)
if helpermachineresult.content.find('添加') != -1:
helpermachineresultstr = helpermachineresult.content[helpermachineresult.content.find('/rr_farm/farm/action/wap,feedFriendAction'):]
feedurls = []
while helpermachineresultstr.find('添加') != -1:
feedurls.append(appmainurl + helpermachineresultstr[helpermachineresultstr.find('/rr_farm/farm/action/wap,feedFriendAction'):helpermachineresultstr.find('\" class=\"blue\">添加')])
helpermachineresultstr = helpermachineresultstr[helpermachineresultstr.find('添加'):]
helpermachineresultstr = helpermachineresultstr[helpermachineresultstr.find('加'):]
for j in range(0, len(feedurls)):
feedurl = feedurls[j]
feedpage = urlfetch.fetch(url=feedurl, payload=[], method=urlfetch.GET, allow_truncated=True, deadline=30)
feedposturl = appmainurl + feedpage.content[feedpage.content.find('/rr_farm/farm/action/wap,feedFriendAction'):feedpage.content.find('\"><input type=\"hidden\" name=\"sid\"')]
leftstr = feedpage.content[feedpage.content.find('【仓库剩余】 '):]
leftstr = leftstr[leftstr.find(';') + 1:leftstr.find('<br/>')]
left = int(leftstr)
hp = HTMLInputParser()
hp.feed(feedpage.content)
hp.close
feedform = {}
for i in range(0, hp.pairs):
feedform[hp.linksnames[i]] = hp.linksvalues[i]
feednum = int(feedform['pc'])
# self.response.out.write(feednum)
if left < feednum:
continue
feedform_data = urllib.urlencode(feedform)
feedresult = urlfetch.fetch(url=feedposturl, payload=feedform_data, method=urlfetch.POST, headers={'Content-Type': 'application/x-www-form-urlencoded'}, allow_truncated=True, deadline=30)
self.response.out.write(feedresult.content)
if helpermachineresult2.content.find('添加') != -1:
helpermachineresultstr = helpermachineresult2.content[helpermachineresult.content.find('/rr_farm/farm/action/wap,feedFriendAction'):]
feedurls = []
while helpermachineresultstr.find('添加') != -1:
feedurls.append(appmainurl + helpermachineresultstr[helpermachineresultstr.find('/rr_farm/farm/action/wap,feedFriendAction'):helpermachineresultstr.find('\" class=\"blue\">添加')])
helpermachineresultstr = helpermachineresultstr[helpermachineresultstr.find('添加'):]
helpermachineresultstr = helpermachineresultstr[helpermachineresultstr.find('加'):]
for j in range(0, len(feedurls)):
feedurl = feedurls[j]
feedpage = urlfetch.fetch(url=feedurl, payload=[], method=urlfetch.GET, allow_truncated=True, deadline=30)
feedposturl = appmainurl + feedpage.content[feedpage.content.find('/rr_farm/farm/action/wap,feedFriendAction'):feedpage.content.find('\"><input type=\"hidden\" name=\"sid\"')]
leftstr = feedpage.content[feedpage.content.find('【仓库剩余】 '):]
leftstr = leftstr[leftstr.find(';') + 1:leftstr.find('<br/>')]
left = int(leftstr)
hp = HTMLInputParser()
hp.feed(feedpage.content)
hp.close
feedform = {}
for i in range(0, hp.pairs):
feedform[hp.linksnames[i]] = hp.linksvalues[i]
feednum = int(feedform['pc'])
# self.response.out.write(feednum)
if left < feednum:
continue
feedform_data = urllib.urlencode(feedform)
feedresult = urlfetch.fetch(url=feedposturl, payload=feedform_data, method=urlfetch.POST, headers={'Content-Type': 'application/x-www-form-urlencoded'}, allow_truncated=True, deadline=30)
self.response.out.write(feedresult.content)
# self.response.out.write(feedurl)
# self.response.out.write(feedpage.content.decode('utf-8'))
# self.response.out.write('<br /><br />')
# self.response.out.write(cropurl)
# self.response.out.write('<br />')
# self.response.out.write(treeurl)
# self.response.out.write('<br />')
# self.response.out.write(animalurl)
# self.response.out.write('<br />')
# self.response.out.write(machineurl)
# self.response.out.write('<br />')
# self.response.out.write(hp.datasets[0].decode('utf-8'))
# self.response.out.write('</body></html>')
def get(self):
if cgi.escape(self.request.get('email')) != "":
useremail = cgi.escape(self.request.get('email'))
else:
useremail = u'flamepjlh@126.com'.decode("utf-8")
userpasswords = u'flamehjhj'.decode("utf-8")
helper = u'246059230'.decode("utf-8")
self.ReapPlants(useremail, userpasswords, helper)
useremail = u'flamepjlh@163.com'.decode("utf-8")
userpasswords = u'flamehjhj'.decode("utf-8")
helper = u'2087648495'.decode("utf-8")
self.ReapPlants(useremail, userpasswords, helper)
return
if cgi.escape(self.request.get('pwd')) != "":
userpasswords = cgi.escape(self.request.get('pwd'))
else:
return
if cgi.escape(self.request.get('helper')) != "":
helper = cgi.escape(self.request.get('helper'))
else:
helper = ""
useremail = useremail.decode("utf-8")
userpasswords = userpasswords.decode("utf-8")
helper = helper.decode("utf-8")
self.ReapPlants(useremail, userpasswords, helper)
self.response.out.write(useremail)
self.response.out.write("<br />")
self.response.out.write(userpasswords)
self.response.out.write("<br />")
self.response.out.write(helper)
# useremail = u'flamepjlh@126.com'
# userpasswords = u'flamehjhj'
# helper = u'246059230'
# self.ReapPlants(useremail, userpasswords, helper)
# useremail = u'flamepjlh@163.com'
# userpasswords = u'flamehjhj'
# helper = u'2087648495'
# self.ReapPlants(useremail, userpasswords, helper)
application = webapp.WSGIApplication(
[('/reapplants', SetAcount)],
debug=True)
def main():
run_wsgi_app(application)
if __name__ == "__main__":
main() | Python |
# -*- coding: utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf8')
import string
import cgi
import urllib
import random
import datetime
from google.appengine.ext import db
from google.appengine.api.labs import taskqueue
from sgmllib import SGMLParser, SGMLParseError
from google.appengine.api import urlfetch
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
class ReapJob(db.Model):
jobobj = db.StringProperty(required=True)
reapurl = db.StringProperty(required=True)
createdtime = db.DateTimeProperty(required=True, auto_now_add=True)
class ReapHandler(webapp.RequestHandler):
def get(self):
if cgi.escape(self.request.get('guard')) != "":
urlcron = "/reapall?email=flamepjlh@126.com&pwd=flamehjhj"
taskregql = ReapJob.gql("WHERE jobobj = :1", "flamepjlh@126.com")
taskrecord = taskregql.get()
countdowntime = 0
if taskrecord == None:
countdowntime = 5
taskqueue.add(url=urlcron, payload=None, countdown=countdowntime, method='GET', name='126restore'+str(random.randint(1,999999)))
else:
datetimenow = datetime.datetime.now()
if taskrecord.createdtime < datetimenow:
taskrecord.delete()
countdowntime = 5
taskqueue.add(url=urlcron, payload=None, countdown=countdowntime, method='GET', name='126restore'+str(random.randint(1,999999)))
urlcron = "/reapall?email=flamepjlh@163.com&pwd=flamehjhj"
taskregql = ReapJob.gql("WHERE jobobj = :1", "flamepjlh@163.com")
taskrecord = taskregql.get()
if countdowntime != 0:
countdowntime += countdowntime + 95 + random.randint(1,60)
if taskrecord == None:
taskqueue.add(url=urlcron, payload=None, countdown=countdowntime, method='GET', name='163restore'+str(random.randint(1,999999)))
else:
datetimenow = datetime.datetime.now()
if taskrecord.createdtime < datetimenow:
taskrecord.delete()
taskqueue.add(url=urlcron, payload=None, countdown=countdowntime, method='GET', name='163restore'+str(random.randint(1,999999)))
urlcron = "/reapall?email=fxckgfw1@gmail.com&pwd=flamehjhj"
taskregql = ReapJob.gql("WHERE jobobj = :1", "fxckgfw1@gmail.com")
taskrecord = taskregql.get()
if countdowntime != 0:
countdowntime += countdowntime + 95 + random.randint(1,60)
if taskrecord == None:
taskqueue.add(url=urlcron, payload=None, countdown=countdowntime, method='GET', name='gmailrestore'+str(random.randint(1,999999)))
else:
datetimenow = datetime.datetime.now()
if taskrecord.createdtime < datetimenow:
taskrecord.delete()
taskqueue.add(url=urlcron, payload=None, countdown=countdowntime, method='GET', name='gmailrestore'+str(random.randint(1,999999)))
return
if cgi.escape(self.request.get('retry')) != "":
retry = string.atoi(cgi.escape(self.request.get('retry')))
else:
retry = 0
if cgi.escape(self.request.get('feed')) == "true":
urlfeed = 'http://twmsg.tk/wp-reap/feed.php?'
else:
urlreap = 'http://twmsg.tk/wp-reap/reap.php?'
if cgi.escape(self.request.get('email')) != "":
useremail = cgi.escape(self.request.get('email'))
else:
useremail = 'flamepjlh@126.com'
userpasswords = 'flamehjhj'
helper = '246059230'
if cgi.escape(self.request.get('pwd')) != "":
userpasswords = cgi.escape(self.request.get('pwd'))
if cgi.escape(self.request.get('setcron')) == "true":
if cgi.escape(self.request.get('time')) != "":
if cgi.escape(self.request.get('time')) != "99999999":
countdowntime = string.atoi(cgi.escape(self.request.get('time')))*60
else:
return
self.response.out.write('countdowntime:' + str(countdowntime))
urlcron = "/reapall?cron=true" + '&email=' + useremail + '&pwd=' + userpasswords
self.response.out.write(urlcron)
timetoexecute = datetime.datetime.now()
timetoexecute = timetoexecute + datetime.timedelta(seconds=countdowntime)
taskregql = ReapJob.gql("WHERE jobobj = :1", useremail)
taskrecord = taskregql.get()
if taskrecord == None:
taskqueue.add(url=urlcron, payload=None, eta=timetoexecute, method='GET', name='next'+cgi.escape(self.request.get('time'))+'r'+str(random.randint(1,999999)));
nextjob = ReapJob(jobobj=useremail, reapurl=urlcron, createdtime=timetoexecute)
nextjob.put()
self.response.out.write('success add!'+useremail)
else:
self.response.out.write('job already exist!:'+useremail)
else:
urlcron = 'http://twmsg.tk/wp-reap/getreaptime.php?' + 'email=' + useremail + '&pwd=' + userpasswords
try:
result = urlfetch.fetch(url=urlcron, payload=[], method=urlfetch.GET, headers={'Content-Type': 'application/x-www-form-urlencoded','User-Agent':'Mozilla/5.0 (SymbianOS/9.4; Series60/5.0 Nokia5800 XpressMusic-1/50.0.5; Profile/MIDP-2.1 Configuration/CLDC-1.1; zh-CN) AppleWebKit/525 (KHTML, like Gecko) WicKed/7.1.123'},follow_redirects = True, allow_truncated=True, deadline=30)
except:
urlcron = "/reapall?setcron=true" + '&email=' + useremail + '&pwd=' + userpasswords
# taskqueue.add(url=urlcron, payload=None, method='GET', countdown=5, name='setnextcron')
return
if cgi.escape(self.request.get('helper')) != "":
helper = cgi.escape(self.request.get('helper'))
else:
helper = ""
if cgi.escape(self.request.get('feed')) == "true":
if helper == "":
urlfeed = urlfeed + 'email=' + useremail + '&pwd=' + userpasswords
else:
urlfeed = urlfeed + 'email=' + useremail + '&pwd=' + userpasswords + '&helper=' + helper
try:
result = urlfetch.fetch(url=urlfeed, payload=[], method=urlfetch.GET, headers={'Content-Type': 'application/x-www-form-urlencoded','User-Agent':'Mozilla/5.0 (SymbianOS/9.4; Series60/5.0 Nokia5800 XpressMusic-1/50.0.5; Profile/MIDP-2.1 Configuration/CLDC-1.1; zh-CN) AppleWebKit/525 (KHTML, like Gecko) WicKed/7.1.123'},follow_redirects = True, allow_truncated=True, deadline=30)
except:
if helper == "":
urlcron = "/reapall?feed=true" + '&email=' + useremail + '&pwd=' + userpasswords + '&retry=' + str(retry + 1)
else:
urlcron = "/reapall?feed=true" + '&email=' + useremail + '&pwd=' + userpasswords + '&helper=' + helper + '&retry=' + str(retry + 1)
if retry < 5:
taskqueue.add(url=urlcron, payload=None, method='GET', countdown=15, name='retryfeed'+str(random.randint(1,999999)))
return
self.response.out.write('success feed!'+useremail+helper)
else:
urlreap = urlreap + 'email=' + useremail + '&pwd=' + userpasswords
if cgi.escape(self.request.get('cron')) != "":
taskregql = ReapJob.gql("WHERE jobobj = :1", useremail)
taskrecord = taskregql.get()
if taskrecord != None:
taskrecord.delete()
try:
result = urlfetch.fetch(url=urlreap, payload=[], method=urlfetch.GET, headers={'Content-Type': 'application/x-www-form-urlencoded','User-Agent':'Mozilla/5.0 (SymbianOS/9.4; Series60/5.0 Nokia5800 XpressMusic-1/50.0.5; Profile/MIDP-2.1 Configuration/CLDC-1.1; zh-CN) AppleWebKit/525 (KHTML, like Gecko) WicKed/7.1.123'},follow_redirects = True, allow_truncated=True, deadline=30)
except:
urlcron = "/reapall?" + 'email=' + useremail + '&pwd=' + userpasswords + '&retry=' + str(retry + 1)
if retry < 10:
taskqueue.add(url=urlcron, payload=None, method='GET', countdown=15, name='retryreap'+str(random.randint(1,999999)))
return
urlcron = "/reapall?setcron=true" + '&email=' + useremail + '&pwd=' + userpasswords
taskqueue.add(url=urlcron, payload=None, method='GET', countdown=10, name='setnextcron'+str(random.randint(1,999999)))
self.response.out.write('success reap!'+useremail)
application = webapp.WSGIApplication(
[('/reapall', ReapHandler)],
debug=True)
def main():
run_wsgi_app(application)
if __name__ == "__main__":
main() | Python |
# -*- coding: utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf8')
import string
import cgi
import urllib
import random
import datetime
import re
from google.appengine.ext import db
from google.appengine.api.labs import taskqueue
from sgmllib import SGMLParser, SGMLParseError
from google.appengine.api import urlfetch
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
num2mask = {
'1':'128.0.0.0',
'2':'192.0.0.0',
'3':'224.0.0.0',
'4':'240.0.0.0',
'5':'248.0.0.0',
'6':'252.0.0.0',
'7':'254.0.0.0',
'8':'255.0.0.0',
'9':'255.128.0.0',
'10':'255.192.0.0',
'11':'255.224.0.0',
'12':'255.240.0.0',
'13':'255.248.0.0',
'14':'255.252.0.0',
'15':'255.254.0.0',
'16':'255.255.0.0',
'17':'255.255.128.0',
'18':'255.255.192.0',
'19':'255.255.224.0',
'20':'255.255.240.0',
'21':'255.255.248.0',
'22':'255.255.252.0',
'23':'255.255.254.0',
'24':'255.255.255.0',
'25':'255.255.255.128',
'26':'255.255.255.192',
'27':'255.255.255.224',
'28':'255.255.255.240',
'29':'255.255.255.248',
'30':'255.255.255.252',
'31':'255.255.255.254',
'32':'255.255.255.255'
}
urlcnroute = 'http://www.ipdeny.com/ipblocks/data/countries/cn.zone'
class RouteHandler(webapp.RequestHandler):
def get(self):
self.response.out.write("""<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>国内ip路由表</title>
<body bgcolor=black>
<font color=white><font class=num>命令提示符:</font><br /><br />
"""
)
if cgi.escape(self.request.get('del')) != "":
lincmd = 'route del -net '
wincmd = 'route -p delete '
else:
lincmd = 'route add -net '
wincmd = 'route add -p '
if cgi.escape(self.request.get('gateway')) != "":
gateway = self.request.get('gateway')
else:
gateway = 'eth0'
result = urlfetch.fetch(url=urlcnroute, payload=[], method=urlfetch.GET, headers={'Content-Type': 'application/x-www-form-urlencoded'},follow_redirects = True, allow_truncated=True, deadline=30)
ippattern = re.compile('(\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3})/(\d{1,2})')
for ip in ippattern.finditer(result.content):
if cgi.escape(self.request.get('os')) == "win":
self.response.out.write(wincmd+ip.group(1)+' mask '+num2mask[ip.group(2)]+' '+gateway+'<br />')
else:
self.response.out.write(lincmd+ip.group(1)+' netmask '+num2mask[ip.group(2)]+' '+gateway+'<br />')
self.response.out.write("</font></body>")
application = webapp.WSGIApplication(
[('/getroute', RouteHandler)],
debug=True)
def main():
run_wsgi_app(application)
if __name__ == "__main__":
main() | Python |
#!/usr/bin/python
import os,shutil
from sys import exit
import subprocess as sp
infolder = "testinput"
outfolder = "testoutput"
if not os.path.exists(infolder):
print "Error, %s does not exist. Please create it and stick some FLAC files in there for testing" % infolder
exit(1)
#files = os.listdir(infolder)
#flacfiles = filter(lambda x: x.endswith(".flac"), files)
#if len(flacfiles) == 0:
# print "No flac files found in %s. Please put some in there for testing (no subfolders please)" % infolder
# exit(2)
if not os.path.exists(outfolder): os.mkdir(outfolder)
testypes = ["mp3","vorbis","flac","aacplusnero","opus"];
for test in testypes:
larg = "--lame-options='-preset standard' "
aarg = "-a 64"
varg = "--vorbis-options='quality=5:resample 32000:downmix'"
exc = " -x'\.(cue|log)/i'" #Exclude cue and log files, case insensitive. for Testing
for opt in ('-c','-f','-t 4','-n'):
cmd = "python2 ./flac2all.py %s %s %s %s %s -o %s %s" % (test,larg,aarg,varg,opt,outfolder,infolder)
print '-'*80
print "Executing: %s" % cmd
print '-'*80
rc = sp.call(cmd,shell=True)
if (rc != 0) :
print "ERROR Executing command: \"%s\"\n" % cmd
exit(rc)
print "Testing exclude (excluding all flac files from input, so processable flac files should == 0 )"
cmd = "python2 ./flac2all.py %s %s %s %s %s -o %s %s" % (test,larg,aarg,varg,exc,outfolder,infolder)
rc = sp.call(cmd,shell=True)
if (rc != 0):
print "ERROR executing command with 'exclude' set. Investigate..."
exit(rc)
#print "All successful! Deleting output folder"
#shutil.rmtree(outfolder)
print "Done!"
| Python |
#!/usr/bin/python
import os,shutil
from sys import exit
import subprocess as sp
infolder = "testinput"
outfolder = "testoutput"
if not os.path.exists(infolder):
print "Error, %s does not exist. Please create it and stick some FLAC files in there for testing" % infolder
exit(1)
#files = os.listdir(infolder)
#flacfiles = filter(lambda x: x.endswith(".flac"), files)
#if len(flacfiles) == 0:
# print "No flac files found in %s. Please put some in there for testing (no subfolders please)" % infolder
# exit(2)
if not os.path.exists(outfolder): os.mkdir(outfolder)
testypes = ["mp3","vorbis","flac","aacplusnero","opus"];
for test in testypes:
larg = "--lame-options='-preset standard' "
aarg = "-a 64"
varg = "--vorbis-options='quality=5:resample 32000:downmix'"
exc = " -x'\.(cue|log)/i'" #Exclude cue and log files, case insensitive. for Testing
for opt in ('-c','-f','-t 4','-n'):
cmd = "python2 ./flac2all.py %s %s %s %s %s -o %s %s" % (test,larg,aarg,varg,opt,outfolder,infolder)
print '-'*80
print "Executing: %s" % cmd
print '-'*80
rc = sp.call(cmd,shell=True)
if (rc != 0) :
print "ERROR Executing command: \"%s\"\n" % cmd
exit(rc)
print "Testing exclude (excluding all flac files from input, so processable flac files should == 0 )"
cmd = "python2 ./flac2all.py %s %s %s %s %s -o %s %s" % (test,larg,aarg,varg,exc,outfolder,infolder)
rc = sp.call(cmd,shell=True)
if (rc != 0):
print "ERROR executing command with 'exclude' set. Investigate..."
exit(rc)
#print "All successful! Deleting output folder"
#shutil.rmtree(outfolder)
print "Done!"
| Python |
#!/usr/bin/env python2
#Version 3
# vim: ts=4 autoindent expandtab number
"""
===============================================================================
Python script for conversion of flac files to flac/mp3/ogg/opus.
Copyright 2006-2015 Ziva-Vatra, Belgrade
(www.ziva-vatra.com, mail: zv@ziva-vatra.com)
Project website: http://code.google.com/p/flac2all/
Licensed under the GNU GPL. Do not remove any information from this header
(or the header itself). If you have modified this code, feel free to add your
details below this (and by all means, mail me, I like to see what other people
have done)
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License (version 2)
as published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
===============================================================================
"""
import sys
import os
import string,re
import pdb
import threading,time,multiprocessing
import subprocess as sp
#CODE
#Class that deals with AAC+
class aacplusNero:
def __init__(self):
pass #keep the constructor empty for now
def AACPconvert(self,aacopts,infile,outfile):
#Uncomment the line below if you want the file currently being
#converted to be displayed
#print parseEscapechars(infile)
#rb stands for read-binary, which is what we are doing, with a 1024 byte buffer
decoder = os.popen(flacpath + "flac -d -s -c " + shell().parseEscapechars(infile),'rb',1024)
#wb stands for write-binary
encoder = os.popen("%sneroAacEnc %s -if - -of %s.mp4 2> /tmp/aacplusLog" % (
aacpath,
aacopts,
shell().parseEscapechars(outfile),
) ,'wb',8192)
for line in decoder.readlines(): #while data exists in the decoders buffer
encoder.write(line) #write it to the encoders buffer
decoder.flush() #if there is any data left in the buffer, clear it
decoder.close() #somewhat self explanetory
encoder.flush() #as above
encoder.close()
#Class that deals with vorbis
class vorbis:
def oggconvert(self,oggencopts,infile,outfile):
#oggenc automatically parses the flac file + metadata, quite wonderful
#really, we don't need to do anything here
#The binary itself deals with the tag conversion etc
#Which makes our life rather easy
os.system("%soggenc %s -Q -o %s.ogg %s" %
(
oggencpath,
oggencopts,
shell().parseEscapechars(outfile),
shell().parseEscapechars(infile)
)
)
# Class that deals with opus. initial opus support (version > 0.1.7) in version 3 of flac2all
# was kindly provided by Christian Elmerot <christian [atsign] elmerot.se > - 3/2/2015
class opus:
def __init__(self):
#Work out what version of opus we have
self.version=None #Unknown by default
try:
sp.call("type %sopusenc" % opusencpath.strip(';'), shell=True)
except OSError as e:
self.version = "INVALID"
return None
if ( sp.call("%sopusenc -V " % opusencpath, stdout=sp.PIPE, stderr=sp.PIPE, shell=True) != 0 ):
fd = os.popen("%sopusenc -v" % opusencpath)
else:
fd = os.popen("%sopusenc -V" % opusencpath)
data = fd.read(256)
fd.close()
data = re.search("\d\.\d\.\d",data).group(0)
(release,major,minor) = map(lambda x: int(x), data.split('.'))
self.version=(release,major,minor)
def opusconvert(self,opusencopts,infile,outfile):
if self.version == "INVALID":
print "ERROR: Could not locate opusenc binary. Cannot convert!"
return None
#As the new versions of opus support flac natively, I think that the best option is to use >0.1.7 by default, but support earlier ones without tagging.
if self.version == None:
print "ERROR! Could not discover opus version, assuming version >= 0.1.7. THIS MAY NOT WORK!"
version = (9,9,9)
else: version=self.version
#If we are a release prior to 0.1.7, use non-tagging type conversion, with warning
if (version[0] == 0) and (version[1] <= 1) and (version[2] <= 6):
print "WARNING: Opus version prior to 0.1.7 detected, NO TAGGING SUPPORT"
decoder = os.popen(flacpath + "flac -d -s -c " + shell().parseEscapechars(infile),'rb',1024)
encoder = os.popen("%sopusenc %s - %s.opus 2> /tmp/opusLog" % (
opusencpath,
opusencopts,
shell().parseEscapechars(outfile),
) ,'wb',8192)
for line in decoder.readlines(): #while data exists in the decoders buffer
encoder.write(line) #write it to the encoders buffer
decoder.flush() #if there is any data left in the buffer, clear it
decoder.close() #somewhat self explanetory
encoder.flush() #as above
encoder.close()
else:
#opusenc >0.1.7 automatically parses the flac file + metadata, similar to oggenc
#The binary itself deals with the tag conversion etc... so no need for anything special
os.system("%sopusenc --comment encoder=\"flac2all v3 (https://code.google.com/p/flac2all/\" %s %s %s.opus 2>/tmp/opusLog" %
(
opusencpath,
opusencopts,
shell().parseEscapechars(infile),
shell().parseEscapechars(outfile)
)
)
#Class that deals with FLAC
class flac:
def flacconvert(self,flacopts, infile, outfile):
os.system("%sflac -s -d -c \"%s\" | %sflac -f -s %s -o \"%s.flac\" -" %
(flacpath, infile, flacpath, flacopts, outfile)
)
os.system("%smetaflac --no-utf8-convert --export-tags-to=- \"%s\" | %smetaflac --import-tags-from=- \"%s.flac\"" %
(flacpath, infile,flacpath, outfile)
)
def getflacmeta(self,flacfile):
#The FLAC file format states that song info will be stored in block 2, and the reference
#encoder does so, but other encoders do not! This caused issue 14 and issue 16.
#As such, we now search by block time VORBIS_COMMENT. There should only be one such.
flacdata = os.popen("%smetaflac --list --block-type VORBIS_COMMENT %s" %
(
metaflacpath,
flacfile
)
)
datalist = [] #init a list for storing all the data in this block
#this dictionary (note different brackets) will store only the comments
#for the music file
commentlist = {}
#parse the metaflac output looking for a Vorbis comment metablock, identified as:
# METADATA block #?
# type: 4 (VORBIS_COMMENT)
#then start scanning for Vorbis comments. This localised searching ensures that
#"comment" tags in non Vorbis metablocks don't corrupt the music tags
foundnewmetadatablock = 0
lookingforvorbiscomments = 0
for data in flacdata.readlines():
#get rid of any whitespace from the left to the right
data = string.strip(data)
#only start looking for Vorbis comments once we have latched onto a
#new metadata block of type 4
if(foundnewmetadatablock == 1 and data == "type: 4 (VORBIS_COMMENT)"):
lookingforvorbiscomments = 1
if(foundnewmetadatablock == 1):
foundnewmetadatablock = 0
if(data[:16] == "METADATA block #"):
foundnewmetadatablock = 1
lookingforvorbiscomments = 0
if (lookingforvorbiscomments == 1):
#check if the tag is a comment field (shown by the first 8 chars
#spelling out "comment[")
if(data[:8] == "comment["):
datalist.append(string.split(data,":",1))
for data in datalist:
#split according to [NAME]=[VALUE] structure
comment = string.split(data[1],"=")
comment[0] = string.strip(comment[0])
comment[1] = string.strip(comment[1])
#convert to upper case
#we want the key values to always be the same case, we decided on
#uppercase (whether the string is upper or lowercase, is dependent
# on the tagger used)
comment[0] = string.upper(comment[0])
#assign key:value pair, comment[0] will be the key, and comment[1]
#the value
commentlist[comment[0]] = comment[1]
return commentlist
def flactest(self,file,outfile):
test = os.popen(flacpath + "flac -s -t \"" + file + "\"",'r')
#filepath = generateoutdir(file,outfile) + "results.log"
#if (os.path.exists(filepath)):
# os.remove(filepath)
#os.mknod(filepath,0775)
#out = os.popen(filepath,'w')
#results = ""
#for line in test.readlines():
# print "++++++++++++" + line
# results = line
# out.write(results)
# print "==============" + results
# test.flush()
test.close()
# out.flush()
# out.close()
#Class dealing with shell/output related things:
class shell:
def generateoutdir(self,indir, outdir,dirpath):
#if we find the dirpath in the current output path, we replace
#it with the new output path. (so that we don't get
#/mnt/convertedfromflac/mnt/flac/[file].mp3, in this case
#"/mnt/" exist in both)
if (string.find(os.path.split(indir)[0], dirpath) != -1):
return string.replace(os.path.split(indir)[0], dirpath, outdir)
else:
#if we do not find an instance of dir path in output
#path (this shows that they are the same), just
#return the output
return outdir
def parseEscapechars(self,file,quoteonly=False):
#TODO: look at docs.python.org/2/library/codecs.html for info on how to do this better
if(quoteonly == False):
#characters which must be escaped in the shell, note
#"[" and "]" seems to be automatically escaped
#(strange, look into this)
escChars = ["\"","*",";"," ","'","(",")","&","`","$"]
for char in escChars:
#add an escape character to the character
file = string.replace(file, char, '\\' + char)
else:
file = string.replace(file, "\"", "\\\"")
return file
def getfiles(self,path):
infiles = os.listdir(path) #the files going in for reading
outfiles = [] #the files going out in a list
for file in infiles:
if(os.path.isdir(os.path.join(path,file))):
#recursive call
outfiles = outfiles + self.getfiles(os.path.join(path,file))
else:
outfiles.append(os.path.join(path,file))
return outfiles
#mp3 class:
class mp3:
def __init__(self):
pass #keep the constructor empty for now
def generateLameMeta(self,metastring):
tagstring = ""
#pointer to the parseEscapechars method in the shell class
parseEscapechars = shell().parseEscapechars
#Dealing with genres defined within lame
acceptable_genres=[\
"A Cappella",\
"Acid",\
"Acid Jazz",\
"Acid Punk",\
"Acoustic",\
"Alternative",\
"Alt. Rock",\
"Ambient",\
"Anime",\
"Avantgarde",\
"Ballad",\
"Bass",\
"Beat",\
"Bebob",\
"Big Band",\
"Black Metal",\
"Bluegrass",\
"Blues",\
"Booty Bass",\
"BritPop",\
"Cabaret",\
"Celtic",\
"Chamber Music",\
"Chanson",\
"Chorus",\
"Christian Gangsta Rap",\
"Christian Rap",\
"Christian Rock",\
"Classical",\
"Classic Rock",\
"Club",\
"Club-House",\
"Comedy",\
"Contemporary Christian",\
"Country",\
"Crossover",\
"Cult",\
"Dance",\
"Dance Hall",\
"Darkwave",\
"Death Metal",\
"Disco",\
"Dream",\
"Drum & Bass",\
"Drum Solo",\
"Duet",\
"Easy Listening",\
"Electronic",\
"Ethnic",\
"Eurodance",\
"Euro-House",\
"Euro-Techno",\
"Fast-Fusion",\
"Folk",\
"Folklore",\
"Folk/Rock",\
"Freestyle",\
"Funk",\
"Fusion",\
"Game",\
"Gangsta Rap",\
"Goa",\
"Gospel",\
"Gothic",\
"Gothic Rock",\
"Grunge",\
"Hardcore",\
"Hard Rock",\
"Heavy Metal",\
"Hip-Hop",\
"House",\
"Humour",\
"Indie",\
"Industrial",\
"Instrumental",\
"Instrumental Pop",\
"Instrumental Rock",\
"Jazz",\
"Jazz+Funk",\
"JPop",\
"Jungle",\
"Latin", \
"Lo-Fi", \
"Meditative", \
"Merengue", \
"Metal", \
"Musical", \
"National Folk", \
"Native American", \
"Negerpunk", \
"New Age", \
"New Wave", \
"Noise", \
"Oldies", \
"Opera", \
"Other", \
"Polka", \
"Polsk Punk", \
"Pop", \
"Pop-Folk", \
"Pop/Funk", \
"Porn Groove", \
"Power Ballad", \
"Pranks", \
"Primus", \
"Progressive Rock", \
"Psychedelic", \
"Psychedelic Rock", \
"Punk", \
"Punk Rock", \
"Rap", \
"Rave", \
"R&B", \
"Reggae", \
"Retro", \
"Revival", \
"Rhythmic Soul", \
"Rock", \
"Rock & Roll", \
"Salsa", \
"Samba", \
"Satire", \
"Showtunes", \
"Ska", \
"Slow Jam", \
"Slow Rock", \
"Sonata", \
"Soul", \
"Sound Clip", \
"Soundtrack", \
"Southern Rock", \
"Space", \
"Speech", \
"Swing", \
"Symphonic Rock", \
"Symphony", \
"Synthpop", \
"Tango", \
"Techno", \
"Techno-Industrial", \
"Terror", \
"Thrash Metal", \
"Top 40", \
"Trailer", \
"Trance", \
"Tribal", \
"Trip-Hop", \
"Vocal"]
genre_is_acceptable = 0 #By default the genre is not acceptable
current_genre = "" #variable stores current genre tag
for genre in acceptable_genres:
#print string.strip(metastring['GENRE'])+" ==> "+string.strip(genre)
try:
current_genre = string.upper(metastring['GENRE'].strip())
except(KeyError):
current_genre = "NO GENRE TAG"
#case-insesitive comparison
if current_genre == string.upper(genre.strip()):
genre_is_acceptable = 1 #we can use the genre
if genre_is_acceptable == 0: #if genre cannot be used
print "The Genre \"" + current_genre + "\" cannot be used with lame, setting to \"Other\" "
metastring['GENRE'] = "Other" #set GENRE to Other
else:
#Capitalise the Genre, as per lame requirements
metastring['GENRE'] = string.capitalize(metastring['GENRE'])
genre_is_acceptable = 0 #reset the boolean value for the next time
try:
tagstring = "--tt " + "\"" + parseEscapechars(metastring["TITLE"],True) + "\""
except(KeyError):
pass #well we skip the comment field if is doesn't exist
try:
tagstring = tagstring + " --ta " + "\"" + parseEscapechars(metastring['ARTIST'],True) + "\""
except(KeyError):
pass
try:
tagstring = tagstring + " --tl " + "\"" + parseEscapechars(metastring['ALBUM'],True) + "\""
except(KeyError):
pass
try:
tagstring = tagstring + " --ty " + "\"" + parseEscapechars(metastring['DATE'],True) + "\""
except(KeyError):
pass
try:
tagstring = tagstring + " --tg " + "\"" + parseEscapechars(metastring['GENRE'],True) + "\""
except(KeyError):
pass
try:
tagstring = tagstring + " --tn " + "\"" + parseEscapechars(metastring['TRACKNUMBER'],True) + "\""
except(KeyError):
pass
#COMMENTS AND CDDB ARE PLACED TOGETHER, as there exists no seperate
#"CDDB Field" option for mp3. this is only if we have a comment to begin with
try:
tagstring = tagstring + " --tc " + "\"" + parseEscapechars(metastring['COMMENT'],True)
try:
tagstring = tagstring + " || CDDB:" + parseEscapechars(metastring['CDDB'],True) + "\""
except(KeyError):
tagstring = tagstring + "\"" #close the final "comment field, without CDDB info
except(KeyError):
#this is for if we have a CDDB value
try:
tagstring = tagstring + " --tc \"CDDB:" + parseEscapechars(metastring['CDDB'],True) + "\""
except(KeyError):
pass
#Metadata population complete
return tagstring
def mp3convert(self,lameopts,infile,outfile):
#give us an output file, full path, which is the same as the infile
#(minus the working directory path) and with the extension stripped
#outfile = os.path.join(outdir+"/",os.path.split(infile)[-1]).strip(".flac")
#pdb.set_trace()
try:
metastring = generateLameMeta(infile)
except(UnboundLocalError):
metastring = "" #If we do not get meta information. leave blank
#Uncomment the line below if you want the file currently being
#converted to be displayed
#print parseEscapechars(infile)
#rb stands for read-binary, which is what we are doing, with a 1024 byte buffer
decoder = os.popen(flacpath + "flac -d -s -c " + shell().parseEscapechars(infile),'rb',1024)
#wb stands for write-binary
encoder = os.popen("%slame --silent %s - -o %s.mp3 %s" % (
lamepath,
lameopts,
shell().parseEscapechars(outfile),
metastring
) ,'wb',8192)
# encoder = os.popen(lamepath + "lame --silent " + lameopts + " - -o " + shell().parseEscapechars(outfile) + ".mp3 " + metastring,'wb',8192)
for line in decoder.readlines(): #while data exists in the decoders buffer
encoder.write(line) #write it to the encoders buffer
decoder.flush() #if there is any data left in the buffer, clear it
decoder.close() #somewhat self explanetory
encoder.flush() #as above
encoder.close()
#END OF CLASSES, Main body of code follows:
#Functions defined here
def header():
return """
Flac2all python script, v3 . Copyright 2006-2015 Ziva-Vatra.com.
Licensed under the GPLv3 .
Project website: http://code.google.com/p/flac2all/
"""
def infohelp():
return """
flac2all [convert type] [input dir] <options>
where \'convert type\' is one of:
\t [mp3]: convert file to mp3
\t [vorbis]: convert file to ogg vorbis
\t [opus]: convert file to opus
\t [flac]: convert file to flac
\t [aacplusnero]: (NO TAGGING SUPPORT) convert file to aacplus using the proprietery (but excellent) Nero AAC encoder."""
def init():
pass #do nothing, prolly remove this function
#The above currently not used for anything useful
#binpath = os.path.defpath #get the $PATH variable from the os
def encode_thread(current_file,filecounter,opts):
#remove the dirpath placed in parameters, so that we work from that
#directory
current_file_local = current_file.replace(opts['dirpath'],'')
if (opts['nodirs'] == True):
outdirFinal = opts['outdir']
else:
if (opts['include_root'] == True):
outdirFinal = opts['outdir'] + os.path.split(opts['dirpath'])[1] + os.path.split(current_file_local)[0]
else:
outdirFinal = opts['outdir'] + os.path.split(current_file_local)[0]
#if the path does not exist, then make it
if (os.path.exists(outdirFinal) == False):
#the try/catch here is to deal with race condition, sometimes one
#thread creates the path before the other, causing errors
try:
#recursive, will make the entire path if required
os.makedirs(outdirFinal)
except(OSError):
print "Directory already exists! Reusing..."
#this chunk of code provides us with the full path sans extension
outfile = os.path.join(outdirFinal,os.path.split(current_file_local)[1])
#return the name on its own, without the extension
outfile = string.split(outfile, ".flac")[0]
#This part deals with copying non-music data over (so everything that isn't
#a flac file)
if (string.lower(current_file [-4:]) != "flac"):
if (opts['copy'] == True):
print "Copying file #%d (%s) to destination" % (filecounter,current_file.split('/')[-1])
if ( os.path.exists(outfile) == True) and (opts['overwrite'] == False):
if os.stat(current_file).st_mtime - os.stat(outfile).st_mtime > 1:
os.system("cp \"%s\" \"%s\"" % (current_file,outdirFinal) )
else:
print "File %s is same size as destination. Not copying" % current_file
filecounter += 1
if(opts['overwrite'] == False): #if we said not to overwrite files
#if a file with the same filename/path does not already exist
#the below is because "vorbis" is "ogg" extension, so we need the right extension
#if we are to correctly check for existing files.
if opts['mode'] == "vorbis":
ext = "ogg"
else:
ext = opts['mode']
if not (os.path.exists(outfile + "." + ext)):
#[case insensitive] check if the last 4 characters say flac (as in
#flac extension, if it doesn't, then we assume it is not a flac
#file and skip it
if (string.lower(current_file [-4:]) == "flac"):
if (opts['mode'] != "test"):
print "converting file #%d to %s" % (filecounter,opts['mode'])
else:
print "testing file #" + str(filecounter)
if(opts['mode'] == "mp3"):
mp3Class.mp3convert(opts['lameopts'],current_file,outfile)
elif(opts['mode'] == "flac"):
flacClass.flacconvert(opts['flacopts'],current_file,outfile)
elif(opts['mode'] == "vorbis"):
vorbisClass.oggconvert(opts['oggencopts'],current_file,outfile)
elif(opts['mode'] == "opus"):
opusClass.opusconvert(opts['opusencopts'],current_file,outfile)
elif(opts['mode'] == "aacplusnero"):
aacpClass.AACPconvert(opts['aacplusopts'],current_file,outfile)
elif(opts['mode'] == "test"):
flacClass.flactest(current_file, outfile)
else:
print "Error, Mode %s not recognised. Thread dying" % opts['mode']
sys.exit(-2)
else:
print "file #%d exists, skipping" % filecounter
else:
#[case insensitive] check if the last 4 characters say flac (as in flac
#extension, if it doesn't, then we assume it is not a flac file and
#skip it
if (string.lower(current_file [-4:]) == "flac"):
if (opts['mode'] != "test"):
print "Converting file %d to %s" % (filecounter,opts['mode'])
else:
print "Testing file %d" % filecounter
if(opts['mode'] == "mp3"):
mp3Class.mp3convert(opts['lameopts'],current_file,outfile)
elif(opts['mode'] == "flac"):
flacClass.flacconvert(opts['flacopts'],current_file,outfile)
elif(opts['mode'] == "vorbis"):
vorbisClass.oggconvert(opts['oggencopts'],current_file,outfile)
elif(opts['mode'] == "opus"):
opusClass.opusconvert(opts['opusencopts'],current_file,outfile)
elif(opts['mode'] == "aacplusNero"):
aacpClass.AACPconvert(opts['aacplusopts'],current_file,outfile)
elif(opts['mode'] == "test"):
flacClass.flactest(current_file, outfile)
else:
print "Error, Mode %s not recognised. Thread dying" % opts['mode']
sys.exit(-2)
return filecounter + 1 #increment the file we are doing
def generateLameMeta(mp3file):
metastring = flac().getflacmeta("\"" + mp3file + "\"")
return mp3Class.generateLameMeta(metastring)
#Metadata population complete
#END Functions
#Code starts here
#Variables are here
#***NOTE***
#if the *path variables below are left blank, then the script will try to find
#the programs automatically. only change these if the script does not work
#(or add the programs to your system $PATH variable)
flacpath="" #path to flac binary, blank by default
metaflacpath="" #path to metaflac, blank be default
oggencpath="" #path to oggenc binary, blank by default
opusencpath="" #path to opusenc binary, blank by default
lamepath="" #path to lame binary, blank by default
aacpath="" #path to aacplus binary, blank by default
opts = {
"outdir":"./", #the directory we output to, defaults to current directory
"overwrite":False, #do we overwrite existing files
"nodirs":False, #do not create directories (dump all files into single dir)
"copy":False, #Copy non flac files (default is to ignore)
"buffer":2048, #How much to read in at a time
"lameopts":"--preset standard -q 0", #your mp3 encoding settings
"oggencopts":"quality=2", # your vorbis encoder settings
"opusencopts":"bitrate 128", # your opus encoder settings
"flacopts":"-q 8", #your flac encoder settings
"aacplusopts":"-q 0.3 ",
"include_root":False,
}
#This area deals with checking the command line options,
from optparse import OptionParser
parser = OptionParser(usage=infohelp())
parser.add_option("-c","--copy",action="store_true",dest="copy",
default=False,help="Copy non flac files across (default=False)")
parser.add_option("-v","--vorbis-options",dest="oggencopts",
default="quality=2",help="Colon delimited options to pass to oggenc,for example:" +
" 'quality=5:resample 32000:downmix:bitrate_average=96'." +
" Any oggenc long option (one with two '--' in front) can be specified in the above format.")
parser.add_option("-p","--opus-options",dest="opusencopts",
default="bitrate 128",help="Colon delimited options to pass to opusenc,for example:" +
" 'bitrate 256:expect-loss:downmix-stereo'." +
" Any opusenc long option (one with two '--' in front) can be specified in the above format.")
parser.add_option("-l","--lame-options",dest="lameopts",
default="-preset standard:q 0",help="Options to pass to lame, for example: '-preset extreme:q 0:h:-abr'. "+
"Any lame option can be specified here, if you want a short option (e.g. -h), then just do 'h'. "+
"If you want a long option (e.g. '--abr'), then you need a dash: '-abr'")
parser.add_option("-a","--aacplus-options",dest="aacplusopts",
default="-q 0.3", help="AACplus options, currently only bitrate supported. e.g: \" -br 64 \""),
parser.add_option("-o","--outdir",dest="outdir",metavar="DIR",
help="Set custom output directory (default='./')",
default="./"),
parser.add_option("-f","--force",dest="overwrite",action="store_true",
help="Force overwrite of existing files (by default we skip)",
default=False),
parser.add_option("-t","--threads",dest="threads",default=multiprocessing.cpu_count(),
help="How many threads to run in parallel (default: autodetect [found %d cpu(s)] )" % multiprocessing.cpu_count())
parser.add_option("-n","--nodirs",dest="nodirs",action="store_true",
default=False,help="Don't create Directories, put everything together")
parser.add_option("-x","--exclude",dest="exclude",default=None, help="exclude certain files from processing by PATTERN (regular expressions supported)")
parser.add_option("-r","--include-root",dest="root_include", action="store_true", default=False, help="Include the top-level directory in output path ( default=False )")
##The below isn't used anymore, so removed as an option (to re-add in future?)
#parser.add_option("-B","--buffer",dest="buffer",metavar="size",
# help="How much we should buffer before encoding to mp3 (in KB). The larger "+
# "you set this too, the more of the song will be buffered before "+
# "encoding. Set it high enough and it will buffer everything to RAM"+
# "before encoding.")
(options,args) = parser.parse_args()
#update the opts dictionary with new values
opts.update(eval(options.__str__()))
#convert the formats in the args to valid formats for lame, oggenc and opusenc
opts['oggencopts'] = ' --'+' --'.join(opts['oggencopts'].split(':'))
opts['opusencopts'] = ' --'+' --'.join(opts['opusencopts'].split(':'))
#lame is stupid, it is not consistent, sometimes using long opts, sometimes not
#so we need to specify on command line with dashes whether it is a long op or short
opts['lameopts'] = ' -'+' -'.join(opts['lameopts'].split(':'))
print header()
#pdb.set_trace()
try:
opts['mode'] = args[0]
except(IndexError): #if no arguments specified
print "No mode specified! Run with '-h' for help"
sys.exit(-1) #quit the program with non-zero status
try:
opts['dirpath'] = os.path.realpath(args[1])
except(IndexError):
print "No directory specified! Run with '-h' for help"
sys.exit(-1) #quit the program with non-zero status
#end command line checking
#start main code
#create instances of classes
mp3Class = mp3()
shellClass = shell()
flacClass = flac()
vorbisClass = vorbis()
opusClass = opus()
aacpClass = aacplusNero()
filelist=shellClass.getfiles(opts['dirpath'])
#if "exclude" set, filter out by regular expression
if opts['exclude'] != None:
rex = re.compile(opts['exclude'])
filelist = filter(lambda x: re.search(rex,x) == None, filelist) #Only return items that don't match
flacnum = 0 #tells us number of flac media files
filenum = 0 #tells us number of files
#pdb.set_trace()
for files in filelist:
filenum += 1
#make sure both flac and FLAC are read
if (string.lower(files [-4:]) == "flac"):
flacnum += 1
print "There are %d files, of which %d are convertable FLAC files" % \
(filenum,flacnum)
print "We are running %s simultaneous transcodes" % opts['threads']
if flacnum == 0:
print "Error, we got no flac files. Are you sure you put in the correct directory?"
sys.exit(-1)
x = 0 #temporary variable, only to keep track of number of files we have done
#Why did we not use "for file in filelist" for the code below? Because this is
#more flexible. As an example for multiple file encoding simultaniously, we
#can do filelist.pop() multiple times (well, along with some threading, but its
#good to plan for the future.
#one thread is always for the main program, so if we want two encoding threads,
#we need three threads in total
opts['threads'] = int(opts['threads']) + 1
while len(filelist) != 0: #while the length of the list is not 0 (i.e. not empty)
#remove and return the first element in the list
current_file = filelist.pop()
#threaded process, used by default
threading.Thread(target=encode_thread,args=(
current_file,
x,
opts
)
).start()
#Don't use threads, single process, used for debugging
#x = encode_thread(current_file,nodirs,x,lameopts,flacopts,oggencopts,mode)
while threading.activeCount() == opts['threads']:
#just sit and wait. we check every tenth second to see if it has
#finished
time.sleep(0.3)
x += 1
#END
| Python |
#!/usr/bin/env python2
#Version 3
# vim: ts=4 autoindent expandtab number
"""
===============================================================================
Python script for conversion of flac files to flac/mp3/ogg/opus.
Copyright 2006-2015 Ziva-Vatra, Belgrade
(www.ziva-vatra.com, mail: zv@ziva-vatra.com)
Project website: http://code.google.com/p/flac2all/
Licensed under the GNU GPL. Do not remove any information from this header
(or the header itself). If you have modified this code, feel free to add your
details below this (and by all means, mail me, I like to see what other people
have done)
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License (version 2)
as published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
===============================================================================
"""
import sys
import os
import string,re
import pdb
import threading,time,multiprocessing
import subprocess as sp
#CODE
#Class that deals with AAC+
class aacplusNero:
def __init__(self):
pass #keep the constructor empty for now
def AACPconvert(self,aacopts,infile,outfile):
#Uncomment the line below if you want the file currently being
#converted to be displayed
#print parseEscapechars(infile)
#rb stands for read-binary, which is what we are doing, with a 1024 byte buffer
decoder = os.popen(flacpath + "flac -d -s -c " + shell().parseEscapechars(infile),'rb',1024)
#wb stands for write-binary
encoder = os.popen("%sneroAacEnc %s -if - -of %s.mp4 2> /tmp/aacplusLog" % (
aacpath,
aacopts,
shell().parseEscapechars(outfile),
) ,'wb',8192)
for line in decoder.readlines(): #while data exists in the decoders buffer
encoder.write(line) #write it to the encoders buffer
decoder.flush() #if there is any data left in the buffer, clear it
decoder.close() #somewhat self explanetory
encoder.flush() #as above
encoder.close()
#Class that deals with vorbis
class vorbis:
def oggconvert(self,oggencopts,infile,outfile):
#oggenc automatically parses the flac file + metadata, quite wonderful
#really, we don't need to do anything here
#The binary itself deals with the tag conversion etc
#Which makes our life rather easy
os.system("%soggenc %s -Q -o %s.ogg %s" %
(
oggencpath,
oggencopts,
shell().parseEscapechars(outfile),
shell().parseEscapechars(infile)
)
)
# Class that deals with opus. initial opus support (version > 0.1.7) in version 3 of flac2all
# was kindly provided by Christian Elmerot <christian [atsign] elmerot.se > - 3/2/2015
class opus:
def __init__(self):
#Work out what version of opus we have
self.version=None #Unknown by default
try:
sp.call("type %sopusenc" % opusencpath.strip(';'), shell=True)
except OSError as e:
self.version = "INVALID"
return None
if ( sp.call("%sopusenc -V " % opusencpath, stdout=sp.PIPE, stderr=sp.PIPE, shell=True) != 0 ):
fd = os.popen("%sopusenc -v" % opusencpath)
else:
fd = os.popen("%sopusenc -V" % opusencpath)
data = fd.read(256)
fd.close()
data = re.search("\d\.\d\.\d",data).group(0)
(release,major,minor) = map(lambda x: int(x), data.split('.'))
self.version=(release,major,minor)
def opusconvert(self,opusencopts,infile,outfile):
if self.version == "INVALID":
print "ERROR: Could not locate opusenc binary. Cannot convert!"
return None
#As the new versions of opus support flac natively, I think that the best option is to use >0.1.7 by default, but support earlier ones without tagging.
if self.version == None:
print "ERROR! Could not discover opus version, assuming version >= 0.1.7. THIS MAY NOT WORK!"
version = (9,9,9)
else: version=self.version
#If we are a release prior to 0.1.7, use non-tagging type conversion, with warning
if (version[0] == 0) and (version[1] <= 1) and (version[2] <= 6):
print "WARNING: Opus version prior to 0.1.7 detected, NO TAGGING SUPPORT"
decoder = os.popen(flacpath + "flac -d -s -c " + shell().parseEscapechars(infile),'rb',1024)
encoder = os.popen("%sopusenc %s - %s.opus 2> /tmp/opusLog" % (
opusencpath,
opusencopts,
shell().parseEscapechars(outfile),
) ,'wb',8192)
for line in decoder.readlines(): #while data exists in the decoders buffer
encoder.write(line) #write it to the encoders buffer
decoder.flush() #if there is any data left in the buffer, clear it
decoder.close() #somewhat self explanetory
encoder.flush() #as above
encoder.close()
else:
#opusenc >0.1.7 automatically parses the flac file + metadata, similar to oggenc
#The binary itself deals with the tag conversion etc... so no need for anything special
os.system("%sopusenc --comment encoder=\"flac2all v3 (https://code.google.com/p/flac2all/\" %s %s %s.opus 2>/tmp/opusLog" %
(
opusencpath,
opusencopts,
shell().parseEscapechars(infile),
shell().parseEscapechars(outfile)
)
)
#Class that deals with FLAC
class flac:
def flacconvert(self,flacopts, infile, outfile):
os.system("%sflac -s -d -c \"%s\" | %sflac -f -s %s -o \"%s.flac\" -" %
(flacpath, infile, flacpath, flacopts, outfile)
)
os.system("%smetaflac --no-utf8-convert --export-tags-to=- \"%s\" | %smetaflac --import-tags-from=- \"%s.flac\"" %
(flacpath, infile,flacpath, outfile)
)
def getflacmeta(self,flacfile):
#The FLAC file format states that song info will be stored in block 2, and the reference
#encoder does so, but other encoders do not! This caused issue 14 and issue 16.
#As such, we now search by block time VORBIS_COMMENT. There should only be one such.
flacdata = os.popen("%smetaflac --list --block-type VORBIS_COMMENT %s" %
(
metaflacpath,
flacfile
)
)
datalist = [] #init a list for storing all the data in this block
#this dictionary (note different brackets) will store only the comments
#for the music file
commentlist = {}
#parse the metaflac output looking for a Vorbis comment metablock, identified as:
# METADATA block #?
# type: 4 (VORBIS_COMMENT)
#then start scanning for Vorbis comments. This localised searching ensures that
#"comment" tags in non Vorbis metablocks don't corrupt the music tags
foundnewmetadatablock = 0
lookingforvorbiscomments = 0
for data in flacdata.readlines():
#get rid of any whitespace from the left to the right
data = string.strip(data)
#only start looking for Vorbis comments once we have latched onto a
#new metadata block of type 4
if(foundnewmetadatablock == 1 and data == "type: 4 (VORBIS_COMMENT)"):
lookingforvorbiscomments = 1
if(foundnewmetadatablock == 1):
foundnewmetadatablock = 0
if(data[:16] == "METADATA block #"):
foundnewmetadatablock = 1
lookingforvorbiscomments = 0
if (lookingforvorbiscomments == 1):
#check if the tag is a comment field (shown by the first 8 chars
#spelling out "comment[")
if(data[:8] == "comment["):
datalist.append(string.split(data,":",1))
for data in datalist:
#split according to [NAME]=[VALUE] structure
comment = string.split(data[1],"=")
comment[0] = string.strip(comment[0])
comment[1] = string.strip(comment[1])
#convert to upper case
#we want the key values to always be the same case, we decided on
#uppercase (whether the string is upper or lowercase, is dependent
# on the tagger used)
comment[0] = string.upper(comment[0])
#assign key:value pair, comment[0] will be the key, and comment[1]
#the value
commentlist[comment[0]] = comment[1]
return commentlist
def flactest(self,file,outfile):
test = os.popen(flacpath + "flac -s -t \"" + file + "\"",'r')
#filepath = generateoutdir(file,outfile) + "results.log"
#if (os.path.exists(filepath)):
# os.remove(filepath)
#os.mknod(filepath,0775)
#out = os.popen(filepath,'w')
#results = ""
#for line in test.readlines():
# print "++++++++++++" + line
# results = line
# out.write(results)
# print "==============" + results
# test.flush()
test.close()
# out.flush()
# out.close()
#Class dealing with shell/output related things:
class shell:
def generateoutdir(self,indir, outdir,dirpath):
#if we find the dirpath in the current output path, we replace
#it with the new output path. (so that we don't get
#/mnt/convertedfromflac/mnt/flac/[file].mp3, in this case
#"/mnt/" exist in both)
if (string.find(os.path.split(indir)[0], dirpath) != -1):
return string.replace(os.path.split(indir)[0], dirpath, outdir)
else:
#if we do not find an instance of dir path in output
#path (this shows that they are the same), just
#return the output
return outdir
def parseEscapechars(self,file,quoteonly=False):
#TODO: look at docs.python.org/2/library/codecs.html for info on how to do this better
if(quoteonly == False):
#characters which must be escaped in the shell, note
#"[" and "]" seems to be automatically escaped
#(strange, look into this)
escChars = ["\"","*",";"," ","'","(",")","&","`","$"]
for char in escChars:
#add an escape character to the character
file = string.replace(file, char, '\\' + char)
else:
file = string.replace(file, "\"", "\\\"")
return file
def getfiles(self,path):
infiles = os.listdir(path) #the files going in for reading
outfiles = [] #the files going out in a list
for file in infiles:
if(os.path.isdir(os.path.join(path,file))):
#recursive call
outfiles = outfiles + self.getfiles(os.path.join(path,file))
else:
outfiles.append(os.path.join(path,file))
return outfiles
#mp3 class:
class mp3:
def __init__(self):
pass #keep the constructor empty for now
def generateLameMeta(self,metastring):
tagstring = ""
#pointer to the parseEscapechars method in the shell class
parseEscapechars = shell().parseEscapechars
#Dealing with genres defined within lame
acceptable_genres=[\
"A Cappella",\
"Acid",\
"Acid Jazz",\
"Acid Punk",\
"Acoustic",\
"Alternative",\
"Alt. Rock",\
"Ambient",\
"Anime",\
"Avantgarde",\
"Ballad",\
"Bass",\
"Beat",\
"Bebob",\
"Big Band",\
"Black Metal",\
"Bluegrass",\
"Blues",\
"Booty Bass",\
"BritPop",\
"Cabaret",\
"Celtic",\
"Chamber Music",\
"Chanson",\
"Chorus",\
"Christian Gangsta Rap",\
"Christian Rap",\
"Christian Rock",\
"Classical",\
"Classic Rock",\
"Club",\
"Club-House",\
"Comedy",\
"Contemporary Christian",\
"Country",\
"Crossover",\
"Cult",\
"Dance",\
"Dance Hall",\
"Darkwave",\
"Death Metal",\
"Disco",\
"Dream",\
"Drum & Bass",\
"Drum Solo",\
"Duet",\
"Easy Listening",\
"Electronic",\
"Ethnic",\
"Eurodance",\
"Euro-House",\
"Euro-Techno",\
"Fast-Fusion",\
"Folk",\
"Folklore",\
"Folk/Rock",\
"Freestyle",\
"Funk",\
"Fusion",\
"Game",\
"Gangsta Rap",\
"Goa",\
"Gospel",\
"Gothic",\
"Gothic Rock",\
"Grunge",\
"Hardcore",\
"Hard Rock",\
"Heavy Metal",\
"Hip-Hop",\
"House",\
"Humour",\
"Indie",\
"Industrial",\
"Instrumental",\
"Instrumental Pop",\
"Instrumental Rock",\
"Jazz",\
"Jazz+Funk",\
"JPop",\
"Jungle",\
"Latin", \
"Lo-Fi", \
"Meditative", \
"Merengue", \
"Metal", \
"Musical", \
"National Folk", \
"Native American", \
"Negerpunk", \
"New Age", \
"New Wave", \
"Noise", \
"Oldies", \
"Opera", \
"Other", \
"Polka", \
"Polsk Punk", \
"Pop", \
"Pop-Folk", \
"Pop/Funk", \
"Porn Groove", \
"Power Ballad", \
"Pranks", \
"Primus", \
"Progressive Rock", \
"Psychedelic", \
"Psychedelic Rock", \
"Punk", \
"Punk Rock", \
"Rap", \
"Rave", \
"R&B", \
"Reggae", \
"Retro", \
"Revival", \
"Rhythmic Soul", \
"Rock", \
"Rock & Roll", \
"Salsa", \
"Samba", \
"Satire", \
"Showtunes", \
"Ska", \
"Slow Jam", \
"Slow Rock", \
"Sonata", \
"Soul", \
"Sound Clip", \
"Soundtrack", \
"Southern Rock", \
"Space", \
"Speech", \
"Swing", \
"Symphonic Rock", \
"Symphony", \
"Synthpop", \
"Tango", \
"Techno", \
"Techno-Industrial", \
"Terror", \
"Thrash Metal", \
"Top 40", \
"Trailer", \
"Trance", \
"Tribal", \
"Trip-Hop", \
"Vocal"]
genre_is_acceptable = 0 #By default the genre is not acceptable
current_genre = "" #variable stores current genre tag
for genre in acceptable_genres:
#print string.strip(metastring['GENRE'])+" ==> "+string.strip(genre)
try:
current_genre = string.upper(metastring['GENRE'].strip())
except(KeyError):
current_genre = "NO GENRE TAG"
#case-insesitive comparison
if current_genre == string.upper(genre.strip()):
genre_is_acceptable = 1 #we can use the genre
if genre_is_acceptable == 0: #if genre cannot be used
print "The Genre \"" + current_genre + "\" cannot be used with lame, setting to \"Other\" "
metastring['GENRE'] = "Other" #set GENRE to Other
else:
#Capitalise the Genre, as per lame requirements
metastring['GENRE'] = string.capitalize(metastring['GENRE'])
genre_is_acceptable = 0 #reset the boolean value for the next time
try:
tagstring = "--tt " + "\"" + parseEscapechars(metastring["TITLE"],True) + "\""
except(KeyError):
pass #well we skip the comment field if is doesn't exist
try:
tagstring = tagstring + " --ta " + "\"" + parseEscapechars(metastring['ARTIST'],True) + "\""
except(KeyError):
pass
try:
tagstring = tagstring + " --tl " + "\"" + parseEscapechars(metastring['ALBUM'],True) + "\""
except(KeyError):
pass
try:
tagstring = tagstring + " --ty " + "\"" + parseEscapechars(metastring['DATE'],True) + "\""
except(KeyError):
pass
try:
tagstring = tagstring + " --tg " + "\"" + parseEscapechars(metastring['GENRE'],True) + "\""
except(KeyError):
pass
try:
tagstring = tagstring + " --tn " + "\"" + parseEscapechars(metastring['TRACKNUMBER'],True) + "\""
except(KeyError):
pass
#COMMENTS AND CDDB ARE PLACED TOGETHER, as there exists no seperate
#"CDDB Field" option for mp3. this is only if we have a comment to begin with
try:
tagstring = tagstring + " --tc " + "\"" + parseEscapechars(metastring['COMMENT'],True)
try:
tagstring = tagstring + " || CDDB:" + parseEscapechars(metastring['CDDB'],True) + "\""
except(KeyError):
tagstring = tagstring + "\"" #close the final "comment field, without CDDB info
except(KeyError):
#this is for if we have a CDDB value
try:
tagstring = tagstring + " --tc \"CDDB:" + parseEscapechars(metastring['CDDB'],True) + "\""
except(KeyError):
pass
#Metadata population complete
return tagstring
def mp3convert(self,lameopts,infile,outfile):
#give us an output file, full path, which is the same as the infile
#(minus the working directory path) and with the extension stripped
#outfile = os.path.join(outdir+"/",os.path.split(infile)[-1]).strip(".flac")
#pdb.set_trace()
try:
metastring = generateLameMeta(infile)
except(UnboundLocalError):
metastring = "" #If we do not get meta information. leave blank
#Uncomment the line below if you want the file currently being
#converted to be displayed
#print parseEscapechars(infile)
#rb stands for read-binary, which is what we are doing, with a 1024 byte buffer
decoder = os.popen(flacpath + "flac -d -s -c " + shell().parseEscapechars(infile),'rb',1024)
#wb stands for write-binary
encoder = os.popen("%slame --silent %s - -o %s.mp3 %s" % (
lamepath,
lameopts,
shell().parseEscapechars(outfile),
metastring
) ,'wb',8192)
# encoder = os.popen(lamepath + "lame --silent " + lameopts + " - -o " + shell().parseEscapechars(outfile) + ".mp3 " + metastring,'wb',8192)
for line in decoder.readlines(): #while data exists in the decoders buffer
encoder.write(line) #write it to the encoders buffer
decoder.flush() #if there is any data left in the buffer, clear it
decoder.close() #somewhat self explanetory
encoder.flush() #as above
encoder.close()
#END OF CLASSES, Main body of code follows:
#Functions defined here
def header():
return """
Flac2all python script, v3 . Copyright 2006-2015 Ziva-Vatra.com.
Licensed under the GPLv3 .
Project website: http://code.google.com/p/flac2all/
"""
def infohelp():
return """
flac2all [convert type] [input dir] <options>
where \'convert type\' is one of:
\t [mp3]: convert file to mp3
\t [vorbis]: convert file to ogg vorbis
\t [opus]: convert file to opus
\t [flac]: convert file to flac
\t [aacplusnero]: (NO TAGGING SUPPORT) convert file to aacplus using the proprietery (but excellent) Nero AAC encoder."""
def init():
pass #do nothing, prolly remove this function
#The above currently not used for anything useful
#binpath = os.path.defpath #get the $PATH variable from the os
def encode_thread(current_file,filecounter,opts):
#remove the dirpath placed in parameters, so that we work from that
#directory
current_file_local = current_file.replace(opts['dirpath'],'')
if (opts['nodirs'] == True):
outdirFinal = opts['outdir']
else:
if (opts['include_root'] == True):
outdirFinal = opts['outdir'] + os.path.split(opts['dirpath'])[1] + os.path.split(current_file_local)[0]
else:
outdirFinal = opts['outdir'] + os.path.split(current_file_local)[0]
#if the path does not exist, then make it
if (os.path.exists(outdirFinal) == False):
#the try/catch here is to deal with race condition, sometimes one
#thread creates the path before the other, causing errors
try:
#recursive, will make the entire path if required
os.makedirs(outdirFinal)
except(OSError):
print "Directory already exists! Reusing..."
#this chunk of code provides us with the full path sans extension
outfile = os.path.join(outdirFinal,os.path.split(current_file_local)[1])
#return the name on its own, without the extension
outfile = string.split(outfile, ".flac")[0]
#This part deals with copying non-music data over (so everything that isn't
#a flac file)
if (string.lower(current_file [-4:]) != "flac"):
if (opts['copy'] == True):
print "Copying file #%d (%s) to destination" % (filecounter,current_file.split('/')[-1])
if ( os.path.exists(outfile) == True) and (opts['overwrite'] == False):
if os.stat(current_file).st_mtime - os.stat(outfile).st_mtime > 1:
os.system("cp \"%s\" \"%s\"" % (current_file,outdirFinal) )
else:
print "File %s is same size as destination. Not copying" % current_file
filecounter += 1
if(opts['overwrite'] == False): #if we said not to overwrite files
#if a file with the same filename/path does not already exist
#the below is because "vorbis" is "ogg" extension, so we need the right extension
#if we are to correctly check for existing files.
if opts['mode'] == "vorbis":
ext = "ogg"
else:
ext = opts['mode']
if not (os.path.exists(outfile + "." + ext)):
#[case insensitive] check if the last 4 characters say flac (as in
#flac extension, if it doesn't, then we assume it is not a flac
#file and skip it
if (string.lower(current_file [-4:]) == "flac"):
if (opts['mode'] != "test"):
print "converting file #%d to %s" % (filecounter,opts['mode'])
else:
print "testing file #" + str(filecounter)
if(opts['mode'] == "mp3"):
mp3Class.mp3convert(opts['lameopts'],current_file,outfile)
elif(opts['mode'] == "flac"):
flacClass.flacconvert(opts['flacopts'],current_file,outfile)
elif(opts['mode'] == "vorbis"):
vorbisClass.oggconvert(opts['oggencopts'],current_file,outfile)
elif(opts['mode'] == "opus"):
opusClass.opusconvert(opts['opusencopts'],current_file,outfile)
elif(opts['mode'] == "aacplusnero"):
aacpClass.AACPconvert(opts['aacplusopts'],current_file,outfile)
elif(opts['mode'] == "test"):
flacClass.flactest(current_file, outfile)
else:
print "Error, Mode %s not recognised. Thread dying" % opts['mode']
sys.exit(-2)
else:
print "file #%d exists, skipping" % filecounter
else:
#[case insensitive] check if the last 4 characters say flac (as in flac
#extension, if it doesn't, then we assume it is not a flac file and
#skip it
if (string.lower(current_file [-4:]) == "flac"):
if (opts['mode'] != "test"):
print "Converting file %d to %s" % (filecounter,opts['mode'])
else:
print "Testing file %d" % filecounter
if(opts['mode'] == "mp3"):
mp3Class.mp3convert(opts['lameopts'],current_file,outfile)
elif(opts['mode'] == "flac"):
flacClass.flacconvert(opts['flacopts'],current_file,outfile)
elif(opts['mode'] == "vorbis"):
vorbisClass.oggconvert(opts['oggencopts'],current_file,outfile)
elif(opts['mode'] == "opus"):
opusClass.opusconvert(opts['opusencopts'],current_file,outfile)
elif(opts['mode'] == "aacplusNero"):
aacpClass.AACPconvert(opts['aacplusopts'],current_file,outfile)
elif(opts['mode'] == "test"):
flacClass.flactest(current_file, outfile)
else:
print "Error, Mode %s not recognised. Thread dying" % opts['mode']
sys.exit(-2)
return filecounter + 1 #increment the file we are doing
def generateLameMeta(mp3file):
metastring = flac().getflacmeta("\"" + mp3file + "\"")
return mp3Class.generateLameMeta(metastring)
#Metadata population complete
#END Functions
#Code starts here
#Variables are here
#***NOTE***
#if the *path variables below are left blank, then the script will try to find
#the programs automatically. only change these if the script does not work
#(or add the programs to your system $PATH variable)
flacpath="" #path to flac binary, blank by default
metaflacpath="" #path to metaflac, blank be default
oggencpath="" #path to oggenc binary, blank by default
opusencpath="" #path to opusenc binary, blank by default
lamepath="" #path to lame binary, blank by default
aacpath="" #path to aacplus binary, blank by default
opts = {
"outdir":"./", #the directory we output to, defaults to current directory
"overwrite":False, #do we overwrite existing files
"nodirs":False, #do not create directories (dump all files into single dir)
"copy":False, #Copy non flac files (default is to ignore)
"buffer":2048, #How much to read in at a time
"lameopts":"--preset standard -q 0", #your mp3 encoding settings
"oggencopts":"quality=2", # your vorbis encoder settings
"opusencopts":"bitrate 128", # your opus encoder settings
"flacopts":"-q 8", #your flac encoder settings
"aacplusopts":"-q 0.3 ",
"include_root":False,
}
#This area deals with checking the command line options,
from optparse import OptionParser
parser = OptionParser(usage=infohelp())
parser.add_option("-c","--copy",action="store_true",dest="copy",
default=False,help="Copy non flac files across (default=False)")
parser.add_option("-v","--vorbis-options",dest="oggencopts",
default="quality=2",help="Colon delimited options to pass to oggenc,for example:" +
" 'quality=5:resample 32000:downmix:bitrate_average=96'." +
" Any oggenc long option (one with two '--' in front) can be specified in the above format.")
parser.add_option("-p","--opus-options",dest="opusencopts",
default="bitrate 128",help="Colon delimited options to pass to opusenc,for example:" +
" 'bitrate 256:expect-loss:downmix-stereo'." +
" Any opusenc long option (one with two '--' in front) can be specified in the above format.")
parser.add_option("-l","--lame-options",dest="lameopts",
default="-preset standard:q 0",help="Options to pass to lame, for example: '-preset extreme:q 0:h:-abr'. "+
"Any lame option can be specified here, if you want a short option (e.g. -h), then just do 'h'. "+
"If you want a long option (e.g. '--abr'), then you need a dash: '-abr'")
parser.add_option("-a","--aacplus-options",dest="aacplusopts",
default="-q 0.3", help="AACplus options, currently only bitrate supported. e.g: \" -br 64 \""),
parser.add_option("-o","--outdir",dest="outdir",metavar="DIR",
help="Set custom output directory (default='./')",
default="./"),
parser.add_option("-f","--force",dest="overwrite",action="store_true",
help="Force overwrite of existing files (by default we skip)",
default=False),
parser.add_option("-t","--threads",dest="threads",default=multiprocessing.cpu_count(),
help="How many threads to run in parallel (default: autodetect [found %d cpu(s)] )" % multiprocessing.cpu_count())
parser.add_option("-n","--nodirs",dest="nodirs",action="store_true",
default=False,help="Don't create Directories, put everything together")
parser.add_option("-x","--exclude",dest="exclude",default=None, help="exclude certain files from processing by PATTERN (regular expressions supported)")
parser.add_option("-r","--include-root",dest="root_include", action="store_true", default=False, help="Include the top-level directory in output path ( default=False )")
##The below isn't used anymore, so removed as an option (to re-add in future?)
#parser.add_option("-B","--buffer",dest="buffer",metavar="size",
# help="How much we should buffer before encoding to mp3 (in KB). The larger "+
# "you set this too, the more of the song will be buffered before "+
# "encoding. Set it high enough and it will buffer everything to RAM"+
# "before encoding.")
(options,args) = parser.parse_args()
#update the opts dictionary with new values
opts.update(eval(options.__str__()))
#convert the formats in the args to valid formats for lame, oggenc and opusenc
opts['oggencopts'] = ' --'+' --'.join(opts['oggencopts'].split(':'))
opts['opusencopts'] = ' --'+' --'.join(opts['opusencopts'].split(':'))
#lame is stupid, it is not consistent, sometimes using long opts, sometimes not
#so we need to specify on command line with dashes whether it is a long op or short
opts['lameopts'] = ' -'+' -'.join(opts['lameopts'].split(':'))
print header()
#pdb.set_trace()
try:
opts['mode'] = args[0]
except(IndexError): #if no arguments specified
print "No mode specified! Run with '-h' for help"
sys.exit(-1) #quit the program with non-zero status
try:
opts['dirpath'] = os.path.realpath(args[1])
except(IndexError):
print "No directory specified! Run with '-h' for help"
sys.exit(-1) #quit the program with non-zero status
#end command line checking
#start main code
#create instances of classes
mp3Class = mp3()
shellClass = shell()
flacClass = flac()
vorbisClass = vorbis()
opusClass = opus()
aacpClass = aacplusNero()
filelist=shellClass.getfiles(opts['dirpath'])
#if "exclude" set, filter out by regular expression
if opts['exclude'] != None:
rex = re.compile(opts['exclude'])
filelist = filter(lambda x: re.search(rex,x) == None, filelist) #Only return items that don't match
flacnum = 0 #tells us number of flac media files
filenum = 0 #tells us number of files
#pdb.set_trace()
for files in filelist:
filenum += 1
#make sure both flac and FLAC are read
if (string.lower(files [-4:]) == "flac"):
flacnum += 1
print "There are %d files, of which %d are convertable FLAC files" % \
(filenum,flacnum)
print "We are running %s simultaneous transcodes" % opts['threads']
if flacnum == 0:
print "Error, we got no flac files. Are you sure you put in the correct directory?"
sys.exit(-1)
x = 0 #temporary variable, only to keep track of number of files we have done
#Why did we not use "for file in filelist" for the code below? Because this is
#more flexible. As an example for multiple file encoding simultaniously, we
#can do filelist.pop() multiple times (well, along with some threading, but its
#good to plan for the future.
#one thread is always for the main program, so if we want two encoding threads,
#we need three threads in total
opts['threads'] = int(opts['threads']) + 1
while len(filelist) != 0: #while the length of the list is not 0 (i.e. not empty)
#remove and return the first element in the list
current_file = filelist.pop()
#threaded process, used by default
threading.Thread(target=encode_thread,args=(
current_file,
x,
opts
)
).start()
#Don't use threads, single process, used for debugging
#x = encode_thread(current_file,nodirs,x,lameopts,flacopts,oggencopts,mode)
while threading.activeCount() == opts['threads']:
#just sit and wait. we check every tenth second to see if it has
#finished
time.sleep(0.3)
x += 1
#END
| Python |
#!/usr/bin/python2
import os,shutil
from sys import exit,platform
import subprocess as sp
from time import sleep
infolder = "testinput"
outfolder = "testoutput"
if not os.path.exists(infolder):
print "Error, %s does not exist. Please create it and stick some FLAC files in there for testing" % infolder
exit(1)
#files = os.listdir(infolder)
#flacfiles = filter(lambda x: x.endswith(".flac"), files)
#if len(flacfiles) == 0:
# print "No flac files found in %s. Please put some in there for testing (no subfolders please)"
# exit(2)
if not os.path.exists(outfolder): os.mkdir(outfolder)
testypes = ["mp3,vorbis,opus","flac","aacplus","mp3","vorbis","flac","opus"];
#testypes = ["mp3,vorbis,opus","flac","mp3","vorbis","flac","opus"];
if ( platform == "linux2") or ( platform == "linux") :
testypes.append("aacplusnero") #Nero AAC is only available on Linux, of the Unix family
for test in testypes:
sleep(10)
args = [
"--lame-options='-preset standard' ",
"--aacplus-options 'br 64'",
"--vorbis-options='quality=5:resample 32000:downmix'",
"--opus-options='bitrate 96'"
]
for opt in ('-c','-f','-t 4','-n'):
cmd = "python2 ./__main__.py %s %s %s -o %s %s" % (test,' '.join(args),opt,outfolder,infolder)
print '-'*80
print "Executing: %s" % cmd
print '-'*80
rc = sp.call(cmd,shell=True)
if (rc != 0) :
print "ERROR Executing command: \"%s\"\n" % cmd
exit(rc)
#print "All successful! Deleting output folder"
#shutil.rmtree(outfolder)
print "Done!"
| Python |
# -*- coding: utf-8 -*-
# vim ts=4 expandtab si
import os
import string
class shell:
def generateoutdir(self,indir, outdir,dirpath):
#if we find the dirpath in the current output path, we replace
#it with the new output path. (so that we don't get
#/mnt/convertedfromflac/mnt/flac/[file].mp3, in this case
#"/mnt/" exist in both)
if (string.find(os.path.split(indir)[0], dirpath) != -1):
return string.replace(os.path.split(indir)[0], dirpath, outdir)
else:
#if we do not find an instance of dir path in output
#path (this shows that they are the same), just
#return the output
return outdir
def parseEscapechars(self,file,quoteonly=False):
if(quoteonly == False):
#characters which must be escaped in the shell, note
#"[" and "]" seems to be automatically escaped
#(strange, look into this)
escChars = ["\"","*",";"," ","'","(",")","&","`"]
for char in escChars:
#add an escape character to the character
file = string.replace(file, char, '\\' + char)
else:
file = string.replace(file, "\"", "\\\"")
return file
def getfiles(self,path):
outfiles = []
for root, dirs, files in os.walk(path):
for infile in files:
outfiles.append(
os.path.abspath(
os.path.join(root,infile)
)
)
return outfiles
| Python |
# vim: ts=4 ai expandtab
import os,re
from shell import shell
from time import time
from flac import flacdecode
from config import opusencpath
import subprocess as sp
#Class that deals with the opus codec
class opus:
def __init__(self,opusencopts):
#Work out what version of opus we have
self.version=None #Unknown by default
#Opus is really all over the place, each version has different
#switches. I guess that is what happens with new stuff.
try:
data = sp.check_output(["%sopusenc" % opusencpath, "-V"])
except sp.CalledProcessError as e:
data = sp.check_output(["%sopusenc" % opusencpath, "-v"])
data = re.search("\d\.\d\.\d",data).group(0)
(release,major,minor) = map(lambda x: int(x), data.split('.'))
self.version=(release,major,minor)
self.opts = opusencopts
def opusConvert(self,infile,outfile,logq):
# As the new versions of opus support flac natively, I think that the best option is to
# use >0.1.7 by default, but support earlier ones without tagging.
startTime = time()
if self.version == None:
print "ERROR! Could not discover opus version, assuming version >= 0.1.7. THIS MAY NOT WORK!"
version = (9,9,9)
else: version=self.version
#If we are a release prior to 0.1.7, use non-tagging type conversion, with warning
if (version[0] == 0) and (version[1] <= 1) and (version[2] <= 6):
print "WARNING: Opus version prior to 0.1.7 detected, NO TAGGING SUPPORT"
decoder = flacdecode(infile)()
encoder = sp.Popen("%sopusenc %s - %s.opus 2> /tmp/opusLog" % (
opusencpath,
self.opts,
shell().parseEscapechars(outfile),
) ,
shell=True,
bufsize=8192,
stdin=sp.PIPE
).stdin
for line in decoder.readlines(): #while data exists in the decoders buffer
encoder.write(line) #write it to the encoders buffer
decoder.flush() #if there is any data left in the buffer, clear it
decoder.close() #somewhat self explanetory
encoder.flush() #as above
encoder.close()
logq.put([infile,outfile,"opus","SUCCESS_NOTAGGING",0, time() - startTime])
else:
#Later versions support direct conversion from flac->opus, so no need for the above.
rc = os.system("%sopusenc %s --quiet %s %s.opus" %
(
opusencpath,
self.opts,
shell().parseEscapechars(infile),
shell().parseEscapechars(outfile)
)
)
if ( rc != 0 ):
logq.put([infile,outfile,"opus","ERROR: error executing opusenc. Could not convert",rc, time() - startTime])
else:
logq.put([infile,outfile,"opus","SUCCESS",rc, time() - startTime])
| Python |
#This file holds all the config details
#***NOTE***
#if the *path variables below are left blank, then the script will try to find
#the programs automatically. only change these if the script does not work
#(or add the programs to your system $PATH variable)
flacpath="" #path to flac binary, blank by default
metaflacpath="" #path to metaflac, blank be default
oggencpath="" #path to oggenc binary, blank by default
lamepath="" #path to lame binary, blank by default
aacpath="/usr/bin/" #path to aacplus binary, blank by default
neroaacpath="" #path to the Nero aacplus binary, blank by default
opusencpath=""
# These are global defaults, if you don't define a shell
# argument, the below will be used instead.
opts = {
"outdir":"./", #the directory we output to, defaults to current directory
"overwrite":False, #do we overwrite existing files
"nodirs":False, #do not create directories (dump all files into single dir)
"copy":False, #Copy non flac files (default is to ignore)
"lameopts":"--preset standard -q 0", #your mp3 encoding settings
"oggencopts":"quality=2", # your vorbis encoder settings
"flacopts":"-q 8", #your flac encoder settings
"aacplusopts":"-a 1 -t 29",
"neroaacplusopts":"-q 0.3 ", #aac as well
"opusopts":"bitrate 96", #For opus (placeholder for now)
}
| Python |
# vim: ts=4 autoindent expandtab
from config import *
import os
from shell import shell
from time import time
#Class that deals with vorbis
class vorbis:
def __init__(self,vorbis_options):
self.opts = vorbis_options
def oggconvert(self,infile,outfile,logq):
#oggenc automatically parses the flac file + metadata, quite wonderful
#really, we don't need to do anything here
#The binary itself deals with the tag conversion etc
#Which makes our life rather easy
startTime = time()
rc = os.system("%soggenc %s -Q -o %s.ogg %s" %
(
oggencpath,
self.opts,
shell().parseEscapechars(outfile),
shell().parseEscapechars(infile)
)
)
if rc == 0: result="SUCCESS"
else: result="ERROR:oggenc"
logq.put([infile,outfile,"vorbis",result,rc, time() - startTime])
| Python |
#!/bin/python2.6
# -*- coding: utf-8 -*-
# vim: ts=4 ai expandtab
from aac import aacplusNero,aacplus
from vorbis import vorbis
from flac import flac
from mp3 import lameMp3 as mp3
from shell import shell
from opus import opus
import multiprocessing as mp
import threading as mt
from optparse import OptionParser
from config import *
import sys, os, time, threading, Queue
sh = shell()
# process Queue, the queue that will hold all the flac files we want to convert.
# format: [ $infile, $target_format ]
pQ = mp.Queue()
#copy Queue (for copying non flac files if requested)
# format: [ $infile, $outfile ]
cQ = mp.Queue()
# logging Queue, the encoders log progress to this
# fomat: [ $infile, $outfile, $format, $error_status, $return_code, $execution_time ]
lQ = mp.Queue()
#This area deals with checking the command line options,
def prog_usage():
return """
Flac2all python script, version 4. Copyright 2006-2015 ziva-vatra
Licensed under the GPLv3 or later (http://www.ziva-vatra.com).
Please see http://www.gnu.org/licenses/gpl.txt for the full licence.
Main project website: http://code.google.com/p/flac2all/
\tUsage: %s enctype1[,enctype2..] [options] inputdir
\tValid encode types are as follows: %s
\tYou can specify multiple encode targets with a comma seperated list.
""" % (sys.argv[0], "mp3 vorbis aacplusnero opus flac test")
# I've decided that the encoder options should just be long options.
# quite frankly, we are running out of letters that make sense.
# plus it makes a distinction between encoder opts, and program opts
# (which will continue to use single letters)
parser = OptionParser(usage=prog_usage())
parser.add_option("-c","--copy",action="store_true",dest="copy",
default=False,help="Copy non flac files across (default=False)")
parser.add_option("","--opus-options",dest="opusencopts",
default="music",help="Colon delimited options to pass to opusenc. Any oggenc long option (one with two '--' in front) can be specified in the above format.")
parser.add_option("","--vorbis-options",dest="oggencopts",
default="quality=2",help="Colon delimited options to pass to oggenc,for example:" +
" 'quality=5:resample 32000:downmix:bitrate_average=96'." +
" Any oggenc long option (one with two '--' in front) can be specified in the above format.")
parser.add_option("","--lame-options",dest="lameopts",
default="-preset standard:q 0",help="Options to pass to lame, for example: '-preset extreme:q 0:h:-abr'. "+
"Any lame option can be specified here, if you want a short option (e.g. -h), then just do 'h'. "+
"If you want a long option (e.g. '--abr'), then you need a dash: '-abr'")
parser.add_option("","--aacplus-options",dest="neroaacplusopts",
default="q 0.3", help="Nero AACplus options, valid options is one of: Quality (q $float), bitrate (br $int), or streaming bitrate (cbr $int) "),
parser.add_option("-o","--outdir",dest="outdir",metavar="DIR",
help="Set custom output directory (default='./')",
default="./"),
parser.add_option("-f","--force",dest="overwrite",action="store_true",
help="Force overwrite of existing files (by default we skip)",
default=False),
parser.add_option("-t","--threads",dest="threads",default=mp.cpu_count(),
help="How many threads to run in parallel (default: autodetect [found %d cpu(s)] )" % mp.cpu_count())
parser.add_option("-n","--nodirs",dest="nodirs",action="store_true",
default=False,help="Don't create Directories, put everything together")
(options,args) = parser.parse_args()
#update the opts dictionary with new values
opts.update(eval(options.__str__()))
#convert the formats in the args to valid formats for lame and oggenc
opts['oggencopts'] = ' --'+' --'.join(opts['oggencopts'].split(':'))
opts['opusencopts'] = ' --'+' --'.join(opts['opusencopts'].split(':'))
# Nero codec is annoying, as it takes bitrate in actual bits/s, rather than kbit/s
# as every other codec on earth works. So we need to parse things out and convert
enctype,rate = opts['neroaacplusopts'].split(' ')
if enctype == "br" or enctype == "cbr":
opts['neroaacplusopts'] = ' -%s %d' % (enctype, int(rate) * 1000 )
else:
opts['neroaacplusopts'] = ' -%s %s' % (enctype, rate)
#lame is stupid, it is not consistent, sometimes using long opts, sometimes not
#so we need to specify on command line with dashes whether it is a long op or short
opts['lameopts'] = ' -'+' -'.join(opts['lameopts'].split(':'))
#pdb.set_trace()
try:
opts['mode'] = args[0]
except(IndexError): #if no arguments specified
print "No mode specified! Run with '-h' for help"
sys.exit(1) #quit the program with non-zero status
try:
opts['dirpath'] = os.path.abspath(args[1])
except(IndexError):
print "No directory specified! Run with '-h' for help"
sys.exit(2) #quit the program with non-zero status
#end command line checking
if os.path.exists(opts['outdir']) == False:
print "Creating output directory"
os.mkdir(opts['outdir'])
# In this version, we can convert multiple format at once, so for e.g.
# mode = mp3,vorbis will create both in parallel
for mode in opts['mode'].split(','):
if mode != "":
try:
os.mkdir(os.path.join(opts['outdir'],mode))
except OSError as e:
if e.errno == 17:
print "Folder %s already exists, reusing..." % mode
elif e.errno == 2:
print "Parent path %s does not exist! quitting..." % (
opts['outdir']
)
else:
#everything else, raise error
raise e
# Magic goes here :)
# 1. populate the queue with flac files
files = sh.getfiles(opts['dirpath'])
count = 0
for infile in files:
for mode in opts['mode'].split(','):
if infile.endswith(".flac"):
pQ.put([infile, opts['dirpath'], opts['outdir'], mode])
count += 1
else:
if opts['copy'] == True:
cQ.put([infile, opts['dirpath'], opts['outdir'], mode])
time.sleep(1) #Delay to resolve queue "broken pipe" errors
print "We have %d flac files to convert" % count
print "We have %d non-flac files to copy across" % cQ.qsize()
#error handling
modeError = Exception("Error understanding mode. Is mode valid?")
# Right, how this will work here, is that we will pass the whole queue
# to the encode threads (one per processor) and have them pop off/on as
# necessary. Allows for far more fine grained control.
class encode_thread(mt.Thread):
def __init__(self, threadID, name, taskq, opts, logq):
mt.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.taskq = taskq
self.opts = opts
self.logq = logq
def run(self):
taskq = self.taskq
opts = self.opts
logq = self.logq
while taskq.empty() == False:
try:
task = taskq.get(timeout=60) #Get the task, with one minute timeout
except Queue.Empty:
#No more tasks after 60 seconds, we can quit
return True
mode = task[3].lower()
infile = task[0]
outfile = task[0].replace(task[1], os.path.join(task[2], task[3]) )
outpath = os.path.dirname(outfile)
try:
if not os.path.exists(outpath): os.makedirs(outpath)
except OSError as e:
#Error 17 means folder exists already. We can reach this despite the check above
#due to a race condition when a bunch of processes spawned all try to mkdir
#So if Error 17, continue, otherwise re-raise the exception
if e.errno != 17: raise(e)
if mode == "mp3":
encoder = mp3(opts['lameopts'])
encf = encoder.mp3convert
elif mode == "ogg" or mode == "vorbis":
encoder = vorbis(opts['oggencopts'])
encf = encoder.oggconvert
elif mode == "aacplus":
encoder = aacplus(opts['aacplusopts'])
encf = encoder.AACPconvert
elif mode == "aacplusnero":
encoder = aacplusNero(opts['neroaacplusopts'])
encf = encoder.AACPconvert
elif mode == "opus":
encoder = opus(opts['opusencopts'])
encf = encoder.opusConvert
elif mode == "flac":
encoder = flac(opts['flacopts'])
encf = encoder.flacConvert
elif mode == "test":
logq.put([infile,outfile,mode,"ERROR: Flac testing not implemented yet", 1,0])
continue
else:
logq.put([infile,outfile,mode,"ERROR: Error understanding mode '%s' is mode valid?" % mode,1,0])
raise modeError
outfile = outfile.rstrip('.flac')
print "Converting: \t %-40s target: %8s " % (task[0].split('/')[-1],task[3])
encf(infile,outfile,logq)
# sys.exit()
#self.exit()
opts['threads'] = int(opts['threads'])
# keep flags for state (pQ,cQ)
sflags = [0,0]
ap = [] #active processes
while True:
cc = opts['threads']
while int(cc) > (len(ap)):
print ">> Spawning encoding process #%d" % len(ap)
# proc = mp.Process(target=encode_thread, args=(pQ, opts, lQ ) )
proc = encode_thread(int(cc), "Thread %d" % int(cc), pQ, opts, lQ )
proc.start()
#proc.join() #This makes it single threaded (for debugging). We wait for proc.
ap.append(proc)
time.sleep(0.5)
# Believe it or not, the only way way to be sure a queue is actually
# empty is to try to get with a timeout. So we get and put back
# and if we get a timeout error (10 secs), register it
# print sflags #Debug
try:
pQ.put(pQ.get(timeout=10))
except mp.TimeoutError as e:
print "Process queue finished."
sflags[0] = 1
except Queue.Empty as e:
print "Process queue finished."
sflags[0] = 1
else:
sflags[0] = 0
sflags[1] = 1
# Commented out until we get the shell_process_thread function written
#
#try:
# cQ.put(cQ.get(timeout=10))
#except mp.TimeoutError as e:
# print "Copy Queue finished."
# sflags[1] = 1
#except Queue.Empty as e:
# print "Copy Queue finished."
# sflags[1] = 1
#else:
# sflags[1] = 0
if sflags == [1,1]:
print "Processing Complete!"
break
#Sometimes processes die (due to errors, or exit called), which
#will slowly starve the script as they are not restarted. The below
#filters out dead processes, allowing us to respawn as necessary
ap = filter(lambda x: x.isAlive() == True, ap)
# Now wait for all running processes to complete
print "Waiting for all running process to complete."
print ap
#We don't use os.join because if a child hangs, it takes the entire program with it
st = time.time()
while True:
if len(filter(lambda x: x.is_alive() == True, ap)) == 0: break
print "-"*80
for proc in filter(lambda x: x.is_alive() == True, ap):
print "Process \"%s\" (PID: %s) is still running! Waiting..." % ( proc.name, proc.pid )
print "-"*80
time.sleep(4)
print ""
if (time.time() - st) > 600:
print "Process timeout reached, terminating stragglers and continuing anyway"
map(lambda x: x.terminate(), filter(lambda x: x.is_alive() == True, ap) )
break
#for item in ap:
# item.join()
# Now we fetch the log results, for the summary
print "Processing run log..."
log = []
while lQ.empty() == False:
log.append(lQ.get(timeout=2))
total = len(log)
successes = len(filter(lambda x: x[4] == 0, log))
failures = total - successes
print "\n\n"
print "="*80
print "| Summary "
print "-"*80
print """
Total files on input: %d
Total files actually processed: %d
--
Execution success rate: %.2f %%
Files we managed to convert successfully: %d
Files we failed to convert due to errors: %d
--
Conversion error rate: %.2f %%
""" % (count, total, ( (float(total)/count) * 100 ), successes, failures, (( failures/float(total)) * 100 ) )
for mode in opts['mode'].split(','):
# 1. find all the logs corresponding to a particular mode
x = filter(lambda x: x[2] == mode, log)
# 2. Get the execution time for all relevant logs
execT = map(lambda y: y[5], x)
esum = sum(execT)
emean = sum(execT)/len(execT)
execT.sort()
if len(execT) % 2 != 0:
#Odd number, so median is middle
emedian = execT[ (len(execT) -1 ) / 2 ]
else:
#Even set. So median is average of two middle numbers
num1 = execT[ ( (len(execT) -1 ) / 2) - 1 ]
num2 = execT[ ( (len(execT) -1 ) / 2) ]
emedian = ( sum([num1,num2]) / 2.0 )
emode = 0
print """
For mode: %s
Total execution time: %.4f seconds
Per file conversion:
\tMean execution time: %.4f seconds
\tMedian execution time: %.4f seconds
""" % (mode,esum, emean, emedian)
errout_file = opts['outdir'] + "/conversion_results.log"
print "Writing log file (%s)" % errout_file
fd = open(errout_file,"w")
fd.write("infile,outfile,format,conversion_status,return_code,execution_time\n")
for item in log:
item = map(lambda x: str(x), item)
line = ','.join(item)
fd.write("%s\n" % line)
fd.close()
print "Done!"
if failures != 0:
print "We had some failures in encoding :-("
print "Writing out error log to file %s" % errout_file
print "Done! Returning non-zero exit status! "
sys.exit(-1)
else:
sys.exit(0)
| Python |
# vim: ts=4 ai expandtab
#Class that deals with AAC+
import os,sys
from shell import shell
from flac import flac,flacdecode
from config import *
#This is for the open source implementation. In this case we went for the
# Open Source Fraunhofer AAC Encoder (fdk-aac)
class aacplus:
def __init__(self,aacopts):
self.opts = aacopts
if os.path.exists("%saac-enc" % aacpath) == False:
print "Error: %saac-enc not found (is fdk-aac installed?) Cannot convert" % aacpath
sys.exit(-1)
def AACPconvert(self,infile,outfile,logq):
inmetadata = flac().getflacmeta("\"" + infile + "\"")
decoder = flacdecode(infile)()
encoder = os.popen("%saac-enc %s - \"%s.aac\" > /tmp/aacplusLog" % (
aacpath,
self.opts,
outfile,
) ,'wb',8192)
for line in decoder.readlines(): #while data exists in the decoders buffer
encoder.write(line) #write it to the encoders buffer
decoder.flush() #if there is any data left in the buffer, clear it
decoder.close() #somewhat self explanetory
encoder.flush() #as above
encoder.close()
#For the binary-only Nero AAC encoder
class aacplusNero:
def __init__(self, aacopts):
self.opts = aacopts
if os.path.exists("%sneroAacEnc" % neroaacpath) == False:
print "ERROR: NeroAacEnc not found! Cannot convert."
sys.exit(-1)
def generateNeroTags(self,indata):
''' The new versions of nero AAC encoder for Linux provides neroAacTag '''
tags = ""
#NeroTag format (for 'standard Nero Digital') along with 'indata' keys
# title = TITLE
# artist = ARTIST
# year = DATE
# album = ALBUM
# genre = GENERE
# track = TRACKNUMBER
# totaltracks =
# disc
# totaldiscs
# url = URL
# copyright = PUBLISHER
# comment = COMMENT (if blank, put in something like 'converted by flac2all ($url)' )
# lyrics
# credits = ENCODEDBY
# rating
# label = PUBLISHER
# composer = COMPOSER
# isrc
# mood
# tempo
# In format: -meta:<name>=<value>
# User-defined fields are -meta-user:<name>=<value>
validnerotags = {
'title':'TITLE',
'artist':'ARTIST',
'year':'DATE',
'album':'ALBUM',
'genre':'GENRE',
'track':'TRACKNUMBER',
'copyright':'PUBLISHER',
'comment':'COMMENT',
'credits':'ENCODEDBY',
'label':'PUBLISHER',
'composer':'COMPOSER',
'url':'URL',
}
for nerokey in validnerotags:
try:
tag = indata[ validnerotags[nerokey] ]
except KeyError as e:
if e.message == 'COMMENT':
tag = " converted by flac2all - http://code.google.com/p/flac2all/ "
else:
continue
tags += " -meta:\"%s\"=\"%s\" " % (nerokey.strip(), tag.strip() )
return tags
def AACPconvert(self,infile,outfile,logq):
inmetadata = flac().getflacmeta("\"" + infile + "\"")
tagcmd = "%sneroAacTag " % neroaacpath
try:
metastring = self.generateNeroTags(inmetadata)
except(UnboundLocalError):
metastring = ""
decoder = flacdecode(infile)()
#wb stands for write-binary
encoder = os.popen("%sneroAacEnc %s -if - -of %s.mp4 > /tmp/aacplusLog" % (
neroaacpath,
self.opts,
shell().parseEscapechars(outfile),
) ,'wb',8192)
for line in decoder.readlines(): #while data exists in the decoders buffer
encoder.write(line) #write it to the encoders buffer
decoder.flush() #if there is any data left in the buffer, clear it
decoder.close() #somewhat self explanetory
encoder.flush() #as above
encoder.close()
#Now as the final event, load up the tags
rc = os.system("%s \"%s.mp4\" %s" % (tagcmd, outfile, metastring))
# print "%s %s.mp4 %s" % (tagcmd, outfile, metastring)
if rc != 0:
logq.put([infile,outfile,"aacNero","WARNING: Could not tag AAC file",rc, time() - startTime])
else:
logq.put([infile,outfile,"aacNero","SUCCESS",0, time() - startTime])
| Python |
# -*- coding: utf-8 -*-
# vim: ts=4 expandtab si
import os,sys
from config import *
from flac import flac, flacdecode
from shell import shell
from time import time
import uuid
import subprocess as sp
class lameMp3:
def __init__(self,lame_options):
self.opts = lame_options
def generateLameMeta(self,metastring):
tagstring = ""
#pointer to the parseEscapechars method in the shell class
parseEscapechars = shell().parseEscapechars
#Dealing with genres defined within lame
acceptable_genres=[\
"A Cappella",\
"Acid",\
"Acid Jazz",\
"Acid Punk",\
"Acoustic",\
"Alternative",\
"Alt. Rock",\
"Ambient",\
"Anime",\
"Avantgarde",\
"Ballad",\
"Bass",\
"Beat",\
"Bebob",\
"Big Band",\
"Black Metal",\
"Bluegrass",\
"Blues",\
"Booty Bass",\
"BritPop",\
"Cabaret",\
"Celtic",\
"Chamber Music",\
"Chanson",\
"Chorus",\
"Christian Gangsta Rap",\
"Christian Rap",\
"Christian Rock",\
"Classical",\
"Classic Rock",\
"Club",\
"Club-House",\
"Comedy",\
"Contemporary Christian",\
"Country",\
"Crossover",\
"Cult",\
"Dance",\
"Dance Hall",\
"Darkwave",\
"Death Metal",\
"Disco",\
"Dream",\
"Drum & Bass",\
"Drum Solo",\
"Duet",\
"Easy Listening",\
"Electronic",\
"Ethnic",\
"Eurodance",\
"Euro-House",\
"Euro-Techno",\
"Fast-Fusion",\
"Folk",\
"Folklore",\
"Folk/Rock",\
"Freestyle",\
"Funk",\
"Fusion",\
"Game",\
"Gangsta Rap",\
"Goa",\
"Gospel",\
"Gothic",\
"Gothic Rock",\
"Grunge",\
"Hardcore",\
"Hard Rock",\
"Heavy Metal",\
"Hip-Hop",\
"House",\
"Humour",\
"Indie",\
"Industrial",\
"Instrumental",\
"Instrumental Pop",\
"Instrumental Rock",\
"Jazz",\
"Jazz+Funk",\
"JPop",\
"Jungle",\
"Latin", \
"Lo-Fi", \
"Meditative", \
"Merengue", \
"Metal", \
"Musical", \
"National Folk", \
"Native American", \
"Negerpunk", \
"New Age", \
"New Wave", \
"Noise", \
"Oldies", \
"Opera", \
"Other", \
"Polka", \
"Polsk Punk", \
"Pop", \
"Pop-Folk", \
"Pop/Funk", \
"Porn Groove", \
"Power Ballad", \
"Pranks", \
"Primus", \
"Progressive Rock", \
"Psychedelic", \
"Psychedelic Rock", \
"Punk", \
"Punk Rock", \
"Rap", \
"Rave", \
"R&B", \
"Reggae", \
"Retro", \
"Revival", \
"Rhythmic Soul", \
"Rock", \
"Rock & Roll", \
"Salsa", \
"Samba", \
"Satire", \
"Showtunes", \
"Ska", \
"Slow Jam", \
"Slow Rock", \
"Sonata", \
"Soul", \
"Sound Clip", \
"Soundtrack", \
"Southern Rock", \
"Space", \
"Speech", \
"Swing", \
"Symphonic Rock", \
"Symphony", \
"Synthpop", \
"Tango", \
"Techno", \
"Techno-Industrial", \
"Terror", \
"Thrash Metal", \
"Top 40", \
"Trailer", \
"Trance", \
"Tribal", \
"Trip-Hop", \
"Vocal"]
genre_is_acceptable = 0 #By default the genre is not acceptable
current_genre = "" #variable stores current genre tag
for genre in acceptable_genres:
#print string.strip(metastring['GENRE'])+" ==> "+string.strip(genre)
try:
current_genre = metastring['GENRE'].strip().upper()
except(KeyError):
current_genre = "NO GENRE TAG"
#case-insesitive comparison
if current_genre == genre.strip().upper():
genre_is_acceptable = 1 #we can use the genre
if genre_is_acceptable == 0: #if genre cannot be used
print "The Genre \"" + current_genre + "\" cannot be used with lame, setting to \"Other\" "
metastring['GENRE'] = "Other" #set GENRE to Other
else:
#Capitalise the Genre, as per lame requirements
metastring['GENRE'] = metastring['GENRE'].capitalize()
genre_is_acceptable = 0 #reset the boolean value for the next time
try:
tagstring = "--tt " + "\"" + parseEscapechars(metastring["TITLE"],True) + "\""
except(KeyError):
pass #well we skip the comment field if is doesn't exist
try:
tagstring = tagstring + " --ta " + "\"" + parseEscapechars(metastring['ARTIST'],True) + "\""
except(KeyError):
pass
try:
tagstring = tagstring + " --tl " + "\"" + parseEscapechars(metastring['ALBUM'],True) + "\""
except(KeyError):
pass
try:
tagstring = tagstring + " --ty " + "\"" + parseEscapechars(metastring['DATE'],True) + "\""
except(KeyError):
pass
try:
tagstring = tagstring + " --tg " + "\"" + parseEscapechars(metastring['GENRE'],True) + "\""
except(KeyError):
pass
try:
tagstring = tagstring + " --tn " + "\"" + parseEscapechars(metastring['TRACKNUMBER'],True) + "\""
except(KeyError):
pass
#COMMENTS AND CDDB ARE PLACED TOGETHER, as there exists no seperate
#"CDDB Field" option for mp3. this is only if we have a comment to begin with
try:
tagstring = tagstring + " --tc " + "\"" + parseEscapechars(metastring['COMMENT'],True)
try:
tagstring = tagstring + " || CDDB:" + parseEscapechars(metastring['CDDB'],True) + "\""
except(KeyError):
tagstring = tagstring + "\"" #close the final "comment field, without CDDB info
except(KeyError):
#this is for if we have a CDDB value
try:
tagstring = tagstring + " --tc \"CDDB:" + parseEscapechars(metastring['CDDB'],True) + "\""
except(KeyError):
pass
#Metadata population complete
return tagstring
def mp3convert(self,infile,outfile,logq):
pipe = "/tmp/flac2all_"+str(uuid.uuid4()).strip()
startTime = time()
inmetadata = flac().getflacmeta(infile)
os.mkfifo(pipe)
try:
metastring = self.generateLameMeta(inmetadata)
except(UnboundLocalError):
metastring = "" #If we do not get meta information. leave blank
#rb stands for read-binary, which is what we are doing, with a 1024 byte buffer
(decoder,stderr) = flacdecode(infile,pipe)()
# if decoder == None:
# logq.put([infile,outfile,"mp3","ERROR: Could not open flac file for decoding.",-1, time() - startTime],timeout=10)
# sys.exit(-1)
#wb stands for write-binary
encoder = sp.check_call("%slame --silent %s %s -o %s.mp3 %s" % (
lamepath,
self.opts,
pipe,
shell().parseEscapechars(outfile),
metastring
) ,shell=True)
os.unlink(pipe)
errline = stderr.read()
errline = errline.upper()
if errline.strip() != '':
print "ERRORLINE: %s" % errline
if errline.find("ERROR") != -1:
logq.put([infile,"mp3","ERROR: decoder error: %s" % errline,-1,time()-startTime], timeout=10)
return False
# for line in decoder.read(): #while data exists in the decoders buffer
# errline = stderr.read(200)
# errline = errline.upper()
# if errline.strip() != '':
# print "ERRORLINE: %s" % errline
# if errline.find("ERROR") != -1:
# logq.put([infile,"mp3","ERROR: decoder error: %s" % errline,-1,time()-starttime], timeout=10)
# return False
# encoder.write(line) #write it to the encoders buffer
# decoder.flush() #if there is any data left in the buffer, clear it
# decoder.close() #somewhat self explanetory
# encoder.flush() #as above
# encoder.close()
logq.put([infile,outfile,"mp3","SUCCESS",0, time() - startTime])
| Python |
#!/usr/bin/python2
import os,shutil
from sys import exit,platform
import subprocess as sp
from time import sleep
infolder = "testinput"
outfolder = "testoutput"
if not os.path.exists(infolder):
print "Error, %s does not exist. Please create it and stick some FLAC files in there for testing" % infolder
exit(1)
#files = os.listdir(infolder)
#flacfiles = filter(lambda x: x.endswith(".flac"), files)
#if len(flacfiles) == 0:
# print "No flac files found in %s. Please put some in there for testing (no subfolders please)"
# exit(2)
if not os.path.exists(outfolder): os.mkdir(outfolder)
testypes = ["mp3,vorbis,opus","flac","aacplus","mp3","vorbis","flac","opus"];
#testypes = ["mp3,vorbis,opus","flac","mp3","vorbis","flac","opus"];
if ( platform == "linux2") or ( platform == "linux") :
testypes.append("aacplusnero") #Nero AAC is only available on Linux, of the Unix family
for test in testypes:
sleep(10)
args = [
"--lame-options='-preset standard' ",
"--aacplus-options 'br 64'",
"--vorbis-options='quality=5:resample 32000:downmix'",
"--opus-options='bitrate 96'"
]
for opt in ('-c','-f','-t 4','-n'):
cmd = "python2 ./__main__.py %s %s %s -o %s %s" % (test,' '.join(args),opt,outfolder,infolder)
print '-'*80
print "Executing: %s" % cmd
print '-'*80
rc = sp.call(cmd,shell=True)
if (rc != 0) :
print "ERROR Executing command: \"%s\"\n" % cmd
exit(rc)
#print "All successful! Deleting output folder"
#shutil.rmtree(outfolder)
print "Done!"
| Python |
#!/bin/python2.6
# -*- coding: utf-8 -*-
# vim: ts=4 ai expandtab
from aac import aacplusNero,aacplus
from vorbis import vorbis
from flac import flac
from mp3 import lameMp3 as mp3
from shell import shell
from opus import opus
import multiprocessing as mp
import threading as mt
from optparse import OptionParser
from config import *
import sys, os, time, threading, Queue
sh = shell()
# process Queue, the queue that will hold all the flac files we want to convert.
# format: [ $infile, $target_format ]
pQ = mp.Queue()
#copy Queue (for copying non flac files if requested)
# format: [ $infile, $outfile ]
cQ = mp.Queue()
# logging Queue, the encoders log progress to this
# fomat: [ $infile, $outfile, $format, $error_status, $return_code, $execution_time ]
lQ = mp.Queue()
#This area deals with checking the command line options,
def prog_usage():
return """
Flac2all python script, version 4. Copyright 2006-2015 ziva-vatra
Licensed under the GPLv3 or later (http://www.ziva-vatra.com).
Please see http://www.gnu.org/licenses/gpl.txt for the full licence.
Main project website: http://code.google.com/p/flac2all/
\tUsage: %s enctype1[,enctype2..] [options] inputdir
\tValid encode types are as follows: %s
\tYou can specify multiple encode targets with a comma seperated list.
""" % (sys.argv[0], "mp3 vorbis aacplusnero opus flac test")
# I've decided that the encoder options should just be long options.
# quite frankly, we are running out of letters that make sense.
# plus it makes a distinction between encoder opts, and program opts
# (which will continue to use single letters)
parser = OptionParser(usage=prog_usage())
parser.add_option("-c","--copy",action="store_true",dest="copy",
default=False,help="Copy non flac files across (default=False)")
parser.add_option("","--opus-options",dest="opusencopts",
default="music",help="Colon delimited options to pass to opusenc. Any oggenc long option (one with two '--' in front) can be specified in the above format.")
parser.add_option("","--vorbis-options",dest="oggencopts",
default="quality=2",help="Colon delimited options to pass to oggenc,for example:" +
" 'quality=5:resample 32000:downmix:bitrate_average=96'." +
" Any oggenc long option (one with two '--' in front) can be specified in the above format.")
parser.add_option("","--lame-options",dest="lameopts",
default="-preset standard:q 0",help="Options to pass to lame, for example: '-preset extreme:q 0:h:-abr'. "+
"Any lame option can be specified here, if you want a short option (e.g. -h), then just do 'h'. "+
"If you want a long option (e.g. '--abr'), then you need a dash: '-abr'")
parser.add_option("","--aacplus-options",dest="neroaacplusopts",
default="q 0.3", help="Nero AACplus options, valid options is one of: Quality (q $float), bitrate (br $int), or streaming bitrate (cbr $int) "),
parser.add_option("-o","--outdir",dest="outdir",metavar="DIR",
help="Set custom output directory (default='./')",
default="./"),
parser.add_option("-f","--force",dest="overwrite",action="store_true",
help="Force overwrite of existing files (by default we skip)",
default=False),
parser.add_option("-t","--threads",dest="threads",default=mp.cpu_count(),
help="How many threads to run in parallel (default: autodetect [found %d cpu(s)] )" % mp.cpu_count())
parser.add_option("-n","--nodirs",dest="nodirs",action="store_true",
default=False,help="Don't create Directories, put everything together")
(options,args) = parser.parse_args()
#update the opts dictionary with new values
opts.update(eval(options.__str__()))
#convert the formats in the args to valid formats for lame and oggenc
opts['oggencopts'] = ' --'+' --'.join(opts['oggencopts'].split(':'))
opts['opusencopts'] = ' --'+' --'.join(opts['opusencopts'].split(':'))
# Nero codec is annoying, as it takes bitrate in actual bits/s, rather than kbit/s
# as every other codec on earth works. So we need to parse things out and convert
enctype,rate = opts['neroaacplusopts'].split(' ')
if enctype == "br" or enctype == "cbr":
opts['neroaacplusopts'] = ' -%s %d' % (enctype, int(rate) * 1000 )
else:
opts['neroaacplusopts'] = ' -%s %s' % (enctype, rate)
#lame is stupid, it is not consistent, sometimes using long opts, sometimes not
#so we need to specify on command line with dashes whether it is a long op or short
opts['lameopts'] = ' -'+' -'.join(opts['lameopts'].split(':'))
#pdb.set_trace()
try:
opts['mode'] = args[0]
except(IndexError): #if no arguments specified
print "No mode specified! Run with '-h' for help"
sys.exit(1) #quit the program with non-zero status
try:
opts['dirpath'] = os.path.abspath(args[1])
except(IndexError):
print "No directory specified! Run with '-h' for help"
sys.exit(2) #quit the program with non-zero status
#end command line checking
if os.path.exists(opts['outdir']) == False:
print "Creating output directory"
os.mkdir(opts['outdir'])
# In this version, we can convert multiple format at once, so for e.g.
# mode = mp3,vorbis will create both in parallel
for mode in opts['mode'].split(','):
if mode != "":
try:
os.mkdir(os.path.join(opts['outdir'],mode))
except OSError as e:
if e.errno == 17:
print "Folder %s already exists, reusing..." % mode
elif e.errno == 2:
print "Parent path %s does not exist! quitting..." % (
opts['outdir']
)
else:
#everything else, raise error
raise e
# Magic goes here :)
# 1. populate the queue with flac files
files = sh.getfiles(opts['dirpath'])
count = 0
for infile in files:
for mode in opts['mode'].split(','):
if infile.endswith(".flac"):
pQ.put([infile, opts['dirpath'], opts['outdir'], mode])
count += 1
else:
if opts['copy'] == True:
cQ.put([infile, opts['dirpath'], opts['outdir'], mode])
time.sleep(1) #Delay to resolve queue "broken pipe" errors
print "We have %d flac files to convert" % count
print "We have %d non-flac files to copy across" % cQ.qsize()
#error handling
modeError = Exception("Error understanding mode. Is mode valid?")
# Right, how this will work here, is that we will pass the whole queue
# to the encode threads (one per processor) and have them pop off/on as
# necessary. Allows for far more fine grained control.
class encode_thread(mt.Thread):
def __init__(self, threadID, name, taskq, opts, logq):
mt.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.taskq = taskq
self.opts = opts
self.logq = logq
def run(self):
taskq = self.taskq
opts = self.opts
logq = self.logq
while taskq.empty() == False:
try:
task = taskq.get(timeout=60) #Get the task, with one minute timeout
except Queue.Empty:
#No more tasks after 60 seconds, we can quit
return True
mode = task[3].lower()
infile = task[0]
outfile = task[0].replace(task[1], os.path.join(task[2], task[3]) )
outpath = os.path.dirname(outfile)
try:
if not os.path.exists(outpath): os.makedirs(outpath)
except OSError as e:
#Error 17 means folder exists already. We can reach this despite the check above
#due to a race condition when a bunch of processes spawned all try to mkdir
#So if Error 17, continue, otherwise re-raise the exception
if e.errno != 17: raise(e)
if mode == "mp3":
encoder = mp3(opts['lameopts'])
encf = encoder.mp3convert
elif mode == "ogg" or mode == "vorbis":
encoder = vorbis(opts['oggencopts'])
encf = encoder.oggconvert
elif mode == "aacplus":
encoder = aacplus(opts['aacplusopts'])
encf = encoder.AACPconvert
elif mode == "aacplusnero":
encoder = aacplusNero(opts['neroaacplusopts'])
encf = encoder.AACPconvert
elif mode == "opus":
encoder = opus(opts['opusencopts'])
encf = encoder.opusConvert
elif mode == "flac":
encoder = flac(opts['flacopts'])
encf = encoder.flacConvert
elif mode == "test":
logq.put([infile,outfile,mode,"ERROR: Flac testing not implemented yet", 1,0])
continue
else:
logq.put([infile,outfile,mode,"ERROR: Error understanding mode '%s' is mode valid?" % mode,1,0])
raise modeError
outfile = outfile.rstrip('.flac')
print "Converting: \t %-40s target: %8s " % (task[0].split('/')[-1],task[3])
encf(infile,outfile,logq)
# sys.exit()
#self.exit()
opts['threads'] = int(opts['threads'])
# keep flags for state (pQ,cQ)
sflags = [0,0]
ap = [] #active processes
while True:
cc = opts['threads']
while int(cc) > (len(ap)):
print ">> Spawning encoding process #%d" % len(ap)
# proc = mp.Process(target=encode_thread, args=(pQ, opts, lQ ) )
proc = encode_thread(int(cc), "Thread %d" % int(cc), pQ, opts, lQ )
proc.start()
#proc.join() #This makes it single threaded (for debugging). We wait for proc.
ap.append(proc)
time.sleep(0.5)
# Believe it or not, the only way way to be sure a queue is actually
# empty is to try to get with a timeout. So we get and put back
# and if we get a timeout error (10 secs), register it
# print sflags #Debug
try:
pQ.put(pQ.get(timeout=10))
except mp.TimeoutError as e:
print "Process queue finished."
sflags[0] = 1
except Queue.Empty as e:
print "Process queue finished."
sflags[0] = 1
else:
sflags[0] = 0
sflags[1] = 1
# Commented out until we get the shell_process_thread function written
#
#try:
# cQ.put(cQ.get(timeout=10))
#except mp.TimeoutError as e:
# print "Copy Queue finished."
# sflags[1] = 1
#except Queue.Empty as e:
# print "Copy Queue finished."
# sflags[1] = 1
#else:
# sflags[1] = 0
if sflags == [1,1]:
print "Processing Complete!"
break
#Sometimes processes die (due to errors, or exit called), which
#will slowly starve the script as they are not restarted. The below
#filters out dead processes, allowing us to respawn as necessary
ap = filter(lambda x: x.isAlive() == True, ap)
# Now wait for all running processes to complete
print "Waiting for all running process to complete."
print ap
#We don't use os.join because if a child hangs, it takes the entire program with it
st = time.time()
while True:
if len(filter(lambda x: x.is_alive() == True, ap)) == 0: break
print "-"*80
for proc in filter(lambda x: x.is_alive() == True, ap):
print "Process \"%s\" (PID: %s) is still running! Waiting..." % ( proc.name, proc.pid )
print "-"*80
time.sleep(4)
print ""
if (time.time() - st) > 600:
print "Process timeout reached, terminating stragglers and continuing anyway"
map(lambda x: x.terminate(), filter(lambda x: x.is_alive() == True, ap) )
break
#for item in ap:
# item.join()
# Now we fetch the log results, for the summary
print "Processing run log..."
log = []
while lQ.empty() == False:
log.append(lQ.get(timeout=2))
total = len(log)
successes = len(filter(lambda x: x[4] == 0, log))
failures = total - successes
print "\n\n"
print "="*80
print "| Summary "
print "-"*80
print """
Total files on input: %d
Total files actually processed: %d
--
Execution success rate: %.2f %%
Files we managed to convert successfully: %d
Files we failed to convert due to errors: %d
--
Conversion error rate: %.2f %%
""" % (count, total, ( (float(total)/count) * 100 ), successes, failures, (( failures/float(total)) * 100 ) )
for mode in opts['mode'].split(','):
# 1. find all the logs corresponding to a particular mode
x = filter(lambda x: x[2] == mode, log)
# 2. Get the execution time for all relevant logs
execT = map(lambda y: y[5], x)
esum = sum(execT)
emean = sum(execT)/len(execT)
execT.sort()
if len(execT) % 2 != 0:
#Odd number, so median is middle
emedian = execT[ (len(execT) -1 ) / 2 ]
else:
#Even set. So median is average of two middle numbers
num1 = execT[ ( (len(execT) -1 ) / 2) - 1 ]
num2 = execT[ ( (len(execT) -1 ) / 2) ]
emedian = ( sum([num1,num2]) / 2.0 )
emode = 0
print """
For mode: %s
Total execution time: %.4f seconds
Per file conversion:
\tMean execution time: %.4f seconds
\tMedian execution time: %.4f seconds
""" % (mode,esum, emean, emedian)
errout_file = opts['outdir'] + "/conversion_results.log"
print "Writing log file (%s)" % errout_file
fd = open(errout_file,"w")
fd.write("infile,outfile,format,conversion_status,return_code,execution_time\n")
for item in log:
item = map(lambda x: str(x), item)
line = ','.join(item)
fd.write("%s\n" % line)
fd.close()
print "Done!"
if failures != 0:
print "We had some failures in encoding :-("
print "Writing out error log to file %s" % errout_file
print "Done! Returning non-zero exit status! "
sys.exit(-1)
else:
sys.exit(0)
| Python |
# -*- coding: utf-8 -*-
# vim: ts=4 expandtab si
import os
from config import *
from shell import shell
from time import time
import subprocess as sp
#This class is called by every other conversion function, to return a "decode" object
class flacdecode:
def __init__(self,infile,pipefile):
self.infile = infile
self.shell = shell
self.pipe = pipefile
def __call__(self):
# fd = sp.Popen([flacpath + "flac", '-d', '-s', '-o',self.pipe, "%s" % self.infile],stdout=sp.PIPE,stderr=sp.PIPE,bufsize=8192)
fd = sp.Popen([flacpath + "flac", '-d', '-s','-f', '-o',self.pipe, "%s" % self.infile],stderr=sp.PIPE)
return (None,fd.stderr)
#Class that deals with FLAC
class flac:
def __init__(self,flacopts=""):
self.opts = flacopts
self.shell = shell()
self.qEscape = lambda x: self.shell.parseEscapechars(x,True)
def flacConvert(self, infile, outfile,logq):
#TODO: see about tag copying across as well
startTime=time()
decoder = flacdecode(self.qEscape(infile))()
encoder = os.popen("%sflac %s -s -f -o \"%s.flac\" -" % (
flacpath,
self.opts,
self.qEscape(outfile),
) ,'wb',8192)
for line in decoder.readlines(): #while data exists in the decoders buffer
encoder.write(line) #write it to the encoders buffer
decoder.flush()
decoder.close()
encoder.flush()
encoder.close()
#To straight up meta copy
rc = os.system("%smetaflac --export-tags-to=- \"%s\" | %smetaflac --import-tags-from=- \"%s.flac\"" % (
metaflacpath,
self.qEscape(infile),
metaflacpath,
self.qEscape(outfile)
)
)
if (rc == 0):
logq.put([infile,outfile,"flac","SUCCESS",rc, time() - startTime])
else:
print "WARNING: Could not transfer tags to new flac file!"
logq.put([infile,outfile,"flac","WARNING: Unable to transfer tag to new flac file",0, time() - startTime])
def getflacmeta(self,flacfile):
#flacdata = os.popen("%smetaflac --list --block-type VORBIS_COMMENT \"%s\"" %
flacdata = sp.check_output([
"%smetaflac" % metaflacpath,
"--list",
"--block-type","VORBIS_COMMENT",
flacfile
]
)
datalist = [] #init a list for storing all the data in this block
#this dictionary (note different brackets) will store only the comments
#for the music file
commentlist = {}
for data in flacdata.split('\n'):
#get rid of any whitespace from the left to the right
data = data.strip()
#check if the tag is a comment field (shown by the first 7 chars
#spelling out "comment")
if(data[:8] == "comment["):
datalist.append( data.split(':') )
for data in datalist:
#split according to [NAME]=[VALUE] structure
comment = data[1].split('=')
comment[0] = comment[0].strip()
comment[1] = comment[1].strip()
#convert to upper case
#we want the key values to always be the same case, we decided on
#uppercase (whether the string is upper or lowercase, is dependent
# on the tagger used)
comment[0] = comment[0].upper()
#assign key:value pair, comment[0] will be the key, and comment[1]
#the value
commentlist[comment[0]] = comment[1]
return commentlist
def flactest(self, infile, outfile,logq):
test = os.popen("%sflac -s -t \"%s\"" % (flacpath,self.qEscape(infile)),'r')
results = test.read()
#filepath = generateoutdir(file,outfile) + "results.log"
#if (os.path.exists(filepath)):
# os.remove(filepath)
#os.mknod(filepath,0775)
#out = os.popen(filepath,'w')
#results = ""
#for line in test.readlines():
# print "++++++++++++" + line
# results = line
# out.write(results)
# print "==============" + results
# test.flush()
test.close()
# out.flush()
# out.close()
| Python |
#!/usr/bin/env python
# Copyright (c) 2008, Luke Freeman
# All rights reserved.
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this
# list of conditions and the following disclaimer in the documentation and/or
# other materials provided with the distribution.
# * Neither the name of Flag-Up nor the names of its contributors may
# be used to endorse or promote products derived from this software without specific
# prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
# GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
try:
import sys
import pygtk
import gtk, gtk.glade
pygtk.require("2.0")
except:
print "Flag-Up requires PyGTK version 2.0 or higher to run. Sorry."
sys.exit(1)
from ui.status_icon import *
icon = StatusIcon()
icon.update_icon(StatusIcon.STATUS_CHECK_UNREAD)
gtk.main()
| Python |
"""
Copyright (c) 2008, Luke Freeman
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
* Neither the name of Flag-Up nor the names of its contributors may
be used to endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
"""
import pygtk
import gtk, gtk.glade
from config.account_manager import *
from config.configuration import *
from ui.status_icon import *
from ui.glade.account_dialog import *
from ui.util import *
# TODO defer saving to the OK button. currently saves at multiple points
# TODO edit button functionality
class PreferencesDialog():
__PREF_GLADE_FILE = 'ui/glade/preferences_dialog.glade'
__config = Configuration()
__acct_mgr = AccountManager() # the account manager
def __init__(self, status_icon):
self.create_dialog()
self.status_icon = status_icon
def create_dialog(self):
self.widgets = gtk.glade.XML(PreferencesDialog.__PREF_GLADE_FILE)
self.widgets.signal_autoconnect(self) # connect the signals defined in the glade file
# get widget references
self.window = self.widgets.get_widget('dialog_preferences')
self.spin_check_interval = self.widgets.get_widget('spin_check_interval')
self.check_flash_icon = self.widgets.get_widget('check_flash_icon')
self.radio_indef_flash = self.widgets.get_widget('radio_indef_flash')
self.radio_fixed_flash = self.widgets.get_widget('radio_fixed_flash')
self.spin_flash_interval = self.widgets.get_widget('spin_flash_interval')
self.lbl_flash_suffix = self.widgets.get_widget('lbl_flash_suffix')
self.tree_accounts = self.widgets.get_widget("tree_accounts")
# define model for accounts tree view
self.account_list = gtk.ListStore (gtk.gdk.Pixbuf, bool, str, str)
self.tree_accounts.set_model(self.account_list)
cell_renderer_text = gtk.CellRendererText()
cell_renderer_pixbuf = gtk.CellRendererPixbuf()
cell_renderer_toggle = gtk.CellRendererToggle()
cell_renderer_toggle.connect('toggled', self.on_tree_accounts_column_toggled, self.account_list)
# create the mail account treeview columns
column = Util.new_treeview_column(self.tree_accounts, cell_renderer_pixbuf, "")
column.set_min_width(22)
self.tree_accounts.append_column(column)
column = Util.new_treeview_column(self.tree_accounts, cell_renderer_toggle, "")
column.set_min_width(22)
self.tree_accounts.append_column(column)
column = Util.new_treeview_column(self.tree_accounts, cell_renderer_text, "Name")
column.set_min_width(250)
self.tree_accounts.append_column(column)
column = Util.new_treeview_column(self.tree_accounts, cell_renderer_text, "Type")
self.tree_accounts.append_column(column)
# load all the currently configured accounts
for account in self.__acct_mgr.accounts.values():
snap_in = self.__config.snapin_by_type_description(account.mail_type)
pixbuf = snap_in.get_icon(snap_in.type)
self.account_list.append([pixbuf, account.enabled, account.name, account.mail_type])
# set preferences dialog icon
pixbuf = self.window.render_icon(gtk.STOCK_PREFERENCES, gtk.ICON_SIZE_MENU)
self.window.set_icon(pixbuf)
# set-up dialog to reflect current options
interval = self.__config.get_value("/check_interval")
self.spin_check_interval.set_value(interval)
do_flash = self.__config.get_value("/flash/do")
self.check_flash_icon.set_active(do_flash)
fixed = self.__config.get_value("/flash/fixed")
self.radio_fixed_flash.set_active(fixed)
self.radio_indef_flash.set_active(not fixed)
fixed_interval = self.__config.get_value("/flash/fixed_interval")
self.spin_flash_interval.set_value(fixed_interval)
# re-create the window for each new view but ensure that display is restricted to a single window
def show(self):
if self.window.get_property('visible') == False:
self.create_dialog()
self.window.show()
else:
self.window.get_window().raise_()
# event handlers ----
# account maintenance buttons
def on_btn_add_account_clicked(self, widget):
result, new_account = AccountDialog(self.window, None).show()
if (result == gtk.RESPONSE_OK):
# configure the account information
self.__acct_mgr.create_or_update_account(new_account)
# show the entry in the list
snap_in = self.__config.snapin_by_type_description(new_account.mail_type)
pixbuf = snap_in.get_icon(snap_in.type)
self.account_list.append([pixbuf, new_account.enabled, new_account.name, new_account.mail_type])
def show_tree_selection_warning(self, mode):
if (self.tree_accounts.get_selection().count_selected_rows() == 0):
message = gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_WARNING, gtk.BUTTONS_OK,
"No Account Selected")
message.format_secondary_text("Please select the acount you wish to %s and try again" % mode)
message.run()
message.destroy()
return True
else:
return False
def on_btn_edit_account_clicked(self, widget):
stop_edit = self.show_tree_selection_warning("edit")
result, edit_account = AccountDialog(self.window, account).show()
def on_btn_del_account_clicked(self, widget):
stop_edit = self.show_tree_selection_warning("remove")
if not stop_edit:
model, citer = self.tree_accounts.get_selection().get_selected()
if citer:
name = self.account_list.get_value(citer, 2)
model.remove(citer)
self.__acct_mgr.delete_account(name)
# dialog buttons
def on_btn_close_clicked(self, widget):
self.window.hide_on_delete()
def on_btn_ok_clicked(self, widget):
# save configuration
check_interval = self.spin_check_interval.get_value_as_int()
self.__config.set_value("/check_interval", check_interval)
do_flash = self.check_flash_icon.get_active()
self.__config.set_value("/flash/do", do_flash)
fixed = self.radio_fixed_flash.get_active()
self.__config.set_value("/flash/fixed", fixed)
fixed_interval = self.spin_flash_interval.get_value_as_int()
self.__config.set_value("/flash/fixed_interval", fixed_interval)
if (not fixed):
self.status_icon.blink_for_duration(-1)
else:
self.status_icon.blink_for_duration(0)
self.__config.set_value("/is_configured", True)
self.window.hide_on_delete()
# treeview handlers
def on_tree_accounts_column_toggled(self, cell, path, model):
# Sets the account enabled/disabled property based on the value of the
# checkbox in the treeview
iter = model.get_iter((int(path),))
name = model.get_value(iter, 1)
enabled = model.get_value(iter, 0)
enabled = not enabled
model.set(iter, 0, enabled)
account = self.__acct_mgr.get_account_from_name(name)
account.enabled = enabled
self.__acct_mgr.create_or_update_account(account)
def on_check_flash_icon_toggled(self, widget):
self.radio_indef_flash.set_sensitive(widget.get_active())
self.radio_fixed_flash.set_sensitive(widget.get_active())
if self.radio_fixed_flash.get_active():
self.spin_flash_interval.set_sensitive(widget.get_active())
self.lbl_flash_suffix.set_sensitive(widget.get_active())
def on_radio_fixed_flash_toggled(self, widget):
self.spin_flash_interval.set_sensitive(widget.get_active())
self.lbl_flash_suffix.set_sensitive(widget.get_active())
| Python |
"""
Copyright (c) 2008, Luke Freeman
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
* Neither the name of Flag-Up nor the names of its contributors may
be used to endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
"""
import pygtk
import gtk, gtk.glade
import gobject
from config.account_manager import *
from config.configuration import *
class AccountDialog:
__config = Configuration() # application configuration item
__acct_mgr = AccountManager() # the account manager
# class initializer
def __init__(self, parent, account):
pref_glade_file = 'ui/glade/account_dialog.glade'
self.widgets = gtk.glade.XML(pref_glade_file)
self.window = self.widgets.get_widget('dialog_add_account')
self.window.set_transient_for(parent);
self.widgets.signal_autoconnect(self) # connect the signals defined in the glade file
self.account = account # the account details (None if in add mode)
# get list of widgets
self.cbo_account_type = self.widgets.get_widget("cbo_account_type")
self.txt_account_name = self.widgets.get_widget("txt_account_name")
self.txt_user_name = self.widgets.get_widget("txt_user_name")
self.txt_password = self.widgets.get_widget("txt_password")
self.chk_account_enabled = self.widgets.get_widget("chk_account_enabled")
# populate the account type list dynamically from the found snap-ins
acc_type_list = gtk.ListStore(gobject.TYPE_STRING)
for snapin in self.__config.all_snapins():
acc_type_list.append([snapin.type_description])
self.cbo_account_type.set_model(acc_type_list)
cell_render = gtk.CellRendererText()
self.cbo_account_type.pack_start(cell_render, True)
self.cbo_account_type.add_attribute(cell_render, 'text', 0)
self.cbo_account_type.set_active(0) # select first element
# helper to get currently selected account type
def get_selected_account_type(self):
model = self.cbo_account_type.get_model()
act_iter = self.cbo_account_type.get_active_iter()
sel_acct_type = model.get_value(act_iter, 0)
return sel_acct_type
# the main loop for the dialog
def show(self):
new_account = None
result = None
# if edit mode, show values
if self.account is not None:
self.txt_account_name.set_text(self.account.name)
# block a response until all of the information has been filled out correctly
# or the user presses cancel
while (new_account is None and result != gtk.RESPONSE_CANCEL):
result = self.window.run()
if (result == gtk.RESPONSE_OK):
a_type = self.get_selected_account_type()
a_name = self.txt_account_name.get_text()
a_user = self.txt_user_name.get_text()
a_pass = self.txt_password.get_text()
a_enabled = self.chk_account_enabled.get_active()
access, message = self.__acct_mgr.can_create(a_name, a_type, a_user, a_pass)
if access:
new_account = Account(a_name, a_type, a_user, a_pass, a_enabled)
if self.account is not None:
new_account.aid = self.account.aid # if updating
# cannot create the account
else:
message_box = gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_INFO, gtk.BUTTONS_NONE,
"Invalid Entries")
message_box.format_secondary_text(message)
message_box.add_button(gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE)
response = message_box.run()
if response == gtk.RESPONSE_CLOSE:
message_box.destroy()
self.window.destroy()
return result, new_account
# event handlers ----
# dialog buttons
def on_btn_type_info_clicked(self, widget):
a_type = self.get_selected_account_type()
snapin = self.__config.snapin_by_type_description(a_type)
| Python |
# Copyright (c) 2008, Luke Freeman
# All rights reserved.
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this
# list of conditions and the following disclaimer in the documentation and/or
# other materials provided with the distribution.
# * Neither the name of Flag-Up nor the names of its contributors may
# be used to endorse or promote products derived from this software without specific
# prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
# GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
import pygtk
import gtk, gtk.glade
import time
class NewMailNotification:
def __init__(self):
pref_glade_file = 'ui/glade/new_mail_dialog.glade'
self.widgets = gtk.glade.XML(pref_glade_file)
self.window = self.widgets.get_widget('new_mail_window')
ebx_msg_main = self.widgets.get_widget('ebx_msg_main')
bg_color = gtk.gdk.color_parse("#FFFFFF")
ebx_msg_main.realize()
ebx_msg_main.modify_bg(gtk.STATE_NORMAL, bg_color)
#self.window.connect("response", lambda dlg, r: dlg.destroy())
self.widgets.signal_autoconnect(self) # connect the signals defined in the glade file
# re-create the window for each new view but ensure that display is restricted to a single window
def show(self):
if self.window.get_property('visible') == False:
if (self.window.is_composited()):
self.window.set_opacity(0.75)
self.window.show()
else:
self.window.get_window().raise_()
def on_tbn_close_clicked(self, widget):
self.window.destroy()
def on_new_mail_window_focus_out_event(self, sender, event):
pass
def on_new_mail_window_key_press_event(self, sender, event):
if event.keyval == 65307:
self.window.hide()
| Python |
# Copyright (c) 2008, Luke Freeman
# All rights reserved.
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this
# list of conditions and the following disclaimer in the documentation and/or
# other materials provided with the distribution.
# * Neither the name of Flag-Up nor the names of its contributors may
# be used to endorse or promote products derived from this software without specific
# prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
# GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
try:
import pygtk
pygtk.require("2.0")
except:
pass
try:
import gtk, gtk.glade
except:
sys.exit(1)
class AboutDialog:
def __init__(self):
pref_glade_file = 'ui/glade/about_dialog.glade'
self.widgets = gtk.glade.XML(pref_glade_file)
self.window = self.widgets.get_widget('about_dialog')
self.window.connect("response", lambda dlg, r: dlg.destroy())
self.widgets.signal_autoconnect(self) # connect the signals defined in the glade file
# re-create the window for each new view but ensure that display is restricted to a single window
def show(self):
if self.window.get_property('visible') == False:
self.window.show()
else:
self.window.get_window().raise_()
def on_about_dialog_close(self, widget):
print "close"
| Python |
# Copyright (c) 2008, Luke Freeman
# All rights reserved.
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this
# list of conditions and the following disclaimer in the documentation and/or
# other materials provided with the distribution.
# * Neither the name of Flag-Up nor the names of its contributors may
# be used to endorse or promote products derived from this software without specific
# prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
# GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
import pygtk
import gtk, gtk.glade
class Util:
def new_treeview_column(tree_view, cell_renderer, column_title):
column_id = len(tree_view.get_columns())
column = gtk.TreeViewColumn(column_title, cell_renderer, text=column_id)
if isinstance(cell_renderer, gtk.CellRendererToggle):
column = gtk.TreeViewColumn(column_title, cell_renderer, active=column_id)
elif isinstance(cell_renderer, gtk.CellRendererPixbuf):
column = gtk.TreeViewColumn(column_title, cell_renderer, pixbuf=column_id)
column.set_resizable(True)
column.set_sort_column_id(column_id)
return column
new_treeview_column = staticmethod(new_treeview_column)
| Python |
"""
Copyright (c) 2008, Luke Freeman
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
* Neither the name of Flag-Up nor the names of its contributors may
be used to endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
"""
import pygtk, gtk
import pynotify
import sys
from ui.glade.preferences_dialog import PreferencesDialog
NOTIFICATION_ID = "_flag_up"
class MailNotification:
def __on_show_preferences_click(self, n, action, args):
dialog = PreferencesDialog(self.status_icon)
dialog.show()
def __init__(self, status_icon, title, body, icon=None, timeout=5000, defined_action=""):
if not pynotify.init(NOTIFICATION_ID):
raise "Could not initialize the notification system"
self.popup = pynotify.Notification(title, body)
self.popup.set_timeout(timeout)
self.popup.attach_to_status_icon(status_icon)
self.status_icon = status_icon
if icon:
self.popup.set_icon_from_pixbuf(icon)
if defined_action == "view_pref":
self.popup.add_action("clicked", "View Preferences", self.__on_show_preferences_click, "")
def show(self):
if not self.popup.show():
raise "Notification Failed!"
| Python |
"""
Copyright (c) 2008, Luke Freeman
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
* Neither the name of Flag-Up nor the names of its contributors may
be used to endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
"""
from config.configuration import *
from ui.glade.preferences_dialog import PreferencesDialog
from ui.glade.about_dialog import AboutDialog
from ui.notification import *
from ui.glade.new_mail_dialog import *
import time
import sys
import pygtk, gtk, gtk.glade
import gobject
from base.singleton import *
class StatusIcon(gtk.StatusIcon):
# constants
STATUS_CHECK_UNREAD = 1
STATUS_CHECK_NONE = 0
STATUS_CHECK_ERROR = -1
STATUS_NEEDS_CONFIG = -2
__config = Configuration()
def __init__(self):
gtk.StatusIcon.__init__(self)
self.update_icon(StatusIcon.STATUS_CHECK_NONE)
self.connect('popup-menu', self.on_status_icon_right_click)
self.connect('activate', self.on_status_icon_left_click)
self.pref_dialog = PreferencesDialog(self)
self.about_dialog = AboutDialog()
if self.__config.is_configured is not True:
gobject.idle_add(self.show_initial_notification)
else:
status = StatusIcon.STATUS_CHECK_UNREAD
if status == StatusIcon.STATUS_CHECK_UNREAD:
gobject.idle_add(self.show_new_mail_notification)
def show_initial_notification(self):
icon = gtk.image_new_from_file('ui/icons/48/welcome-smiley.png').get_pixbuf()
welcome_message = "Hey there! Welcome to <b>Flag-Up</b>. The Flag-Up main icon will tell " \
"you your mail status.\n\nTo get started " \
"you will need to set up your mail accounts. Please click on the " \
"<b>View Preferences</b> button " \
"below.\n\nOh .. and thank you!"
MailNotification(self, "Welcome!", welcome_message, icon, 50000, "view_pref").show()
return False
def show_new_mail_notification(self):
#message = "You have <b>5</b> new mail message(s).\n\n"
#message += "<span size='small'>testing ....</span>\n\n"
#message += "Please 'Right Click' the status icon to see your messages."
#MailNotification(self, "You Have New Mail!", message, None, 50000, "view_mail").show()
x = NewMailNotification()
x.show()
def create_popup_menu(self):
popup_menu = gtk.Menu()
check_mail_item = gtk.ImageMenuItem("Check for new mail")
check_mail_item.set_image(gtk.image_new_from_file('ui/icons/16/gnome-mail-send-receive.png'))
check_mail_item.connect("activate", self.on_check_mail_item_activate)
check_mail_item.show()
popup_menu.append(check_mail_item)
preferences_item = gtk.ImageMenuItem(gtk.STOCK_PREFERENCES)
preferences_item.connect("activate", self.on_preferences_item_activate)
preferences_item.show()
popup_menu.append(preferences_item)
separator = gtk.SeparatorMenuItem()
separator.show()
popup_menu.append(separator)
# add mail summaries
no_mail_item = gtk.ImageMenuItem("No New Mail ..")
no_mail_item.show()
popup_menu.append(no_mail_item)
separator = gtk.SeparatorMenuItem()
separator.show()
popup_menu.append(separator)
about_item = gtk.ImageMenuItem(gtk.STOCK_ABOUT)
about_item.connect("activate", self.on_about_item_activate)
about_item.show()
popup_menu.append(about_item)
quit_item = gtk.ImageMenuItem(gtk.STOCK_QUIT)
quit_item.connect("activate", self.on_quit_item_activate)
quit_item.show()
popup_menu.append(quit_item)
return popup_menu
def blink_for_duration(self, duration):
self.set_blinking(True)
if (duration) >= 0:
gobject.timeout_add(duration * 1000, self.set_blinking, False)
def update_icon(self, status):
icon_path_format = "ui/icons/%(icon_name)s.png"
if status == StatusIcon.STATUS_CHECK_UNREAD:
tooltip_text = 'You have unread email'
#icon_name = 'gnome-mail-unread'
icon_name = 'mail-up-48'
elif status == StatusIcon.STATUS_CHECK_NONE:
tooltip_text = 'You have no new messages'
icon_name = 'gnome-mail-envelope'
elif status == StatusIcon.STATUS_CHECK_ERROR:
tooltip_text = 'An error occurred checking your mail'
icon_name = 'gnome-dialog-warning'
elif status == StatusIcon.STATUS_NEEDS_CONFIG:
tooltip_text = 'Flag-Up has not yet been configured for any mail accounts'
icon_name = '48/gnome-mail-warning'
else:
raise Exception("An invalid status was set [code = %d]" % status)
self.set_tooltip(tooltip_text)
icon_path = icon_path_format % { 'icon_name' : icon_name }
self.set_tooltip(tooltip_text)
self.set_from_file(icon_path)
# flashing? if so, set duration
if status == StatusIcon.STATUS_CHECK_UNREAD:
do_flash = self.__config.get_value("/flash/do")
if (do_flash):
fixed = self.__config.get_value("/flash/fixed")
fixed_interval = self.__config.get_value("/flash/fixed_interval")
duration = fixed_interval if fixed else -1
self.blink_for_duration(duration)
elif status != StatusIcon.STATUS_CHECK_NONE:
self.blink_for_duration(-1)
# event handlers -----
# status icon handlers
def on_status_icon_right_click(self, data, event_button, event_time):
menu = self.create_popup_menu()
menu.popup(None, None, None, event_button, event_time)
def on_status_icon_left_click(self, event):
pass
# popup menu handlers
def on_about_item_activate(self, event):
self.about_dialog.show()
def on_quit_item_activate(self, event):
sys.exit(1)
def on_preferences_item_activate(self, event):
self.pref_dialog.show()
def on_check_mail_item_activate(self, event):
self.update_icon(StatusIcon.STATUS_CHECK_UNREAD)
gobject.idle_add(self.show_new_mail_notification)
| Python |
#!/usr/bin/env python
# Copyright (c) 2008, Luke Freeman
# All rights reserved.
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this
# list of conditions and the following disclaimer in the documentation and/or
# other materials provided with the distribution.
# * Neither the name of Flag-Up nor the names of its contributors may
# be used to endorse or promote products derived from this software without specific
# prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
# GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
try:
import sys
import pygtk
import gtk, gtk.glade
pygtk.require("2.0")
except:
print "Flag-Up requires PyGTK version 2.0 or higher to run. Sorry."
sys.exit(1)
from ui.status_icon import *
icon = StatusIcon()
icon.update_icon(StatusIcon.STATUS_CHECK_UNREAD)
gtk.main()
| Python |
# Copyright (c) 2008, Luke Freeman
# All rights reserved.
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this
# list of conditions and the following disclaimer in the documentation and/or
# other materials provided with the distribution.
# * Neither the name of Flag-Up nor the names of its contributors may
# be used to endorse or promote products derived from this software without specific
# prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
# GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
import sys, os, re
import gconf
from base.base_util import *
from base.singleton import *
# globals
CONFIGURATION_ROOT = "/apps/flag-up"
configuration = gconf.client_get_default()
class Account(object):
def __init__(self, name, mail_type, user, password, enabled):
self.aid = None
self.name = name
self.mail_type = mail_type
self.user = user
self.password = password
self.enabled = enabled
class AccountManager(Singleton):
accounts = {}
__first_time = True
def __init__(self):
if self.__first_time:
# load all existing accounts
acct_dirs = configuration.all_dirs(self.__full_conf_path("/accounts"))
if len(acct_dirs) > 0:
for acct_dir in acct_dirs:
acct = Account(
configuration.get_value("%s/name" % acct_dir),
configuration.get_value("%s/type" % acct_dir),
configuration.get_value("%s/user" % acct_dir),
configuration.get_value("%s/password" % acct_dir),
configuration.get_value("%s/enabled" % acct_dir)
)
acct_id = acct_dir.split("/").pop()
acct.aid = acct_id
self.accounts[acct.name] = acct
self.__first_time = False
def __full_conf_path(self, conf_item):
return "%s%s" % (CONFIGURATION_ROOT, conf_item)
def __get_next_acct_num(self):
next_num = "1".rjust(8, "0") # set the initial account number
acct_dirs = configuration.all_dirs(self.__full_conf_path("/accounts"))
if len(acct_dirs) > 0:
next_num = max(acct_dirs).split("/").pop()
next_num = str(int(next_num) + 1).rjust(8,"0")
return next_num
# create or update account configuration
def create_or_update_account(self, account):
if account.aid == None:
account.aid = self.__get_next_acct_num()
# write to gconf
account_folder = self.__full_conf_path("/accounts/%s" % account.aid)
configuration.set_value(("%s/name" % account_folder), account.name)
configuration.set_value(("%s/type" % account_folder), account.mail_type)
configuration.set_value(("%s/user" % account_folder), account.user)
configuration.set_value(("%s/password" % account_folder), account.password)
configuration.set_value(("%s/enabled" % account_folder), account.enabled)
self.accounts[account.name] = account
def delete_account(self, name):
account = self.accounts[name]
account_folder = self.__full_conf_path("/accounts/%s" % account.aid)
entries = configuration.all_entries(account_folder)
for entry in entries:
configuration.unset(entry.key)
configuration.suggest_sync()
del self.accounts[name]
# checks to see if you can create the account
def can_create(self, name, mail_type, user, password):
can_create = True
message = ""
if self.accounts.has_key(name):
can_create = False
message = "The account name you specified is already in use. Account names must be unique."
elif name == "" or mail_type == "" or user == "" or password == "":
can_create = False
message = "One or more of the account details was not filled out. All entries are mandatory."
return can_create, message
def get_account_from_name(self, name):
return self.accounts[name]
# account management methods
def check_all_accounts(self):
pass
def check_single_account(self, name):
pass
| Python |
# Copyright (c) 2008, Luke Freeman
# All rights reserved.
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this
# list of conditions and the following disclaimer in the documentation and/or
# other materials provided with the distribution.
# * Neither the name of Flag-Up nor the names of its contributors may
# be used to endorse or promote products derived from this software without specific
# prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
# GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
import sys, os, re
import gconf
import gtk
from base.singleton import *
# globals
CONFIGURATION_ROOT = "/apps/flag-up"
configuration = gconf.client_get_default()
# dummy class for snap-in loading
class SnapIn(object):
ROOT_DIR = "./snap_ins"
description = "Contact the developer to fix this"
author = "Developer Name"
type = ""
type_description = "#ERROR"
def get_icon(type, width=16, height=16):
file_name = os.path.join(SnapIn.ROOT_DIR + "/icons/", type + ".png")
if (not os.path.isfile(file_name)):
file_name = os.path.join(SnapIn.ROOT_DIR + "/icons/", "generic.png")
pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(file_name, width, height)
return pixbuf
get_icon = staticmethod(get_icon)
# TODO thread safety
class Configuration(Singleton):
first_time = None
def __init__(self):
# prevent loading after the first time
if self.first_time == None:
self.first_time = self.is_configured
if self.first_time is None or self.first_time is False:
self.do_initial_setup()
else:
self.load()
def __full_conf_path(self, conf_item):
return "%s%s" % (CONFIGURATION_ROOT, conf_item)
def load(self):
snapin_path = self.get_value("/snap_in_dir")
self.__init_snapin_system(snapin_path)
def do_initial_setup(self):
initial_config = {
"/snap_in_dir": "%s/snap_ins" % os.getcwd(),
"/is_configured": False,
"/check_interval": 5,
"/flash/do": True,
"/flash/indef": True,
"/flash/fixed": False,
"/flash/fixed_interval": 5
}
for conf_key in initial_config.keys():
self.set_value(conf_key, initial_config[conf_key])
self.load() # load the initial config
# attribute accessors
def get_is_configured(self):
is_configured = self.get_value("/is_configured")
return True if is_configured else False
def set_is_configured(self, is_configured):
self.set_value("/is_configured", is_configured)
is_configured = property(get_is_configured, set_is_configured)
# configuration functions
def set_value(self, key, value):
full_key = self.__full_conf_path(key)
configuration.set_value(full_key, value)
def get_value(self, key):
full_key = self.__full_conf_path(key)
try:
value = configuration.get_value(full_key)
return value
except ValueError:
return None
# snap-ins
# snap-in configuration / initialization
def __load_snapins(self, directory):
files = os.listdir(directory)
regex = re.compile('^(?!__)\w+(.py)$') # find all files ending in '.py' not starting with '__'
for f in files:
if regex.match(f):
module = f.split(".")[0]
__import__(module, None, None, [''])
def __init_snapin_system(self, directory):
if os.path.exists(directory):
if not directory in sys.path:
sys.path.insert(0, directory)
self.__load_snapins(directory)
else: # cannot initialise snap-ins: path does not exist
raise "Cannot configure snap-ins: snap-ins path is invalid or does not exist"
# snap in retrieval functions
def snapin_by_type_description(self, type_desc):
snapins = self.all_snapins()
for snapin in snapins:
if snapin.type_description == type_desc:
return snapin
return None
# return all snap-ins
def all_snapins(self):
return SnapIn.__subclasses__()
| Python |
class Singleton(object):
__instance = None # single instance
__name = ""
def __new__(cls, *args, **keywords):
return cls.getInstance(cls, *args, **keywords)
def __init__(self):
pass
@classmethod
def getInstance(cls, *args, **keywords):
if cls.__instance is None:
cls.__instance = object.__new__(cls, *args, **keywords)
return cls.__instance
def get_name(self):
return self.__name
def set_name(self, name):
self.__name = name
name = property(get_name, set_name)
| Python |
# Copyright (c) 2008, Luke Freeman
# All rights reserved.
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this
# list of conditions and the following disclaimer in the documentation and/or
# other materials provided with the distribution.
# * Neither the name of Flag-Up nor the names of its contributors may
# be used to endorse or promote products derived from this software without specific
# prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
# GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
class BaseUtil:
def find_in_seq(function, seq):
for node in seq:
if function(node):
return node
return None
find_in_seq = staticmethod(find_in_seq)
| Python |
# Copyright (c) 2008, Luke Freeman
# All rights reserved.
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this
# list of conditions and the following disclaimer in the documentation and/or
# other materials provided with the distribution.
# * Neither the name of Flag-Up nor the names of its contributors may
# be used to endorse or promote products derived from this software without specific
# prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
# GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
from config.configuration import SnapIn
class Agent(SnapIn):
type = "yahoo"
type_description = 'Yahoo / YMail Account'
def check_mail(self):
return True
| Python |
# Copyright (c) 2008, Luke Freeman
# All rights reserved.
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this
# list of conditions and the following disclaimer in the documentation and/or
# other materials provided with the distribution.
# * Neither the name of Flag-Up nor the names of its contributors may
# be used to endorse or promote products derived from this software without specific
# prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
# GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
import urllib2
from xml.dom import minidom
from config.configuration import SnapIn
# RSS details
GMAIL_REALM = 'New mail feed'
GMAIL_URL = 'https://mail.google.com/mail/feed/atom'
class Agent(SnapIn):
# agent information
description = 'Gmail Flag-Up Mail Check Agent'
author = 'Luke Freeman'
type = 'gmail'
type_description = 'Gmail Account'
def poll(self):
auth_handler = urllib2.HTTPBasicAuthHandler()
auth_handler.add_password(GMAIL_REALM, GMAIL_URL, "freeman.luke", "m0nkeytre3")
url_opener = urllib2.build_opener(auth_handler)
urllib2.install_opener(url_opener)
dom = minidom.parseString(urllib2.urlopen(GMAIL_URL).read())
elements = dom.getElementsByTagName("fullcount")
unread_count = elements[0].firstChild.wholeText
# define the return message
messages = []
return_message = {
"unread_count" : unread_count,
"messages" : messages
}
return return_message
| Python |
#!/usr/bin/python
import sys, os, re, time
import shutil, signal, socket
from optparse import OptionParser
try:
import uno
from com.sun.star.beans import PropertyValue
except ImportError:
print "Please install pygtk"
raise SystemExit
LOGFILE = '/var/log/ooconvert.log'
class Log:
def __init__(self, f):
self.f = f
def write(self, s):
try:
s = s.encode('CP1251')
except:
pass
s = s.strip()
if s != "":
s = "[%s] %s\n" % (time.ctime(), s)
self.f.write(s)
self.f.flush()
def init_openoffice():
# Init: Connect to running soffice process
context = uno.getComponentContext()
resolver=context.ServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", context)
try:
ctx = resolver.resolve("uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext")
except:
s = "Could not connect to running openoffice."
print s
raise Exception, s
smgr=ctx.ServiceManager
desktop = smgr.createInstanceWithContext("com.sun.star.frame.Desktop",ctx)
return desktop
def convert(file, desktop, format, file_save):
file_l=file.lower()
properties=[]
p=PropertyValue()
p.Name="Hidden"
p.Value=True
properties.append(p)
doc=desktop.loadComponentFromURL("file://%s" % file, "_blank", 0, tuple(properties));
if not doc:
print "Failed to open '%s'" % file
return
# Save File
properties=[]
p=PropertyValue()
p.Name="Overwrite"
p.Value=True
properties.append(p)
p=PropertyValue()
p.Name="FilterName"
p.Value=format
properties.append(p)
p=PropertyValue()
p.Name="Hidden"
p.Value=True
try:
doc.storeToURL("file://%s" % file_save, tuple(properties))
print "Created %s" % file_save
except ValueError:
print "Failed while writing: '%s'" % file_save
#?
doc.dispose()
# DAEMON ============================================================================================
def print_help():
print 'Usage: /etc/init.d/ooReporter.py (start|stop|restart)';
def have_param(param_name, long_name):
i = 0;
for i in sys.argv:
if ((i == param_name) or (i == long_name)):
return True
return False;
def sigINTHandler(signum, frame):
print "server stopping..."
s.running = 0;
s.server.shutdown(2);
sys.exit(1)
if __name__ == "__main__" :
parser = OptionParser(description='Convert a file from one format to another using OpenOffice')
parser.add_option("-f","--from",action="store",dest="from_file",help="File to convert")
parser.add_option("-a","--action",action="store",dest="format",help="Format to use")
parser.add_option("-t","--to", action="store",dest="to_file",help="Result file")
(opt,args) = parser.parse_args()
if not opt.from_file:
parser.error("set the file to convert")
if not opt.format:
parser.error("set the format to use")
if not opt.to_file:
parser.error("set the result file")
desktop = init_openoffice()
convert(opt.from_file, desktop,opt.format,opt.to_file)
| Python |
# Copyright (c) 2006 Nuxeo SARL <http://nuxeo.com>
# Author: Laurent Godard <lgodard@indesko.com>, Infrae <info@infrae.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the Lesser GNU General Public License version
# 2.1 as published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
# 02111-1307, USA.
#
# See ``COPYING`` for more information
FILTERS = {
'writer': {
'PDF': {'FilterName': 'writer_pdf_Export',
'Extension': 'pdf',
'isGraphical': False,
'zipMe': False},
'OOO': {'FilterName': 'StarOffice XML (Writer)',
'Extension': 'sxw',
'isGraphical': False,
'zipMe': False},
'ODOC': {'FilterName': 'writer8', #OpenDocument OOo 2
'Extension': 'odt',
'isGraphical': False,
'zipMe': False},
'MSXP': {'FilterName': 'MS Word 97',
'Extension': 'doc',
'isGraphical': False,
'zipMe': False},
'MS95': {'FilterName': 'MS Word 95',
'Extension': 'doc',
'isGraphical': False,
'zipMe': False},
'MS60': {'FilterName': 'MS WinWord 6.0',
'Extension': 'doc',
'isGraphical': False,
'zipMe': False},
'RTF': {'FilterName': 'Rich Text Format',
'Extension': 'rtf',
'isGraphical': False,
'zipMe': False},
'HTML': {'FilterName': 'HTML (StarWriter)',
'Extension': 'html',
'isGraphical': False,
'zipMe': True},
'XHTML': {'FilterName': 'XHTML plus MathML File',
'Extension': 'xhtml',
'isGraphical': False,
'zipMe': True},
'TEX': {'FilterName': 'Latex File',
'Extension': 'tex',
'isGraphical': False,
'zipMe': True},
'TXT': {'FilterName': 'Text',
'Extension': 'txt',
'isGraphical': False,
'zipMe': False},
},
'calc': {
'PDF': {'FilterName': 'calc_pdf_Export',
'Extension': 'pdf',
'isGraphical': False,
'zipMe': False},
'OOO': {'FilterName': 'StarOffice XML (Calc)',
'Extension': 'sxc',
'isGraphical': False,
'zipMe': False},
'ODOC': {'FilterName': 'calc8', #OpenDocument OOo 2
'Extension': 'odc',
'isGraphical': False,
'zipMe': False},
'MSXP': {'FilterName': 'MS Excel 97',
'Extension': 'xls',
'isGraphical': False,
'zipMe': False},
'MS95': {'FilterName': 'MS Excel 95',
'Extension': 'xls',
'isGraphical': False,
'zipMe': False},
'MS60': {'FilterName': 'MS Excel 5.0/95',
'Extension': 'xls',
'isGraphical': False,
'zipMe': False},
'HTML': {'FilterName': 'HTML (StarCalc)',
'Extension': 'html',
'isGraphical': False,
'zipMe': True},
'TXT': {'FilterName': 'Text',
'Extension': 'txt',
'isGraphical': False,
'zipMe': False},
},
'draw': {
'PDF': {'FilterName': 'draw_pdf_Export',
'Extension': 'pdf',
'isGraphical': False,
'zipMe': False},
'OOO': {'FilterName': 'StarOffice XML (Draw)',
'Extension': 'sxd',
'isGraphical': False,
'zipMe': False},
'ODOC': {'FilterName': 'draw8', #OpenDocument OOo 2
'Extension': 'odd',
'isGraphical': False,
'zipMe': False},
'JPG': {'FilterName': 'image/jpeg',
'Extension': 'jpg',
'isGraphical': True,
'zipMe': True},
'PNG': {'FilterName': 'image/png',
'Extension': 'png',
'isGraphical': True,
'zipMe': True},
'TIFF': {'FilterName': 'image/tiff',
'Extension': 'tif',
'isGraphical': True,
'zipMe': True},
'SVG': {'FilterName': 'image/svg+xml',
'Extension': 'svg',
'isGraphical': True,
'zipMe': True},
'EPS': {'FilterName': 'application/postscript',
'Extension': 'eps',
'isGraphical': True,
'zipMe': True},
'SWF': {'FilterName': 'draw_flash_Export',
'Extension': 'swf',
'isGraphical': False,
'zipMe': False},
'HTML': {'FilterName': 'draw_html_Export',
'Extension': 'html',
'isGraphical': False,
'zipMe': True},
},
'impress': {
'PDF': {'FilterName': 'impress_pdf_Export',
'Extension': 'pdf',
'isGraphical': False,
'zipMe': False},
'OOO': {'FilterName': 'StarOffice XML (Impress)',
'Extension': 'sxi',
'isGraphical': False,
'zipMe': False},
'ODOC': {'FilterName': 'impress8', #OpenDocument OOo 2
'Extension': 'odp',
'isGraphical': False,
'zipMe': False},
'MSXP': {'FilterName': 'MS Powerpoint 97',
'Extension': 'ppt',
'isGraphical': False,
'zipMe': False},
'JPG': {'FilterName': 'image/jpeg',
'Extension': 'jpg',
'isGraphical': True,
'zipMe': True},
'PNG': {'FilterName': 'image/png',
'Extension': 'png',
'isGraphical': True,
'zipMe': True},
'TIFF': {'FilterName': 'image/tiff',
'Extension': 'tif',
'isGraphical': True,
'zipMe': True},
'SVG': {'FilterName': 'image/svg+xml',
'Extension': 'svg',
'isGraphical': True,
'zipMe': True},
'EPS': {'FilterName': 'application/postscript',
'Extension': 'eps',
'isGraphical': True,
'zipMe': True},
'SWF': {'FilterName': 'impress_flash_Export',
'Extension': 'swf',
'isGraphical': False,
'zipMe': False},
'HTML': {'FilterName': 'impress_html_Export',
'Extension': 'html',
'isGraphical': False,
'zipMe': True},
},
}
def getFilter(docType, targetFormat):
"""Get a filter or return None if no filter could be found.
"""
try:
return FILTERS[docType][targetFormat]
except KeyError:
return None
| Python |
#!/usr/bin/python
import sys, os, re, time
import shutil, signal, socket
from optparse import OptionParser
try:
import uno
from com.sun.star.beans import PropertyValue
except ImportError:
print "Please install pygtk"
raise SystemExit
LOGFILE = '/var/log/ooconvert.log'
class Log:
def __init__(self, f):
self.f = f
def write(self, s):
try:
s = s.encode('CP1251')
except:
pass
s = s.strip()
if s != "":
s = "[%s] %s\n" % (time.ctime(), s)
self.f.write(s)
self.f.flush()
def init_openoffice():
# Init: Connect to running soffice process
context = uno.getComponentContext()
resolver=context.ServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", context)
try:
ctx = resolver.resolve("uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext")
except:
s = "Could not connect to running openoffice."
print s
raise Exception, s
smgr=ctx.ServiceManager
desktop = smgr.createInstanceWithContext("com.sun.star.frame.Desktop",ctx)
return desktop
def convert(file, desktop, format, file_save):
file_l=file.lower()
properties=[]
p=PropertyValue()
p.Name="Hidden"
p.Value=True
properties.append(p)
doc=desktop.loadComponentFromURL("file://%s" % file, "_blank", 0, tuple(properties));
if not doc:
print "Failed to open '%s'" % file
return
# Save File
properties=[]
p=PropertyValue()
p.Name="Overwrite"
p.Value=True
properties.append(p)
p=PropertyValue()
p.Name="FilterName"
p.Value=format
properties.append(p)
p=PropertyValue()
p.Name="Hidden"
p.Value=True
try:
doc.storeToURL("file://%s" % file_save, tuple(properties))
print "Created %s" % file_save
except ValueError:
print "Failed while writing: '%s'" % file_save
#?
doc.dispose()
# DAEMON ============================================================================================
def print_help():
print 'Usage: /etc/init.d/ooReporter.py (start|stop|restart)';
def have_param(param_name, long_name):
i = 0;
for i in sys.argv:
if ((i == param_name) or (i == long_name)):
return True
return False;
def sigINTHandler(signum, frame):
print "server stopping..."
s.running = 0;
s.server.shutdown(2);
sys.exit(1)
if __name__ == "__main__" :
parser = OptionParser(description='Convert a file from one format to another using OpenOffice')
parser.add_option("-f","--from",action="store",dest="from_file",help="File to convert")
parser.add_option("-a","--action",action="store",dest="format",help="Format to use")
parser.add_option("-t","--to", action="store",dest="to_file",help="Result file")
(opt,args) = parser.parse_args()
if not opt.from_file:
parser.error("set the file to convert")
if not opt.format:
parser.error("set the format to use")
if not opt.to_file:
parser.error("set the result file")
desktop = init_openoffice()
convert(opt.from_file, desktop,opt.format,opt.to_file)
| Python |
#!/usr/bin/env python
## flamingo - 2D Game Engine
## Copyright (C) 2009 Bradley Zeis
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
##
## Bradley Zeis
## bradzeis@gmail.com
import sys
from . import event
_BACKEND = None
_INITIALIZED = False
def load(display_name, event_name):
"""Load a display backend.
If the display backend has already been initialized, there will be no effect.
Return: None
"""
if _INITIALIZED:
return
try:
global _BACKEND
__import__(display_name)
_BACKEND = sys.modules[display_name]
event.load(event_name)
event.init()
except ImportError:
raise ImportError, "could not import backend '{0}'".format(display_name)
def init(width, height, caption, fullscreen=0, depth=0, flags=0):
"""Initialize the display.
If a backend is not loaded before this is called, an AttributeError is raised.
Backend:
Backends should not change the values of display._BACKEND or display._INITIALIZED
Return: None
"""
try:
_BACKEND.init(width, height, caption, fullscreen, flags, depth)
except AttributeError:
raise AttributeError, "a display backend has not been loaded"
Display.width = width
Display.height = height
Display.caption = caption
Display.fullscreen = fullscreen
Display.depth = 0
Display.flags = 0
def get_init():
"""Return true if the display is initialized.
Return: boolean
"""
return _INITIALIZED
def quit():
"""Quit the display.
If a backend is not loaded before this is called, an AttributeError is raised.
Return: None
"""
try:
_BACKEND.quit()
except AttributeError:
raise AttributeError, "a display backend has not been loaded"
Display.clear()
def flip():
"""Update the contents on the display surface.
If a backend is not loaded, an AttributeError will be raised.
Return: None
"""
try:
_BACKEND.flip()
except AttributeError:
raise AttributeError, "a display backend has not been loaded"
def get_size():
"""Get the caption of the display window.
Return: string
"""
return Display.width, Display.height
def set_size(width, height):
"""Set the size of the display window.
If the display size can't be changed by the current backend, the backend should
do nothing instead of raising an exception.
Return: None
"""
try:
_BACKEND.set_caption(width, height)
except AttributeError:
raise AttributeError, "a display backend has not been loaded"
def get_caption():
"""Get the caption of the display window.
Return: string
"""
return Display.caption
def set_caption(caption):
"""Set the caption of the display window.
Return: None
"""
try:
_BACKEND.set_caption(caption)
except AttributeError:
raise AttributeError, "a display backend has not been loaded"
class Display(object):
"""Holds information about the display surface."""
width = 0
height = 0
caption = ""
fullscreen = 0
depth = 0
flags = 0
@classmethod
def clear(cls):
width = 0
height = 0
caption = 0
fullscreen = 0
depth = 0
flags = 0
| Python |
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
##
## Bradley Zeis
## flamingoengine@gmail.com
import pygame
from ... import constants as flconstants
type_map = {
pygame.constants.QUIT: flconstants.QUIT,
pygame.constants.VIDEOEXPOSE: flconstants.NOEVENT,
pygame.constants.VIDEORESIZE: flconstants.NOEVENT,
pygame.constants.KEYDOWN: flconstants.KEYDOWN,
pygame.constants.KEYUP: flconstants.KEYUP,
pygame.constants.MOUSEMOTION: flconstants.MOUSEMOTION,
pygame.constants.MOUSEBUTTONDOWN: flconstants.MOUSEBUTTONDOWN,
pygame.constants.MOUSEBUTTONUP: flconstants.MOUSEBUTTONUP,
pygame.constants.JOYAXISMOTION: flconstants.NOEVENT,
pygame.constants.JOYBALLMOTION: flconstants.NOEVENT,
pygame.constants.JOYHATMOTION: flconstants.NOEVENT,
pygame.constants.JOYBUTTONUP: flconstants.NOEVENT,
pygame.constants.JOYBUTTONDOWN: flconstants.NOEVENT
}
key_map = {
pygame.constants.KMOD_ALT: flconstants.K_ALT,
pygame.constants.KMOD_CAPS: flconstants.K_CAPS,
pygame.constants.KMOD_CTRL: flconstants.K_CTRL,
pygame.constants.KMOD_LALT: flconstants.K_LALT,
pygame.constants.KMOD_LCTRL: flconstants.K_LCTRL,
pygame.constants.KMOD_LMETA: flconstants.K_LMETA,
pygame.constants.KMOD_LSHIFT: flconstants.K_LSHIFT,
pygame.constants.KMOD_META: flconstants.K_META,
pygame.constants.KMOD_NUM: flconstants.K_NUM,
pygame.constants.KMOD_RALT: flconstants.K_RALT,
pygame.constants.KMOD_RCTRL: flconstants.K_RCTRL,
pygame.constants.KMOD_RMETA: flconstants.K_RMETA,
pygame.constants.KMOD_RSHIFT: flconstants.K_RSHIFT,
pygame.constants.KMOD_SHIFT: flconstants.K_SHIFT,
pygame.constants.K_CAPSLOCK: flconstants.K_CAPS,
pygame.constants.K_LALT: flconstants.K_LALT,
pygame.constants.K_LCTRL: flconstants.K_LCTRL,
pygame.constants.K_LMETA: flconstants.K_LMETA,
pygame.constants.K_LSHIFT: flconstants.K_LSHIFT,
pygame.constants.K_RALT: flconstants.K_RALT,
pygame.constants.K_RCTRL: flconstants.K_RCTRL,
pygame.constants.K_RMETA: flconstants.K_RMETA,
pygame.constants.K_RSHIFT: flconstants.K_RSHIFT,
pygame.constants.K_0: flconstants.K_0,
pygame.constants.K_1: flconstants.K_1,
pygame.constants.K_2: flconstants.K_2,
pygame.constants.K_3: flconstants.K_3,
pygame.constants.K_4: flconstants.K_4,
pygame.constants.K_5: flconstants.K_5,
pygame.constants.K_6: flconstants.K_6,
pygame.constants.K_7: flconstants.K_7,
pygame.constants.K_8: flconstants.K_8,
pygame.constants.K_9: flconstants.K_9,
pygame.constants.K_AMPERSAND: flconstants.K_AMPERSAND,
pygame.constants.K_ASTERISK: flconstants.K_ASTERISK,
pygame.constants.K_AT: flconstants.K_AT,
pygame.constants.K_BACKQUOTE: flconstants.K_BACKQUOTE,
pygame.constants.K_BACKSLASH: flconstants.K_BACKSLASH,
pygame.constants.K_BACKSPACE: flconstants.K_BACKSPACE,
pygame.constants.K_BREAK: flconstants.K_BREAK,
pygame.constants.K_CAPSLOCK: flconstants.K_CAPSLOCK,
pygame.constants.K_CARET: flconstants.K_CARET,
pygame.constants.K_CLEAR: flconstants.K_CLEAR,
pygame.constants.K_COLON: flconstants.K_COLON,
pygame.constants.K_COMMA: flconstants.K_COMMA,
pygame.constants.K_DELETE: flconstants.K_DELETE,
pygame.constants.K_DOLLAR: flconstants.K_DOLLAR,
pygame.constants.K_DOWN: flconstants.K_DOWN,
pygame.constants.K_END: flconstants.K_END,
pygame.constants.K_EQUALS: flconstants.K_EQUALS,
pygame.constants.K_ESCAPE: flconstants.K_ESCAPE,
pygame.constants.K_EURO: flconstants.K_EURO,
pygame.constants.K_EXCLAIM: flconstants.K_EXCLAIM,
pygame.constants.K_F1: flconstants.K_F1,
pygame.constants.K_F10: flconstants.K_F10,
pygame.constants.K_F11: flconstants.K_F11,
pygame.constants.K_F12: flconstants.K_F12,
pygame.constants.K_F13: flconstants.K_F13,
pygame.constants.K_F14: flconstants.K_F14,
pygame.constants.K_F15: flconstants.K_F15,
pygame.constants.K_F2: flconstants.K_F2,
pygame.constants.K_F3: flconstants.K_F3,
pygame.constants.K_F4: flconstants.K_F4,
pygame.constants.K_F5: flconstants.K_F5,
pygame.constants.K_F6: flconstants.K_F6,
pygame.constants.K_F7: flconstants.K_F7,
pygame.constants.K_F8: flconstants.K_F8,
pygame.constants.K_F9: flconstants.K_F9,
pygame.constants.K_GREATER: flconstants.K_GREATER,
pygame.constants.K_HOME: flconstants.K_HOME,
pygame.constants.K_INSERT: flconstants.K_INSERT,
pygame.constants.K_KP0: flconstants.K_KP0,
pygame.constants.K_KP1: flconstants.K_KP1,
pygame.constants.K_KP2: flconstants.K_KP2,
pygame.constants.K_KP3: flconstants.K_KP3,
pygame.constants.K_KP4: flconstants.K_KP4,
pygame.constants.K_KP5: flconstants.K_KP5,
pygame.constants.K_KP6: flconstants.K_KP6,
pygame.constants.K_KP7: flconstants.K_KP7,
pygame.constants.K_KP8: flconstants.K_KP8,
pygame.constants.K_KP9: flconstants.K_KP9,
pygame.constants.K_KP_DIVIDE: flconstants.K_KP_DIVIDE,
pygame.constants.K_KP_ENTER: flconstants.K_KP_ENTER,
pygame.constants.K_KP_EQUALS: flconstants.K_KP_EQUALS,
pygame.constants.K_KP_MINUS: flconstants.K_KP_MINUS,
pygame.constants.K_KP_MULTIPLY: flconstants.K_KP_MULTIPLY,
pygame.constants.K_KP_PERIOD: flconstants.K_KP_PERIOD,
pygame.constants.K_KP_PLUS: flconstants.K_KP_PLUS,
pygame.constants.K_LAST: flconstants.K_LAST,
pygame.constants.K_LEFT: flconstants.K_LEFT,
pygame.constants.K_LEFTBRACKET: flconstants.K_LEFTBRACKET,
pygame.constants.K_LEFTPAREN: flconstants.K_LEFTPAREN,
pygame.constants.K_LESS: flconstants.K_LESS,
pygame.constants.K_LSUPER: flconstants.K_LSUPER,
pygame.constants.K_MENU: flconstants.K_MENU,
pygame.constants.K_MINUS: flconstants.K_MINUS,
pygame.constants.K_MODE: flconstants.K_MODE,
pygame.constants.K_NUMLOCK: flconstants.K_NUMLOCK,
pygame.constants.K_PAGEDOWN: flconstants.K_PAGEDOWN,
pygame.constants.K_PAGEUP: flconstants.K_PAGEUP,
pygame.constants.K_PAUSE: flconstants.K_PAUSE,
pygame.constants.K_PERIOD: flconstants.K_PERIOD,
pygame.constants.K_PLUS: flconstants.K_PLUS,
pygame.constants.K_POWER: flconstants.K_POWER,
pygame.constants.K_PRINT: flconstants.K_PRINT,
pygame.constants.K_QUESTION: flconstants.K_QUESTION,
pygame.constants.K_QUOTE: flconstants.K_QUOTE,
pygame.constants.K_QUOTEDBL: flconstants.K_QUOTEDBL,
pygame.constants.K_RETURN: flconstants.K_RETURN,
pygame.constants.K_RIGHT: flconstants.K_RIGHT,
pygame.constants.K_RIGHTBRACKET: flconstants.K_RIGHTBRACKET,
pygame.constants.K_RIGHTPAREN: flconstants.K_RIGHTPAREN,
pygame.constants.K_RSUPER: flconstants.K_RSUPER,
pygame.constants.K_SCROLLOCK: flconstants.K_SCROLLOCK,
pygame.constants.K_SEMICOLON: flconstants.K_SEMICOLON,
pygame.constants.K_SLASH: flconstants.K_SLASH,
pygame.constants.K_SPACE: flconstants.K_SPACE,
pygame.constants.K_SYSREQ: flconstants.K_SYSREQ,
pygame.constants.K_TAB: flconstants.K_TAB,
pygame.constants.K_UNDERSCORE: flconstants.K_UNDERSCORE,
pygame.constants.K_UNKNOWN: flconstants.K_UNKNOWN,
pygame.constants.K_UP: flconstants.K_UP,
pygame.constants.K_a: flconstants.K_a,
pygame.constants.K_b: flconstants.K_b,
pygame.constants.K_c: flconstants.K_c,
pygame.constants.K_d: flconstants.K_d,
pygame.constants.K_e: flconstants.K_e,
pygame.constants.K_f: flconstants.K_f,
pygame.constants.K_g: flconstants.K_g,
pygame.constants.K_h: flconstants.K_h,
pygame.constants.K_i: flconstants.K_i,
pygame.constants.K_j: flconstants.K_j,
pygame.constants.K_k: flconstants.K_k,
pygame.constants.K_l: flconstants.K_l,
pygame.constants.K_m: flconstants.K_m,
pygame.constants.K_n: flconstants.K_n,
pygame.constants.K_o: flconstants.K_o,
pygame.constants.K_p: flconstants.K_p,
pygame.constants.K_q: flconstants.K_q,
pygame.constants.K_r: flconstants.K_r,
pygame.constants.K_s: flconstants.K_s,
pygame.constants.K_t: flconstants.K_t,
pygame.constants.K_u: flconstants.K_u,
pygame.constants.K_v: flconstants.K_v,
pygame.constants.K_w: flconstants.K_w,
pygame.constants.K_x: flconstants.K_x,
pygame.constants.K_y: flconstants.K_y,
pygame.constants.K_z: flconstants.K_z
}
mb_map = {
1: flconstants.MB_1,
2: flconstants.MB_2,
3: flconstants.MB_3,
4: flconstants.MS_UP,
5: flconstants.MS_DOWN,
}
def init():
pass
def poll():
events = pygame.event.get()
l = []
for event in events:
try: e = [-1, type_map[event.type]]
except KeyError: continue
if event.type == pygame.constants.QUIT:
e = [-2, -2]
elif event.type == pygame.constants.MOUSEMOTION:
e[0] = flconstants.M_MOTION
elif event.type == pygame.constants.KEYDOWN or event.type == pygame.constants.KEYUP:
try: e[0] = key_map[event.key]
except KeyError: continue
elif event.type == pygame.constants.MOUSEBUTTONDOWN or event.type == pygame.constants.MOUSEBUTTONUP:
e[0] = mb_map[event.button]
l.append(e)
return l
| Python |
#!/usr/bin/env python
## flamingo - 2D Game Engine
## Copyright (C) 2009 Bradley Zeis
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
##
## Bradley Zeis
## bradzeis@gmail.com
| Python |
#!/usr/bin/env python
## flamingo - 2D Game Engine
## Copyright (C) 2009 Bradley Zeis
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
##
## Bradley Zeis
## bradzeis@gmail.com
| Python |
#!/usr/bin/env python
## flamingo - 2D Game Engine
## Copyright (C) 2009 Bradley Zeis
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
##
## Bradley Zeis
## flamingoengine@gmail.com
import pygame.display
def init(width, height, caption, fullscreen, depth, flags):
pygame.display.init()
pygame.display.set_mode((width, height),
pygame.constants.OPENGL | pygame.constants.DOUBLEBUF | flags, depth)
pygame.display.set_caption(caption)
def quit():
pygame.display.quit()
def flip():
pygame.display.flip()
def set_size(width, height):
pass
def set_caption():
pygame.display.set_caption(caption)
| Python |
#!/usr/bin/env python
## flamingo - 2D Game Engine
## Copyright (C) 2009 Bradley Zeis
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
##
## Bradley Zeis
## bradzeis@gmail.com
| Python |
#!/usr/bin/env python
## flamingo - 2D Game Engine
## Copyright (C) 2009 Bradley Zeis
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
##
## Bradley Zeis
## flamingoengine@gmail.com
import pygame.display
def init(width, height, caption, fullscreen, depth, flags):
pygame.display.init()
pygame.display.set_mode((width, height),
pygame.constants.OPENGL | pygame.constants.DOUBLEBUF | flags, depth)
pygame.display.set_caption(caption)
def quit():
pygame.display.quit()
def flip():
pygame.display.flip()
def set_size(width, height):
pass
def set_caption():
pygame.display.set_caption(caption)
| Python |
#!/usr/bin/env python
## flamingo - 2D Game Engine
## Copyright (C) 2009 Bradley Zeis
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
##
## Bradley Zeis
## bradzeis@gmail.com
| Python |
#!/usr/bin/env python
## flamingo - 2D Game Engine
## Copyright (C) 2009 Bradley Zeis
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
##
## Bradley Zeis
## flamingoengine@gmail.com
"""Empty mixer for use when regular mixers aren't available."""
THREADED = True
def init(*args):
pass
def start():
pass
def quit():
pass
def ms_to_samp(ms):
return int(ms * (SAMPLERATE / 1000.0))
def samp_to_ms(samp):
return int(samp / (SAMPLERATE / 1000.0))
class Sound(object):
def __init__(*args, **kwargs):
pass
def play(*args, **kwargs):
return SoundEvent()
def resample(self, samplerate):
pass
def __getattr__(self, *args):
return None
class StreamingSound(object):
def __init__(*args, **kwargs):
pass
def play(*args, **kwargs):
return SoundEvent()
def __getattr__(self, *args):
return None
class SoundEvent(object):
def __getattr__(self, *args):
return None
def pause(self):
pass
def unpause(self):
pass
def stop(self):
pass
class Mixer(object):
def __init__(*args, **kwargs):
pass
@classmethod
def tick(*args):
pass
| Python |
#!/usr/bin/env python
## flamingo - 2D Game Engine
## Copyright (C) 2009 Bradley Zeis
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
##
## Bradley Zeis
## flamingoengine@gmail.com
"""Flamingo audio mixer backend for the PyAudio PortAudio bindings.
This module is heavily influenced by SWMixer by Nathan Whitehead.
"""
import time
import wave
import thread
import math
import numpy
import pyaudio
from ... import core
from ... import flmath
from ... import util
import abstractmixer
##-------- Constants
SAMPLERATE = 0
CHANNELS = 0
CHUNKSIZE = 0
PYAUDIO = None
STREAM = None
THREADED = True
THREAD = None
LOCK = thread.allocate_lock()
half_pi = math.pi * 0.5
##-------- Initialization Functions
def init(samplerate=44100, chunksize=256):
"""Initialize the mixer.
samplerate - (int) The number of samples per second.
chunksize - (int) The number of samples processed at a time.
Returns: None
"""
global SAMPLERATE, CHANNELS, CHUNKSIZE, PYAUDIO, STREAM
SAMPLERATE = samplerate
CHANNELS = 2
CHUNKSIZE = chunksize
PYAUDIO = pyaudio.PyAudio()
STREAM = PYAUDIO.open(
format = pyaudio.paInt16,
channels = CHANNELS,
rate = SAMPLERATE,
output= True
)
Channel()
def start():
"""Start a new mixing thread."""
global THREAD
def f():
while True:
try: Mixer.tick(core.GAME.data.delta_time)
except AttributeError: pass
THREAD = thread.start_new_thread(f, ())
def quit():
pass
##-------- Audio Functions
def resample(src, scale):
"""Resample a mono or stereo source."""
n = round(len(src) * scale)
return numpy.interp(
numpy.linspace(0.0, 1.0, n, endpoint=False),
numpy.linspace(0.0, 1.0, len(src), endpoint=False),
src
)
def interleave(left, right):
"""Convert two mono sources into one stereo source."""
return numpy.ravel(numpy.vstack((left, right)), order='F')
def uninterleave(src):
"""Convert one stereo source into two mono sources."""
return src.reshape(2, len(src)/2, order='FORTRAN')
def stereo_to_mono(left, right):
"""Convert one stereo source into one mono source."""
return (0.5 * left + 0.5 * right).astype(numpy.int16)
def calculate_pan(left, right, pan):
"""Pan two mono sources in the stereo field."""
if pan < -1: pan = -1
elif pan > 1: pan = 1
pan = ((pan + 1.0) * 0.5) * half_pi
l, r = math.cos(pan), math.sin(pan)
return left * l, right * r
def __distance__(distance):
if distance > 1:
v = distance**-1
if v > 0.01:
return v
return 0
return 1
distance_formula = __distance__
def ms_to_samp(ms):
return int(ms * (SAMPLERATE / 1000.0))
def samp_to_ms(samp):
return int(samp / (SAMPLERATE / 1000.0))
##-------- Sounds
class Sound(abstractmixer.Sound):
"""A sound completely loaded into memory."""
def __init__(self, filename):
## See if data is cached
try:
self.data = core._Data.aud_cache[filename]
except KeyError:
## Read Data
wav = wave.open(filename, 'rb')
num_ch = wav.getnchannels()
self.framerate = wav.getframerate()
fr = wav.getframerate()
sw = wav.getsampwidth()
data = []
r = ' '
while r != '':
r = wav.readframes(4096)
data.append(r)
if sw == 2:
self.data = numpy.fromstring(''.join(data), dtype=numpy.int16)
if sw == 4:
self.data = numpy.fromstring(''.join(data), dtype=numpy.int32)
self.data /= 65536.0
if sw == 1:
self.data = numpy.fromstring(''.join(data), dtype=numpy.uint8)
self.data *= 256.0
wav.close()
## Resample
if fr != SAMPLERATE:
scale = SAMPLERATE * 1.0 / fr
if num_ch == 1:
self.data = resample(self.data, scale)
if num_ch == 2:
left, right = uninterleave(self.data)
nleft = resample(left, scale)
nright = resample(right, scale)
self.data = interleave(nleft, nright)
## Stereo Conversion
if num_ch != CHANNELS:
if num_ch == 1:
## Need Stereo
self.data = interleave(self.data, self.data)
core._Data.aud_cache[filename] = self.data
def play(self, channel=0, volume=1.0, loops=0, pos=(0,0)):
"""Plays the audio data.
channel - Mixer channel to play the audio on.
volume - The volume to play at.
loops - The number of times to loop the audio. -1 is infinite
pos - The position in 2d space to play the sound at.
Returns: SoundEvent
"""
sndevent = SoundEvent(self.data, volume, loops, flmath.Vector(pos))
if Mixer.channels == []:
Channel()
LOCK.acquire()
Mixer.channels[channel].add_src(sndevent)
LOCK.release()
return sndevent
def resample(self, samplerate):
self.data = resample(self.data, SAMPLERATE * 1.0 / samplerate)
##-------- Properties
def _get_length(self):
return len(self.data)
length = property(_get_length)
class StreamingSound(abstractmixer.StreamingSound):
"""A sound streamed directly from disk."""
def __init__(self, filename):
self.filename = filename
def play(self, channel=0, volume=1.0, loops=0):
"""Plays the audio stream.
channel - Mixer channel to play the audio on.
volume - The volume to play at.
loops - The number of times to loop the audio. -1 is infinite
Returns: StreamingSoundEvent
"""
sndevent = StreamingSoundEvent(self.filename, volume, loops)
if Mixer.channels == []:
Channel()
LOCK.acquire()
Mixer.channels[channel].add_src(sndevent)
LOCK.release()
return sndevent
## Properties won't work, they're just there for compatibility
## with Sound
##-------- Properties
def _get_length(self):
return None
length = property(_get_length)
class SoundEvent(object):
"""Represents one Sound source currently playing."""
def __init__(self, data, volume, loops, pos):
self.data = data
self.seek = 0
self.volume = volume
self.loops = loops
self.pos = pos
self.active = True
self.done = False
def get_samples(self, sz):
"""Return a new buffer of samples from the audio data.
sz - The size, in samples, of the buffer
Returns: numpy.array
"""
if not self.active:
return
z = self.data[self.seek:self.seek + sz]
self.seek += sz
if len(z) < sz:
# oops, sample data didn't cover buffer
if self.loops != 0:
# loop around
self.loops -= 1
self.seek = sz - len(z)
z = numpy.append(z, self.data[:sz - len(z)])
else:
# nothing to loop, just append zeroes
z = numpy.append(z, numpy.zeros(sz - len(z), numpy.int16))
# and stop the sample, it's done
self.done = True
if self.seek == len(self.data):
# this case loops without needing any appending
if self.loops != 0:
self.loops -= 1
self.seek = 0
else:
self.done = True
return uninterleave(z * self.volume)
def pause(self):
LOCK.acquire()
self.active = False
LOCK.release()
def unpause(self):
LOCK.acquire()
self.active = True
LOCK.release()
def stop(self):
LOCK.acquire()
self.done = True
LOCK.release()
class StreamingSoundEvent(object):
"""Represents one StreamingSound currently playing."""
def __init__(self, filename, volume, loops):
self.stream = wave.open(filename, 'rb')
self.volume = volume
self.seek = 0
self.loops = loops
self.pos = (0, 0)
self.active = True
self.done = False
self.buf = ''
def get_samples(self, sz):
"""Return a new buffer of samples from the audio data.
sz - The size, in samples, of the buffer
Returns: numpy.array
"""
szb = sz * 2
while len(self.buf) < szb:
s = self.read()
if s is None or s == '': break
self.buf += s[:]
z = numpy.fromstring(self.buf[:szb], dtype=numpy.int16)
if len(z) < sz:
# In this case we ran out of stream data
# append zeros (don't try to be sample accurate for streams)
z = numpy.append(z, numpy.zeros(sz - len(z), numpy.int16))
if self.loops != 0:
self.loops -= 1
self.seek = 0
self.stream.rewind()
self.buf = ''
else:
self.done = True
self.stream.close()
else:
# remove head of buffer
self.buf = self.buf[szb:]
return uninterleave(z * self.volume)
def read(self):
"""Return a buffer from the audio file."""
return self.stream.readframes(4096)
def pause(self):
LOCK.acquire()
self.active = False
LOCK.release()
def unpause(self):
LOCK.acquire()
self.active = True
LOCK.release()
def stop(self):
LOCK.acquire()
self.done = True
self.stream.close()
LOCK.release()
##-------- Mixer
class Channel(abstractmixer.Channel):
"""Represents a channel on a hardware mixer."""
def __init__(self, volume=1.0, pan=0):
self.id = len(Mixer.channels)
Mixer.channels.append(self)
self.srcs = []
self.effects = []
self.volume = volume
self.pan = 0
def add_src(self, src):
"""Add a SoundEvent or StreamingSoundEvent to the channel."""
self.srcs.append(src)
def add_effect(self, effect):
LOCK.acquire()
self.effects.append(effect)
LOCK.release()
class Mixer(abstractmixer.Mixer):
"""Represents a limited hardware mixer.
A Mixer essentially acts as a Master Bus on an analogue mixer. All of
the other Channel's output goes through the mixer to get written to
the output stream.
"""
channels = []
effects = []
volume = 1.0
time_slept = 0 ## ms since last tick()
@classmethod
def tick(self, dt):
"""Write all of the audio buffers to the output stream.
Basic Steps:
1. Create a buffer for each Channel
2. For each Sound on each Channel, calculate panning/volume,
write to Channel Buffer
3. Write each Sound to the appropriate Channel buffer
4. Run each of the Channel's effects on it's Channel buffer
5. Mix together all of the Channel buffers to the Mixer buffer
6. Run Mixer effects on the Mixer buffer
7. Write Mixer buffer to output stream
Returns: None
"""
sz = CHUNKSIZE * CHANNELS
out = numpy.zeros(sz, numpy.float)
chout = numpy.zeros(CHUNKSIZE)
LOCK.acquire()
for ch in self.channels:
rmlist = []
## Create Channel Buffer
choutl, choutr = chout.copy(), chout.copy()
for src in ch.srcs:
if not src.active:
continue
## Read Data from Sound Buffer
l, r = src.get_samples(sz)
if src.done:
rmlist.append(src)
continue
## Calculate Sound Volume/Pan from distance
d = flmath.distance(src.pos, (0,0))
dist_vol = distance_formula(d)
angle_pan = 0
if d != 0:
a = math.radians(src.pos.angle) / 2.0
angle_pan = (2 * a) / half_pi - 1
if angle_pan > 1:
angle_pan = 1 - (angle_pan - 1)
l *= dist_vol
r *= dist_vol
l, r = calculate_pan(l, r, ch.pan - angle_pan)
## Write Sound to Channel buffer
choutl += l
choutr += r
## Render Channel Effects
for effect in ch.effects:
choutl, choutr = effect.process(choutl, choutr, CHUNKSIZE)
## Write Channel buffer to Mixer buffer
s = interleave(choutl, choutr) * ch.volume
out = out + s - (out * s) / 65536
for src in rmlist:
ch.srcs.remove(src)
## Render Mixer Effects
l, r = uninterleave(out)
for effect in self.effects:
effect.process(l, r, CHUNKSIZE)
LOCK.release()
## Write Mixer buffer to Output Stream
out = interleave(l, r) * self.volume
out = out.clip(-32767.0, 32767.0)
outdata = (out.astype(numpy.int16)).tostring()
#while STREAM.get_write_available() < sz: time.sleep(0.001)
STREAM.write(outdata, CHUNKSIZE)
| Python |
#!/usr/bin/env python
## flamingo - 2D Game Engine
## Copyright (C) 2009 Bradley Zeis
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
##
## Bradley Zeis
## flamingoengine@gmail.com
"""Empty mixer for use when regular mixers aren't available."""
THREADED = True
def init(*args):
pass
def start():
pass
def quit():
pass
def ms_to_samp(ms):
return int(ms * (SAMPLERATE / 1000.0))
def samp_to_ms(samp):
return int(samp / (SAMPLERATE / 1000.0))
class Sound(object):
def __init__(*args, **kwargs):
pass
def play(*args, **kwargs):
return SoundEvent()
def resample(self, samplerate):
pass
def __getattr__(self, *args):
return None
class StreamingSound(object):
def __init__(*args, **kwargs):
pass
def play(*args, **kwargs):
return SoundEvent()
def __getattr__(self, *args):
return None
class SoundEvent(object):
def __getattr__(self, *args):
return None
def pause(self):
pass
def unpause(self):
pass
def stop(self):
pass
class Mixer(object):
def __init__(*args, **kwargs):
pass
@classmethod
def tick(*args):
pass
| Python |
Subsets and Splits
SQL Console for ajibawa-2023/Python-Code-Large
Provides a useful breakdown of language distribution in the training data, showing which languages have the most samples and helping identify potential imbalances across different language groups.