Exemplo n.º 1
0
    def perform(self):
        try:
            empty = {"received": "none"}

            self.sock.connect(('ote.nic.io', 700))
            self.sock.recv().decode("latin1")
            self.command = Command(self.init['domain'], self.init['action'],
                                   self.sock)
            self.command.login()

            perform = {
                'create': self.command.createDomain,
                'backorder': self.command.backorder,
            }

            if self.init['action'] in perform:
                empty = perform[self.init['action']]()

            print "Empty"
            print empty

            yield json.dumps(empty)

        finally:
            self.sock.close()
Exemplo n.º 2
0
 def __init__(self):
     Command.__init__(self)
     parser = self._get_args_parser()
     parser.add_argument('--refs-dir',
                         action = 'store', dest = 'refs_dir', default = os.path.join(tempfile.gettempdir(), 'refs'),
                         help = 'Directory containing the references')
     parser.add_argument('-o', '--out-dir',
                         action = 'store', dest = 'out_dir', default = os.path.join(tempfile.gettempdir(), 'out'),
                         help = 'Directory containing the results')
     parser.add_argument('--src-dir',
                         action = 'store', dest = 'src_dir', default = os.path.abspath("../"),
                         help = 'Directory of poppler sources')
     parser.add_argument('--builder',
                         action = 'store', dest = 'builder',
                         choices=['autotools'], default = 'autotools',
                         help = 'Build system to use')
     parser.add_argument('--prefix',
                         action = 'store', dest = 'prefix', default = '/usr/local',
                         help = 'Build prefix')
     parser.add_argument('--good',
                         action = 'store', dest = 'good', metavar = 'REVISION',
                         help = 'Good revision')
     parser.add_argument('--bad',
                         action = 'store', dest = 'bad', default = 'HEAD', metavar = 'REVISION',
                         help = 'Bad revision')
     parser.add_argument('test')
Exemplo n.º 3
0
 def __init__(self):
     Command.__init__(self)
     parser = self._get_args_parser()
     parser.add_argument(
         '--refs-dir',
         action='store',
         dest='refs_dir',
         default=os.path.join(tempfile.gettempdir(), 'refs'),
         help='Directory where the references will be created')
     parser.add_argument(
         '-f',
         '--force',
         action='store_true',
         dest='force',
         default=False,
         help=
         'Create references again for tests that already have references')
     parser.add_argument(
         '-c',
         '--checksums-only',
         action='store_true',
         dest='checksums_only',
         default=False,
         help=
         'Leave only checksum files in references dir, other files will be deleted'
     )
     parser.add_argument('tests')
Exemplo n.º 4
0
def handleCommand(command):
  """Process an incoming command from the redis pubsub command queue.
  
  Parameters:
  command - standard command packet structure
  """
  try:
    print(f'Processing {command}')

    # Send command and its options to the command class in commands.py
    c = Command(command['command'], command['options'])

    # Run corresponding handle command function
    out = c.handleCommand()
    print(out)

    # Send result of the command to redis key value store
    r.set(out['key'], out['result'])

    # Send result of command over redis pubsub
    r.publish('data', json.dumps(out))
  except json.JSONDecodeError as error:
    print(error.msg)
  except redis.exceptions.TimeoutError:
    print('Redis connection timed out')
  except redis.exceptions.ConnectionError:
    print('Could not establish Redis connection')
  except Exception as e:
    print(e)
Exemplo n.º 5
0
 def __init__(self, gitify):
     Command.__init__(self, gitify)
     self.parser = optparse.OptionParser(
         usage="%prog help [<command>]",
         description="Show help on the given command or about the whole "
         "script if none given.",
         add_help_option=False)
Exemplo n.º 6
0
 def __init__(self, gitify):
     Command.__init__(self, gitify)
     self.parser = optparse.OptionParser(
         usage="%prog help [<command>]",
         description="Show help on the given command or about the whole "
             "script if none given.",
         add_help_option=False)
Exemplo n.º 7
0
    def __init__(self, *args, **kwargs):
        Command.__init__(self, *args, **kwargs)

        if not self.args:
            return self.message(self.syntax, self.user)

        query = ' '.join(self.args)
        url = "http://en.wikipedia.org/w/api.php?format=json&action=query&%s&prop=revisions&rvprop=content" % urllib.urlencode(
            {'titles': query})
        results = json.loads(urllib.urlopen(url).read())['query']

        if not results.get('pages', False): return
        page = results['pages'].popitem()[1]
        title = page['title']

        if not page.get('pageid', False):
            return self.message("No Wikipedia page for \"%s\"" % query,
                                self.user)

        url = "http://en.wikipedia.org/w/api.php?action=query&prop=info&pageids=%s&inprop=url&format=xml" % page[
            'pageid']
        xml = ElementTree.fromstring(urllib.urlopen(url).read())
        url = xml.findall(".//page[1]")[0].get('fullurl')

        # TODO: return first paragraph

        self.message("%s (%s)" % (title, url), self.user)
