示例#1
0
    def _parse_metrics(self, message):
        """
        Given a raw message of metrics split by newline characters, this will
        parse the metrics and return an array of metric objects.

        This will raise a :exc:`ValueError` if any metrics are invalid, unless
        ``ignore_errors`` is set to True.
        """
        results = []
        for line in message.split("\n"):
            # If the line is blank, we ignore it
            if len(line) == 0: continue

            # Parse the line, and skip it if its invalid
            try:
                (key, value, metric_type, flag) = parser.parse_line(line)
            except ValueError:
                self.logger.error("Invalid line syntax: %s" % line)
                continue

            # Create the metric and store it in our results
            if metric_type in metrics.METRIC_TYPES:
                # Create and store the metric object
                metric = metrics.METRIC_TYPES[metric_type](key, value, flag)
                results.append(metric)
            else:
                # Ignore the bad invalid metric, but log it
                self.logger.error("Invalid metric '%s' in line: %s" % (metric_type, line))

        return results
示例#2
0
    def _parse_metrics(self, message):
        """
        Given a raw message of metrics split by newline characters, this will
        parse the metrics and return an array of metric objects.

        This will raise a :exc:`ValueError` if any metrics are invalid, unless
        ``ignore_errors`` is set to True.
        """
        results = []
        for line in message.split("\n"):
            # If the line is blank, we ignore it
            if len(line) == 0: continue

            # Parse the line, and skip it if its invalid
            try:
                (key, value, metric_type, flag) = parser.parse_line(line)
            except ValueError:
                self.logger.error("Invalid line syntax: %s" % line)
                continue

            # Create the metric and store it in our results
            if metric_type in metrics.METRIC_TYPES:
                # Create and store the metric object
                metric = metrics.METRIC_TYPES[metric_type](key, value, flag)
                results.append(metric)
            else:
                # Ignore the bad invalid metric, but log it
                self.logger.error("Invalid metric '%s' in line: %s" % (metric_type, line))

        return results
示例#3
0
    def check(cls, paths):
        '''Will check if there are keys available there, as in --path

        paths can be a string (one address), or a list of
        '''
        #TODO: more solid check: something like
        if type(paths) is not str:
            out = []
            for p in paths:
                try:
                    res = cls.check(p)
                except:
                    continue
                else:
                    if res:
                        out.extend(res)
            return out

        buf = NamedTemporaryFile()
        try:
            subprocess.check_call(
                [cls.undertakerexec, paths, '--batch', '--path'], stderr=buf)
        except subprocess.CalledProcessError as exc:
            return False

        out = []
        buf.seek(0)
        for line in buf:
            ret = parser.parse_line(line)
            if ret and ret['type'] == 'found':
                out.append(ret['content'])
        return out
示例#4
0
    def check(cls, paths):
        '''Will check if there are keys available there, as in --path

        paths can be a string (one address), or a list of
        '''
        #TODO: more solid check: something like
        if type(paths) is not str:
            out = []
            for p in paths:
                try:
                    res = cls.check(p)
                except:
                    continue
                else:
                    if res:
                        out.extend(res)
            return out

        buf = NamedTemporaryFile()
        try:
            subprocess.check_call([cls.undertakerexec, paths, '--batch',
                '--path'], stderr=buf)
        except subprocess.CalledProcessError as exc:
            return False

        out = []
        buf.seek(0)
        for line in buf:
            ret = parser.parse_line(line)
            if ret and ret['type'] == 'found':
                out.append(ret['content'])
        return out
示例#5
0
def command():
    content = request.get_json(silent=True)
    game_id = content.get('game_id')
    team_id = content.get('team_id')
    line = content.get('line')

    result = parse_line(game_id, team_id, line, parser_cursor)
    cnx.commit()
    return result
示例#6
0
文件: evaluator.py 项目: heptonion/QN
def repl():

    from sys import exit, stdout

    def prompt():
        print("\x1B[2mdq>\x1B[22m ", end='')
        line = input()
        if line in ['exit', 'quit']:
            exit()
        return line + "\n"

    stream = TokenStream("", prompt)

    try:
        while True:
            tree = parse_line(stream)

            if tree is None:
                continue

            if isinstance(tree, ParseError):
                tree.display(stream.log)
                continue

            if isinstance(tree, ParseTree) and tree.kind == 'assignment':
                name = tree.children[0].val
                q = makeQueue(tree.children[1])
                GLOBALS[name] = q

            elif isinstance(tree, ParseTree) and tree.kind == 'output':
                cmd = tree.children[0].val
                q = makeQueue(tree.children[1])
                if cmd == 'print':
                    smartPrint(q, stdout)
                elif cmd == 'printNum':
                    printNum(q, stdout)
                elif cmd == 'printStr':
                    printStr(q, stdout)
                elif cmd == 'printRepr':
                    printRepr(q, stdout)
                else:
                    raise Exception("this should never happen")

            else:
                q = makeQueue(tree)
                fq = Take(q, 1024 * 1024)
                smartPrint(fq, stdout)
                if fq.halted:
                    print("\x1B[93mwarning\x1B[39m: output truncated")

    except KeyboardInterrupt:
        print("\b\b")

    except EOFError:
        print('exit')
