1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 """Common shared functions that do not fit anywhere else.
16 """
17
18 import os
19 import sys
20 import traceback
21 from hashlib import md5
22
23
29
30
32 """ Import certain class with certain inputs """
33 mod = __import__(modpath, globals(), locals(), [modname], -1)
34 cls = getattr(mod, classname)
35 return cls(*args)
36
38 """ Parse XY or XYSigma data to list """
39
40 ifile = open(filename, "r")
41 inlines = ifile.readlines()
42 ifile.close()
43
44
45 datalist = []
46 for line in inlines:
47 terms = line.strip().split()
48 if len(terms) > 1 and terms[0] not in ["#", ""]:
49 datalist.append((float(terms[0]), float(terms[1])))
50 return datalist
51
52
53
54
56 '''Print a red warning message to the std output
57 warningMsg : the warning message to be printed
58 '''
59
60 print 'WARNING: ' + warningMsg
61 return
62
63
65 '''Get unique items from a sequence while keeping its original order'''
66 seen = set()
67 for item in seq:
68 if item in seen: continue
69 seen.add(item)
70 yield item
71 pass
72
73
75 '''get the md5 id of the file path
76 fullpath - the abs path of the file
77 return - the file path'''
78 fid = None
79 fid = md5(open(fullpath, 'rb').read()).hexdigest()
80 return fid
81
82
84 '''Print the information for debug'''
85 exc_type, exc_value, exc_traceback = sys.exc_info()
86 traceback.print_exception(exc_type, exc_value, exc_traceback,
87 limit=100, file=sys.stdout)
88 return
89
90
91
92
93
94 import csv, codecs, cStringIO
95
97 """
98 Iterator that reads an encoded stream and reencodes the input to UTF-8
99 """
101 self.reader = codecs.getreader(encoding)(f)
102
105
107 return self.reader.next().encode("utf-8")
108
110 """
111 A CSV reader which will iterate over lines in the CSV file "f",
112 which is encoded in the given encoding.
113 """
114
115 - def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
116 f = UTF8Recoder(f, encoding)
117 self.reader = csv.reader(f, dialect=dialect, **kwds)
118
120 row = self.reader.next()
121 return [unicode(s, "utf-8") for s in row]
122
125
127 """
128 A CSV writer which will write rows to CSV file "f",
129 which is encoded in the given encoding.
130 """
131
132 - def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
133
134 self.queue = cStringIO.StringIO()
135 self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
136 self.stream = f
137 self.encoder = codecs.getincrementalencoder(encoding)()
138
140 self.writer.writerow([s.encode("utf-8") for s in row])
141
142 data = self.queue.getvalue()
143 data = data.decode("utf-8")
144
145 data = self.encoder.encode(data)
146
147 self.stream.write(data)
148
149 self.queue.truncate(0)
150
152 for row in rows:
153 self.writerow(row)
154