Exemplo n.º 8
0
def test_vote(poll):
    """ Test the vote command """
    user_msg = create_user_msg()
    for vote in {"!v", "!vote"}:
        # Test invalid vote command
        _, msg = Command(user_msg).commands[vote]()
        assert "Please format your vote as" in msg

        # Test poll not found
        _, msg = Command(user_msg).commands[vote]("fake-id", 3)
        assert "Poll fake-id does not exist or has expired" in msg

        # Test invalid poll prints out exception message instead of letting exception bubble up
        with mock.patch("poll.Poll.load") as m_load:
            m_load.side_effect = ValueError("mock value error")
            _, msg = Command(user_msg).commands[vote]("fake-id", 3)
            assert "mock value error" in msg

        # Test invalid vote choice
        _, msg = Command(user_msg).commands[vote](poll.poll_id, 420)
        assert "420 is not an available selection" in msg

        # Test valid vote choice
        _, msg = Command(user_msg).commands[vote](poll.poll_id, "2")
        assert "You have selected" in msg
Exemplo n.º 9
0
 def __init__(self):
     Command.__init__(self)
     parser = self._get_args_parser()
     parser.add_argument('--refs-dir',
                         action='store',
                         dest='refs_dir',
                         default=os.path.join(tempfile.gettempdir(),
                                              'refs'),
                         help='Directory containing the references')
     parser.add_argument(
         '-o',
         '--out-dir',
         action='store',
         dest='out_dir',
         default=os.path.join(tempfile.gettempdir(), 'out'),
         help='Directory where test results will be created')
     parser.add_argument(
         '--keep-results',
         action='store_true',
         dest='keep_results',
         default=False,
         help='Do not remove result files for passing tests')
     parser.add_argument('--create-diffs',
                         action='store_true',
                         dest='create_diffs',
                         default=False,
                         help='Create diff files for failed tests')
     parser.add_argument('--update-refs',
                         action='store_true',
                         dest='update_refs',
                         default=False,
                         help='Update references for failed tests')
     parser.add_argument('tests')
Exemplo n.º 10
0
    def run(self):
        Command.init(self.State)
        while True:
            try:
                x = input()
                if x == '':
                    x = ['']
                else:
                    x = x.split()

                if x[0] in self.CommandsDict.keys():
                    execution_code = self.CommandsDict[x[0]].execute(x)

                    if execution_code == CommandExecutionCode.REQUEST_FINISH:
                        break
                    elif execution_code == CommandExecutionCode.WORD_KNOWN:
                        pass
                    elif execution_code == CommandExecutionCode.WORD_UNKNOWN:
                        pass
                    elif execution_code == CommandExecutionCode.NO_ANSWER:
                        pass
                    elif execution_code == CommandExecutionCode.COMMAND_NOT_IMPLEMENTED:
                        print('{name}: Command not implemented.'.format(
                            name=self.CommandsDict[x].names[0]))
                else:
                    print('Error: no such command.')
            except ValueError as e:
                print('Error: {error}.'.format(error=e))
Exemplo n.º 11
0
 def __init__(self):
     Command.__init__(self)
     parser = self._get_args_parser()
     parser.add_argument('--refs-dir',
                         action='store',
                         dest='refs_dir',
                         default=os.path.join(tempfile.gettempdir(),
                                              'refs'),
                         help='Directory containing the references')
     parser.add_argument('-o',
                         '--out-dir',
                         action='store',
                         dest='out_dir',
                         default=os.path.join(tempfile.gettempdir(), 'out'),
                         help='Directory containing the results')
     parser.add_argument('-p',
                         '--pretty-diff',
                         action='store_true',
                         dest='pretty_diff',
                         default=False,
                         help='Include pretty diff output')
     parser.add_argument(
         '-n',
         '--no-browser',
         action='store_false',
         dest='launch_browser',
         default=True,
         help='Do not launch a web browser with the results')
     parser.add_argument('tests')
Exemplo n.º 12
0
def test_run_c_negative_count(capsys):
    """ Test should command with option --c COUNT, when COUNT < 0 and failed + capture its output and compare it to
                the expected output"""
    command = Command("cd ./home -c -4")
    command.exe()
    out, err = capsys.readouterr()
    expected_output = "-c should have a zero or positive number after\n"
    assert expected_output == out
Exemplo n.º 13
0
 def configure(self):
     """Set initial machine variables that won't need to be modified during
     runtime"""
     connect_command = Command(self.instructions['connect'])
     scale_commands = [Command(c) for c in self.machine['scale'].values()]
     invert_commands = [Command(c) for c in self.machine['invert'].values()]
     self.ser_info.enqueue(connect_command)
     self.ser_info.enqueue(scale_commands)
     self.ser_info.enqueue(invert_commands)
