A basic example of using multiple agents
344944
def multi_agent_example():
    """"""
    env = holodeck.make("UrbanCity")

    cmd0 = np.array([0, 0, -2, 10])
    cmd1 = np.array([0, 0, 5, 10])
    for i in range(10):
        env.reset()
        # This will queue up a new agent to spawn into the environment, given that the coordinates are not blocked.
        sensors = [Sensors.PIXEL_CAMERA, Sensors.LOCATION_SENSOR, Sensors.VELOCITY_SENSOR]
        agent = AgentDefinition("uav1", agents.UavAgent, sensors)
        env.spawn_agent(agent, [1, 1, 5])

        env.set_control_scheme("uav0", ControlSchemes.UAV_ROLL_PITCH_YAW_RATE_ALT)
        env.set_control_scheme("uav1", ControlSchemes.UAV_ROLL_PITCH_YAW_RATE_ALT)

        env.tick()  # Tick the environment once so the second agent spawns before we try to interact with it.

        env.act("uav0", cmd0)
        env.act("uav1", cmd1)
        for _ in range(1000):
            states = env.tick()
            uav0_terminal = states["uav0"][Sensors.TERMINAL]
            uav1_reward = states["uav1"][Sensors.REWARD]
295212
function Session_createAgent(agentInfo, cb) {
  if (!this._channel) return

  DEBUG("session.createAgent()", utils.JS(agentInfo))

  var session = this

  this._ragentServer.send("createAgent", agentInfo, onResponse)

  //-----------------------------------
  function onResponse(err, agentInfo) {
    if (err) {
      DEBUG("session.createAgent() error", err)
      return cb(err)
    }

    DEBUG("session.createAgent() success", utils.JS(agentInfo))
    var agent = agents.createAgent(session, agentInfo)
    session._agents.set(agentInfo.id, agent)

    cb(null, agent)
  }
}
440487
public static void applyUserAgent(String agent) {
    LOGGER.info("Applying agent: " + agent);
    System.setProperty("http.agent", agent);
    System.setProperty("https.agent", agent);
  }
1105278
def load_agents(self, config_file=None):
        
        if config_file is not None:
            self.overall_config = config_file
        self.agents.clear()
        num_participants = get_num_players(self.overall_config)
        try:
            for i in range(num_participants):
                self.load_agent(i)
        except BaseException as e:
            raise ValueError(f"{str(e)}\nPlease check your config files! {self.overall_config_path}")
515621
def agents(self):
        """"""
        ret = []
        for player in self.players:
            if player.isComputer: continue
            try:
                if player.observer: continue
            except: pass
            ret.append(player)
        return ret
750155
def _move_agent(self, agent, direction, wrap_allowed=True):
        
        x,y = agent.coords['x'], agent.coords['y']
        print('moving agent ', agent.name, 'to x,y=', direction, 'wrap_allowed = ', wrap_allowed)
        agent.coords['x'] = x + direction[0]
        agent.coords['y'] = y + direction[1]
1205068
def get_create_base_agent(self, agent):
        
        try:
            base_agent = self.agents[agent.name]
        except KeyError:
            base_agent = BaseAgent(agent.name)
            self.agents[agent.name] = base_agent

        return base_agent
