Beispiel #1
0
def getbuiltins():
    builtins = []

    def help(args, env):
        if (len(args) > 1):
            if (args[1] in env['commands']):
                return (env['commands'][args[1]].help_message, 0)
            else:
                return ("command " + args[1] + " not found", 0)
        else:
            helpmessage = ""
            for name, cmd in env['commands'].items():
                helpmessage += name + '\n'
                helpmessage += cmd.help_message + '\n'
            return (helpmessage, 0)

    builtins.append(
        command.command("help",
                        ("Usage: help [command]\n"
                         "Displays the specified command's help message.\n"),
                        help))

    def killbot(args, env):
        return ("Exiting...", 1)

    builtins.append(
        command.command("killbot", ("Usage: killbot\n"
                                    "Kills the bot\n"), killbot))

    return builtins
Beispiel #2
0
def main():    

    log("\n[KAISSA64] Start new session...\n")    
    start = time.time()    
    startWorkers() # Init multiprocessing           
    
    if len(sys.argv) > 1:
        depth = int(sys.argv[1])
        if depth < 10: # for example: 3 both for default and max depth
            defaultDepth = depth
            maxDepth = defaultDepth
        else: # 37 for example: 3 for default and 7 for max depth               
            defaultDepth = math.floor(depth / 10)
            maxDepth = depth % 10
    else:    
        defaultDepth = 3    
        maxDepth = defaultDepth

    board = chess.Board()    

    while True:
        msg = input()
        log(f">>> {msg}")    
        if msg == "quit": break
        command(msg, board, defaultDepth, maxDepth)

    stopWorkers()
    end = time.time()    
    log(f"\n[KAISSA64] Session was ended after {round(end - start, 2)} sec...")
Beispiel #3
0
    def __parseCommand(self, cmdString, fin):
        # print(cmdString)
        cmdSplitted = cmdString.split(' ')
        timestamp = [int(cmdSplitted[0])]  # starttime and endtime
        if cmdSplitted[1] in parseMetadata.__DroneFlyingStatusLabel:
            assert cmdSplitted[2].upper() == 'STARTED'
            cmd = cmdSplitted[1]
            interStatus = list()
            while True:
                tmpStr = fin.readline().strip('\n')
                tmpStrSplitted = tmpStr.split(' ')
                if tmpStrSplitted[1] == cmd and tmpStrSplitted[2].upper(
                ) == 'PROGRESSED':
                    # timestamp.append(int(tmpStrSplitted[0]))
                    pass
                elif tmpStrSplitted[1] == cmd and tmpStrSplitted[2].upper(
                ) == 'FINISHED':
                    timestamp.append(int(tmpStrSplitted[0]))
                    break
                else:
                    interStatus.append(tmpStr)
            cmdClass = command(timestamp, cmd, interStatus, None)

        elif cmdSplitted[1] in parseMetadata.__DroneProgrammingLabel:
            cmd = cmdSplitted[1]
            cmdClass = command(timestamp, cmd, None, cmdSplitted[2:])

        return cmdClass
 def setUp(self):
     self.__dummycount = 0
     self.__dummyargs = []
     self.__dummykw = {}
     arg1 = command.argument('banana', True)
     arg2 = command.argument('melon', False)
     self.c1 = command.command('peel', self.__dummy_callback, [])
     self.c2 = command.command('fruitbowl', self.__dummy_callback,
                               [arg1, arg2])
 def setUp(self):
     self.__dummycount = 0
     self.__dummyargs = []
     self.__dummykw = {}
     arg1 = command.argument('banana', True)
     arg2 = command.argument('melon', False)
     self.c1 = command.command('peel', self.__dummy_callback, [])
     self.c2 = command.command('fruitbowl', self.__dummy_callback,
                               [arg1, arg2])
Beispiel #6
0
def parse(string):
	if string[:1] == '/':
		command.command(string)

	else:
		try:
			ps = parser.evaluate(string,vars.vars)
			vars.vars['a'] = float(ps)
			print("%f" % ps)
		except:
			print("Failed to parse: %s" % (string))	