Exemplo n.º 14
0
    def send(self, message, payload=None):
        """Formats message and payload into packet and sends it to device.

        Args:
            command: Command to send.
            payload: Additional payload to send in packet.
        """
        cmd = Command(message, payload)
        rospy.logdebug("Sending %s: %s", Message.to_string(message), payload)
        self.conn.write(cmd.serialize())
Exemplo n.º 15
0
    def send(self, message, payload=None):
        """Formats message and payload into packet and sends it to device.

        Args:
            command: Command to send.
            payload: Additional payload to send in packet.
        """
        cmd = Command(message, payload)
        rospy.logdebug("Sending %s: %s", Message.to_string(message), payload)
        self.conn.write(cmd.serialize())
Exemplo n.º 16
0
 def __init__(self, gitify):
     Command.__init__(self, gitify)
     self.parser = optparse.OptionParser(
         usage = "%prog",
         description = """
         """,
         add_help_option=False)
     self.parser.add_option("-v", "--verbose", dest="verbose",
         action="store_true", default=False,
         help="""Show git-svn output.""")
Exemplo n.º 17
0
    def __init__(self, *args, **kwargs):
        Command.__init__(self, *args, **kwargs)

        if len(self.args) < 2:
            return self.message(self.syntax, self.user)

        user = self.args.pop(0)
        command = self.args.pop(0)

        self.client.parseChannelMessage(
            user, self.channel, '!%s %s' % (command, ' '.join(self.args)))
Exemplo n.º 18
0
 def test_subn(self):
     self.interpreter.V[1].value = 100
     Command.SubN(self.interpreter)\
         .execute_command(self.interpreter.V[1], 130)
     self.assertEqual(30, self.interpreter.V[1].value)
     self.assertEqual(1, self.interpreter.V[0xf].value)
     self.interpreter.V[1].value = 10
     Command.SubN(self.interpreter)\
         .execute_command(self.interpreter.V[1], 9)
     self.assertEqual(0xff, self.interpreter.V[1].value)
     self.assertEqual(0, self.interpreter.V[0xf].value)
Exemplo n.º 19
0
 def test_wait_pushing(self):
     self.interpreter.instruction_pointer = 4
     self.controller.return_value = None
     Command.WaitPushing(self.interpreter)\
         .execute_command(self.interpreter.V[1])
     self.assertEqual(2, self.interpreter.instruction_pointer)
     self.controller.return_value = 15
     Command.WaitPushing(self.interpreter)\
         .execute_command(self.interpreter.V[1])
     self.assertEqual(2, self.interpreter.instruction_pointer)
     self.assertEqual(15, self.interpreter.V[1].value)
Exemplo n.º 20
0
 def test_add(self):
     self.interpreter.V[1].value = 10
     Command.Add(self.interpreter)\
         .execute_command(self.interpreter.V[1], 20)
     self.assertEqual(30, self.interpreter.V[1].value)
     self.assertEqual(0, self.interpreter.V[0xf].value)
     self.interpreter.V[0].value = 255
     Command.Add(self.interpreter)\
         .execute_command(self.interpreter.V[0], 1)
     self.assertEqual(0, self.interpreter.V[0].value)
     self.assertEqual(1, self.interpreter.V[0xf].value)
Exemplo n.º 21
0
 def test_sub(self):
     self.interpreter.V[0].value = 100
     Command.Sub(self.interpreter)\
         .execute_command(self.interpreter.V[0], 30)
     self.assertEqual(70, self.interpreter.V[0].value)
     self.assertEqual(1, self.interpreter.V[0xf].value)
     self.interpreter.V[1].value = 10
     Command.Sub(self.interpreter)\
         .execute_command(self.interpreter.V[1], 11)
     self.assertEqual(0xff, self.interpreter.V[1].value)
     self.assertEqual(0, self.interpreter.V[0xf].value)
Exemplo n.º 22
0
def test_commands_delegation():
    cmd_out = Command(None, 'send', test_room, 'testing', test_owner)
    answer = ReplyObject('testing', True, True)
    assert cmd_out == answer, "delegation to modules doesn't work"

    cmd_out = Command(None, 'machine', test_room, '', test_user)
    answer = ReplyObject('I am the machine!', True)
    assert cmd_out == answer, "delegation to modules doesn't work"

    cmd_out = Command(None, 'secret', test_room, '', test_owner)
    answer = ReplyObject('This is a secret command!', True)
    assert cmd_out == answer, "delegation to secret commands doesn't work"