1312528
function Agent(options) {
  if (!(this instanceof Agent)) return new Agent(options);

  EventEmitter.call(this);

  this.defaultPort = 80;
  this.protocol    = 'http:';

  this.options = util._extend({}, options);
  // don't confuse net and make it think that we're connecting to a pipe
  this.options.path = null;

  this.requests    = {};
  this.sockets     = {};
  this.freeSockets = {};

  this.keepAliveMsecs = this.options.keepAliveMsecs || 1000;
  this.keepAlive      = this.options.keepAlive || false;

  this.maxSockets     = this.options.maxSockets || Agent.defaultMaxSockets;
  this.maxFreeSockets = this.options.maxFreeSockets || 256;

  var self = this;
  this.on('free', function(socket, options) {
    var name = self.getName(options);
    debug('agent.on(free)', name);

    if (!self.isSocketDestroyed(socket) && self.requests[name] && self.requests[name].length) {
      self.requests[name].shift().onSocket(socket);
      if (self.requests[name].length === 0) {
        // don't leak
        delete self.requests[name];
      }
    }
    else {
      // If there are no pending requests, then put it in
      // the freeSockets pool, but only if we're allowed to do so.
      var req = socket._httpMessage;
      if (req && req.shouldKeepAlive && !self.isSocketDestroyed(socket) && self.options.keepAlive) {
        var freeSockets = self.freeSockets[name];
        var freeLen     = freeSockets ? freeSockets.length : 0;
        var count       = freeLen;

        if (self.sockets[name]) count += self.sockets[name].length;

        debug('potentially pooling', freeLen, count);

        if (count > self.maxSockets || freeLen >= self.maxFreeSockets) {
          debug('destroying socket', name);
          self.removeSocket(socket, options);
          socket.destroy();
        } else {
          debug('pooling socket', name);
          freeSockets = freeSockets || [];
          self.freeSockets[name] = freeSockets;
          socket.setKeepAlive(true, self.keepAliveMsecs);

          if (socket.unref) {
            socket.unref();
          }
          else if (socket.socket &&
                   socket.socket._handle &&
                   socket.socket._handle.unref) {
            socket.socket._handle.unref();
          }

          socket._httpMessage = null;
          self.removeSocket(socket, options);
          freeSockets.push(socket);

          // set timeout on idle sockets
          if (options.keepAliveTimeoutMsecs !== undefined) {
            socket._yakaa_timeout = setTimeout(function () {
              self.emit('yakaa_destroy');
              socket.destroySoon();
            }, options.keepAliveTimeoutMsecs);
          }

        }
      } else {
        self.removeSocket(socket, options);
        socket.destroy();
      }
    }
  });
}
939465
def run(self, num_runs, show_trails, log_file_base):
        
        print("--------------------------------------------------")
        print("Starting Simulation - target = ", self.agent_list[0].target_y, self.agent_list[0].target_x)
        self.world.grd.set_tile(self.agent_list[0].target_y , self.agent_list[0].target_x , 'T')
        self.highlight_cell_surroundings(self.agent_list[0].target_y, self.agent_list[0].target_x)
        self.start_all_agents()
        # save the agents results here
        try:
            with open (log_file_base + '__agents.txt', "w") as f:
                f.write("Starting World = \n")
                f.write(str(self.world.grd))
        except Exception:
            print('Cant save log results to ' + log_file_base)
            
        for cur_run in range(0,num_runs):
            print("WorldSimulation:run#", cur_run)
            for num, agt in enumerate(self.agent_list):
                if show_trails == 'Y':
                    if len(self.agent_list) == 1 or len(self.agent_list) > 9:
                        self.world.grd.set_tile(agt.current_y, agt.current_x, 'o')
                    else:
                        self.world.grd.set_tile(agt.current_y, agt.current_x, str(num))
                agt.do_your_job()
                self.world.grd.set_tile(agt.current_y, agt.current_x, 'A')    # update the main world grid with agents changes
            
            # save grid after each run if required
            if log_file_base != 'N':
                self.world.grd.save(log_file_base + '_' + str(cur_run) + '.log')
    
        # save the agents results here
        with open (log_file_base + '__agents.txt', "a") as f:
            f.write("\nWorld tgt= [" + str(self.agent_list[0].target_y) + "," + str(self.agent_list[0].target_x) + "]\n")
            f.write(str(self.world.grd))
            f.write('\n\nAgent Name , starting, num Steps , num Climbs\n')
            for num, agt in enumerate(self.agent_list):
                res = agt.name + ' , [' + str(agt.start_y) + ', ' + str(agt.start_x) + '], '
                res += str(agt.num_steps)  + ' , ' + str(agt.num_climbs) + ' , '
                res += ''.join([a for a in agt.results])
                f.write(res + '\n')
961927
function makeStations(agent) {
    let functor = function (id) {
        return new StationImpl(agent, id);
    };
    functor.search = search_1.makeDefaultSearch(agent, "station" /* STATION */);
    functor.names = function (ids) {
        return names_1.getNames(agent, "station" /* STATION */, ids);
    };
    return functor;
}
1218276
function Agent(options) {
  EventEmitter.call(this);
  this.setMaxListeners(0);

  options = assign({}, options);

  this._settings = options.settings;
  this._log = (options.log || defaultLogger).child({ component: 'http' });
  this.endpoints = {};

  // * Using an own HTTPS agent, because the global agent does not look at `NPN/ALPNProtocols` when
  //   generating the key identifying the connection, so we may get useless non-negotiated TLS
  //   channels even if we ask for a negotiated one. This agent will contain only negotiated
  //   channels.
  options.ALPNProtocols = supportedProtocols;
  options.NPNProtocols = supportedProtocols;
  this._httpsAgent = new https.Agent(options);

  this.sockets = this._httpsAgent.sockets;
  this.requests = this._httpsAgent.requests;
}
895975
def agents():
    """"""
    print 'The following LiveSync agents are active:'
    agent_list = LiveSyncAgent.find().order_by(LiveSyncAgent.backend_name, db.func.lower(LiveSyncAgent.name)).all()
    table_data = [['ID', 'Name', 'Backend', 'Initial Export', 'Queue']]
    for agent in agent_list:
        initial = (cformat('%{green!}done%{reset}') if agent.initial_data_exported else
                   cformat('%{yellow!}pending%{reset}'))
        if agent.backend is None:
            backend_title = cformat('%{red!}invalid backend ({})%{reset}').format(agent.backend_name)
        else:
            backend_title = agent.backend.title
        table_data.append([unicode(agent.id), agent.name, backend_title, initial,
                           unicode(agent.queue.filter_by(processed=False).count())])
    table = AsciiTable(table_data)
    table.justify_columns[4] = 'right'
    print table.table
    if not all(a.initial_data_exported for a in agent_list):
        print
        print "You need to perform the initial data export for some agents."
        print cformat("To do so, run "
                      "%{yellow!}indico livesync initial_export %{reset}%{yellow}<agent_id>%{reset} for those agents.")