Beispiel #7
0
 def run(self):
     while True:
         command_list = self.queue.get()
         if command_list is None:
             break
         for c in range(command_list.qsize()):
             com = command_list.get()
             print(c, ": ", com)
             command(self.ip_addr, self.port, com)
             time.sleep(0.5)
         self.queue.task_done()
Beispiel #8
0
    def testCommandOverwrite(self):
        commandTest = command.command(unittest, 'testplugin')
        self.assertEqual(commandTest.name, 'testplugin')
        self.assertEqual(commandTest.plugin, unittest)
        self.assertEqual(commandTest.shortdesc, 'no description')
        self.assertEqual(commandTest.devcommand, False)

        commandTest = command.command(unittest,
                                      'testplugin',
                                      shortdesc='python testing is fun!')
        self.assertEqual(commandTest.name, 'testplugin')
        self.assertEqual(commandTest.plugin, unittest)
        self.assertEqual(commandTest.shortdesc, 'python testing is fun!')
        self.assertEqual(commandTest.devcommand, False)
Beispiel #9
0
    def testPluginOverwrite(self):
        commandTest = command.command(unittest, 'TestCommand')
        pluginTest = plugin.plugin(unittest, 'TestPlugin', [commandTest])
        self.assertEqual(pluginTest.plugin, unittest)
        self.assertEqual(pluginTest.name, 'TestPlugin')
        self.assertEqual(pluginTest.commands, [commandTest])

        commandTest2 = command.command(unittest,
                                       'TestCommand',
                                       shortdesc='Description!')
        pluginTest = plugin.plugin(unittest, 'TestPlugin', [commandTest2])
        self.assertEqual(pluginTest.plugin, unittest)
        self.assertEqual(pluginTest.name, 'TestPlugin')
        self.assertEqual(pluginTest.commands, [commandTest2])
        self.assertEqual(pluginTest.commands[0].shortdesc, 'Description!')
Beispiel #10
0
def main():
    client = mqtt.Client(server_id)

    client.connect(ip)
    client.on_message = on_message
    client.loop_start()
    client.subscribe(topic)

    # wait until client is connected
    while not client.is_connected:
        time.sleep(1)

    # expect a cli command
    command()

    disconnect(client)
def create(**kw):

    url = "%s/%s" % (kw.get("broker", broker.OPENSHIFT_BROKER_URL), _path)
    cmd = command.command(
        {
            "alter": {
                "class": "optional",
                "type": "flag"
            },
            "debug": {
                "class": "optional",
                "type": "flag"
            },
            "ssh": {
                "class": "required",
                "type": "string"
            },
            "password": {
                "class": "required",
                "type": "string"
            },
            "namespace": {
                "class": "required",
                "type": "string"
            },
            "rhlogin": {
                "class": "required",
                "type": "string"
            }
        }, kw)

    return broker.broker(url, cmd)
Beispiel #12
0
def do_command(arguments, configuration):
    """Executes a command.
    """
    term = Terminal(configuration)
    configuration['terminal'] = term
    cmd = command(arguments, configuration)
    _, err = cmd.execute()
    if err:
        term.warn(err.reason)
Beispiel #13
0
    def __init__(self, name, new=True):

        self.name = name

        if new:

            #Check whether there are sessions with the same name
            for session in get_all_sessions():
                if name == session.name:
                    raise MoreSessionsWithTheSameNameException

            #Create the session
            command.command('screen -d -m -S ' + name)

            #Look for the id
            for session in get_all_sessions():
                if session.name == self.name:
                    self.id = session.id
Beispiel #14
0
 def testCommandArgs(self):
     commandTest = command.command(unittest,
                                   'testplugin',
                                   shortdesc='python testing is fun!',
                                   devcommand=True)
     self.assertEqual(commandTest.name, 'testplugin')
     self.assertEqual(commandTest.plugin, unittest)
     self.assertEqual(commandTest.shortdesc, 'python testing is fun!')
     self.assertEqual(commandTest.devcommand, True)