Exemplo n.º 23
0
    def test_shift_left(self):
        self.interpreter.V[0].value = 4
        Command.ShiftLeft(self.interpreter)\
            .execute_command(self.interpreter.V[0], None)
        self.assertEqual(8, self.interpreter.V[0].value)
        self.assertEqual(0, self.interpreter.V[0xf].value)

        self.interpreter.V[1].value = 128
        Command.ShiftLeft(self.interpreter)\
            .execute_command(self.interpreter.V[1], None)
        self.assertEqual(0, self.interpreter.V[1].value)
        self.assertEqual(1, self.interpreter.V[0xf].value)
Exemplo n.º 24
0
    def test_shift_right(self):
        self.interpreter.V[0].value = 2
        Command.ShiftRight(self.interpreter)\
            .execute_command(self.interpreter.V[0], None)
        self.assertEqual(1, self.interpreter.V[0].value)
        self.assertEqual(0, self.interpreter.V[0xf].value)

        self.interpreter.V[1].value = 15
        Command.ShiftRight(self.interpreter)\
            .execute_command(self.interpreter.V[1], None)
        self.assertEqual(7, self.interpreter.V[1].value)
        self.assertEqual(1, self.interpreter.V[0xf].value)
Exemplo n.º 25
0
    class __MyShell:
        def __init__(self):
            """The constructor for __MyShell.
                    :field com: The Command object, init to None."""
            self.com = None

        def run_command(self, cmd_line):
            """ Get the user input and create + execute the command and prints a summary"""
            self.com = Command(cmd_line=cmd_line)
            self.com.exe()
            self.com.print_return_codes()
            self.com = None
Exemplo n.º 26
0
 def __init__(self):
     Command.__init__(self)
     parser = self._get_args_parser()
     parser.add_argument('--refs-dir',
                         action = 'store', dest = 'refs_dir', default = os.path.join(tempfile.gettempdir(), 'refs'),
                         help = 'Directory containing the references')
     parser.add_argument('-o', '--out-dir',
                         action = 'store', dest = 'out_dir', default = os.path.join(tempfile.gettempdir(), 'out'),
                         help = 'Directory containing the results')
     parser.add_argument('-p', '--pretty-diff',
                         action = 'store_true', dest = 'pretty_diff', default = False,
                         help = 'Include pretty diff output')
     parser.add_argument('tests')
Exemplo n.º 27
0
 def __init__(self):
     Command.__init__(self)
     parser = self._get_args_parser()
     parser.add_argument('--refs-dir',
                         action = 'store', dest = 'refs_dir', default = os.path.join(tempfile.gettempdir(), 'refs'),
                         help = 'Directory where the references will be created')
     parser.add_argument('-f', '--force',
                         action = 'store_true', dest = 'force', default = False,
                         help = 'Create references again for tests that already have references')
     parser.add_argument('-c', '--checksums-only',
                         action = 'store_true', dest = 'checksums_only', default = False,
                         help = 'Leave only checksum files in references dir, other files will be deleted')
     parser.add_argument('tests')
Exemplo n.º 28
0
 def __init__(self, gitify):
     Command.__init__(self, gitify)
     self.version = pkg_resources.get_distribution(
         "git-svn-helpers").version
     self.parser = optparse.OptionParser(usage="%prog",
                                         version="%prog " + self.version,
                                         description="""
         """,
                                         add_help_option=False)
     self.parser.add_option("-v",
                            "--verbose",
                            dest="verbose",
                            action="store_true",
                            default=False,
                            help="""Show git-svn output.""")
Exemplo n.º 29
0
def analyze(path: Path):
    global current_file_path
    current_file_path = path

    with open(path) as file:
        current_command = None

        def start_command(command):
            nonlocal current_command
            if current_command is not None: current_command.do()
            if command.multiline:
                current_command = command
            else:
                command.do()
                current_command = None

        for i, line in enumerate(file.readlines()):
            if len(line) > 0 and line.startswith("!"):
                action, args, body = re.match(command_pattern, line).groups()
                try:
                    start_command(
                        Command.create(action, args, body, start_index=i))
                except ValueError:
                    pass
                else:
                    continue
            if current_command is not None:
                current_command += line

        if current_command: current_command.do()
        from cards import current_card
        if current_card: current_card.close(i)
Exemplo n.º 30
0
def execute_command(command: Command, cache: Cache) -> Union[str, bytes]:
    args = command.args
    result: Union[str, bytes] = _NOT_EXECUTED
    if isinstance(command, CommandSet):
        if cache.set_item(args[0], command.get_bytes_attachment(),
                          int(args[1])):
            result = _SUCCESS
        else:
            result = _FAILURE
    elif isinstance(command, CommandGet):
        item = cache.get_item(args[0])
        if item is None:
            result = _NOT_FOUND
        else:
            result = str(len(item)).encode() + SEPARATOR_BINARY + item
    elif isinstance(command, CommandDelete):
        if cache.delete_item(args[0]):
            result = _SUCCESS
        else:
            result = _FAILURE

    if isinstance(result, str):
        result += SEPARATOR
    else:
        result += SEPARATOR_BINARY
    return result