示例#7
0
def run_controller(circuit, instruction: str, flags=""):
    parsed, _ = parser.parse_line(instruction)
    print(instruction, parsed)
    clock = circuit_module.Clock()
    with scope("IR"):
        ir = bus()
    with scope("FLAGS"):
        flags_in = Lines("CAEZ")
    with scope("STEPPER"):
        stepper = bus(6)
    inputs = clock.clk >> clock.clk_s >> clock.clk_e >> ir >> flags_in >> stepper
    output = inputs >> circuit_module.controller
    simulation = {}
    es = tag_outputs(circuit, ["CONTROL", "ENABLER"])
    ss = tag_outputs(circuit, ["CONTROL", "SELECTOR"])
    rounds = []
    for step in range(6):
        e_found = set()
        s_found = set()
        for clock_round in range(4):
            f = clock.step()
            f.update({stepper[j]: int(j == step) for j in range(6)})
            f.update({ir[j]: k for j, k in enumerate(parsed)})
            f.update(
                {flags_in[j]: int(letter in flags) for j, letter in enumerate("CAEZ")}
            )
            simulation.update(simulate(f, circuit, simulation))
            new_es = set(e for e in es if simulation[e])
            new_ss = set(s for s in ss if simulation[s])
            if clock_round == 3:
                assert (
                    len(
                        [
                            line
                            for line in new_es
                            if line not in Lines(new_es).typed(("E", "B1"))
                            and line not in Lines(new_es).typed(("ALU", "OP"))
                        ]
                    )
                    == 0
                )
            if clock_round != 1:
                assert len(new_ss) == 0
            e_found.update(new_es)
            s_found.update(new_ss)
        rounds.append({"e": Lines(e_found), "s": Lines(s_found)})
    return rounds
示例#8
0
	def on_input (self, reactor):
		"""	Yield incoming `Message` objects """
		super(IRCClient, self).on_input()
		while self.buffer:
			line = self.buffer.pop(0)

			# Skip the line if it is a PING
			if line.startswith('PING :'):
				self.socket.send("PONG :" + line[6:] + "\r\n")
				break
			
			# Handler disconnections
			if line.startswith('ERROR :'):
				reactor.disconnect(self)
				break
			
			yield self.parse(handler=self, **parse_line(line))
示例#9
0
def test_parser():
    tests = [("NOP", Instr("NOP", Operand(IMPL, None))),
             ("ADC #16", Instr("ADC", Operand(IMM, 16))),
             ("ADC $FF", Instr("ADC", Operand(ZP_ABS, 255))),
             ("ADC 16, X", Instr("ADC", Operand(ABS_X, 16))),
             ("ADC ($100)", Instr("ADC", Operand(INDIR, 256))),
             ("ADC (120)", Instr("ADC", Operand(ZP_INDIR, 120))),
             ("ADC (120, X)", Instr("ADC", Operand(INDEXED_INDIR_X, 120))),
             ("ADC (120), X", Instr("ADC", Operand(INDIR_INDEXED_X, 120))),]

    succeeded = 0
    failed = 0
    
    for i in range(len(tests)):
        test = tests[i]
        result = parser.parse_line(test[0], i)[0]
        if result == test[1]:
            succeeded += 1
        else:
            print("Failed: " + test[0] + " => " + str(result) + "( expected " + str(test[1]) + " )")
            failed += 1

    print(str(succeeded) + " succeeded, " + str(failed) + " failed")
示例#10
0
 def test_parse_line_begin_freq(self):
     actual = parser.parse_line(freq)
     expected = ('core', 'blockchain', parser.parse_parameters(parameters),
                 480000, freq_measure)
     self.assertEqual(actual, expected)
示例#11
0
 def test_parse_line_begin_stats(self):
     actual = parser.parse_line(stats)
     expected = ('topology', 'messages-ping',
                 parser.parse_parameters(parameters), 1080000,
                 stats_measure)
     self.assertEqual(actual, expected)
示例#12
0
This file is part of NecroDancer Stat Tracker.

NecroDancer Stat Tracker 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.

NecroDancer Stat Tracker 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 NecroDancer Stat Tracker.  If not, see <http://www.gnu.org/licenses/>.
"""


import config
config.open_()  # Open config file so logctl doesn't error
import logctl
import parser
import runctl


run = runctl.Run()
log = logctl.open_latest()
while True:
    current_line = logctl.readline(log)
    parser.parse_line(current_line, run)