Beispiel #15
0
def do_command(arguments, configuration):
    """Executes a command.
    """
    term = Terminal(configuration)
    configuration['terminal'] = term
    cmd = command(arguments, configuration)
    _, err = cmd.execute()
    if err:
        term.warn(err.reason)
Beispiel #16
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("table")
    args = parser.parse_args()

    test = DataBase.DataBase(args.table)

    cmd = command.command(test)
    cmd.cmdloop()
Beispiel #17
0
    def __init__(self,name,new=True):

        self.name = name

        if new:

            #Check whether there are sessions with the same name
            for session in get_all_sessions():
                if name == session.name:
                    raise MoreSessionsWithTheSameNameException

            #Create the session
            command.command('screen -d -m -S '+name)

            #Look for the id
            for session in get_all_sessions():
                if session.name == self.name:
                    self.id = session.id
Beispiel #18
0
def info(**kw):
    
    url = "%s/%s" % (kw.get("broker", broker.OPENSHIFT_BROKER_URL), _path) 

    cmd = command.command({
        "debug": {"class": "optional", "type": "flag"}, 
        "password": {"class": "required", "type": "string"}, 
        "rhlogin": {"class": "required", "type": "string"}}, kw)

    return broker.broker(url, cmd)
Beispiel #19
0
def handle_message(event):
    if (event.message.text == "おみくじ" or event.message.text == "おみくじをひく"):
        omikuji(event, line_bot_api)
    elif (event.message.text == '闇鍋ガチャ' or event.message.text == '闇鍋'):
        yaminabe(event, line_bot_api)
    elif (event.message.text == '参拝' or event.message.text == 'デバック神社'):
        debugjinja(event, line_bot_api)
    elif (event.message.text == 'ヘルプ'):
        help(event, line_bot_api)
    elif (event.message.text == 'qiita'):
        qiita(event, line_bot_api)

    else:
        '''
        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(text=event.message.text)
        )
        '''
        command(event, line_bot_api)
Beispiel #20
0
 def __init__(self):
     chatbot.ChatBot.__init__(self, config_file['user'], config_file['password'], wiki_name)
     self.command = command(self, config_file['user'], config_file['password'])
     self.last_updated = time.time()
     self.logger_on = False
     self.hello_status = True
     self.youtubeinfo = True
     self.twitterinfo = True
     self.seen = True
     self.tell = True
     self.new_day = False
     self.updated = False
     self.log_thread()
Beispiel #21
0
def interface(data, user):
	try:
		logging.info('Starting taskmaster as {}'.format(user))
		t = taskmaster(data,)

		task = command()
		task.user = user
		task.t = t
		task.cmdloop()

	except:
		print("An Taskmaster shell error occured")
	finally:
		t.join()
Beispiel #22
0
def _run(action, **kw):
    
    url = "%s/%s" % (kw.get("broker", broker.OPENSHIFT_BROKER_URL), _path) 
    kw.update({"action": action})
    cmd = command.command({
            "cartridge": { "class": "required", "type": "app-cartridge" },
            "debug": {"class": "optional", "type": "flag"}, 
            "password": {"class": "required", "type": "string"}, 
            "app_name": {"class": "required", "type": "string"}, 
            "action": {"class": "required", "type": "app-action"}, 
            "rhlogin": {"class": "required", "type": "string"
            }}, kw)

    return broker.broker(url, cmd)