Exemplo n.º 31
0
def test_waifu(m_request):
    """ Test the waifu command """
    user_msg = create_user_msg()
    for cmd in {"!w", "!waifu"}:
        # Test non-200 status code
        # We don't care about content since it's mocked. Just reuse the youtube one
        m_request.return_value = create_mock_response(500, kind="youtube")
        _, msg = Command(user_msg).commands[cmd]()
        assert "I coudn't get that waifu" in msg

        # Test 200 status code
        # We don't care about content since it's mocked. Just reuse the youtube one
        m_request.return_value = create_mock_response(200, kind="youtube")
        kind, msg = Command(user_msg).commands[cmd]()
        assert kind == "file"
        assert msg == "temp.jpg"
Exemplo n.º 32
0
def test_nut():
    """ Test the nut command """
    user_msg = create_user_msg()
    for cmd in {"!n", "!nut"}:
        _, msg = Command(user_msg).commands[cmd]()
        assert "Remember" in msg
        assert ", don't " in msg
Exemplo n.º 33
0
 def __init__(self):
     Command.__init__(self)
     parser = self._get_args_parser()
     parser.add_argument('--refs-dir',
                         action = 'store', dest = 'refs_dir', default = os.path.join(tempfile.gettempdir(), 'refs'),
                         help = 'Directory containing the references')
     parser.add_argument('-o', '--out-dir',
                         action = 'store', dest = 'out_dir', default = os.path.join(tempfile.gettempdir(), 'out'),
                         help = 'Directory where test results will be created')
     parser.add_argument('--keep-results',
                         action = 'store_true', dest = 'keep_results', default = False,
                         help = 'Do not remove result files for passing tests')
     parser.add_argument('--create-diffs',
                         action = 'store_true', dest = 'create_diffs', default = False,
                         help = 'Create diff files for failed tests')
     parser.add_argument('tests')
Exemplo n.º 34
0
async def on_message(msg):
    """ Main Message Event Handler """
    # Only do something if command starts with ! or bot is not sending message
    if msg.author != CLIENT.user and msg.content.startswith("!"):
        LOGGER.log(f"Got {msg.content} from {msg.author} in {msg.channel}")

        args = msg.content.split(" ")
        cmd = args.pop(0)
        bot_cmd = Command(msg)

        if cmd not in bot_cmd.commands:
            await msg.channel.send(
                f"```Hello. I'm sorry I don't understand {cmd}. Please type "
                '"!help" to see a list of available commands\n```'
            )
            return

        try:
            type_, resp = bot_cmd.commands[cmd](*args)

            if type_ == "text":
                await msg.channel.send(resp)
            elif type_ == "file":
                await msg.channel.send(file=discord.File(resp))
            elif type_ == "list":
                for item in resp:
                    await msg.channel.send(item)
            elif type_ == "user":
                await msg.author.send(resp)

        except Exception as error:  #  pylint: disable=broad-except
            error_msg = f"Unexpected error with id: {uuid.uuid4()}"
            print(f"{error_msg} {error}", flush=True)
            traceback.print_exc()
            await msg.channel.send(f"```{error_msg} :(```")
Exemplo n.º 35
0
def insert(_name):
    connection = None
    _id = None

    try:
        params = config()
        connection = psycopg2.connect(**params)
        cursor = connection.cursor()

        cursor.execute(Command.insert(), (_name, ))

        _id = cursor.fetchone()[0]

        connection.commit()

        connection.close()

    except (Exception, psycopg2.DatabaseError) as error:
        print(error)

    finally:
        if connection is not None:
            connection.close()

    return _id
Exemplo n.º 36
0
def delete(_id):
    connection = None
    rows_deleted = 0

    try:
        params = config()
        connection = psycopg2.connect(**params)
        cursor = connection.cursor()

        cursor.execute(Command.delete(), (_id, ))

        rows_deleted = cursor.rowcount

        connection.commit()

        cursor.close()

    except (Exception, psycopg2.DatabaseError) as error:
        print(error)

    finally:
        if connection is not None:
            connection.close()

    return rows_deleted
Exemplo n.º 37
0
def test_run_help(capsys):
    """ Test should check that the option --help works correctly + capture its output and compare it to
                the expected output"""
    command = Command("cd ./home --help")
    command.exe()
    out, err = capsys.readouterr()
    assert "usage: [COMMAND] [OPTION]" in out
    assert "Options:" in out
    assert "-c [count]" in out
    assert "--failed-count [N]" in out
    assert "--sys-trace" in out
    assert "--call-trace" in out
    assert "--log-trace" in out
    assert "--debug" in out
    assert "--help" in out
    assert "Exit status:" in out
