def addSwitch(): SwitchQueue = Queue() name = input("Enter the name of the Switch in Single small Letter") switch = Switch(SwitchQueue, "Active", name) toSwitchConnectionObjects = switch.toHostPipe() NETWORK_Connection_Register[1].append( (name, switch, toSwitchConnectionObjects))
def test_FlowManager(self): network = { "openflow:1": Switch("openflow:1"), "openflow:3": Switch("openflow:3") } fm = flow_manager.FlowManager(network=network, solution=None, controller_address=TEST_SERVER) fm.network["openflow:1"].add_flow("0", Flow("0")) fm.network["openflow:1"].remove_flow("0", "0")
def _get_switch(self, dpid): """ Returns the switch representation of the datapath id. """ if dpid in self.dpids: switch = Switch(self.dpids[dpid]) for ofpport in self.port_state[dpid].values(): switch.add_port(ofpport) return switch
def __init__(self): GPIO.setup(pin_dir, GPIO.OUT) GPIO.setup(pin_step, GPIO.OUT) print("pins set up") self.inches = 0 self.switch = Switch() self.start = time.time() self.lc = lcm.LCM()
def __init__(self, pin, valq, loop_interval, debug=False): ''' @param pin [pin1, pin2] @param valq value queue @param loop_interval sec @param debug debug flag ''' self.logger = init_logger(__class__.__name__, debug) self.logger.debug('pin:%s', pin) if len(pin) != 2: return None self.pin = pin self.valq = valq self.loop_interval = loop_interval self.switch = [] for p in self.pin: sw = Switch(p, timeout_sec=[], debug=debug) self.switch.append(sw) self.stat = [-1, -1] self.sl = SwitchListener(self.switch, self.cb, self.loop_interval, debug=debug)
def main(self, debug): print('### RotaryEncoderListener demo') self.rel = RotaryEncoderListener(self.pin_re, self.cb_re, debug=debug) self.sw = Switch(self.pin_sw, debug=debug) self.sl = SwitchListener([self.sw], self.cb_sw, debug=debug) self.start_sec = time.time() self.loop_flag = True while self.loop_flag: time.sleep(1) self.sl.stop() self.rel.stop() print('') print('### RotaryKey demo') self.rek = RotaryKey(self.pin_re, self.pin_sw, self.cb_rk, debug=debug) self.loop_flag = True while self.loop_flag: time.sleep(1) self.rek.stop() print('') print('### Finished')
def __init__(self, pin_led, pin_sw, debug=False): print('pin_led:%d' % pin_led) print('pin_sw :%d' % pin_sw) self.pin_led = pin_led self.pin_sw = pin_sw self.long_press = [ { 'timeout': 0.7, 'blink': { 'on': 1, 'off': 0 } }, # multi click { 'timeout': 1, 'blink': { 'on': 0.2, 'off': 0.04 } }, # blink1 { 'timeout': 3, 'blink': { 'on': 0.1, 'off': 0.04 } }, # blink2 { 'timeout': 5, 'blink': { 'on': 0.02, 'off': 0.04 } }, # blink3 { 'timeout': 7, 'blink': { 'on': 0, 'off': 0 } } ] # end self.timeout_sec = [] for i in range(len(self.long_press)): self.timeout_sec.append(self.long_press[i]['timeout']) self.sw = Switch(self.pin_sw, self.timeout_sec, debug=debug) self.sl = SwitchListener([self.sw], self.sw_callback, debug=debug) self.led = Led(self.pin_led) self.active = True
def __addElements(self, top): self.__topLevel = top self.__topLevelWindow = top.getTopLevel() self.__topLevelWindow.protocol('WM_DELETE_WINDOW', self.__closeWindow) from Switch import Switch self.__banks = [] for num in range(3, 9): testbank = Switch(self.__loader, self.__topLevel, self.__topLevelWindow, num, self.__banks) self.__banks.append(testbank)
class LightSwitch: """The Client class""" def __init__(self): self._lamp = Light() self._switchUp = FlipUpCommand(self._lamp) self._switchDown = FlipDownCommand(self._lamp) self._switch = Switch(self._switchUp, self._switchDown) def switch(self, cmd): cmd = cmd.strip().upper() try: if cmd == "ON": self._switch.flipUp() elif cmd == "OFF": self._switch.flipDown() else: print "Argument \"ON\" OR \"OFF\" is required." except Exception, msg: print "Exception occured: %s" % msg
def criar_ambiente_sw(): sw = Switch(24, '192.168.2.1', '255.255.255.0', '22:22:11:22') sinet.initialize(sw) sinet.connect(client_1) sinet.connect(client_2) sinet.connect(client_3) sinet.run(Message(client_1.address, client_3.address, u'Pacote ICMP')) sinet.run(Message(client_1.address, client_3.address, u'Pacote ICMP')) sinet.run(Message(client_1.address, client_2.address, u'Pacote ICMP')) sinet.run(Message(client_1.address, client_2.address, u'Pacote ICMP')) sinet.run(Message(client_2.address, client_3.address, u'Pacote ICMP')) sinet.run(Message(client_3.address, client_2.address, u'Pacote ICMP'))
def run_latency(warmup_time_s, upstream_ip, upstream_port, duration_s, ssl): switch = Switch(DPID("00:00:00:00:00:00:00:01"), warmup_time_s, upstream_ip, upstream_port, 1, False, ssl) switch.start() time.sleep(duration_s) print("stop!") switch.stop() FileWriter().write_results_to_file(switch.get_results())
def setUp(self): self.wiringCfg={ "0": [ 0 ], "1": [ 2 ], "2": [ 1 ] } self.switch=Switch(Wiring(self.wiringCfg))
def main(self): totalSwitches = int(input("How many switches you want?")) self.switches = [] for i in range(totalSwitches): totalPorts = int( input("Enter total number of ports for switch " + str(i) + ":")) self.switches.append(Switch(i, totalPorts)) print("Now time for connection configuration") for i in range(totalSwitches): print("Ports configuration for switch ", i) for j in range(self.switches[i].ports): a = int(input("Enter other switch ID:")) b = int(input("Enter other switch's port ID:")) self.switches[i].portsConf[j] = ["", a, b] for i in range(self.switches[0].ports): self.switches[0].portsConf[i][0] = "dp" #for first time root ports setting oppPorts = self.getOppositePorts("dp", self.switches[0]) listKeys = list(oppPorts.keys()) #keys of oppPorts dict self.rootSelectionFromRoot(oppPorts, listKeys) #get list of switches jin ke root port set ni hoi basic rp setting k bad nonRootList = self.getNonRootSwitches() #set nonRoot switche's port to rp one by one if nonRootList: portsDist = {} for i in range(len(nonRootList)): portsDist = {} currentSwitch = self.switches[nonRootList[i]] for j in range(currentSwitch.ports): currentPort = currentSwitch.portsConf[j] portsDist[j] = self.setRPOfNonROOT(currentSwitch, currentPort, dist=0) #work for dp print("thanks")
class TestSwitch(unittest.TestCase): def setUp(self): self.wiringCfg={ "0": [ 0 ], "1": [ 2 ], "2": [ 1 ] } self.switch=Switch(Wiring(self.wiringCfg)) def testSignal(self): self.assertEqual([0],self.switch.signalIn([0])) self.assertEqual([2],self.switch.signalIn([1])) self.assertEqual([1],self.switch.signalIn([2])) def testReverseSignal(self): self.assertEqual([0],self.switch.reverseSignal([0])) self.assertEqual([2],self.switch.reverseSignal([1])) self.assertEqual([1],self.switch.reverseSignal([2]))
def __init__(self,id,ip,binaad,binaid): self.id = id self.ip = ip self.binaid = binaid self.binaad = binaad SnmpProtocol2 = SnmpProtocol() switches = [] stmt = SnmpProtocol2.execute(ip, '1.3.6.1.2.1.4.22.1.1', '"INTEGER: 28"') eachline = stmt.splitlines () for i in eachline: a = (i.split ('.')) if (a[14].split (' ')[0] != '1'): ip =a[11] + "." + a[12] + "." + a[13] + "." + a[14].split (' ')[0] switch = Switch(ip) switches.append(switch) self.switches = switches
def __init__(self, pin_re, pin_sw, cb_func, chl=CH_LIST, debug=False): self.logger = init_logger(__class__.__name__, debug) self.logger.debug('pin_re:%s', pin_re) self.logger.debug('pin_sw:%d', pin_sw) self.logger.debug('chl :%s', chl) self.pin_re = pin_re self.pin_sw = pin_sw self.cb_func = cb_func self.chl = chl self.chl_len = len(self.chl) self.chl_i = 0 self.cur_ch = self.CH_LIST[self.chl_i] self.out_ch = '' self.rl = RotaryEncoderListener(self.pin_re, self.cb_re, debug=debug) self.sw = Switch(self.pin_sw, debug=debug) self.sl = SwitchListener([self.sw], self.cb_sw, debug=debug)
def __init__(self, encoder_left: Encoder, encoder_right: Encoder, imu: IMU): ### Switch On/Off self.switch_OnOff = Switch() ### Encoders self.encoder_left = encoder_left self.encoder_right = encoder_right ### IMU self.imu = imu ### PID self.PID_stab = PID(self.P_stab, self.I_stab, self.D_stab) self.PID_position = PID(self.P_position, self.I_position, self.D_position) ### Motors self.Motors = Motors()
log.quiet = options.quiet options.rate = if_else(options.verbose, options.rate, max(options.rate, 0.1)) options.version = VERSION options.max_update_time = 60 options.device = tokenize(options.device, 'device', []) options.cutoff_temp = tokenize(options.cutoff_temp, 'cutoff_temp', [95], float) options.cutoff_interval = tokenize(options.cutoff_interval, 'cutoff_interval', [0.01], float) switch = None try: switch = Switch(options) if not options.no_ocl: import OpenCLMiner for miner in OpenCLMiner.initialize(options): switch.add_miner(miner) if not options.no_bfl: import BFLMiner for miner in BFLMiner.initialize(options): switch.add_miner(miner) if not switch.servers: print '\nAt least one server is required\n' elif not switch.miners: print '\nNothing to mine on, exiting\n'
def OnMenuConnect(self, event): if (self.switch == None): self.switch = Switch(self.config, self.fielddef, self.package) self.switch.online() self.dataFrame.setSwitch(self.switch) self.switch.setTransactionThread(self.dataFrame)
def ascii_copy(self, db, switch_cons): """ This method is to """ sys = "" founds = 0 switch_cons.sendline('switchback') switch_cons.expect(defn.SWITCH_PROMPT) #For storing the kickstart and the system images switch_cons.sendline('show version | grep "image file is"') switch_cons.expect(defn.SWITCH_PROMPT) string = switch_cons.before if "///" in string: sys = string.split('///')[1] sys = sys.split()[0] if sys != "": switch_cons.sendline('dir') switch_cons.expect(defn.SWITCH_PROMPT) dir = switch_cons.before imgs = dir.split() if sys in imgs: founds = 1 logging.info("Found sys %d", founds) if founds == 1: db.update_images(self.switch_name, "", sys) else: db.update_images(self.switch_name, "", "") #Now write erase and copy the running config to file switch_cons.sendline('delete run_power_config n') switch_cons.expect(defn.SWITCH_PROMPT, 60) switch_cons.sendline('delete start_power_config n') switch_cons.expect(defn.SWITCH_PROMPT, 60) #no boot kick and sys switch_cons.sendline('config t') switch_cons.expect(defn.SWITCH_PROMPT, 60) switch_cons.sendline('no boot nxos') switch_cons.expect(defn.SWITCH_PROMPT, 60) #write erase switch_cons.sendline('write erase') switch_cons.expect('Do you wish to proceed anyway') switch_cons.sendline('y') switch_cons.expect(defn.SWITCH_PROMPT, 120) #write erase boot switch_cons.sendline('write erase boot') switch_cons.expect('Do you wish to proceed anyway') switch_cons.sendline('y') switch_cons.expect(defn.SWITCH_PROMPT, 120) "Now copy the running config to run_power_config file" switch_cons.sendline('show running-config vdc-all > run_power_config') i = switch_cons.expect( [defn.SWITCH_PROMPT, r'yes/no', pexpect.TIMEOUT, pexpect.EOF]) if i == 0: pass if i == 1: switch_cons.sendline('yes') switch_cons.expect(defn.SWITCH_PROMPT, 180) if i == 2 or i == 3: print "Something wrong with switch %s so go ahead and poweroff" % self.switch_name return False "Now copy the startup config to run_power_config file" switch_cons.sendline( 'show startup-config vdc-all > start_power_config') i = switch_cons.expect( [defn.SWITCH_PROMPT, r'yes/no', pexpect.TIMEOUT, pexpect.EOF]) if i == 0: pass if i == 1: switch_cons.sendline('yes') switch_cons.expect(defn.SWITCH_PROMPT, 180) if i == 2 or i == 3: print "Something wrong with switch %s so go ahead and poweroff" % self.switch_name return False Switch.setip(switch_cons, self.mgmt_ip) #Copy the kickstart and system image to server only if present if founds == 1: d_file = "%s/%s.system.gbin" % (self.switch_name, self.switch_name) Switch.copy_files_to_server(switch_cons=switch_cons, s_file=sys, d_file=d_file) d_file = "%s/%s.run_power_config" % (self.switch_name, self.switch_name) Switch.copy_files_to_server(switch_cons=switch_cons, s_file='run_power_config', d_file=d_file) d_file = "%s/%s.start_power_config" % (self.switch_name, self.switch_name) Switch.copy_files_to_server(switch_cons=switch_cons, s_file='start_power_config', d_file=d_file) return True
def copy_images_to_switch(self, log): """ This definition is to copy the right set of images to switch which has been used for sanities for other its not required so just return """ dir = '' logging.info("Copy the sys=%s images if not available to the switch", self.sys) console = pexpect.spawn('telnet %s %s' % (self.console_ip, self.act_port)) console.logfile = log time.sleep(2) console.sendline('') i = console.expect([ pexpect.TIMEOUT, pexpect.EOF, defn.SWITCH_LOGIN, defn.SWITCH_PROMPT, 'loader>.*' ], 120) if i == 0 or i == 1: logging.debug(str(console)) console.close() return if i == 2 or i == 3: if i == 2: console.sendline('admin') console.expect('assword:') console.sendline(self.switch_pwd) console.expect(defn.SWITCH_PROMPT) console.sendline('switchback') console.expect(defn.SWITCH_PROMPT) console.sendline('terminal length 0') console.expect(defn.SWITCH_PROMPT) console.sendline('dir') console.expect(defn.SWITCH_PROMPT) dirs = console.before if self.sys in dirs.split(): logging.info("Found the System image in bootflash") console.close() return logging.info("Did not find System image in bootflash") if i == 4: console.sendline('') console.expect('loader>.*') console.sendline('dir') console.expect('loader>.*') dirs = console.before if self.sys in dirs.split(): logging.info("Found the System image in bootflash") console.close() return logging.info("Did not find System image in bootflash") if i == 2 or i == 3: console.sendline('reload') console.expect('y/n') console.sendline('y') console.expect('loader>.*', 60) console.sendline('') i = console.expect([pexpect.TIMEOUT, pexpect.EOF, 'loader>.*']) if i == 0 or i == 1: logging.debug(str(console)) console.close() return if i == 2: console.sendline('dir') console.expect('loader>.*') imgs = n9kSwitch.get_images_in_switch(console.before) for im in imgs: match = re.match(r'n9.*dk9([0-9A-Za-z\.]+)', im) if match: break console.sendline('boot %s' % im) console.exit() console = self.load_or_telnet_image(log) Switch.setip(console, self.mgmt_ip) for img in imgs: console.sendline('delete bootflash:%s' % img) console.expect(defn.SWITCH_PROMPT) time.sleep(10) d_file = self.sys s_file = "%s/%s.system.gbin" % (self.switch_name, self.switch_name) Switch.copy_files_to_switch(switch_cons=console, s_file=s_file, d_file=d_file) d_file = "power_config" s_file = "%s/%s.run_power_config" % (self.switch_name, self.switch_name) Switch.copy_files_to_switch(switch_cons=console, s_file=s_file, d_file=d_file) s_file = "%s/%s.start_power_config" % (self.switch_name, self.switch_name) Switch.copy_files_to_switch(switch_cons=console, s_file=s_file, d_file=d_file) console.close() return
def ascii_copy(self, db, switch_cons): """ This method is to """ sys = "" founds = 0 switch_cons.sendline('switchback') switch_cons.expect(defn.SWITCH_PROMPT) #For storing the kickstart and the system images switch_cons.sendline('show version | grep "image file is"') switch_cons.expect(defn.SWITCH_PROMPT) string = switch_cons.before if "///" in string: sys = string.split('///')[1] sys = sys.split()[0] if sys != "": switch_cons.sendline('dir') switch_cons.expect(defn.SWITCH_PROMPT) dir = switch_cons.before imgs = dir.split() if sys in imgs: founds = 1 logging.info("Found sys %d", founds) if founds==1: db.update_images(self.switch_name,"",sys) else: db.update_images(self.switch_name,"","") #Now write erase and copy the running config to file switch_cons.sendline('delete run_power_config n') switch_cons.expect(defn.SWITCH_PROMPT, 60) switch_cons.sendline('delete start_power_config n') switch_cons.expect(defn.SWITCH_PROMPT, 60) #no boot kick and sys switch_cons.sendline('config t') switch_cons.expect(defn.SWITCH_PROMPT, 60) switch_cons.sendline('no boot nxos') switch_cons.expect(defn.SWITCH_PROMPT, 60) #write erase switch_cons.sendline('write erase') switch_cons.expect('Do you wish to proceed anyway') switch_cons.sendline('y') switch_cons.expect(defn.SWITCH_PROMPT, 120) #write erase boot switch_cons.sendline('write erase boot') switch_cons.expect('Do you wish to proceed anyway') switch_cons.sendline('y') switch_cons.expect(defn.SWITCH_PROMPT, 120) "Now copy the running config to run_power_config file" switch_cons.sendline('show running-config vdc-all > run_power_config') i = switch_cons.expect([defn.SWITCH_PROMPT,r'yes/no',pexpect.TIMEOUT, pexpect.EOF]) if i==0: pass if i==1: switch_cons.sendline('yes') switch_cons.expect(defn.SWITCH_PROMPT,180) if i==2 or i==3: print "Something wrong with switch %s so go ahead and poweroff" % self.switch_name return False "Now copy the startup config to run_power_config file" switch_cons.sendline('show startup-config vdc-all > start_power_config') i = switch_cons.expect([defn.SWITCH_PROMPT,r'yes/no',pexpect.TIMEOUT, pexpect.EOF]) if i==0: pass if i==1: switch_cons.sendline('yes') switch_cons.expect(defn.SWITCH_PROMPT,180) if i==2 or i==3: print "Something wrong with switch %s so go ahead and poweroff" % self.switch_name return False Switch.setip(switch_cons,self.mgmt_ip) #Copy the kickstart and system image to server only if present if founds==1: d_file = "%s/%s.system.gbin"%(self.switch_name,self.switch_name) Switch.copy_files_to_server(switch_cons=switch_cons,s_file=sys,d_file=d_file) d_file = "%s/%s.run_power_config"%(self.switch_name,self.switch_name) Switch.copy_files_to_server(switch_cons=switch_cons,s_file='run_power_config',d_file=d_file) d_file = "%s/%s.start_power_config"%(self.switch_name,self.switch_name) Switch.copy_files_to_server(switch_cons=switch_cons,s_file='start_power_config',d_file=d_file) return True
def selectNextAction(self, playerCurrentPokemon): # Want to select the edge that has min cost # Cost(action) = max damage could receive in current round + -(max damage could give in current round) # Total out edge = 4(moves of current pokemon) + numPokemonAlive(switches to the rest alive pokemon) numRemainingAlivePokemon = 0 remainingAliveIndexList = [] for pokemonNum in range(Constants.NUM_POKEMON_PER_PLAYER): if self.pokemons[pokemonNum] != self.currentPokemon: if self.pokemons[pokemonNum].isAlive(): numRemainingAlivePokemon += 1 remainingAliveIndexList.append(pokemonNum) costList = np.zeros(4 + numRemainingAlivePokemon) # Calculate what is the max damage AI could receive damageReceivedList = np.array([ calculateDamage(playerCurrentPokemon.getMove1().getName(), playerCurrentPokemon, self.currentPokemon), calculateDamage(playerCurrentPokemon.getMove2().getName(), playerCurrentPokemon, self.currentPokemon), calculateDamage(playerCurrentPokemon.getMove3().getName(), playerCurrentPokemon, self.currentPokemon), calculateDamage(playerCurrentPokemon.getMove4().getName(), playerCurrentPokemon, self.currentPokemon) ]) maxDamageReceived = np.max(damageReceivedList) maxDamageReceived = np.ones(4) * maxDamageReceived # Calculate what is the max damage the AI can do damageGiveList = np.array([ calculateDamage(self.currentPokemon.getMove1().getName(), self.currentPokemon, playerCurrentPokemon), calculateDamage(self.currentPokemon.getMove2().getName(), self.currentPokemon, playerCurrentPokemon), calculateDamage(self.currentPokemon.getMove3().getName(), self.currentPokemon, playerCurrentPokemon), calculateDamage(self.currentPokemon.getMove4().getName(), self.currentPokemon, playerCurrentPokemon) ]) costList[:4] = maxDamageReceived - damageGiveList # (4,) damageReceivedSwitchList = np.zeros(numRemainingAlivePokemon) indexInCostList = 4 for index in remainingAliveIndexList: pokemonToSwitch = self.pokemons[index] damageReceivedList = np.array([ calculateDamage(playerCurrentPokemon.getMove1().getName(), playerCurrentPokemon, pokemonToSwitch), calculateDamage(playerCurrentPokemon.getMove2().getName(), playerCurrentPokemon, pokemonToSwitch), calculateDamage(playerCurrentPokemon.getMove3().getName(), playerCurrentPokemon, pokemonToSwitch), calculateDamage(playerCurrentPokemon.getMove4().getName(), playerCurrentPokemon, pokemonToSwitch) ]) maxDamageReceived = np.max(damageReceivedList) costList[indexInCostList] = maxDamageReceived indexInCostList += 1 # Select the min cost edge minEdgeIndex = np.argmin(costList) if minEdgeIndex <= 3: # If the best action is one of the current pokemon moves moveOptions = [ self.currentPokemon.getMove1(), self.currentPokemon.getMove2(), self.currentPokemon.getMove3(), self.currentPokemon.getMove4() ] return moveOptions[minEdgeIndex] else: # If the best action is switching offset = minEdgeIndex - 4 pokemonToSwitchIndex = remainingAliveIndexList[offset] self.currentPokemon = self.pokemons[pokemonToSwitchIndex] return Switch(pokemonToSwitchIndex)
class EosIpCommand_test(unittest.TestCase): def setUp(self): self.switch = Switch() vlan = VLAN('vlan1', 1, None) self.switch.add_vlan(vlan) self.cmd = EosIpCommand(None, self.switch) def test_default_unknownCommand(self): argStr = 'unknown' result = self.cmd.onecmd(argStr) self.assertIn('NOTICE', result) self.assertIn('unknown command', result) def test_default_accessGroup(self): argStr = 'access-group' self.cmd._do_access_group = Mock(return_value=None) self.cmd.onecmd(argStr) self.assertEqual(1, self.cmd._do_access_group.call_count) def test_do_access_group_noArgument(self): result = self.cmd._do_access_group('') self.assertIn('ERROR', result) self.assertIn('argument', result) def test_do_access_group_statementOccursOutsideRouterInterfaceMode(self): # TO-DO Is state correctly handled? result = self.cmd._do_access_group('1') self.assertIn('ERROR', result) self.assertIn('router interface', result) def test_set_state(self): old_state = self.cmd._state self.assertNotEqual(old_state, self.cmd.set_state('interface')) def test_do_access_group_invalidInterface(self): self.cmd.set_state(('router', 'config', 'interface ge.1.1')) result = self.cmd._do_access_group('1') self.assertIn('ERROR', result) self.assertIn('unknown interface', result) def test_do_access_group_InterfaceIsLoopback(self): self.cmd.set_state(('router', 'config', 'interface loopback 3')) result = self.cmd._do_access_group('1') self.assertIn('ERROR', result) self.assertIn('ACLs', result) self.assertIn('loopback interface', result) def test_do_access_group_InterfaceVlanIdIsInvalid(self): self.cmd.set_state(('router', 'config', 'interface vlan 0')) result = self.cmd._do_access_group('1') self.assertIn('ERROR', result) self.assertIn('Illegal VLAN ID', result) def test_do_access_group_sequenceIsIgnored(self): self.cmd.set_state(('router', 'config', 'interface vlan 1')) result = self.cmd._do_access_group(('1', 'sequence', '1')) self.assertIn('WARN', result) self.assertIn('Ignoring', result) self.assertIn('sequence', result) self.assertIn('in', result) def test_do_access_group_vlanDoesNotExist(self): self.cmd.set_state(('router', 'config', 'interface vlan 2')) result = self.cmd._do_access_group('1') self.assertIn('ERROR', result) self.assertIn('exist', result) def test_do_access_group_invalidACLNumber(self): self.cmd.set_state(('router', 'config', 'interface vlan 1')) result = self.cmd._do_access_group('a') self.assertIn('NOTICE', result) self.assertIn('unknown command', result) def test_do_access_group_unsupportedDirection(self): self.cmd.set_state(('router', 'config', 'interface vlan 1')) result = self.cmd._do_access_group(('1', 'out')) self.assertIn('ERROR', result) self.assertIn('direction', result) ##### ##### def test_default_helperAddress(self): argStr = 'helper-address' self.cmd._do_helper_address = Mock(return_value=None) self.cmd.onecmd(argStr) self.assertEqual(1, self.cmd._do_helper_address.call_count) def test_do_helper_address_noArgument(self): result = self.cmd._do_helper_address('') self.assertIn('ERROR', result) self.assertIn('argument', result) def test_do_helper_address_excessArgument(self): arg_list = ['192.0.2.47', 'excess arg'] result = self.cmd._do_helper_address(arg_list) self.assertIn('NOTICE', result) self.assertIn('unknown', result) self.assertIn('excess', result) def test_do_helper_address_statementOccursOutsideRouterInterfaceMode(self): arg_list = ['192.0.2.47'] result = self.cmd._do_helper_address(arg_list) self.assertIn('ERROR', result) self.assertIn('router interface', result) def test_do_helper_address_unknownInterface(self): arg_list = ['192.0.2.47'] self.cmd.set_state(('router', 'interface')) result = self.cmd._do_helper_address(arg_list) self.assertIn('ERROR', result) self.assertIn('unknown interface', result) def test_do_helper_address_interfaceIsLoopback(self): arg_list = ['192.0.2.47'] self.cmd.set_state(('router', 'interface loopback 3')) result = self.cmd._do_helper_address(arg_list) self.assertIn('ERROR', result) self.assertIn('loopback interface', result) def test_do_helper_address_interfaceIsVLANwithIDNull(self): arg_list = ['192.0.2.47'] self.cmd.set_state(('router', 'interface vlan -1')) result = self.cmd._do_helper_address(arg_list) self.assertIn('ERROR', result) self.assertIn('Illegal', result) self.assertIn('-1', result) def test_do_helper_address_interfaceIsVLANwithID4096(self): arg_list = ['192.0.2.47'] self.cmd.set_state(('router', 'interface vlan 4096')) result = self.cmd._do_helper_address(arg_list) self.assertIn('ERROR', result) self.assertIn('Illegal', result) self.assertIn('4096', result) def test_do_helper_address_interfaceIsVLANNotDefinedForSwitch(self): arg_list = ['192.0.2.47'] self.cmd.set_state(('router', 'interface vlan 4095')) result = self.cmd._do_helper_address(arg_list) self.assertIn('ERROR', result) self.assertIn('does not exist', result) self.assertIn('4095', result) def test_do_helper_address_invalidIPv4Address(self): arg_list = ['192.0.2.477'] self.cmd.set_state(('router', 'interface vlan 1')) result = self.cmd._do_helper_address(arg_list) self.assertIn('ERROR', result) self.assertIn('invalid', result) self.assertIn('477', result) def test_do_helper_address_sucess(self): arg_list = ['192.0.2.47'] self.cmd.set_state(('router', 'interface vlan 2')) vlan2_mock = Mock(spec=VLAN) vlan2_mock.get_tag.return_value = 2 self.switch.add_vlan(vlan2_mock) result = self.cmd._do_helper_address(arg_list) self.assertEqual('', result) vlan2_mock.add_ipv4_helper_address.assert_called_once_with(arg_list[0]) def test_do_address(self): confFragment = 'address' self.cmd.do_address = Mock(return_value=None) self.cmd.onecmd(confFragment) self.assertEqual(1, self.cmd.do_address.call_count) def test_do_address_noArgument(self): result = self.cmd.do_address('') self.assertIn('ERROR', result) self.assertIn('argument', result) def test_do_address_statementOccursOutsideRouterInterfaceMode(self): arg_str = '192.0.2.47' result = self.cmd.do_address(arg_str) self.assertIn('ERROR', result) self.assertIn('router interface', result) def test_do_address_argumentTooSmall(self): arg_str = '192.0.2.47' self.cmd.set_state(('router', 'interface vlan 2')) result = self.cmd.do_address(arg_str) self.assertIn('NOTICE', result) self.assertIn('unknown command', result) def test_do_address_WrongArgument(self): arg_str = '192.0.2.77 255.255.256.0' self.cmd.set_state(('router', 'interface vlan 2')) result = self.cmd.do_address(arg_str) self.assertIn('NOTICE', result) self.assertIn('unknown command', result) self.assertIn('invalid IPv4 address', result) def test_do_address_interfaceIsNotVLANOrLoopback(self): arg_str = '192.0.2.77 255.255.255.0' self.cmd.set_state(('router', 'interface ge.1.1 2')) result = self.cmd.do_address(arg_str) self.assertIn('ERROR', result) self.assertIn('unknown interface', result) def test_do_address_interfaceInvalidVlanId(self): arg_str = '192.0.2.77 255.255.255.0' self.cmd.set_state(('router', 'interface vlan 0')) result = self.cmd.do_address(arg_str) self.assertIn('ERROR', result) self.assertIn('Illegal VLAN ID', result) def test_do_address_interfaceInvalidLoopbackNumber(self): arg_str = '192.0.2.77 255.255.255.0' self.cmd.set_state(('router', 'interface loopback 8')) result = self.cmd.do_address(arg_str) self.assertIn('ERROR', result) self.assertIn('Illegal Loopback ID', result) def test_do_address_interfaceNotDefinedForSwitch(self): arg_str = '192.0.2.77 255.255.255.0' self.cmd.set_state(('router', 'interface loopback 2')) result = self.cmd.do_address(arg_str) self.assertIn('ERROR', result) self.assertIn('Interface', result) self.assertIn('not defined', result) def test_do_address_vlanOk(self): arg_str = '192.0.2.77 255.255.255.0' self.cmd.set_state(('router', 'interface vlan 1')) result = self.cmd.do_address(arg_str) self.assertEqual('', result) def test_do_address_loopbackOk(self): arg_str = '192.0.2.77 255.255.255.0' self.cmd.set_state(('router', 'interface loopback 0')) self.switch.add_loopback(0) result = self.cmd.do_address(arg_str) self.assertEqual('', result) ##### ##### def test_do_routing(self): confFragment = 'routing' self.cmd.do_routing = Mock(return_value=None) self.cmd.onecmd(confFragment) self.assertEqual(1, self.cmd.do_routing.call_count) def test_do_routing_unknownArg(self): result = self.cmd.do_routing('arg') self.assertIn('NOTICE', result) self.assertIn('Ignoring unknown', result) def test_do_routing_ok(self): result = self.cmd.do_routing('') self.assertEqual('', result) ##### ##### def test_do_route(self): confFragment = 'route' self.cmd.do_route = Mock(return_value=None) self.cmd.onecmd(confFragment) self.assertEqual(1, self.cmd.do_route.call_count) def test_do_route_noArg(self): result = self.cmd.do_route('') self.assertIn('ERROR', result) self.assertIn('needs argument', result) def test_do_route_statementOccursOutsideRouterConfigureMode(self): argStr = '192.0.3.0 255.255.255.0 192.0.2.77' result = self.cmd.do_route(argStr) self.assertIn('INFO', result) self.assertIn('outside', result) def test_do_route_wrongNrOfArg(self): argStr = '192.0.3.477 255.255.255.0' result = self.cmd.do_route(argStr) self.assertIn('NOTICE', result) self.assertIn('unknown', result) def test_do_route_wrongTypeOfArg(self): argStr = '192.0.a.77 255.255.255.0 192.0.2.77' result = self.cmd.do_route(argStr) self.assertIn('NOTICE', result) self.assertIn('unknown', result) def test_do_route_wrongIpAddress(self): argStr = '192.0.3.77 255.255.256.0 192.0.2.77' result = self.cmd.do_route(argStr) self.assertIn('NOTICE', result) self.assertIn('invalid', result) def test_do_route_ok(self): argStr = '192.0.3.77 255.255.255.0 192.0.2.77' self.cmd.set_state(('router', 'configure')) result = self.cmd.do_route(argStr) self.assertEqual('', result)
host = input("Host: ") username = input("Login: "******"host": host, "username": username, "password": password, "secret": password, "device_type": "ubiquiti_edge", } net_connect = Netmiko(**edge1) switch = Switch(interpreter.getDeviceName(net_connect.find_prompt())) switch.addVlanList(net_connect.send_command("show vlan")) switch.addPortToPorts(net_connect.send_command("show vlan port all")) while True: mainMenu.printMenu() choice = input("Choose: ") if choice == "1": for vlan in switch.getVlans(): print(vlan.getDescription() + " " + vlan.getNumber()) elif choice == "2": for port in switch.getPorts(): print(port.getPortNr() + " " + port.getPortVlan()) elif choice == "3": switch = Switch(interpreter.getDeviceName(net_connect.find_prompt())) switch.addVlanList(net_connect.send_command("show vlan"))
#!/usr/bin/env python import sys import yaml import Command from Task import Task from Switch import Switch from Variables import Variables from Result import Result with open(sys.argv[2]) as f: yml = yaml.load(f, Loader=yaml.SafeLoader) with open('/Users/hirano.shigetoshi/fzfyml_list.txt', 'a') as f: f.write(sys.argv[2] + '\n') variables = Variables(sys.argv) switch = Switch(yml.get('switch_task', {}), variables) base_task = Task(yml['base_task'], variables, switch.get_expect()) task = base_task if sys.argv[1] == 'run': while True: r = Command.execute(task.get_cmd()) result = Result(r, task.get_transform()) if result.is_empty(): break if switch.has(result.key): variables.set_pre_result(result) task = task.create_switch_task(switch.get_switch_dict(result.key)) else: task.output(result) break
#!/usr/bin/env python3 ''' This program tests whether the switch is working by continuously checking the state, and printing a message when it detects a switch change ''' from Switch import Switch s = Switch() while True: if s.is_changed_state(): print("switch pressed")
class StartMaker(): ip = IP() host = [] enlacePP = [] enlacePP = [] switch = [] router = [] nic_host = [] nic_switch = [] nic_router = [] # All Class Objects store in arrays[n] started 0 to n-1 # Start Hosts 0~11 for n in range(0,12): host.append(Host()) # Start Enlace 0~21 for n in range(0,22): enlacePP.append(EnlacePP()) # Start Switchs 0~2 for n in range(0,3): switch.append(Switch()) switch[0].setNome('switch_0') switch[1].setNome('Switch_1') switch[2].setNome('Switch_2') # Start Routers 0~2 for n in range(0,3): router.append(Router()) router[0].setNome('Router_0') router[1].setNome('Router_1') router[2].setNome('Router_2') # Start Hosts-NICs ( 12th ) # NIC receved MAC, Enlace and Host # Network 201.10.0.0 nic_host.append(NIC('01:0A:00:FF:0A:01',enlacePP[0],host[0])) nic_host.append(NIC('02:0A:00:FF:0A:02',enlacePP[1],host[1])) nic_host.append(NIC('03:0A:00:FF:0A:03',enlacePP[2],host[2])) nic_host.append(NIC('04:0A:00:FF:0A:04',enlacePP[3],host[3])) # Network 200.171.0.0 nic_host.append(NIC('05:0B:00:EE:0B:05',enlacePP[5],host[4])) nic_host.append(NIC('06:0B:00:EE:0B:06',enlacePP[6],host[5])) nic_host.append(NIC('07:0B:00:EE:0B:07',enlacePP[7],host[6])) nic_host.append(NIC('08:0B:00:EE:0B:08',enlacePP[8],host[7])) # Network 192.168.0.0 nic_host.append(NIC('09:0C:00:CC:0C:09',enlacePP[10],host[8])) nic_host.append(NIC('0A:0C:00:CC:0C:0A',enlacePP[11],host[9])) nic_host.append(NIC('0B:0C:00:CC:0C:0B',enlacePP[12],host[10])) nic_host.append(NIC('0C:0C:00:CC:0C:0C',enlacePP[13],host[11])) # Start Switchs-NICs ( 15th ) # Nic receved MAC, Enlace and Switch # Switch 0 nic_switch.append(NIC('040A7119SW01',enlacePP[0],switch[0])) nic_switch.append(NIC('040A7119SW02',enlacePP[1],switch[0])) nic_switch.append(NIC('040A7119SW03',enlacePP[2],switch[0])) nic_switch.append(NIC('040A7119SW04',enlacePP[3],switch[0])) # Dedicated Router 0 - Network 201.10.0.0 nic_switch.append(NIC('040A7119SW05',enlacePP[4],switch[0]))# Local Network 201.10.0.0 # Switch 1 nic_switch.append(NIC('040A7119SW06',enlacePP[5],switch[1])) nic_switch.append(NIC('040A7119SW07',enlacePP[6],switch[1])) nic_switch.append(NIC('040A7119SW08',enlacePP[7],switch[1])) nic_switch.append(NIC('040A7119SW09',enlacePP[8],switch[1])) # Dedicated Router 1 - Network 200.171.0.0 nic_switch.append(NIC('0040A7119SW10',enlacePP[9],switch[1]))# Local Network 200.171.0.0 # Switch 2 nic_switch.append(NIC('040A7119SW11',enlacePP[10],switch[2])) nic_switch.append(NIC('040A7119SW12',enlacePP[11],switch[2])) nic_switch.append(NIC('040A7119SW13',enlacePP[12],switch[2])) nic_switch.append(NIC('040A7119SW14',enlacePP[13],switch[2])) # Dedicated Router 2 - 192.168.0.0 nic_switch.append(NIC('040A7119SW15',enlacePP[14],switch[2]))# Local Network 192.168.0.0 # Start Routers-NICs ( 12th ) # Router 0 Networks 10.0.0.0 and 201.10.0.0 nic_router.append(NIC('040A7119SR01',enlacePP[4],router[0])) # Network 201.10.0.0 - Local nic_router.append(NIC('040A7119SR02',enlacePP[15],router[0])) # Network 10.0.0.0 nic_router.append(NIC('040A7119SR03',enlacePP[16],router[0])) # unused nic_router.append(NIC('040A7119SR04',enlacePP[17],router[0])) # unused # Router 1 Networks 10.0.0.0, 11.0.0.0 and 200.171.0.0 nic_router.append(NIC('040A7119SR05',enlacePP[15],router[1])) # Network 10.0.0.0 - 201.10.0.0 nic_router.append(NIC('040A7119SR06',enlacePP[18],router[1])) # Network 11.0.0.0 - 192.168.0.0 nic_router.append(NIC('040A7119SR07',enlacePP[9],router[1])) # Network 200.171.0.0 - Local nic_router.append(NIC('040A7119SR08',enlacePP[19],router[1])) # Internet # Router 2 Networks 11.0.0.0 and 192.168.0.0 nic_router.append(NIC('040A7119SR09',enlacePP[18],router[2])) # Network 11.0.0.0 nic_router.append(NIC('040A7119SR10',enlacePP[14],router[2])) # Network 192.168.0.0 - Local nic_router.append(NIC('040A7119SR11',enlacePP[20],router[2])) # unused nic_router.append(NIC('040A7119SR12',enlacePP[21],router[2])) # unused # Set Routers IP router[0].setIP('201.10.0.1') router[1].setIP('200.171.0.1') router[2].setIP('192.168.0.1') # Adding Routes #router.setRota(Rota('<destination>','<route>','<mask>', '<metric>', '<MAC>')) # Router 0 to Router 1 Network A router[0].setRota(Rota('201.10.0.0','201.10.0.1','255.255.0.0', '0', '040A7119SR01')) # Network 201.10.0.0 - Local router[0].setRota(Rota('200.171.0.0','200.171.0.1','255.255.0.0', '0', '040A7119SR02')) router[0].setRota(Rota('192.168.0.0','192.168.0.1','255.255.0.0', '0', '040A7119SR02')) router[0].setRota(Rota('10.0.0.0','10.0.0.1','255.0.0.0', '0', '040A7119SR02')) router[0].setRotaDefault(Rota('10.0.0.0','10.0.0.1','255.0.0.0', '0', '040A7119SR02')) # Router 1 Network 01, 02 and 04 router[1].setRota(Rota('200.171.0.0','200.171.0.1','255.255.0.0', '0', '040A7119SR07')) # Network 200.171.0.0 - Local router[1].setRota(Rota('201.10.0.0','201.10.0.1','255.255.0.0', '0', '040A7119SR05')) # Network 10.0.0.0 - 201.10.0.0 router[1].setRota(Rota('10.0.0.0','10.0.0.1','255.0.0.0', '0', '040A7119SR05')) # Network 10.0.0.0 - R05 router[1].setRota(Rota('192.168.0.0','192.168.0.1','255.255.0.0', '0', '040A7119SR06')) # Network 11.0.0.0 - 192.168.0.0 router[1].setRota(Rota('11.0.0.0','11.0.0.1','255.0.0.0', '0', '040A7119SR06')) # Network 11.0.0.0 - R06 router[1].setRotaDefault(Rota('0.0.0.0','0.0.0.0','0.0.0.0', '0', 'INTERNET')) # Router 2 Network 02 and 05 router[2].setRota(Rota('192.168.0.0','192.168.0.1','255.255.0.0', '0', '040A7119SR10')) # Network 192.168.0.0 - Local router[2].setRota(Rota('11.0.0.0','11.0.0.1','255.0.0.0', '0', '040A7119SR09')) router[2].setRota(Rota('200.171.0.0','200.171.0.1','255.255.0.0', '0', '040A7119SR09')) router[2].setRota(Rota('201.10.0.0','201.10.0.1','255.255.0.0', '0', '040A7119SR09')) router[2].setRotaDefault(Rota('11.0.0.0','11.0.0.1','255.0.0.0', '0', '040A7119SR09')) # HOSTs reset IPs# for n in range(0,12): host[n].setIP('ip-not-found') host[n].setMascara('255.255.0.0') host[n].setLigado(False) nic_host[n].setLigado(False) nic_host[n].setTDados(False) host[n].resetPing() # SWITCHs reset# switch[0].setLigado(False) for n in range(0,5): nic_switch[n].setLigado(False) nic_switch[n].setTDados(False) switch[1].setLigado(False) for n in range(5,10): nic_switch[n].setLigado(False) nic_switch[n].setTDados(False) switch[2].setLigado(False) for n in range(10,15): nic_switch[n].setLigado(False) nic_switch[n].setTDados(False) # ROUTERs # router[0].setLigado(False) for n in range(0,4): nic_router[n].setLigado(False) nic_router[n].setTDados(False) router[1].setLigado(False) for n in range(4,8): nic_router[n].setLigado(False) nic_router[n].setTDados(False) router[2].setLigado(False) for n in range(8,12): nic_router[n].setLigado(False) nic_router[n].setTDados(False)
def __init__(self, switch): Switch.__init__(self, switch)
def selectNextActionTyping(self, playerCurrentPokemon, allPlayerPokemon): numRemainingAlivePokemon = 0 remainingAliveIndexList = [] for pokemonNum in range(Constants.NUM_POKEMON_PER_PLAYER): if self.pokemons[pokemonNum] != self.currentPokemon: if self.pokemons[pokemonNum].isAlive(): numRemainingAlivePokemon += 1 remainingAliveIndexList.append(pokemonNum) costList = np.zeros(1 + numRemainingAlivePokemon) oppMultiplierList = np.array([ getMultiplier(playerCurrentPokemon.getMove1().getName(), playerCurrentPokemon, self.currentPokemon), getMultiplier(playerCurrentPokemon.getMove2().getName(), playerCurrentPokemon, self.currentPokemon), getMultiplier(playerCurrentPokemon.getMove3().getName(), playerCurrentPokemon, self.currentPokemon), getMultiplier(playerCurrentPokemon.getMove4().getName(), playerCurrentPokemon, self.currentPokemon) ]) maxOppMultiplier = np.max(oppMultiplierList) # Calculate what is the max damage the AI can do aiMultiplierList = np.array([ getMultiplier(self.currentPokemon.getMove1().getName(), self.currentPokemon, playerCurrentPokemon), getMultiplier(self.currentPokemon.getMove2().getName(), self.currentPokemon, playerCurrentPokemon), getMultiplier(self.currentPokemon.getMove3().getName(), self.currentPokemon, playerCurrentPokemon), getMultiplier(self.currentPokemon.getMove4().getName(), self.currentPokemon, playerCurrentPokemon) ]) maxAIMultiplier = np.max(aiMultiplierList) # compute cost edgeCost = 0 diff = maxAIMultiplier - maxOppMultiplier if diff >= 1.0: edgeCost = 1.0 elif (0 >= diff and diff < 1.0): edgeCost = 2.0 else: edgeCost = 4.0 # compute heuristic minHeuristicCurr = 0 for aiPoke in self.pokemons: if not (aiPoke.isAlive()): continue heuristic = 0 for oppPoke in allPlayerPokemon: if not (oppPoke.isAlive()): continue # Calculate what is the max damage the AI can do damageGiveList = np.array([ calculateDamage(self.currentPokemon.getMove1().getName(), self.currentPokemon, oppPoke), calculateDamage(self.currentPokemon.getMove2().getName(), self.currentPokemon, oppPoke), calculateDamage(self.currentPokemon.getMove3().getName(), self.currentPokemon, oppPoke), calculateDamage(self.currentPokemon.getMove4().getName(), self.currentPokemon, oppPoke) ]) maxDamageDealt = np.max(damageGiveList) # to incentivize staying in, skip current pokemon if you can kill it if oppPoke.getBattleHP() - maxDamageDealt <= 0: continue oppMultiplierList = np.array([ getMultiplier(oppPoke.getMove1().getName(), oppPoke, aiPoke), getMultiplier(oppPoke.getMove2().getName(), oppPoke, aiPoke), getMultiplier(oppPoke.getMove3().getName(), oppPoke, aiPoke), getMultiplier(oppPoke.getMove4().getName(), oppPoke, aiPoke) ]) maxOppMultiplier = np.max(oppMultiplierList) aiMultiplierList = np.array([ getMultiplier(aiPoke.getMove1().getName(), aiPoke, oppPoke), getMultiplier(aiPoke.getMove2().getName(), aiPoke, oppPoke), getMultiplier(aiPoke.getMove3().getName(), aiPoke, oppPoke), getMultiplier(aiPoke.getMove4().getName(), aiPoke, oppPoke) ]) maxAIMultiplier = np.max(aiMultiplierList) diff = maxAIMultiplier - maxOppMultiplier if diff >= 1.0: heuristic += 1.0 elif (0 >= diff and diff < 1.0): heuristic += 2.0 else: heuristic += 4.0 minHeuristicCurr = min(minHeuristicCurr, heuristic) costList[0] = edgeCost + minHeuristicCurr minHeuristicRest = 0 for aiPoke in self.pokemons: if not (aiPoke.isAlive()): continue heuristic = 0 for oppPoke in allPlayerPokemon: if not (oppPoke.isAlive()): continue oppMultiplierList = np.array([ getMultiplier(oppPoke.getMove1().getName(), oppPoke, aiPoke), getMultiplier(oppPoke.getMove2().getName(), oppPoke, aiPoke), getMultiplier(oppPoke.getMove3().getName(), oppPoke, aiPoke), getMultiplier(oppPoke.getMove4().getName(), oppPoke, aiPoke) ]) maxOppMultiplier = np.max(oppMultiplierList) aiMultiplierList = np.array([ getMultiplier(aiPoke.getMove1().getName(), aiPoke, oppPoke), getMultiplier(aiPoke.getMove2().getName(), aiPoke, oppPoke), getMultiplier(aiPoke.getMove3().getName(), aiPoke, oppPoke), getMultiplier(aiPoke.getMove4().getName(), aiPoke, oppPoke) ]) maxAIMultiplier = np.max(aiMultiplierList) diff = maxAIMultiplier - maxOppMultiplier if diff >= 1.0: heuristic += 1.0 elif (0 >= diff and diff < 1.0): heuristic += 2.0 else: heuristic += 4.0 minHeuristicRest = min(minHeuristicRest, heuristic) # repeat for switching indexInCostList = 1 for i in remainingAliveIndexList: aiPoke = self.pokemons[i] oppMultiplierList = np.array([ getMultiplier(playerCurrentPokemon.getMove1().getName(), playerCurrentPokemon, aiPoke), getMultiplier(playerCurrentPokemon.getMove2().getName(), playerCurrentPokemon, aiPoke), getMultiplier(playerCurrentPokemon.getMove3().getName(), playerCurrentPokemon, aiPoke), getMultiplier(playerCurrentPokemon.getMove4().getName(), playerCurrentPokemon, aiPoke) ]) maxOppMultiplier = np.max(oppMultiplierList) # Calculate what is the max damage the AI can do aiMultiplierList = np.array([ getMultiplier(aiPoke.getMove1().getName(), aiPoke, playerCurrentPokemon), getMultiplier(aiPoke.getMove2().getName(), aiPoke, playerCurrentPokemon), getMultiplier(aiPoke.getMove3().getName(), aiPoke, playerCurrentPokemon), getMultiplier(aiPoke.getMove4().getName(), aiPoke, playerCurrentPokemon) ]) maxAIMultiplier = np.max(aiMultiplierList) edgeCost = 0 diff = maxAIMultiplier - maxOppMultiplier if diff >= 1.0: edgeCost = 1.0 elif (0 >= diff and diff < 1.0): edgeCost = 2.0 else: edgeCost = 4.0 costList[indexInCostList] = edgeCost + minHeuristicRest indexInCostList += 1 # Select the min cost edge minEdgeIndex = np.argmin(costList) if minEdgeIndex == 0: # If the best action is one of the current pokemon moves moveOptions = [ self.currentPokemon.getMove1(), self.currentPokemon.getMove2(), self.currentPokemon.getMove3(), self.currentPokemon.getMove4() ] damageGiveList = np.array([ calculateDamage(self.currentPokemon.getMove1().getName(), self.currentPokemon, playerCurrentPokemon), calculateDamage(self.currentPokemon.getMove2().getName(), self.currentPokemon, playerCurrentPokemon), calculateDamage(self.currentPokemon.getMove3().getName(), self.currentPokemon, playerCurrentPokemon), calculateDamage(self.currentPokemon.getMove4().getName(), self.currentPokemon, playerCurrentPokemon) ]) bestMoveIndex = np.argmax(damageGiveList) return moveOptions[bestMoveIndex] else: # If the best action is switching offset = minEdgeIndex - 1 pokemonToSwitchIndex = remainingAliveIndexList[offset] self.currentPokemon = self.pokemons[pokemonToSwitchIndex] return Switch(pokemonToSwitchIndex)
if __name__ == "__main__": db = Database('127.0.0.1', 'root', '', 'ilab') print "Sit back and relax will take some time..." print "(DO NOT CTRL+C)" strfile = '%ssw_details.log' % defn.log_dir cli_cmd = 'rm %s' % (strfile) subprocess.call(cli_cmd, shell=True) fout = file(strfile, 'a') logging.basicConfig(filename=strfile, format='%(asctime)s: %(levelname)s : %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p', level=logging.DEBUG) switches = db.select('switches_test',None,'*') for switch in switches sw = Switch(switch_name = str(switch['switch_name']), \ console_ip = str(switch['console_ip']), \ mgmt_ip = str(switch['mgmt_ip']), \ act_port = str(switch['active_port']), \ stnd_port = str(switch['standby_port']), \ switch_pwd = str(switch['switch_pwd']), \ console_pwd = 'nbv123', \ log = strfile, \ kick = str(switch['kickstart']), \ sys = str(switch['system'])) switch_details(db,sw,fout) print "Collected all the Current Details"
class MainFrame(wx.Frame): def __init__(self, parent, title, theProject, fielddef, config, package, transDescs): self.theProject = theProject self.config = config self.fielddef = fielddef self.package = package self.transDescs = transDescs self.switch = None self.splitter = None self.configChanged = False wx.Frame.__init__(self, parent, -1, title, wx.Point(200, 200), wx.Size(800, 600)) wx.EVT_SIZE(self, self.OnSize) self.Menubar = wx.MenuBar(wx.MB_DOCKABLE) wx.EVT_MENU(self, 0x201, self.OnMenuClose) wx.EVT_MENU(self, 0x203, self.OnMenuConnect) wx.EVT_MENU(self, 0x204, self.OnMenuDisconnect) wx.EVT_MENU(self, 0x205, self.OnMenuSetting) wx.EVT_MENU(self, 0x206, self.OnMenuHelp) FileMenu = wx.Menu("", wx.MENU_TEAROFF) FileMenu.Append(0x201, "Exit", "") self.Menubar.Append(FileMenu, "File") MngMenu = wx.Menu("", wx.MENU_TEAROFF) MngMenu.Append(0x203, "Open Connection", "") MngMenu.Append(0x204, "Close Connection", "") MngMenu.Append(0x205, "Setting", "") self.Menubar.Append(MngMenu, "Managment") HelpMenu = wx.Menu("", wx.MENU_TEAROFF) HelpMenu.Append(0x206, "About") self.Menubar.Append(HelpMenu, "Help") self.SetMenuBar(self.Menubar) self.splitter = wx.SplitterWindow(self, -1, style=wx.SP_3D) if doingStressTest: self.dataFrame = StressTestFrame(self.splitter, self.package, self.transDescs) else: self.dataFrame = SingleCaseFrame(self.splitter, self.package, self.transDescs) self.logFrame = MsgLogFrame(self.splitter, -1) self.splitter.SplitVertically(self.dataFrame, self.logFrame, 550) self.dataFrame._logFrame = self.logFrame wx.EVT_CLOSE(self, self.OnCloseWindow) icon = wx.Icon('icons/Simulator.ico', wx.BITMAP_TYPE_ICO) self.SetIcon(icon) def OnCloseWindow(self, event): if self.configChanged: SaveConfiguration(self.theProject, self.config) if (self.switch != None): self.switch.quit() self.dataFrame.OnCloseWindow(event) self.Destroy() event.Skip() def OnSize(self, event): size = self.GetClientSize() if (self.splitter != None): self.splitter.SetSize(size) event.Skip() def OnMenuClose(self, event): self.Close() event.Skip() def OnMenuOpen(self, event): dlg = wx.FileDialog(self) btn = dlg.ShowModal() if (btn == wx.ID_OK): filename = dlg.GetPath() self.transDesc = CreateTransDescObject(self.fields, filename, self.config) self.dataFrame.setTransDesc(self.transDesc) self.config['case'] = filename return def OnMenuConnect(self, event): if (self.switch == None): self.switch = Switch(self.config, self.fielddef, self.package) self.switch.online() self.dataFrame.setSwitch(self.switch) self.switch.setTransactionThread(self.dataFrame) def OnMenuDisconnect(self, event): if (self.switch != None): self.switch.quit() self.switch = None self.dataFrame.setSwitch(None) def OnMenuSetting(self, event): dlg = SettingDialog(self, "Setting Dialog", self.config) dlg.CenterOnScreen() val = dlg.ShowModal() if (val == wx.ID_OK): if dlg.changed: self.config = dlg.config self.configChanged = true dlg.Destroy() def OnMenuHelp(self, event): dlg = AboutDialog(self, "About") dlg.CenterOnScreen() dlg.ShowModal() dlg.Destroy()
log.quiet = options.quiet options.rate = if_else(options.verbose, max(options.rate, 60), max(options.rate, 0.1)) options.version = VERSION options.max_update_time = 60 options.device = tokenize(options.device, 'device', []) options.cutoff_temp = tokenize(options.cutoff_temp, 'cutoff_temp', [95], float) options.cutoff_interval = tokenize(options.cutoff_interval, 'cutoff_interval', [0.01], float) switch = None try: switch = Switch(options) if not options.no_ocl: import OpenCLMiner for miner in OpenCLMiner.initialize(options): switch.add_miner(miner) if not options.no_bfl: import BFLMiner for miner in BFLMiner.initialize(options): switch.add_miner(miner) for miner in switch.miners: miner.start() if switch.miners:
def __init__(self): self._lamp = Light() self._switchUp = FlipUpCommand(self._lamp) self._switchDown = FlipDownCommand(self._lamp) self._switch = Switch(self._switchUp, self._switchDown)
def setUp(self): self.switch = Switch() vlan = VLAN('vlan1', 1, None) self.switch.add_vlan(vlan) self.cmd = EosIpCommand(None, self.switch)
def selectNextActionOffensive(self, playerCurrentPokemon, allPlayerPokemon): # Want to select the edge that has min cost # Cost(action) = max damage could receive in current round + -(max damage could give in current round) # Total out edge = 4(moves of current pokemon) + numPokemonAlive(switches to the rest alive pokemon) numRemainingAlivePokemon = 0 remainingAliveIndexList = [] for pokemonNum in range(Constants.NUM_POKEMON_PER_PLAYER): if self.pokemons[pokemonNum] != self.currentPokemon: if self.pokemons[pokemonNum].isAlive(): numRemainingAlivePokemon += 1 remainingAliveIndexList.append(pokemonNum) costList = np.zeros(1 + numRemainingAlivePokemon) opponentsHPLeft = 0 for pokemonNum in range(Constants.NUM_POKEMON_PER_PLAYER): if allPlayerPokemon[pokemonNum].isAlive(): opponentsHPLeft += allPlayerPokemon[pokemonNum].getBattleHP() # Calculate what is the max damage the AI can do damageGiveList = np.array([ calculateDamage(self.currentPokemon.getMove1().getName(), self.currentPokemon, playerCurrentPokemon), calculateDamage(self.currentPokemon.getMove2().getName(), self.currentPokemon, playerCurrentPokemon), calculateDamage(self.currentPokemon.getMove3().getName(), self.currentPokemon, playerCurrentPokemon), calculateDamage(self.currentPokemon.getMove4().getName(), self.currentPokemon, playerCurrentPokemon) ]) for i in range(0, len(damageGiveList)): damageGiveList[i] = min(damageGiveList[i], playerCurrentPokemon.getBattleHP()) bestMoveIndex = np.argmax(damageGiveList) g = playerCurrentPokemon.getBattleHP() - np.max(damageGiveList) heuristic = opponentsHPLeft costList[0] = g + heuristic damageReceivedSwitchList = np.zeros(numRemainingAlivePokemon) indexInCostList = 1 for index in remainingAliveIndexList: pokemonToSwitch = self.pokemons[index] damageGivenList = np.array([ calculateDamage(pokemonToSwitch.getMove1().getName(), pokemonToSwitch, playerCurrentPokemon), calculateDamage(pokemonToSwitch.getMove2().getName(), pokemonToSwitch, playerCurrentPokemon), calculateDamage(pokemonToSwitch.getMove3().getName(), pokemonToSwitch, playerCurrentPokemon), calculateDamage(pokemonToSwitch.getMove4().getName(), pokemonToSwitch, playerCurrentPokemon) ]) for i in range(0, len(damageGivenList)): damageGivenList[i] = min(damageGivenList[i], playerCurrentPokemon.getBattleHP()) g = playerCurrentPokemon.getBattleHP() - np.max(damageGivenList) heuristic = opponentsHPLeft costList[indexInCostList] = g + heuristic indexInCostList += 1 # Select the min cost edge minEdgeIndex = np.argmin(costList) if minEdgeIndex == 0: # If the best action is one of the current pokemon moves moveOptions = [ self.currentPokemon.getMove1(), self.currentPokemon.getMove2(), self.currentPokemon.getMove3(), self.currentPokemon.getMove4() ] return moveOptions[bestMoveIndex] else: # If the best action is switching offset = minEdgeIndex - 1 pokemonToSwitchIndex = remainingAliveIndexList[offset] self.currentPokemon = self.pokemons[pokemonToSwitchIndex] return Switch(pokemonToSwitchIndex)
def copy_images_to_switch(self, log): """ This definition is to copy the right set of images to switch which has been used for sanities for other its not required so just return """ dir = '' logging.info("Copy the sys=%s images if not available to the switch", self.sys) console = pexpect.spawn('telnet %s %s'%(self.console_ip,self.act_port)) console.logfile = log time.sleep(2) console.sendline('') i = console.expect([pexpect.TIMEOUT, pexpect.EOF, defn.SWITCH_LOGIN, defn.SWITCH_PROMPT, 'loader>.*'], 120) if i==0 or i==1: logging.debug(str(console)) console.close() return if i==2 or i==3: if i==2: console.sendline('admin') console.expect('assword:') console.sendline(self.switch_pwd) console.expect(defn.SWITCH_PROMPT) console.sendline('switchback') console.expect(defn.SWITCH_PROMPT) console.sendline('terminal length 0') console.expect(defn.SWITCH_PROMPT) console.sendline('dir') console.expect(defn.SWITCH_PROMPT) dirs = console.before if self.sys in dirs.split(): logging.info("Found the System image in bootflash") console.close() return logging.info("Did not find System image in bootflash") if i==4: console.sendline('') console.expect('loader>.*') console.sendline('dir') console.expect('loader>.*') dirs = console.before if self.sys in dirs.split(): logging.info("Found the System image in bootflash") console.close() return logging.info("Did not find System image in bootflash") if i==2 or i==3: console.sendline('reload') console.expect('y/n') console.sendline('y') console.expect('loader>.*', 60) console.sendline('') i = console.expect([pexpect.TIMEOUT, pexpect.EOF, 'loader>.*']) if i==0 or i==1: logging.debug(str(console)) console.close() return if i==2: console.sendline('dir') console.expect('loader>.*') imgs = n9kSwitch.get_images_in_switch(console.before) for im in imgs: match = re.match(r'n9.*dk9([0-9A-Za-z\.]+)', im) if match: break console.sendline('boot %s' % im) console.exit() console = self.load_or_telnet_image(log) Switch.setip(console,self.mgmt_ip) for img in imgs: console.sendline('delete bootflash:%s' % img) console.expect(defn.SWITCH_PROMPT) time.sleep(10) d_file = self.sys s_file = "%s/%s.system.gbin"%(self.switch_name,self.switch_name) Switch.copy_files_to_switch(switch_cons=console, s_file=s_file, d_file=d_file) d_file = "power_config" s_file = "%s/%s.run_power_config"%(self.switch_name,self.switch_name) Switch.copy_files_to_switch(switch_cons=console, s_file=s_file, d_file=d_file) s_file = "%s/%s.start_power_config"%(self.switch_name,self.switch_name) Switch.copy_files_to_switch(switch_cons=console, s_file=s_file, d_file=d_file) console.close() return
def selectNextActionDefensive(self, playerCurrentPokemon, allPlayerPokemon): # Want to select the edge that has min cost # Cost(action) = max damage could receive in current round + -(max damage could give in current round) # Total out edge = 4(moves of current pokemon) + numPokemonAlive(switches to the rest alive pokemon) numRemainingAlivePokemon = 0 remainingAliveIndexList = [] for pokemonNum in range(Constants.NUM_POKEMON_PER_PLAYER): if self.pokemons[pokemonNum] != self.currentPokemon: if self.pokemons[pokemonNum].isAlive(): numRemainingAlivePokemon += 1 remainingAliveIndexList.append(pokemonNum) costList = np.zeros(1 + numRemainingAlivePokemon) currTotalHP = 0 for pokemonNum in range(Constants.NUM_POKEMON_PER_PLAYER): if self.pokemons[pokemonNum].isAlive(): currTotalHP += self.pokemons[pokemonNum].getBattleHP() # Calculate what is the max damage AI could receive damageReceivedList = np.array([ calculateDamage(playerCurrentPokemon.getMove1().getName(), playerCurrentPokemon, self.currentPokemon), calculateDamage(playerCurrentPokemon.getMove2().getName(), playerCurrentPokemon, self.currentPokemon), calculateDamage(playerCurrentPokemon.getMove3().getName(), playerCurrentPokemon, self.currentPokemon), calculateDamage(playerCurrentPokemon.getMove4().getName(), playerCurrentPokemon, self.currentPokemon) ]) for i in range(0, len(damageReceivedList)): damageReceivedList[i] = min(damageReceivedList[i], self.currentPokemon.getBattleHP()) maxDamageReceived = np.max(damageReceivedList) g = maxDamageReceived maxHeuristicCurr = 0 # compute heuristic for aiPoke in self.pokemons: if not (aiPoke.isAlive()): continue maxDamageTaken = 0 for oppPoke in allPlayerPokemon: if not (oppPoke.isAlive()): continue # Calculate what is the max damage the AI can do damageGiveList = np.array([ calculateDamage(self.currentPokemon.getMove1().getName(), self.currentPokemon, oppPoke), calculateDamage(self.currentPokemon.getMove2().getName(), self.currentPokemon, oppPoke), calculateDamage(self.currentPokemon.getMove3().getName(), self.currentPokemon, oppPoke), calculateDamage(self.currentPokemon.getMove4().getName(), self.currentPokemon, oppPoke) ]) maxDamageDealt = np.max(damageGiveList) # to incentivize staying in, skip current pokemon if you can kill it if oppPoke.getBattleHP() - maxDamageDealt <= 0: continue # Calculate what is the max damage AI could receive damageReceivedList = np.array([ calculateDamage(oppPoke.getMove1().getName(), oppPoke, aiPoke), calculateDamage(oppPoke.getMove2().getName(), oppPoke, aiPoke), calculateDamage(oppPoke.getMove3().getName(), oppPoke, aiPoke), calculateDamage(oppPoke.getMove4().getName(), oppPoke, aiPoke) ]) for i in range(0, len(damageReceivedList)): damageReceivedList[i] = min(damageReceivedList[i], aiPoke.getBattleHP()) maxDamageTaken = max(maxDamageTaken, np.max(damageReceivedList)) maxHeuristicCurr += maxDamageTaken costList[0] = g + maxHeuristicCurr maxHeuristicRest = 0 # compute heuristic for aiPoke in self.pokemons: if not (aiPoke.isAlive()): continue maxDamageTaken = 0 for oppPoke in allPlayerPokemon: if not (oppPoke.isAlive()): continue # Calculate what is the max damage AI could receive damageReceivedList = np.array([ calculateDamage(oppPoke.getMove1().getName(), oppPoke, aiPoke), calculateDamage(oppPoke.getMove2().getName(), oppPoke, aiPoke), calculateDamage(oppPoke.getMove3().getName(), oppPoke, aiPoke), calculateDamage(oppPoke.getMove4().getName(), oppPoke, aiPoke) ]) for i in range(0, len(damageReceivedList)): damageReceivedList[i] = min(damageReceivedList[i], aiPoke.getBattleHP()) maxDamageTaken = max(maxDamageTaken, np.max(damageReceivedList)) maxHeuristicRest += maxDamageTaken damageReceivedSwitchList = np.zeros(numRemainingAlivePokemon) indexInCostList = 1 for index in remainingAliveIndexList: pokemonToSwitch = self.pokemons[index] damageReceivedList = np.array([ calculateDamage(playerCurrentPokemon.getMove1().getName(), playerCurrentPokemon, pokemonToSwitch), calculateDamage(playerCurrentPokemon.getMove2().getName(), playerCurrentPokemon, pokemonToSwitch), calculateDamage(playerCurrentPokemon.getMove3().getName(), playerCurrentPokemon, pokemonToSwitch), calculateDamage(playerCurrentPokemon.getMove4().getName(), playerCurrentPokemon, pokemonToSwitch) ]) for i in range(0, len(damageReceivedList)): damageReceivedList[i] = min(damageReceivedList[i], pokemonToSwitch.getBattleHP()) maxDamageReceived = np.max(damageReceivedList) g = maxDamageReceived heuristic = maxHeuristicRest costList[indexInCostList] = g + heuristic indexInCostList += 1 # Select the min cost edge minEdgeIndex = np.argmin(costList) if minEdgeIndex == 0: # If the best action is one of the current pokemon moves # Calculate what is the max damage the AI can do damageGiveList = np.array([ calculateDamage(self.currentPokemon.getMove1().getName(), self.currentPokemon, playerCurrentPokemon), calculateDamage(self.currentPokemon.getMove2().getName(), self.currentPokemon, playerCurrentPokemon), calculateDamage(self.currentPokemon.getMove3().getName(), self.currentPokemon, playerCurrentPokemon), calculateDamage(self.currentPokemon.getMove4().getName(), self.currentPokemon, playerCurrentPokemon) ]) moveOptions = [ self.currentPokemon.getMove1(), self.currentPokemon.getMove2(), self.currentPokemon.getMove3(), self.currentPokemon.getMove4() ] return moveOptions[np.argmax(damageGiveList)] else: # If the best action is switching offset = minEdgeIndex - 1 pokemonToSwitchIndex = remainingAliveIndexList[offset] self.currentPokemon = self.pokemons[pokemonToSwitchIndex] return Switch(pokemonToSwitchIndex)