rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
'clear to clear database (you will
'clear to clear database (you will '
def run(self): '''Main function for this class''' self.load_state() if self.current_block is None: if self.db_manager.chunk_count() != 0: raise CreateError('No state information, but chunk ' 'count is not 0. Probably the scan ' 'finished already. Abort process to ' 'avoid loss of data. Use parameter ' 'clear to clear d...
chunk = Chunk()
chunk = Chunk(False)
def chunk_load(self, chunk_id): '''Return chunk object by chunk_id''' result = self.conn.execute( "SELECT * FROM chunk " "WHERE id = ?", (chunk_id,)).fetchone() if result is None: return None chunk = Chunk() (chunk.id, chunk.block_start, chunk.block_size, chunk.clock_start, chunk.clock_end, chunk.concat) = result retur...
"concat = ?," "position = ? "
"concat = ? "
def chunk_save(self, chunk): '''Insert or update info in chunk table''' if chunk.new: cur = self.conn.execute( "INSERT INTO chunk " "VALUES (?, ?, ?, ?, ?, ?)", (chunk.id, chunk.block_start, chunk.block_size, chunk.clock_start, chunk.clock_end, chunk.concat))
for chunk1 in self.db_manager.chunk_query(): concat_chunk = None for chunk2 in self.db_manager.chunk_query():
for chunk2 in self.db_manager.chunk_query(): target = None for chunk1 in self.db_manager.chunk_query():
def sort(self): '''Sort chunks and try to concatenate parts of the same recording''' self.db_manager.chunk_reset_concat() for chunk1 in self.db_manager.chunk_query(): concat_chunk = None for chunk2 in self.db_manager.chunk_query(): if chunk1.id == chunk2.id: continue delta = chunk2.clock_start - chunk1.clock_end if (de...
if concat_chunk is None: concat_chunk = chunk2 else: old_delta = concat_chunk.clock_start - chunk1.clock_end if delta < old_delta: concat_chunk = chunk2 if concat_chunk is None: continue chunk1.concat = concat_chunk.id self.db_manager.chunk_save(chunk1)
if target is not None: if delta >= chunk2.clock_start - target.clock_end: new_target = False if new_target: target = chunk1 if target is not None: chunk2.concat = target.id self.db_manager.chunk_save(chunk2)
def sort(self): '''Sort chunks and try to concatenate parts of the same recording''' self.db_manager.chunk_reset_concat() for chunk1 in self.db_manager.chunk_query(): concat_chunk = None for chunk2 in self.db_manager.chunk_query(): if chunk1.id == chunk2.id: continue delta = chunk2.clock_start - chunk1.clock_end if (de...
self.block_start = block_start self.clock_start = clock_start
self.chunk.block_start = block_start self.chunk.clock_start = clock_start
def load_state(self): current_block = self.db_manager.state_query('current_block') block_start = self.db_manager.state_query('block_start') clock_start = self.db_manager.state_query('clock_start') old_clock = self.db_manager.state_query('old_clock') time_elapsed = self.db_manager.state_query('time_elapsed')
marker_bit_1 = ord(buf[4] >> 6) & 3 marker_bit_2 = ord(buf[4] >> 2) & 1 marker_bit_3 = ord(buf[6] >> 2) & 1 marker_bit_4 = ord(buf[8] >> 2) & 1
marker_bit_1 = (ord(buf[4]) >> 6) & 3 marker_bit_2 = (ord(buf[4]) >> 2) & 1 marker_bit_3 = (ord(buf[6]) >> 2) & 1 marker_bit_4 = (ord(buf[8]) >> 2) & 1
def mpeg_header(self, buf): '''Check if buffer is mpeg header and return system clock or None''' # Partial Program Stream Pack header format # ========================================= # # Name |Number of bits| Description # ----------------------|--------------|------------------...
clock_bits[32] = ord(buf[4] >> 5) & 1; clock_bits[31] = ord(buf[4] >> 4) & 1; clock_bits[30] = ord(buf[4] >> 3) & 1; clock_bits[29] = ord(buf[4] >> 1) & 1; clock_bits[28] = ord(buf[4] >> 0) & 1; clock_bits[27] = ord(buf[5] >> 7) & 1; clock_bits[26] = ord(buf[5] >> 6) & 1; clock_bits[25] = ord(buf[5] >> 5) & 1; clock_bi...
clock_bits[32] = (ord(buf[4]) >> 5) & 1; clock_bits[31] = (ord(buf[4]) >> 4) & 1; clock_bits[30] = (ord(buf[4]) >> 3) & 1; clock_bits[29] = (ord(buf[4]) >> 1) & 1; clock_bits[28] = (ord(buf[4]) >> 0) & 1; clock_bits[27] = (ord(buf[5]) >> 7) & 1; clock_bits[26] = (ord(buf[5]) >> 6) & 1; clock_bits[25] = (ord(buf[5]) >> ...
def mpeg_header(self, buf): '''Check if buffer is mpeg header and return system clock or None''' # Partial Program Stream Pack header format # ========================================= # # Name |Number of bits| Description # ----------------------|--------------|------------------...
"ORDERD BY block_start"):
"ORDER BY block_start"):
def chunk_query_ids(self): '''Return iterator for all chunk ids''' for result in self.conn.execute( "SELECT id FROM chunk " "ORDERD BY block_start"): yield result[0]
self.tweet("", None, body)
self.tweet(None, body)
def sendMessage(self, body, html=None, to_user=secret.iembot_user): if (not self.authenticated): log.msg("No Connection, Lets wait and try later...") reactor.callLater(3, self.sendMessage, body, html, to_user) return message = domish.Element(('jabber:client','message')) message['to'] = '%s@%s' % (to_user, secret.chatse...
print 'MISSING %s' % (nwsli,)
state = mesonet.nwsli2state[ nwsli[-2:] ] print 'MISSING %s %s %s' % (state, nwsli, row[1])
def ask_nws(nwsli): URL = "https://ops13jweb.nws.noaa.gov/nwsli/liu/AsciiReport.jsp?v_sid=%s&v_wfo=&v_city=&v_county=&v_state=&v_region=&v_declat=&v_declon=&v_pgma=&v_pid=&v_owner=&orderBy=sid#" % (nwsli,) username = 'daryl.herzmann' req = urllib2.Request(URL) base64string = base64.encodestring( '%s:%s' % (username, ...
print 'Unknown 3 CHAR ID: %s' % (sid,)
print 'Unknown 3 CHAR ID: %s %s' % (sid, tp.get_product_id())
def process_site(tp, sid, ts, data): """ I process a dictionary of data for a particular site """ isCOOP = 0 if len(sid) == 3: if CHAR3LOOKUP.has_key(sid): state = CHAR3LOOKUP[sid] else: print 'Unknown 3 CHAR ID: %s' % (sid,) return elif len(sid) == 5: if mesonet.nwsli2state.has_key( sid[-2:]): state = mesonet.nwsli2st...
print 'Unknown 5 CHAR State ID: %s' % (sid,)
print 'Unknown 5 CHAR State ID: %s %s' % (sid, tp.get_product_id())
def process_site(tp, sid, ts, data): """ I process a dictionary of data for a particular site """ isCOOP = 0 if len(sid) == 3: if CHAR3LOOKUP.has_key(sid): state = CHAR3LOOKUP[sid] else: print 'Unknown 3 CHAR ID: %s' % (sid,) return elif len(sid) == 5: if mesonet.nwsli2state.has_key( sid[-2:]): state = mesonet.nwsli2st...
print 'Unknown ID: %s' % (sid,)
print 'Unknown ID: %s %s' % (sid, tp.get_product_id())
def process_site(tp, sid, ts, data): """ I process a dictionary of data for a particular site """ isCOOP = 0 if len(sid) == 3: if CHAR3LOOKUP.has_key(sid): state = CHAR3LOOKUP[sid] else: print 'Unknown 3 CHAR ID: %s' % (sid,) return elif len(sid) == 5: if mesonet.nwsli2state.has_key( sid[-2:]): state = mesonet.nwsli2st...
rs = postgis.query( sql ).dictresult()
try: rs = postgis.query( sql ).dictresult() except: return
def lookup_touches(ugc): touches[ ugc ] = [] sql = """select ugc from nws_ugc WHERE ugc != '%s' and ST_Touches(geom, (select geom from nws_ugc WHERE ugc = '%s' LIMIT 1))""" % ( ugc, ugc) rs = postgis.query( sql ).dictresult() for i in range(len(rs)): touches[ ugc ].append( rs[i]['ugc'] )
warning = [ugc,]
warning = [ugc,'ZZZ']
def lookup_touches(ugc): touches[ ugc ] = [] sql = """select ugc from nws_ugc WHERE ugc != '%s' and ST_Touches(geom, (select geom from nws_ugc WHERE ugc = '%s' LIMIT 1))""" % ( ugc, ugc) rs = postgis.query( sql ).dictresult() for i in range(len(rs)): touches[ ugc ].append( rs[i]['ugc'] )
<link rel="icon" type="image/png" href="%simages/favicon.png"/>
<link rel="shortcut icon" type="image/png" href="%simages/favicon.png"/>
def producehtml(name, debug): ui = pages.UIs[name] js = jslist(name, debug) css = csslist(name, debug, gen=True) csshtml = "\n".join(" <link rel=\"stylesheet\" href=\"%s%s\" type=\"text/css\"/>" % (config.STATIC_BASE_URL, x) for x in css) jshtml = "\n".join(" <script type=\"text/javascript\" src=\"%s%s\"></script>" %...
if options.syslog_prefix:
if options.syslog and options.syslog_prefix:
def help_reactors(*args): run_twistd(["--help-reactors"]) sys.exit(1)
twisted_fail = lambda x, y=None: fail("you don't seem to have twisted's %s module." % x, "your distro is most likely modular, look for a twisted web package%s." % (" %s" % y if y else "",))
def twisted_fail(x, y=None): fail("you don't seem to have twisted's %s module." % x, "your distro is most likely modular, look for a twisted %s package%s." % (x, " %s" % y if y else "",))
def check_twisted(): try: import twisted except ImportError: fail("qwebirc requires twisted (at least 8.2.0), see http://twistedmatrix.com/") twisted_fail = lambda x, y=None: fail("you don't seem to have twisted's %s module." % x, "your distro is most likely modular, look for a twisted web package%s." % (" %s" % y if ...
fail("you don't seem to have twisted's mail module, your distro is most likely modular, look for a twisted mail package.")
def check_twisted(): try: import twisted except ImportError: fail("qwebirc requires twisted (at least 8.2.0), see http://twistedmatrix.com/") twisted_fail = lambda x, y=None: fail("you don't seem to have twisted's %s module." % x, "your distro is most likely modular, look for a twisted web package%s." % (" %s" % y if ...
twistedfail("words")
twisted_fail("words")
def check_twisted(): try: import twisted except ImportError: fail("qwebirc requires twisted (at least 8.2.0), see http://twistedmatrix.com/") twisted_fail = lambda x, y=None: fail("you don't seem to have twisted's %s module." % x, "your distro is most likely modular, look for a twisted web package%s." % (" %s" % y if ...
self.cmapname = cmapname
def __init__(self, tree, token, match): PostProcessor.__init__(self, tree, token, match) try: # Recupero el programa, por defecto "dot". self.program = self.program.lower() except AttributeError: self.program = 'dot' try: # Recupero la lista de formatos, por defecto ("png",) self.formats = set(x.strip() for x in self.f...
submeta = meta.subtypes[keys[vart]]
submeta = meta.subtypes[vart]
def _set_vars(self, data): # proceso la tabla especial "variables" meta = data._meta keys = dict((k.lower(), k) for k in meta.subtypes.keys()) vart = keys.get(CSVShelf.VARTABLE.lower(), None) if vart: submeta = meta.subtypes[keys[vart]] key, val, typ = submeta.summary[:3] for item in getattr(data, str(vart)): vname = s...
return bool(value)
return value is not None
def _verify(self, symbols, value): return bool(value)
self._style = style or dict(TableBuilder.STYLE) if not style and vertical:
self._style = deepcopy(TableBuilder.STYLE) if vertical:
def __init__(self, style=None, vertical=False, repeat=False): """Construye una tabla a partir de los datos dados. Construye una tabla HTML. Puede recibir un diccionario con atributos para los siguientes elementos: 'table': <table>. Por defecto, {'width': '100%', 'cellspacing': '0', 'class' : 'htable'}, 'head':...
self.errmsg
str(self.errmsg)
def __str__(self): error = [ "%s, LINE %s" % ( os.path.basename(self.source.id) if self.source else "<>", self.token.lineno), "Error interpretando %s" % str(self.token), self.errmsg ] #error.extend(traceback.format_exception(*self.exc_info)) return "\n".join(error)
if int(dat[2]) == 500 and a = 'y':
if int(dat[2]) == 500 and a == 'y':
def httpd_stats(self,opts): q = "Would you like to output http 500 errors? (y/n):" a = raw_input(q) while a not in ('y','n'): q = "Invalid response please enter y or n:" a = raw_input(q) #this was not fun to type! codes = { 100:{'desc':'continue','count':0}, 101:{'desc':'switching protocol','count':0}, 200:{'desc':'O...
500tmp = open('/tmp/sysadmin_http500.tmp','w+')
tmp = open('/tmp/sysadmin_http500.tmp','w+')
def httpd_stats(self,opts): q = "Would you like to output http 500 errors? (y/n):" a = raw_input(q) while a not in ('y','n'): q = "Invalid response please enter y or n:" a = raw_input(q) if a == 'y': 500tmp = open('/tmp/sysadmin_http500.tmp','w+') #this was not fun to type! codes = { 100:{'desc':'continue','count':0...
500tmp.write("HTTP 500 - %s\n" % dat[2])
tmp.write("HTTP 500 - %s\n" % dat[2])
def httpd_stats(self,opts): q = "Would you like to output http 500 errors? (y/n):" a = raw_input(q) while a not in ('y','n'): q = "Invalid response please enter y or n:" a = raw_input(q) if a == 'y': 500tmp = open('/tmp/sysadmin_http500.tmp','w+') #this was not fun to type! codes = { 100:{'desc':'continue','count':0...
500tmp.close()
tmp.close()
def httpd_stats(self,opts): q = "Would you like to output http 500 errors? (y/n):" a = raw_input(q) while a not in ('y','n'): q = "Invalid response please enter y or n:" a = raw_input(q) if a == 'y': tmp = open('/tmp/sysadmin_http500.tmp','w+') #this was not fun to type! codes = { 100:{'desc':'continue','count':0}, ...
tmp.close()
if a == 'y': tmp.close()
def httpd_stats(self,opts): q = "Would you like to output http 500 errors? (y/n):" a = raw_input(q) while a not in ('y','n'): q = "Invalid response please enter y or n:" a = raw_input(q) if a == 'y': tmp = open('/tmp/sysadmin_http500.tmp','w+') #this was not fun to type! codes = { 100:{'desc':'continue','count':0}, ...
self.assertRaises(Exception, test_view('sale_opportunity'))
test_view('sale_opportunity')
def test0005views(self): ''' Test views. ''' self.assertRaises(Exception, test_view('sale_opportunity'))
'MIN(__id) AS id', 'id AS opportunity', 'MIN(COALESCE(write_date, create_date)) AS date', 'COALESCE(write_uid, create_uid) AS user', ] + [name for name, field in self._columns.iteritems()
'MIN("%s".__id) AS id' % table, '"%s".id AS opportunity' % table, 'MIN(COALESCE("%s".write_date, "%s".create_date)) AS date' % (table, table), 'COALESCE("%s".write_uid, "%s".create_uid) AS user' % (table, table), ] + ['"%s"."%s"' % (table, name) for name, field in self._columns.iteritems()
def _table_query_fields(self, context=None): return [ 'MIN(__id) AS id', 'id AS opportunity', 'MIN(COALESCE(write_date, create_date)) AS date', 'COALESCE(write_uid, create_uid) AS user', ] + [name for name, field in self._columns.iteritems() if name not in ('id', 'opportunity', 'date', 'user') and not hasattr(field, 's...
'id', 'COALESCE(write_uid, create_uid)', ] + [name for name, field in self._columns.iteritems()
'"%s".id' % table, 'COALESCE("%s".write_uid, "%s".create_uid)' % (table, table), ] + ['"%s"."%s"' % (table, name) for name, field in self._columns.iteritems()
def _table_query_group(self, context=None): return [ 'id', 'COALESCE(write_uid, create_uid)', ] + [name for name, field in self._columns.iteritems() if name not in ('id', 'opportunity', 'date', 'user') and not hasattr(field, 'set')]
def is_k_sparse(vec, k): """ checks if 95% of the weight of a normalized vector vec is in less than k of its entries. """ WEIGHT=0.95 n=len(vec) if k<0 or k>n: raise ValueError(" k has to be in 1 .. len(vec) ") exfilt = numpy.concatenate( (numpy.ones(k), numpy.zeros(n-k) ) ) out = False for filt in itertools.pe...
DIR_DIM_START = 1 DIR_DIM_STOP = 202
def is_k_sparse(vec, k): """ checks if 95% of the weight of a normalized vector vec is in less than k of its entries. """ WEIGHT=0.95 # 95% n=len(vec) if k<0 or k>n: raise ValueError(" k has to be in 1 .. len(vec) ") # a filter with k entries set to 1 exfilt = numpy.concatenate( (numpy.ones(k), numpy.zeros(n-k) ...
out = numpy.zeros(n) for k in range(1,n+1): count=0 for sample in dsamples: if is_k_sparse(sample, k): count +=1 if k==1: out[0]=float(count) else: out[k-1]=float(count)-numpy.sum( out[0:k-1] ) outf = numpy.divide(out,N)
largelast = numpy.sort(dsamples,1) counts = numpy.zeros(n) for sample in largelast: k=1 val=sample[n-k] while val < WEIGHT: k+=1 val = val + sample[n-k] counts[k-1] +=1 outf = numpy.divide(counts,N)
def get_sparse_stats(dsamples): """ Takes the output of numpy.random.dirichlet and spits out the proportions of the samples that are k-sparse for k=1 ... n returns an array of counts of sparseness [ # 1-sparse, # 2-sparse, # 3-sprase, ..., # n-sparse ] note that we subtract from k-sparse all the k-1 sparse since we ...
def get_sparse_for_alpha(alpha, nrange=None, recomendalpha=False): """ let's see a plot of sparseness for different n as a funciton of \alpha """ N = 5000 if not nrange: nrange = numpy.arange(DIR_DIM_START, DIR_DIM_STOP,1, dtype=float) totaln = len(nrange) interesting = 70 results = [] for n in nrange: ...
def get_sparse_stats(dsamples): """ Takes the output of numpy.random.dirichlet and spits out the proportions of the samples that are k-sparse for k=1 ... n returns an array of counts of sparseness [ # 1-sparse, # 2-sparse, # 3-sprase, ..., # n-sparse ] note that we subtract from k-sparse all the k-1 sparse since we ...
def __init__(self, exampledir): self.name = None self.desc = None self.args = dict() self.argn = None self.flags = dict() self.params = dict() self.groups = dict() self.examples = dict() self.exampledir = exampledir def _extractName(self, dp):
def __init__(self, content): self.content = LineHolder(content) self.result = None self.apply_lite_formatter() def apply_lite_formatter(self): """ add space before title and NOTE/WARNING/... """ doclines = list() prev = "" for line in self.content.lines: if line.startswith(" if prev != "": doclines.append("") elif l...
def addAsciiDocLine(line, doclines): if line.startswith("# ==== ") or line.startswith("# === ") or line.startswith("# == ") or line.startswith("# ."): doclines.append("") doclines.append(line[2:]) return 1 #indent asciidoc bis elif line.startswith("# WARNING:") or line.startswith("# NOTE:") or line.startswith("# IMPORT...
match = nameregex.match(dp.preview_line())
commandregex = re.compile('\\\\(\S*?):(\S*)(.*)') match = commandregex.match(self.content.preview_line())
def _extractName(self, dp): """ extract a command with it's name and a description # \cmd:name description # extended description """ match = nameregex.match(dp.preview_line()) if match: dp.get_line() (name, value, desc) = match.groups(1) desc = [ desc.strip() ] desc.extend(self._extractBlock(dp)) return (nam...
dp.get_line() (name, value, desc) = match.groups(1)
self.content.get_line() (command, value, desc) = match.groups(1)
def _extractName(self, dp): """ extract a command with it's name and a description # \cmd:name description # extended description """ match = nameregex.match(dp.preview_line()) if match: dp.get_line() (name, value, desc) = match.groups(1) desc = [ desc.strip() ] desc.extend(self._extractBlock(dp)) return (nam...
desc.extend(self._extractBlock(dp)) return (name, value, desc)
desc.extend(self.extract_block()) return (command, value, desc)
def _extractName(self, dp): """ extract a command with it's name and a description # \cmd:name description # extended description """ match = nameregex.match(dp.preview_line()) if match: dp.get_line() (name, value, desc) = match.groups(1) desc = [ desc.strip() ] desc.extend(self._extractBlock(dp)) return (nam...
pass def _extractBlock(self, dp): """ extract a block will stop if the next line is not a comment or is a command """ doclines = list() line = dp.preview_line() while line.startswith(" if addAsciiDocLine(dp.preview_line(), doclines): dp.get_line() continue doclines.append(dp.get_line()[2:].strip()) line = dp.preview_l...
def extract_command(self): """ handle command """ ln = self.content.preview_line() (command, value, desc) = self.extract_command_name() if command == "example": self.result.extend(self.generate_example(value, desc))
def _extractName(self, dp): """ extract a command with it's name and a description # \cmd:name description # extended description """ match = nameregex.match(dp.preview_line()) if match: dp.get_line() (name, value, desc) = match.groups(1) desc = [ desc.strip() ] desc.extend(self._extractBlock(dp)) return (nam...
print "WARNING: unknown command:", dp.preview_line() dp.get_line() def extractFunctionName(self, dp): line = dp.get_line() name = funcregex.match(line) if name: name = name.groups(1)[0] self.name = name def extractDescription(self, dp): """ extract description """
print "WARNING unknow command:", command, value, desc def generate_example(self, value, desc): """ get an example """
def extractCommand(self, dp): """ extract doxygen like command """ ret = self._extractName(dp) if ret: #print "matched: %s - %s : %s" % (ret[0], ret[1], ret[2]) (name, value, desc) = ret if name == "arg": self.args[value] = (desc) elif name == "argn": self.argn = (value, desc) elif name == "flag": self.flags...
docline.append(dp.get_line()[3:].strip()) docline.extend(self._extractBlock(dp)) self.desc = docline def getDoc(self, sample): """ get an example """ p = os.path.join(self.exampledir, sample)
p = os.path.join(EXAMPLE_DIR, value)
def extractDescription(self, dp): """ extract description """ docline = list() #print "extract desc" docline.append(dp.get_line()[3:].strip()) docline.extend(self._extractBlock(dp)) self.desc = docline #print "description:", "\n".join(self.desc) #print ""
p = os.path.join(self.exampledir, sample, "CMakeLists.txt")
p = os.path.join(EXAMPLE_DIR, value, "CMakeLists.txt")
def getDoc(self, sample): """ get an example """ p = os.path.join(self.exampledir, sample) if not os.path.exists(p): p += ".cmake" if not os.path.isfile(p): p = os.path.join(self.exampledir, sample, "CMakeLists.txt") if os.path.exists(p): lines = list() try: with open(p, "r") as f: lines = f.readlines() except IOError:...
return lines return list() def generateFunction(self):
docline.append("") docline.append("=== Example: %s ===" % value) docline.append("[source,cmake,numbered]") docline.append("----") docline.extend(lines) docline.append("----") docline.append("") else: print "sample not found:", p return docline def generate(self): """ generate the asciidoc output for this block """ sel...
def getDoc(self, sample): """ get an example """ p = os.path.join(self.exampledir, sample) if not os.path.exists(p): p += ".cmake" if not os.path.isfile(p): p = os.path.join(self.exampledir, sample, "CMakeLists.txt") if os.path.exists(p): lines = list() try: with open(p, "r") as f: lines = f.readlines() except IOError:...
docline.extend(self.desc)
docline.extend(self.content.lines)
def generateFunction(self): """ generate documentation for a function """ docline = list() docline.append("== %s ==" % (self.name)) docline.append("=== Description ===") docline.extend(self.desc) docline.append("")
for k in self.args.keys():
for k in self.commands['arg'].keys():
def generateFunction(self): """ generate documentation for a function """ docline = list() docline.append("== %s ==" % (self.name)) docline.append("=== Description ===") docline.extend(self.desc) docline.append("")
if self.argn:
if self.commands.get('argn'):
def generateFunction(self): """ generate documentation for a function """ docline = list() docline.append("== %s ==" % (self.name)) docline.append("=== Description ===") docline.extend(self.desc) docline.append("")
for k in self.flags.keys():
for k in self.commands['flag'].keys():
def generateFunction(self): """ generate documentation for a function """ docline = list() docline.append("== %s ==" % (self.name)) docline.append("=== Description ===") docline.extend(self.desc) docline.append("")
for k in self.params.keys():
for k in self.commands['param'].keys():
def generateFunction(self): """ generate documentation for a function """ docline = list() docline.append("== %s ==" % (self.name)) docline.append("=== Description ===") docline.extend(self.desc) docline.append("")
for k in self.groups.keys():
for k in self.commands['group'].keys():
def generateFunction(self): """ generate documentation for a function """ docline = list() docline.append("== %s ==" % (self.name)) docline.append("=== Description ===") docline.extend(self.desc) docline.append("")
for (k, v) in self.args.iteritems():
for (k, v) in self.commands['arg'].iteritems():
def generateFunction(self): """ generate documentation for a function """ docline = list() docline.append("== %s ==" % (self.name)) docline.append("=== Description ===") docline.extend(self.desc) docline.append("")
if self.argn: docline.append(" * _<remaining args>_ .. : %s" % " ".join(self.argn[1])) for (k, v) in self.flags.iteritems():
if self.commands.get('argn'): docline.append(" * _<remaining args>_ .. : %s" % " ".join(self.commands['argn'].values()[0])) for (k, v) in self.commands['flag'].iteritems():
def generateFunction(self): """ generate documentation for a function """ docline = list() docline.append("== %s ==" % (self.name)) docline.append("=== Description ===") docline.extend(self.desc) docline.append("")
for (k, v) in self.params.iteritems():
for (k, v) in self.commands['param'].iteritems():
def generateFunction(self): """ generate documentation for a function """ docline = list() docline.append("== %s ==" % (self.name)) docline.append("=== Description ===") docline.extend(self.desc) docline.append("")
for (k, v) in self.groups.iteritems():
for (k, v) in self.commands['group'].iteritems():
def generateFunction(self): """ generate documentation for a function """ docline = list() docline.append("== %s ==" % (self.name)) docline.append("=== Description ===") docline.extend(self.desc) docline.append("")
def generate(self): docline = list() if self.name is None: docline.extend(self.desc) docline.append("") else: docline.extend(self.generateFunction()) for (k, v) in self.examples.iteritems(): docline.append("=== Example: %s ===" % k) docline.append("[source,cmake,numbered]") docline.append("----") docline.extend(sel...
class LineHolder: """ simple class to store and fetch lines """
def generate(self): #this is doc only, not a function... docline = list() if self.name is None: docline.extend(self.desc) docline.append("") else: #will generate function stuff only if a function is actually defined docline.extend(self.generateFunction())
def doc_process_command(dp, fc): doclines = [] line = dp.preview_line() if line.startswith(" fc.extractDescription(dp) elif line.startswith(" fc.extractCommand(dp) else: doclines.append(dp.get_line()) return doclines def doc_process(dp, exampledir): getdoc = 0 doclines = list() fc = DocBlock(exampledir) while dp....
class CMakeDocParser: """ Extract doc from a cmake like file This class strip """ def __init__(self, lines): self.dp = LineHolder(lines) self.blocks = list() self.current_block = list() def cleanup_line(self, line): """ remove comment from a line """ if line.startswith(" return line[2:].strip() elif line.startswith("...
def doc_process_command(dp, fc): doclines = [] line = dp.preview_line() if line.startswith("#!"): fc.extractDescription(dp) #indent asciidoc #elif addAsciiDocLine(line, doclines): # dp.get_line() #handle command elif line.startswith("# \\"): fc.extractCommand(dp) else: doclines.append(dp.get_line()) return doclines
dp = CmakeDocParser(lines) doclines = doc_process(dp, exampledir) docs = "\n".join(doclines)
dp = CMakeDocParser(lines) dp.parse_block() docs = list() for b in dp.blocks: docs.append(str(b))
def extract_doc_from_cmake(fname, exampledir): """ return a list with line of doc """ with open(fname, "r") as f: lines = f.readlines() dp = CmakeDocParser(lines) doclines = doc_process(dp, exampledir) #print doclines docs = "\n".join(doclines) return docs
def generate_doc(fname, exampledir, outdir):
def generate_doc(fname, outdir):
def generate_doc(fname, exampledir, outdir): """ generate a .txt based on a cmake file if the doc is not empty """ dest = os.path.join(outdir, os.path.basename(fname)) dest = dest.replace(".cmake", ".txt") docs = extract_doc_from_cmake(fname, exampledir) if len(docs) > 0: print "Generated:", dest with open(dest, "w") ...
docs = extract_doc_from_cmake(fname, exampledir)
docs = extract_doc_from_cmake(fname)
def generate_doc(fname, exampledir, outdir): """ generate a .txt based on a cmake file if the doc is not empty """ dest = os.path.join(outdir, os.path.basename(fname)) dest = dest.replace(".cmake", ".txt") docs = extract_doc_from_cmake(fname, exampledir) if len(docs) > 0: print "Generated:", dest with open(dest, "w") ...
f.write(l)
f.write(l + '\n')
def generate_doc(fname, exampledir, outdir): """ generate a .txt based on a cmake file if the doc is not empty """ dest = os.path.join(outdir, os.path.basename(fname)) dest = dest.replace(".cmake", ".txt") docs = extract_doc_from_cmake(fname, exampledir) if len(docs) > 0: print "Generated:", dest with open(dest, "w") ...
example = sys.argv[2]
EXAMPLE_DIR = sys.argv[2]
def usage(): print "usage:" print "generate_doc_from_cmake source_dir example_dir dest_dir" exit(2)
generate_doc(f, example, dest)
generate_doc(f, dest)
def usage(): print "usage:" print "generate_doc_from_cmake source_dir example_dir dest_dir" exit(2)
docline.append(" * remaining args: %s" % " ".join(self.argn[1]))
docline.append(" * _<remaining args>_ .. : %s" % " ".join(self.argn[1]))
def generate(self): #this is doc only, not a function... docline = list() if self.name is None: docline.extend(self.desc) docline.append("") return docline
print "loaded configuration:" print self.configstore
LOGGER.debug("[toc] configuration:") for line in str(self.configstore).split("\n"): if len(line) > 0: LOGGER.debug(line)
def _load_configuration(self): for name, project in self.buildable_projects.iteritems(): qibuild.configstore.read(os.path.join(project.directory, "qibuild.manifest"), self.configstore) qibuild.configstore.read(os.path.join(self.worktree, "config"), self.configstore) print "loaded configuration:" print self.configstore
doclines = list() for line in lines: stripped = line.strip() if not stripped.startswith("
dp = CmakeDocParser(lines) doclines = doc_process(dp) docs = "\n".join(doclines) return docs def generate_doc(fname, exampledir, outdir): """ generate a .txt based on a cmake file if the doc is not empty """ dest = os.path.join(outdir, os.path.basename(fname)) dest = dest.replace(".cmake", ".txt") docs = extract_d...
def extract_doc_from_cmake(fname): with open(fname, "r") as f: lines = f.readlines() doclines = list() for line in lines: stripped = line.strip() if not stripped.startswith("# "): continue line = line[2:] if line.startswith("."): doclines.append("\n") if line.startswith("== "): doclines.append("\n") if line.startswit...
line = line[2:] if line.startswith("."): doclines.append("\n") if line.startswith("== "): doclines.append("\n") if line.startswith("=== "): doclines.append("\n") if line.startswith("==== "): doclines.append("\n") doclines.append(line) print "".join(doclines) with open(fname + ".txt", "w") as f: for l in doclines: f.wr...
generate_doc(f, example, dest)
def extract_doc_from_cmake(fname): with open(fname, "r") as f: lines = f.readlines() doclines = list() for line in lines: stripped = line.strip() if not stripped.startswith("# "): continue line = line[2:] if line.startswith("."): doclines.append("\n") if line.startswith("== "): doclines.append("\n") if line.startswit...
games = [game for game in self.bot.lobby.list(self.bot.lobby.host)] if not games: write("%s: No games in lobby" % (nick))
l = ["\x02%s\x02 [%i/%i] (version: %s)" % (g.description, g.currentPlayers, g.maxPlayers, g.multiplayerVersion) for g in self.bot.lobby.list(self.bot.lobby.host)] if not l: message = 'No games in lobby' elif len(l) == 1: message = "1 game hosted: %s" % (l[0])
def list(self, nick, write): try: games = [game for game in self.bot.lobby.list(self.bot.lobby.host)] if not games: write("%s: No games in lobby" % (nick)) else: if len(games) == 1: message = "1 game hosted: " else: message = "%i games hosted: " % (len(games)) l = ["\x02%s\x02 [%i/%i]" % (g.description, g.currentPlayer...
if len(games) == 1: message = "1 game hosted: " else: message = "%i games hosted: " % (len(games)) l = ["\x02%s\x02 [%i/%i]" % (g.description, g.currentPlayers, g.maxPlayers) for g in games] message += ", ".join(l) write("%s: %s" % (nick, message))
message = "%i games hosted: %s" % (len(l), ", ".join(l)) write("%s: %s" % (nick, message))
def list(self, nick, write): try: games = [game for game in self.bot.lobby.list(self.bot.lobby.host)] if not games: write("%s: No games in lobby" % (nick)) else: if len(games) == 1: message = "1 game hosted: " else: message = "%i games hosted: " % (len(games)) l = ["\x02%s\x02 [%i/%i]" % (g.description, g.currentPlayer...
message = "New game: \x02%s\x02 (%i players)" % (g.description, g.maxPlayers)
message = "New game: \x02%s\x02 (%i players, version: %s)" % (g.description, g.maxPlayers, g.multiplayerVersion)
def run(self): self.stopChecking.clear() while not self.stopChecking.isSet(): try: new_games = [game for game in self.lobby.list(self.lobby.host)] except: new_games = [] if self.games == None: self.games = {} for g in new_games: self.games[g.host] = g else: new_game_dict = {} for g in new_games: if g.host in self.games...
protocol.sendStatusMessage(self.gameHost, status, message, self.wfile)
protocol.sendStatusMessage(self.gameHost, status, str(message), self.wfile)
def sendStatusMessage(self, status, message): logging.debug("(%s) Sending response status (%d) and message: %s" % (self.gameHost, status, message)) try: protocol.sendStatusMessage(self.gameHost, status, message, self.wfile) except NotImplementedError: # Ignore the case where sending of status messages isn't supported p...
logging.debug("(%s) Game with same ID already present, linking games...", (self.gameHost))
logging.debug("(%s) Game with same ID already present, linking games..." % self.gameHost)
def handle(self): global requests, requestlock, gamedb
if self.g.lobbyVersion == 3: self.sendStatusMessage(self.SUCCESS_OK, MOTDstring) else: self.sendStatusMessage(self.SUCCESS_OK, MOTD22string)
if self.g.lobbyVersion: if self.g.lobbyVersion == 3: self.sendStatusMessage(self.SUCCESS_OK, MOTDstring) else: self.sendStatusMessage(self.SUCCESS_OK, MOTD22string)
def handle(self): global requests, requestlock, gamedb
return
def handle(self): global requests, requestlock, gamedb
return "/antibody/%i/" % self.antibody.id
return "/experimentdb/antibody/%i/" % self.id
def get_absolute_url(self): return "/antibody/%i/" % self.antibody.id
projID=project.project_slug proj_subproject=SubProject.objects.filter(project__project_slug=projID) proj_experiment=Experiment.objects.filter(project__project_slug=projID) return render_to_response('project_detail.html', {'project': project, 'proj_subproject':proj_subproject, 'proj_experiment': proj_experiment},context...
return render_to_response('project_detail.html', {'project': project},context_instance=RequestContext(request))
def detail(request, project): project = get_object_or_404(Project, pk=project) projID=project.project_slug proj_subproject=SubProject.objects.filter(project__project_slug=projID) proj_experiment=Experiment.objects.filter(project__project_slug=projID) return render_to_response('project_detail.html', {'project': project,...
,}, name="primer-new"),
,}, name="primer-edit"),
def delete_primer(*args, **kwargs): return delete_object(*args, **kwargs)
return "/experimentdb/cell-line/%i/" % self.name
return "/experimentdb/cell-line/%i/" % self.id
def get_absolute_url(self): return "/experimentdb/cell-line/%i/" % self.name
funcs = LoadFunctionDefs('Engine\\C_Verb.h') OutputMarshallers(funcs, 'Engine\\C_VerbMarshallers.inc')
funcs = LoadFunctionDefs(sys.argv[1]) OutputMarshallers(funcs, sys.argv[2])
def OutputMarshallers(funcs, filename): f = open(filename, 'w') for func in funcs: (ret, name, args) = func f.write('if( !strcmp( node->lexData.stringVal, \"%s\" ) )\n' % name.lower()) f.write('{\n') num = 0 for arg in args: (type, param) = arg if type.endswith(('*', '&')): type = type[:-1] if type == 'Context': f.wri...
map_list = map_list or (models.MapRenderingJob.objects.filter(status=2) .filter(resultmsg="ok") .order_by('maptitle'))
if map_list is None: map_list = (models.MapRenderingJob.objects.filter(status=2) .filter(resultmsg="ok") .order_by('maptitle'))
def all_maps(request): """Displays all maps, sorted alphabetically, eventually matching the search terms, when provided.""" map_list = None if request.method == 'POST': form = forms.MapSearchForm(request.POST) if form.is_valid(): map_list = (models.MapRenderingJob.objects .order_by('maptitle') .filter(status=2) .filt...
<input type="text" name="lon_bottom_right" id="lat_bottom_right"
<input type="text" name="lat_bottom_right" id="lat_bottom_right"
def render(self, name, value, attrs=None): """ Render a map """ upper_left_lat, upper_left_lon = 0, 0 lower_right_lat, lower_right_lon = 0, 0
<input type="text" name="lat_bottom_right" id="lon_bottom_right"
<input type="text" name="lon_bottom_right" id="lon_bottom_right"
def render(self, name, value, attrs=None): """ Render a map """ upper_left_lat, upper_left_lon = 0, 0 lower_right_lat, lower_right_lon = 0, 0
def save_recording_in_database(filename, data, tracker):
def save_recording_in_database(filename, data, tracker, debug=False):
def save_recording_in_database(filename, data, tracker): # datastructure: # xml-file as Episode (category='ds*') with files from resource-tags # files from resource-tags as Episodes (category='file/ds*/:link') # with self and alternatives as files dsfiles = deepcopy(data['files']) for f in data['files']: f.pop('alte...
save_recording_in_database(filename, data, tracker)
save_recording_in_database(filename, data, tracker, debug)
def fill_database(files, debug=False, trackback=False): tracker = Trackbacker(trackback) for filename in files: category = get_category(filename) if not category or ("penta" not in category and "ds" not in category): print(style.red+"* errör can't categorize ", filename, " found:", category, style.default) continue # ...
return json.dumps({"html": html.body}) value = json.dumps({ "comments": list(map(comment_to_json,comments)),
value = json.dumps({"html": html.body}) else: value = json.dumps({ "comments": list(map(comment_to_json,comments)),
def template_comments(web, site, episode, comments, cmnt): if cmnt is None: cmnt = "" if len(cmnt): cmnt = cmnt[1:] comments, reply, author, hash, a, b, c = do_the_comments(web, comments, cmnt) if cmnt == "atom": return template("atom.tpl", title = "Pentamedia-Portal // {0} // Comments".format(episode.name), episode...
episodes = dict([(c, reversed(Episode.find().\ filter_by(category=c).\ order_by(Episode.date).\ limit(13).all())) for c in ['pentaradio','pentamusic','pentacast'] ])
episodes = {} for category in ['pentaradio','pentamusic','pentacast']: episode = list(reversed(Episode.find().\ filter_by(category=category).\ order_by(Episode.date).\ all() )) if len(episode) > 13: episode = episode[:13] episode.append({'name': "more …", 'link': ""}) episodes[category] = episode
def start(web): # FIXME wrap db queries into one episodes = dict([(c, reversed(Episode.find().\ filter_by(category=c).\ order_by(Episode.date).\ limit(13).all())) for c in ['pentaradio','pentamusic','pentacast'] ]) return template("start.html", episodes = episodes, css = "start" )
else: log = git("log --name-only --format=%n {1}..{2}".\
else: log = git("log --name-only --format=%n {0}..{1}".\
def main(): log = "" git_test = getoutput("git log --format=%n") if "fatal" in git_test or "--format" in git_test: print("ERROR: your git version is to old.") os.system("git --version") exit(1) if not os.path.exists("cweb.git"): print("* no c3d2-web git repository found") os.mkdir("cweb.git") git("init") git("remote ...
filename = "./pentamusic-0x001.xml" pprint(load_file(filename))
filebase = "../c3d2-web/content/news/" with open("pentafiles.txt", "r") as text: for line in text: raw = filebase + line filename = raw.rstrip() pprint(load_file(filename))
def test(): from pprint import pprint filename = "./pentamusic-0x001.xml" pprint(load_file(filename))
@post("/(?P<site>pentaradio|pentacast|pentamusic)/:id/comment/new") def new_comment(web, site, id):
@post("/(?P<site>pentaradio|pentacast|pentamusic)/:id/comment/new(?P<isjson>\.json)?") def new_comment(web, site, id, isjson):
def start(web): # FIXME wrap db queries into one episodes = {} for category in ['pentaradio','pentamusic','pentacast']: episode = list(reversed(Episode.find().\ filter_by(category=category).\ order_by(Episode.date).\ all() )) if len(episode) > 13: episode = episode[:13] episode.append({'name': "more …", 'link': ""}) ep...
return redirect("/{0}/{1}".format(site,id))
if isjson is None: isjson = "" else: isjson = ".json?html=1" return redirect("/{0}/{1}{2}".format(site,id,isjson))
def replyer(x): a = x.group()[1:] i = find(Comment.id).filter_by(author=a).order_by(Comment.date).all() if i: reply.append(i[-1][0]) return i and '@<a href="/{0}/{1}/reply?{2}#new">{3}</a>'.\ format(site, id, i[-1][0], a)\ or "@{0}".format(a)
parser.add_option("-a", "--all" ,dest="update_all", action="store_true", help = "update everthing again [default: %default]", default = False) parser.add_option("-d", "--debug", dest="debug", action="store_true", help = "show errors [default: %default]", default = False) parser.add_option("-t", "--no-trackback",dest="t...
parser.add_option("-a", "--all", dest="update_all", action="store_true", default = False, help = "update everthing again [default: %default]") parser.add_option("-d", "--debug", dest="debug", action="store_true", default = False, help = "show errors [default: %default]") parser.add_option("-t", "--no-trackback", dest="...
def main(update_all, debug, trackback): log = "" links_count, tb_count, skip_count, error_count, ign_count = 0, 0, 0, 0, 0 git_test = getoutput("git log --format=%n") if "fatal" in git_test or "--format" in git_test: print("ERROR: your git version is to old.") os.system("git --version") exit(1) if not os.path.exists(...
main(opts.update_all, opts.debug, opts.trackback)
main(opts.update_all, opts.debug, not opts.no_trackback)
def main(update_all, debug, trackback): log = "" links_count, tb_count, skip_count, error_count, ign_count = 0, 0, 0, 0, 0 git_test = getoutput("git log --format=%n") if "fatal" in git_test or "--format" in git_test: print("ERROR: your git version is to old.") os.system("git --version") exit(1) if not os.path.exists(...
fulllog, old = False, 0
fulllog, old = False, ""
def main(): log = "" git_test = getoutput("git log --format=%n") if "fatal" in git_test or "--format" in git_test: print("ERROR: your git version is to old.") os.system("git --version") exit(1) if not os.path.exists("cweb.git"): print("* no c3d2-web git repository found") os.mkdir("cweb.git") os.system(git+"init") os...
if web.input('reply') != -1: reply = web.input('reply')
if web.input('reply') != "-1": try: reply = int(web.input('reply')) except: pass
def replyer(x): a = x.group()[1:] i = find(Comment.id).filter_by(author=a).order_by(Comment.date).all() if i: reply.append(i[-1][0]) return i and '@<a href="/{0}/{1}/reply?{2}#new">{3}</a>'.\ format(site, id, i[-1][0], a)\ or "@{0}".format(a)
for comment in comments:
for comment in list(comments):
def episode(web, site, id, cmnt): try: # FIXME wrap db queries into one episode = Episode.find().filter_by(link = id).one() files = File.find().filter_by(episode = episode.id).all() comments = Comment.find().filter_by(episode = episode.id).\ order_by(Comment.date).all() except: return redirect("/{0}".format(site)) ...
@route("/datenspuren/(?P<id>.[^/]*)/(?P<filename>(.[^/](?!(atom|json)))*)(?P<mode>/(comment|rate|reply))?")
@route("/datenspuren/(?P<id>[^/]+)/(?P<filename>([^/](?!(atom|json)))+)(?P<mode>/(comment|rate|reply))?")
def main(web, site): # FIXME wrap db queries into one episodes = Episode.find().filter_by(category=site).\ order_by(Episode.date).all() episodes.reverse() comments_count = [ Comment.find().filter_by(episode = e.id).count() for e in episodes ] ratings = [ do_the_ratings(0, 0, Rating.find().\ filter_by(episode = e.id).al...
@route("/datenspuren/(?P<id>([^/](?!(atom|json)))*)(?P<mode>/(comment|rate|reply))?")
@route("/datenspuren/(?P<id>([^/](?!(atom|json)))+)(?P<mode>/(comment|rate|reply))?")
def datenspur_file(web, id, filename, mode): try: # FIXME wrap db queries into one episode = Episode.find().filter_by(link = filename).\ filter(Episode.category.endswith(id)).\ order_by(Episode.date).one() comments = Comment.find().filter_by(episode = episode.id).all() files = File.find().filter_by(episode = episode...
entries = entries
comments = entries
def feed_all_comments(web, mode): # FIXME wrap db queries into one episodes = Episode.find().all() comments = Comment.find().all() trackbacks = Trackback.find().all() if mode == "atom": entries = comments + trackbacks entries.sort(key=lambda e: e.date) entries.reverse() id_episodes = {} for episode in episodes: id_epis...
print("{0} Shownotes scaned. {4} ignored. " + \
print(("{0} Shownotes scaned. {4} ignored. " + \
def print_stats(self): if self.disabled: return print("{0} Shownotes scaned. {4} ignored. " + \ "{1} Trackback links discovered. " + \ "{2} skipped. {3} failed to use.".\ format(self.count.links, self.count.tb, self.count.skip,\ self.count.error, self.count.ign))