Exemplo n.º 38
0
    def __init__(self, *args, **kwargs):
        Command.__init__(self, *args, **kwargs)

        if not self.args:
            return self.message(self.syntax, self.user)
        
        query = ' '.join(self.args)
        url = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&%s" % urllib.urlencode({'q': query})
        results = json.loads(urllib.urlopen(url).read())['responseData']['results']

        if not results:
            return self.message("No Google results for \"%s\"" % query, self.user)
        
        result = results[0]
        title = HTMLParser().unescape(result['titleNoFormatting'])[:-4].strip()
        url = result['unescapedUrl'].rstrip('/')
        self.message("%s (%s)" % (title, url), self.user)
Exemplo n.º 39
0
    def __init__(self, *args, **kwargs):
        Command.__init__(self, *args, **kwargs)

        if not self.args:
            return self.message(self.syntax, self.user)            
        
        query = service.YouTubeVideoQuery()
        query.vq = ' '.join(self.args)
        feed = service.YouTubeService().YouTubeQuery(query)

        if not feed.entry:
            return self.message("No YouTube results for \"%s\"" % query.vq, self.user)

        video = feed.entry[0].media
        title = video.title.text
        duration = datetime.timedelta(seconds=int(video.duration.seconds))
        url = video.player.url.split('&')[0]
        self.message("%s [%s] (%s)" % (title, duration, url), self.user)
Exemplo n.º 40
0
 def __init__(self):
     Command.__init__(self)
     parser = self._get_args_parser()
     parser.add_argument('--refs-dir',
                         action = 'store', dest = 'refs_dir', default = os.path.join(tempfile.gettempdir(), 'refs'),
                         help = 'Directory containing the references')
     parser.add_argument('-o', '--out-dir',
                         action = 'store', dest = 'out_dir', default = os.path.join(tempfile.gettempdir(), 'out'),
                         help = 'Directory containing the results')
     parser.add_argument('-p', '--pretty-diff',
                         action = 'store_true', dest = 'pretty_diff', default = False,
                         help = 'Include pretty diff output')
     parser.add_argument('-n', '--no-browser',
                         action = 'store_false', dest = 'launch_browser', default = True,
                         help = 'Do not launch a web browser with the results')
     parser.add_argument('--no-absolute-paths',
                         action = 'store_false', dest = 'use_abs_paths', default = True,
                         help = 'Do use absolute paths in the generated HTML')
     parser.add_argument('tests')
Exemplo n.º 41
0
 def __init__(self):
     Command.__init__(self)
     parser = self._get_args_parser()
     parser.add_argument(
         "--refs-dir",
         action="store",
         dest="refs_dir",
         default=os.path.join(tempfile.gettempdir(), "refs"),
         help="Directory containing the references",
     )
     parser.add_argument(
         "-o",
         "--out-dir",
         action="store",
         dest="out_dir",
         default=os.path.join(tempfile.gettempdir(), "out"),
         help="Directory where test results will be created",
     )
     parser.add_argument(
         "--keep-results",
         action="store_true",
         dest="keep_results",
         default=False,
         help="Do not remove result files for passing tests",
     )
     parser.add_argument(
         "--create-diffs",
         action="store_true",
         dest="create_diffs",
         default=False,
         help="Create diff files for failed tests",
     )
     parser.add_argument(
         "--update-refs",
         action="store_true",
         dest="update_refs",
         default=False,
         help="Update references for failed tests",
     )
     parser.add_argument("tests")
Exemplo n.º 42
0
 def __init__(self):
     Command.__init__(self)
     parser = self._get_args_parser()
     parser.add_argument(
         "--refs-dir",
         action="store",
         dest="refs_dir",
         default=os.path.join(tempfile.gettempdir(), "refs"),
         help="Directory containing the references",
     )
     parser.add_argument(
         "-o",
         "--out-dir",
         action="store",
         dest="out_dir",
         default=os.path.join(tempfile.gettempdir(), "out"),
         help="Directory containing the results",
     )
     parser.add_argument(
         "--src-dir",
         action="store",
         dest="src_dir",
         default=os.path.abspath("../"),
         help="Directory of poppler sources",
     )
     parser.add_argument(
         "--builder",
         action="store",
         dest="builder",
         choices=["autotools"],
         default="autotools",
         help="Build system to use",
     )
     parser.add_argument("--prefix", action="store", dest="prefix", default="/usr/local", help="Build prefix")
     parser.add_argument("--good", action="store", dest="good", metavar="REVISION", help="Good revision")
     parser.add_argument(
         "--bad", action="store", dest="bad", default="HEAD", metavar="REVISION", help="Bad revision"
     )
     parser.add_argument("test")