Beispiel #23
0
def onPlayerChat(players, data, rcon):
    output.debug('%s: %s: %s' % (data[0], data[1], data[2]))
    if data[0] == 'Server':
        return
    chatlog.info(' - '.join(data))
    gamelog.info('onChat;' + ';'.join(data))
    who = players.getplayer(data[0])
    if not who:
        players.connect(data[0])
        who = players.getplayer(data[0])
    chat = data[1]
    target = data[2]
    
    if chat.startswith('/'):
        chat = chat[:1]
        target = 'Private'
        
    for word in kickwords:
        if re.search('\\b' + word + '\\b', chat, re.I):
            if who.warning:
                output.info('kicking %s for bad language' % who.name)
                rcon.send('punkBuster.pb_sv_command', 'PB_SV_Kick %s 10 That Language is not Tolerated here.' % (who.name))
            else:
                output.info('warning %s for bad language' % who.name)
                who.warning = 1
                rcon.send('admin.say', 'That language is NOT tolerated here!  This is your only warning!',
                          'player', who.name)
    
    for word in banwords:
        if re.search('\\b' + word + '\\b', chat, re.I):
            output.info('banning %s for really bad language' % who.name)
            rcon.send('punkBuster.pb_sv_command', 'pb_sv_banGUID %s %s %s %s' % (who.pbid, 
                      who.name, who.ip, 'Monitor Language Ban'))
            
    players.addchat(who.name, '%s: %s' % (target, chat))
    command.command(who, chat, rcon, players)
Beispiel #24
0
    def create_command(self, cmd_str):
        """
            validate command string format, return command
        """
        # parse cmd_str
        cmd_items = cmd_str.rstrip(" ").rstrip("\n").split(" ")
        action, res_id = cmd_items
        # validate it
        assert action.lower() in ["lock", "unlock"]

        # return command object
        cmd_type = COMMAND_TYPE.LOCK
        if action.lower() == "unlock":
            cmd_type = COMMAND_TYPE.UNLOCK
        return command.command(cmd_type, int(res_id))
Beispiel #25
0
    def testCommandChangeArgs(self):
        commandTest = command.command(unittest,
                                      'testplugin',
                                      shortdesc='python testing is fun!')
        self.assertEqual(commandTest.name, 'testplugin')
        self.assertEqual(commandTest.plugin, unittest)
        self.assertEqual(commandTest.shortdesc, 'python testing is fun!')
        self.assertEqual(commandTest.devcommand, False)

        commandTest.shortdesc = 'We\'ve changed the description!'
        self.assertEqual(commandTest.name, 'testplugin')
        self.assertEqual(commandTest.plugin, unittest)
        self.assertEqual(commandTest.shortdesc,
                         'We\'ve changed the description!')
        self.assertEqual(commandTest.devcommand, False)
Beispiel #26
0
    def create_command(self, cmd_str):
        """
            validate command string format, return command
        """
        # parse cmd_str
        cmd_items = cmd_str.rstrip(" ").rstrip("\n").split(" ")
        action, res_id = cmd_items
        # validate it
        assert action.lower() in ["lock", "unlock"]

        # return command object
        cmd_type = COMMAND_TYPE.LOCK
        if action.lower() == "unlock":
            cmd_type = COMMAND_TYPE.UNLOCK
        return command.command(cmd_type, int(res_id))
Beispiel #27
0
def sendCommand(strCommand, value):
    response = 1
    objCommand = com.command(strCommand)
    objCommand.maxCharCommand = maxCharCommand
    objCommand.isValidCommand = com.commandValidation(objCommand.name)
    objCommand.value = com.makeCommandNameCompatible(value, maxCharCommand)
    objCommand.name = com.makeCommandNameCompatible(objCommand.name, maxCharCommand)
    if (objCommand.isValidCommand):
        ArduinoSerial = serial.Serial(port, baudrate)
        print(str(objCommand.name) + str(objCommand.value))
        ArduinoSerial.write(str.encode(str(objCommand.name) + str(objCommand.value)))
        time.sleep(2)
        #read response
        ArduinoSerial.close() 
    return response
Beispiel #28
0
def main():
    args = command.command()
    if args.test:
        test.run_test()
        return 0

    if args.folder is None:
        print("folder is a required argument if not using test option ")
        return 0

    if os.path.exists(args.folder):
        if args.duplicates:
            command.remove_duplicates_decision(args.folder)
        if args.order:
            command.file_order_decision(args.folder)
    else:
        print("The folder does not exist")