477247
def agent_create(self, data, **kwargs):
        ""
        api_path = "/api/v2/agents"
        return self.call(api_path, method="POST", data=data, **kwargs)
1146472
def solveAgents(self):
        '''
        
        '''
        #for this_type in self.agents:
        #    this_type.solve()
        try:
            multiThreadCommands(self.agents,['solve()'])
        except Exception as err:
            if self.print_parallel_error_once:
                # Set flag to False so this is only printed once.
                self.print_parallel_error_once = False
                print("**** WARNING: could not execute multiThreadCommands in HARK.core.Market.solveAgents(), so using the serial version instead. This will likely be slower. The multiTreadCommands() functions failed with the following error:", '\n    ', sys.exc_info()[0], ':', err) #sys.exc_info()[0])
            multiThreadCommandsFake(self.agents,['solve()'])
496332
def main():
    '''  '''
    conn = symphony.Config('example-bot.cfg')
    # connect to pod
    agent, pod, symphony_sid = conn.connect()
    agent.test_echo('test')
    # main loop
    msgFormat = 'MESSAGEML'
    message = '<messageML> hello world. </messageML>'
    # send message
    agent.send_message(symphony_sid, msgFormat, message)
365558
function(agent, id, type, pid, info, socket) {
  let record = {
    id: id,
    type: type,
    pid: pid,
    info: info,
    socket: socket
  };
  if (type === 'client') {
    agent.clients[id] = record;
  } else {
    if (!agent.idMap[id]) {
      agent.idMap[id] = record;
      let list = agent.typeMap[type] = agent.typeMap[type] || [];
      list.push(record);
    } else {
      let slaves = agent.slaveMap[id] = agent.slaveMap[id] || [];
      slaves.push(record);
    }
  }
  return record;
}
16402
def inference(self, state_arr, limit=1000):
        '''
        
        '''
        self.__inferencing_flag = True

        agent_x, agent_y = np.where(state_arr[0] == 1)
        agent_x, agent_y = agent_x[0], agent_y[0]
        self.__create_enemy(self.__map_arr)
        result_list = [(agent_x, agent_y, 0.0)]
        result_val_list = [agent_x, agent_y]
        for e in range(self.__enemy_num):
            result_val_list.append(self.__enemy_pos_list[e][0])
            result_val_list.append(self.__enemy_pos_list[e][1])
        result_val_list.append(0.0)
        result_list.append(tuple(result_val_list))

        self.t = 0
        while self.t < limit:
            next_action_arr = self.extract_possible_actions(state_arr)
            next_q_arr = self.function_approximator.inference_q(next_action_arr)
            action_arr, q = self.select_action(next_action_arr, next_q_arr)
            self.__move_enemy(action_arr)

            agent_x, agent_y = np.where(action_arr[0] == 1)
            agent_x, agent_y = agent_x[0], agent_y[0]
            
            result_val_list = [agent_x, agent_y]
            for e in range(self.__enemy_num):
                result_val_list.append(self.__enemy_pos_list[e][0])
                result_val_list.append(self.__enemy_pos_list[e][1])
            try:
                result_val_list.append(q[0])
            except IndexError:
                result_val_list.append(q)

            result_list.append(tuple(result_val_list))

            # Update State.
            state_arr = self.update_state(state_arr, action_arr)

            # Epsode.
            self.t += 1
            # Check.
            end_flag = self.check_the_end_flag(state_arr)
            if end_flag is True:
                break

        return result_list