Exemplo n.º 43
0
 def __init__(self):
     Command.__init__(self)
     parser = self._get_args_parser()
     parser.add_argument('--refs-dir',
                         action = 'store', dest = 'refs_dir', default = os.path.join(tempfile.gettempdir(), 'refs'),
                         help = 'Directory containing the references')
     parser.add_argument('-o', '--out-dir',
                         action = 'store', dest = 'out_dir', default = os.path.join(tempfile.gettempdir(), 'out'),
                         help = 'Directory where test results will be created')
     parser.add_argument('--docs-dir',
                         action = 'store', dest = 'docs_dir',
                         help = 'Base documents directory')
     parser.add_argument('--keep-results',
                         action = 'store_true', dest = 'keep_results', default = False,
                         help = 'Do not remove result files for passing tests')
     parser.add_argument('--create-diffs',
                         action = 'store_true', dest = 'create_diffs', default = False,
                         help = 'Create diff files for failed tests')
     parser.add_argument('--update-refs',
                         action = 'store_true', dest = 'update_refs', default = False,
                         help = 'Update references for failed tests')
     parser.add_argument('tests', metavar = 'TEST', nargs = '+',
                         help = 'Tests directory or individual test to run')
Exemplo n.º 44
0
    def __init__(self, *args, **kwargs):
        Command.__init__(self, *args, **kwargs)

        if not self.args:
            return self.message(self.syntax, self.user)

        query = ' '.join(self.args)
        url = "http://en.wikipedia.org/w/api.php?format=json&action=query&%s&prop=revisions&rvprop=content" % urllib.urlencode({'titles': query})
        results = json.loads(urllib.urlopen(url).read())['query']

        if not results.get('pages', False): return
        page = results['pages'].popitem()[1]
        title = page['title']

        if not page.get('pageid', False): 
            return self.message("No Wikipedia page for \"%s\"" % query, self.user)

        url = "http://en.wikipedia.org/w/api.php?action=query&prop=info&pageids=%s&inprop=url&format=xml" % page['pageid']
        xml = ElementTree.fromstring(urllib.urlopen(url).read())
        url = xml.findall(".//page[1]")[0].get('fullurl')

        # TODO: return first paragraph

        self.message("%s (%s)" % (title, url), self.user)
Exemplo n.º 45
0
	def trig_help(self, bot, source, target, trigger, argument):
		"""Help command. Use it to get information about other commands."""
		trigger_found = False
		for command in Command.__subclasses__():
			fname = "trig_" + argument
			if fname in command.__dict__:
				trigger_found = True
				f = command.__dict__[fname]
				if f.__doc__:
					return "%s: %s" % (argument, f.__doc__)
		
		if trigger_found:
			return "I can offer nothing."
		else:
			return "That's not a command! Try `help <command>`"
Exemplo n.º 46
0
	def trig_commands(self, bot, source, target, trigger, argument):
		triggers = []
		for command in Command.__subclasses__():
			for trigger in command.triggers:
				if trigger not in triggers:
					triggers.append(trigger)

			l = command.__dict__
			l = filter(is_trigger, l)
			l = map(remove_first_five, l)

			for trigger in l:
				if trigger not in triggers:
					triggers.append(trigger)
		
		return "Commands: %s" % ", ".join(sorted(triggers))
Exemplo n.º 47
0
    def run(self):
        while True:
            try:
                query = raw_input(self.prompt + " ").strip()

                if query:
                    command = Command.create(self._pass_storage, query)

                    if isinstance(command, Exit):
                        break

                    output = command.execute()

                    print output

            except BaseError as exc:
                print "Error:", exc.__class__.__name__
Exemplo n.º 48
0
    def __init__(self, _client):
    	self.client = _client

        # Tcp Connection
        self.tcpCon = None

    	# Start TCP
    	self.startTcp()
    	#self.startUdp()

    	# Start network tasks for readers
        # TCP Reader
        taskMgr.add(self.tcpReaderTask, "tcpReaderTask", -39)
        # UDP Reader
        #taskMgr.add(self.udpReaderTask, "udpReaderTask", -39)
        print "Client: Readers Started!"

        # Create Commands
        self.command = Command(self)
        self.commands = {
            cmdToClient_authResponse   : self.command.authResponse,
            cmdToClient_newState       : self.command.updateState,
            cmdToClient_newPlayerJoined: self.command.newPlayerJoined
        }
Exemplo n.º 49
0
 def __init__(self):
     Command.__init__(self, "test")
Exemplo n.º 50
0
 def __init__(self, *args, **kwargs):
     Command.__init__(self, *args, **kwargs)
     self.parseURL(self.args)
Exemplo n.º 51
0
 def __init__(self):
     Command.__init__(self)