Beispiel #29
0
def get_all_sessions():

    raw_screens = command.command('screen -ls',return_output=True)
    screen_sessions = []

    for n,line in enumerate(raw_screens):

        #Skip the first and last lines
        if n == 0 or n > len(raw_screens) -3:
            continue

        session, date, attached_state = line.strip().split('\t')

        id, name = session.split('.')
        session = ScreenSession(name,new=False)
        session.id = int(id)
        screen_sessions.append(session)

    return screen_sessions
Beispiel #30
0
def get_all_sessions():

    raw_screens = command.command('screen -ls', return_output=True)
    screen_sessions = []

    for n, line in enumerate(raw_screens):

        #Skip the first and last lines
        if n == 0 or n > len(raw_screens) - 3:
            continue

        session, date, attached_state = line.strip().split('\t')

        id, name = session.split('.')
        session = ScreenSession(name, new=False)
        session.id = int(id)
        screen_sessions.append(session)

    return screen_sessions
Beispiel #31
0
class start(query):
    desc = 'Main menu.'

    def start_handle(self):
        self.user.mute = False
        self.user.notify(message('Mute mode is off'))

    def stop_handle(self):
        self.user.mute = True
        self.user.notify(message('Mute mode is on'))

    def send_handle(self):
        self.user.next_action(send_message.get_receiver)

    def my_name(self):
        message_text = 'Your nickname is %s\n' % self.user.login
        if self.user.show_service_name:
            message_text += ('You can also be found by %s' %
                             self.user.get_service_login())
        self.user.notify(message(message_text))

    def hide_id(self):
        self.user.show_service_name = False
        self.user.notify(
            message("""
Your service id was hidden. Your messages' receivers would not see \
your service id. You couldn't be found by your service id.
        """))

    def disclose_id(self):
        self.user.show_service_name = True
        self.user.notify(message('Your service nickname was disclosed.'))

    commands = list(query.commands)
    commands.append(
        command('/continue', start_handle, 'continue receiving messages',
                lambda user: user.mute))
    commands.append(
        command('/pause', stop_handle, 'pause receiving messages',
                lambda user: not user.mute))
    commands.append(command('/send', send_handle, 'send a message'))
    commands.append(command('/name', my_name, 'your nickname'))
    commands.append(
        command('/hide', hide_id, 'hide service id',
                lambda user: user.show_service_name))
    commands.append(
        command('/unhide', disclose_id, 'disclose service id',
                lambda user: not user.show_service_name))
Beispiel #32
0
def run_project(command):
#    print ("Finding project {0}:".format(command.name))
    projects.load_until(command.name)

    if command.name in projects.projects_by_name:
        proj = projects.projects_by_name[command.name][0]
#        print ("Using {0}".format(proj.name))

        if len(command.children) > 0:
            for cmd in command.children:
                try:
                    proj.run_command(cmd)
                except PykeError as ve:
                    print ("{0}: {1}".format(t.make_error('Error'), ve))
                    break
        else:
            c = com.command("describe", command)
            command.children.append(c)
            proj.run_command(c)
    else:
        raise PykeError("Unable to find project \"{0}\".".format(t.make_project_name(command.name)))
Beispiel #33
0
def onInit(plugin_in):
    plugins_command = command.command(plugin_in,
                                      'plugins',
                                      shortdesc='Print a list of plugins',
                                      devcommand=True)
    commands_command = command.command(plugin_in,
                                       'commands',
                                       shortdesc='Print a list of commands')
    help_command = command.command(plugin_in,
                                   'help',
                                   shortdesc='Redirects to !commands')
    info_command = command.command(plugin_in,
                                   'info',
                                   shortdesc='Print some basic bot info')
    plugintree_command = command.command(
        plugin_in,
        'plugintree',
        shortdesc='Print a tree of plugins and commands',
        devcommand=True)
    uptime_command = command.command(plugin_in,
                                     'uptime',
                                     shortdesc='Print the bot\'s uptime',
                                     devcommand=True)
    hostinfo_command = command.command(
        plugin_in,
        'hostinfo',
        shortdesc='Prints information about the bots home',
        devcommand=True)
    cpuinfo_command = command.command(
        plugin_in,
        'cpuinfo',
        shortdesc='Prints info about the system CPUs',
        devcommand=True)
    return plugin.plugin(plugin_in, 'botutils', [
        plugins_command, commands_command, help_command, info_command,
        plugintree_command, uptime_command, hostinfo_command, cpuinfo_command
    ])
Beispiel #34
0
    def __init__(self, frame_title):
        wx.Frame.__init__(
            self,
            parent=None,
            id=wx.ID_ANY,
            title=frame_title,
            pos=wx.DefaultPosition,
            size=wx.DefaultSize,
        )

        self.serial_port = Serial()
        self.command = command()

        self.create_objects()
        self.connect_events()
        self.arrange_objects()

        pub.subscribe(self.on_recieve_area_update, "update")
        pub.subscribe(self.on_serial_read_error, "serial_read_error")
        pub.subscribe(self.on_run_write_error, "run_write_error")
        pub.subscribe(self.on_run_seq_started, "run_seq_started")
        pub.subscribe(self.on_run_seq_finished, "run_seq_finished")
        pub.subscribe(self.on_single_command_finished,
                      "single_command_finished")
Beispiel #35
0
    def kill(self):

        command.command('screen -S '+self.name+' -X quit')
Beispiel #36
0
 def testCommandBasicArgs(self):
     commandTest = command.command(unittest, 'testplugin')
     self.assertEqual(commandTest.name, 'testplugin')
     self.assertEqual(commandTest.plugin, unittest)
     self.assertEqual(commandTest.shortdesc, 'no description')
     self.assertEqual(commandTest.devcommand, False)
Beispiel #37
0
def command_factory(name, ma=0, ol=[None]):
    return lambda *args, **kwargs: command(name, max_args=ma, option_list=ol, 
                                           arguments=args, options=kwargs)
Beispiel #38
0
def onInit(plugin):
    define_command = command.command(plugin, 'define', shortdesc='Define X')
    randefine_command = command.command(plugin, 'randefine', shortdesc='Define a random thing')
    return plugin.plugin.plugin(plugin, 'urbandictionary', [define_command, randefine_command])
Beispiel #39
0
    def send_command(self,command_to_send):

       command.command(['screen', '-r', self.name, '-X', 'stuff',command_to_send+' \r'])
Beispiel #40
0
import maya.mel as mel
import sys
sys.path.insert(0, "/Users/raychen/Library/Preferences/Autodesk/maya/2015-x64/prefs/scriptEditorTemp/")
import command
while True:
	reload(command)
	command.command(command.c_type, command.pVec)
	mel.eval("refresh -f")
Beispiel #41
0
def onInit(plugin):
    xkcd_command = command.command(
        plugin, 'xkcd', shortdesc='Posts the latest XKCD, or by specific ID')
    return plugin.plugin.plugin(plugin, 'comics', [xkcd_command])
Beispiel #42
0
from command import command


if __name__ == "__main__":
    param = sys.argv

    if len(param) == 1:
        print("blank, update, print")
        print("toggle src, toggle domain")

    elif "toggle" in param:
        db = db()
        if "src" in param:
            db.commandToggleSource()
        elif "domain" in param:
            db.commandToggleUserdomain()

    else:
        command = command()

        if "blank" in param:
            command.blankHosts()

        elif "update" in param:
            command.updateHosts()

        elif "print" in param:
            command.printHosts()

    exit()
Beispiel #43
0
    def send_command(self, command_to_send):

        command.command([
            'screen', '-r', self.name, '-X', 'stuff', command_to_send + ' \r'
        ])
Beispiel #44
0
    def kill(self):

        command.command('screen -S ' + self.name + ' -X quit')