Exemplo n.º 52
0
class NetworkManager():
    
    def __init__(self, _client):
    	self.client = _client

        # Tcp Connection
        self.tcpCon = None

    	# Start TCP
    	self.startTcp()
    	#self.startUdp()

    	# Start network tasks for readers
        # TCP Reader
        taskMgr.add(self.tcpReaderTask, "tcpReaderTask", -39)
        # UDP Reader
        #taskMgr.add(self.udpReaderTask, "udpReaderTask", -39)
        print "Client: Readers Started!"

        # Create Commands
        self.command = Command(self)
        self.commands = {
            cmdToClient_authResponse   : self.command.authResponse,
            cmdToClient_newState       : self.command.updateState,
            cmdToClient_newPlayerJoined: self.command.newPlayerJoined
        }

    ## SETUP TCP ##
    def startTcp(self):
    	"""
    	Setup all tcp related classes
    	"""
        self.tcpManager = QueuedConnectionManager()
        self.tcpReader = QueuedConnectionReader(self.tcpManager, 0)
        self.tcpWriter = ConnectionWriter(self.tcpManager, 0)

    def startUdp(self):
    	"""
    	Setup all udp related classes
    	"""
        self.udpManager = QueuedConnectionManager()
        self.udpReader = QueuedConnectionReader(self.udpManager, 0)
        self.udpWriter = ConnectionWriter(self.udpManager, 0)

    # TCP Reader Task
    def tcpReaderTask(self, task):
        """
        Handle any data from server by sending it to the Handlers.
        """
        while 1:
            (datagram, data, opcode) = self.tcpNonBlockingRead(self.tcpReader)
            if opcode is MSG_NONE:
                # Do nothing or use it as some 'keep_alive' thing.
                break 
            else:
                # Handle it
                self.tcpHandleDatagram(data, opcode)
                
        return Task.cont

    # TCP NonBlockingRead
    def tcpNonBlockingRead(self, qcr):
        """
        Return a datagram collection and type if data is available on
        the queued connection tcpReader
        
        @param qcr: self.tcpReader
        """
        if self.tcpReader.dataAvailable():
            datagram = NetDatagram()
            if self.tcpReader.getData(datagram):
                data = PyDatagramIterator(datagram)
                opcode = data.getUint16()
                
            else:
                data = None
                opcode = MSG_NONE
            
        else:
            datagram = None
            data = None
            opcode = MSG_NONE
            
        # Return the datagram to keep a handle on the data
        return (datagram, data, opcode)

    # TCP Handle Datagram
    def tcpHandleDatagram(self, data, opcode):
        """
        Check for the handle assigned to the opcode.
        """
        if opcode in self.commands:
        	self.commands[opcode](opcode, data)

        else:
            print "Client: BAD-opcode - %d" % opcode
            print "Client: Opcode Data -", data
            
        return



    # Connect to a Server
    def connectToServer(self, _hostIP):
        # TCP Connection
        self.tcpConnection = self.tcpManager.openTCPClientConnection(_hostIP, 
                                    clTCPPORT, clTIMEOUT)

        if self.tcpConnection != None:
            self.tcpReader.addConnection(self.tcpConnection)
            print "Client: Connected to %s" % _hostIP
            self.tcpCon = self.tcpConnection
            # Temp test
            self.command.authREQ(self.tcpCon)
Exemplo n.º 53
0
def _find_command_class(root_dir, args):
  args, command_class_name = _find_command_class_name(root_dir, args)
  return args, Command.find_command_class(command_class_name)
Exemplo n.º 54
0
#!/usr/bin/env python
from commands import Command



c = Command()
c = Command()
c.timeline()
c.sort()
Exemplo n.º 55
0
Arquivo: views.py Projeto: osa1/kweb
def parse_code(code, tool, action, path, current_file, args):
    curr_id = str(uuid.uuid4())
    command = Command(code, tool, action, path, current_file, curr_id, args)
    command.run()
    return curr_id
Exemplo n.º 56
0
        if not l:
            continue
        l = re.sub(' +', ',', l)
        l = re.sub('\t+', ',', l)
        line = l.split(",")

        arr = []
        for i in line:
            if i != '':
                arr.append(i)
        inputFile.append(arr)

    fProcess.process(inputFile)
    s_call = Syscall(mem.get_registers(), mem)
    ins = Instruction(mem.get_registers(), mem, s_call)
    com = Command(mem.get_registers(), mem, ins)
    #debug = False
    while True:
        if debug:
            command = raw_input("")
            print "PC: " + hex(mem.get_registers().PC)
            print "Instruction Word: " + hex(mem.get_val_in_address(mem.get_registers().PC))
            line = command.split(" ")
            if len(line) > 2:
                if line[1] == "mem":
                    com.execute_command(line[0] + " " + line[1], line[2])
                elif line[1] == 'reg':
                    com.execute_command(line[0] + " " + line[1], line[2])
                elif line[1] == 'inst':
                    com.execute_command(line[0] + " " + line[1], mem.get_val_in_address(mem.get_registers().PC))