Currently uses the robot singleton from the API server to connect to
    Smoothie. Those calls should be separated out from the singleton so it can
    be used directly without requiring a full initialization of the API robot.
481580
async def _update_firmware(filename, loop):
    
    try:
        from opentrons import robot
    except ModuleNotFoundError:
        res = "Unable to find module `opentrons`--not updating firmware"
        rc = 1
        log.error(res)
    else:
        # ensure there is a reference to the port
        if not robot.is_connected():
            robot.connect()

        # get port name
        port = str(robot._driver.port)
        # set smoothieware into programming mode
        robot._driver._smoothie_programming_mode()
        # close the port so other application can access it
        robot._driver._connection.close()

        # run lpc21isp, THIS WILL TAKE AROUND 1 MINUTE TO COMPLETE
        update_cmd = 'lpc21isp -wipe -donotstart {0} {1} {2} 12000'.format(
            filename, port, robot.config.serial_speed)
        proc = await asyncio.create_subprocess_shell(
            update_cmd,
            stdout=asyncio.subprocess.PIPE,
            loop=loop)
        rd = await proc.stdout.read()
        res = rd.decode().strip()
        await proc.communicate()
        rc = proc.returncode

        if rc == 0:
            # re-open the port
            robot._driver._connection.open()
            # reset smoothieware
            robot._driver._smoothie_reset()
            # run setup gcodes
            robot._driver._setup()

    return res, rc
913301
static synchronized Udev getInstance() {
        if (instance == null) {
            try {
                instance = new Udev();
            } catch (IOException e) {
                System.err.println("Udev: failed to open connection");
                e.printStackTrace();
            }
        }
        return instance;
    }
1311690
def connect_controller(self, vid, pid, serial):
        """"""
        self.lib.tdConnectTellStickController(vid, pid, serial)
998510
def connect(*args, **kwargs):
    """"""
    global __CONNECTION
    if __CONNECTION is None:
        __CONNECTION = Connection(*args, **kwargs)

    return __CONNECTION
362993
def connect(self, port=None):
        '''  '''
        if port is None:
            self.port = search_for_port('/dev/ttyUSB*', 'ROBOFORTH\r\n',
                                        'ROBOFORTH')
        else:
            self.port = port

        if self.port is None:
            raise ArmException('ST Robotics connection not found.')

        self.ser = r12_serial_port(port)

        if not self.ser.isOpen():
            self.ser.open()

        if not self.ser.isOpen():
            raise ArmException('Failed to open serial port. Exiting.')

        return self.port
652760
function start() {
    return __awaiter(this, void 0, void 0, function* () {
        yield __1.driver.connect();
        yield __1.driver.login({ username: config_1.botUser.username, password: config_1.botUser.password });
        yield __1.driver.subscribeToMessages();
        yield __1.driver.respondToMessages((err, msg, msgOpts) => {
            if (err)
                throw err;
            console.log('[respond]', JSON.stringify(msg), JSON.stringify(msgOpts));
            demo(msg).catch((e) => console.error(e));
        }, {
            rooms: ['general'],
            allPublic: false,
            dm: true,
            edited: true,
            livechat: false
        });
    });
}
1369142
function ConnectedInstance (requestOptions, authToken, credentials) {
  this.__REQUEST_OPTIONS = requestOptions;
  this.__TOKEN = authToken;
  this.__CREDENTIALS = credentials;
  
  this.SurveyFieldwork = {
    status : bindAPI(this, API, 'statusSurveyFieldwork'),
    start : bindAPI(this, API, 'startSurveyFieldwork'),
    stop : bindAPI(this, API, 'stopSurveyFieldwork')
  };
  
  this.DefaultTexts = {
    get : bindAPI(this, API, 'getDefaultTexts')
  };
  
  this.SurveyTranslations = {
    get : bindAPI(this, API, 'getSurveyTranslations'),
    add : bindAPI(this, API, 'addSurveyTranslations'),
    update : bindAPI(this, API, 'updateSurveyTranslations'),
    remove : bindAPI(this, API, 'removeSurveyTranslations')
  };
  
  this.SurveyLanguages = {
    get : bindAPI(this, API, 'getSurveyLanguages'),
    add : bindAPI(this, API, 'addSurveyLanguages'),
    update : bindAPI(this, API, 'updateSurveyLanguages'),
    remove : bindAPI(this, API, 'removeSurveyLanguages')
  };
  
  this.SurveySettings = {
    get : bindAPI(this, API, 'getSurveySettings'),
    update : bindAPI(this, API, 'updateSurveySettings')
  };
  
  this.SurveyScript = {
    get : bindAPI(this, API, 'getSurveyScript'),
    update : bindAPI(this, API, 'updateSurveyScript')
  };
  
  this.SurveyData = {
    request : bindAPI(this, API, 'requestSurveyData')
  };
  
  this.Surveys = {
    get : bindAPI(this, API, 'getSurveys'),
    add : bindAPI(this, API, 'addSurveys'),
    update : bindAPI(this, API, 'updateSurveys'),
    remove : bindAPI(this, API, 'removeSurveys')
  };
  
  this.SurveyPublish = {
    get : bindAPI(this, API, 'getSurveyPublish'),
    update : bindAPI(this, API, 'updateSurveyPublish')
  };
  
  this.BackgroundTasks = {
    get : bindAPI(this, API, 'getBackgroundTasks')
  };
  
  this.InterviewQuality = {
    get : bindAPI(this, API, 'getInterviewQuality'),
    update : bindAPI(this, API, 'updateInterviewQuality')
  };
  
}
162337
def connected(self, **kwargs):
        """"""
        self.bot.log.info('Server config: %r', self.bot.server_config)

        # recompile when I'm sure of my nickname
        self.bot.config['nick'] = kwargs['me']
        self.bot.recompile()

        # Let all plugins know that server can handle commands
        self.bot.notify('server_ready')

        # detach useless events
        self.bot.detach_events(*self.before_connect_events)
717347
def connect(self, autospawn=False, wait=False):
		''''''
		if self._loop_closed:
			raise PulseError('Eventloop object was already'
				' destroyed and cannot be reused from this instance.')
		if self.connected is not None: self._ctx_init()
		flags, self.connected = 0, None
		if not autospawn: flags |= c.PA_CONTEXT_NOAUTOSPAWN
		if wait: flags |= c.PA_CONTEXT_NOFAIL
		try: c.pa.context_connect(self._ctx, self.server, flags, None)
		except c.pa.CallError: self.connected = False
		while self.connected is None: self._pulse_iterate()
		if self.connected is False: raise PulseError('Failed to connect to pulseaudio server')
869568
def get_instance(cls):
        
        if not cls.prepared:
            raise SingletonNotPreparedError(
                "prepare must be called before get_instance"
            )

        if hasattr(cls.local, 'tchannel') and cls.local.tchannel is not None:
            return cls.local.tchannel

        cls.local.tchannel = cls.tchannel_cls(*cls.args, **cls.kwargs)

        return cls.local.tchannel
492306
def get(cls):
        
        app = AndroidApplication.instance()
        f = app.create_future()

        if cls._instance:
            f.set_result(cls._instance)
            return f

        def on_service(obj_id):
            #: Create the manager
            if not cls.instance():
                m = cls(__id__=obj_id)
            else:
                m = cls.instance()
            f.set_result(m)

        cls.from_(app).then(on_service)

        return f
166353
def main():
    
    prog = sys.argv[0]

    arg_parser = create_parser(prog)

    opts = parse_cmdline(arg_parser)

    print('Parameters: server=%s\n username=%s\n namespace=%s\n'
          ' classname=%s\n max_pull_size=%s\n use_pull=%s' %
          (opts.server, opts.user, opts.namespace, opts.classname,
           opts.max_object_count, opts.usepull))

    # call method to connect to the server
    conn = WBEMConnection(opts.server, (opts.user, opts.password),
                          default_namespace=opts.namespace,
                          no_verification=True,
                          use_pull_operations=opts.usepull)

    #Call method to create iterator
    instances = []
    try:
        iter_instances = conn.IterEnumerateInstances(
            opts.classname,
            MaxObjectCount=opts.max_object_count)

        # generate instances with
        for instance in iter_instances:
            print(' %s %s' % (type(instances), type(instance)))
            instances.append(instance)
            print('\npath=%s\n%s' % (instance.path, instance.tomof()))

    # handle exceptions
    except CIMError as ce:
        print('Operation Failed: CIMError: code=%s, Description=%s' %
              (ce.status_code_name, ce.status_description))
        sys.exit(1)
    except Error as err:
        print ("Operation failed: %s" % err)
        sys.exit(1)

    inst_paths = [inst.path for inst in instances]

    paths = []
    try:
        iter_paths = conn.IterEnumerateInstancePaths(
            opts.classname,
            MaxObjectCount=opts.max_object_count)

        # generate instances with
        for path in iter_paths:
            print('path=%s' % path)
            paths.append(path)

        if len(paths) != len(paths):
            print('Error path and enum response sizes different enum=%s path=%s'
                  % (len(paths), len(paths)))
        for path in paths:
            found = False
            for inst_path in inst_paths:                
                if path == inst_path:
                    found = True
                    break
                else:
                    print('No match \n%s\n%s' %(path, inst_path))
            if not found:
                print('Path %s not found in insts' % path)
    # handle exceptions
    except CIMError as ce:
        print('Operation Failed: CIMError: code=%s, Description=%s' %
              (ce.status_code_name, ce.status_description))
        sys.exit(1)
    except Error as err:
        print ("Operation failed: %s" % err)
        sys.exit(1)

    return 0
775941
async def _connect_with_login(self, endpoints):
        
        success = False
        try:
            await self._connect(endpoints)
            # It's possible that we may get several discharge-required errors,
            # corresponding to different levels of authentication, so retry
            # a few times.
            for i in range(0, 2):
                result = (await self.login())['response']
                macaroonJSON = result.get('discharge-required')
                if macaroonJSON is None:
                    self.info = result
                    success = True
                    return result
                macaroon = bakery.Macaroon.from_dict(macaroonJSON)
                self.bakery_client.handle_error(
                    httpbakery.Error(
                        code=httpbakery.ERR_DISCHARGE_REQUIRED,
                        message=result.get('discharge-required-error'),
                        version=macaroon.version,
                        info=httpbakery.ErrorInfo(
                            macaroon=macaroon,
                            macaroon_path=result.get('macaroon-path'),
                        ),
                    ),
                    # note: remove the port number.
                    'https://' + self.endpoint + '/',
                )
            raise errors.JujuAuthError('failed to authenticate '
                                       'after several attempts')
        finally:
            if not success:
                await self.close()
638737
function getInstanceRoute(machineName, versionKey, instanceKey){

        let manifest = getManifest();

        let machine = manifest.machines[machineName];
        if (!machine) {
            throw new Error("Machine does not exists");
        }

        let version = machine.versions[versionKey];
        if (!version) {
            throw new Error("Version does not exists");
        }

        let instance = version.instances[instanceKey];
        if (!instance) {
            throw new Error("Instance does not exists");
        }

        return instance.route;
    }
513488
@Override
    public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable environment) throws Exception {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(this, tc, "getObjectInstance", new Object[] { obj, name, nameCtx, environment });
        Object ret = null;

        if (obj instanceof Reference) {
            Reference ref = (Reference) obj;
            String clsName = ref.getClassName();

            if (clsName.equals(ConnectionFactory.class.getName())) {
                ret = this.createConnectionFactory();
                ((JmsConnectionFactory) ret).setReference(ref);
            }

            else if (clsName.equals(QueueConnectionFactory.class.getName())) {
                ret = this.createQueueConnectionFactory();
                ((JmsQueueConnectionFactory) ret).setReference(ref);
            }

            else if (clsName.equals(TopicConnectionFactory.class.getName())) {
                ret = this.createTopicConnectionFactory();
                ((JmsTopicConnectionFactory) ret).setReference(ref);
            }

            else if (clsName.equals(JmsQueueImpl.class.getName())) {
                ret = new JmsQueueImpl(ref);
            }

            else if (clsName.equals(JmsTopicImpl.class.getName())) {
                ret = new JmsTopicImpl(ref);
            }

            else {
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                    SibTr.debug(tc, "class name is " + clsName);
            }
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.exit(this, tc, "getObjectInstance", ret);
        return ret;
    }
872075
def _get_instance(hosts=None, profile=None):
    '''
    
    '''
    es = None
    proxies = None
    use_ssl = False
    ca_certs = None
    verify_certs = True
    http_auth = None
    timeout = 10

    if profile is None:
        profile = 'elasticsearch'

    if isinstance(profile, six.string_types):
        _profile = __salt__['config.option'](profile, None)
    elif isinstance(profile, dict):
        _profile = profile
    if _profile:
        hosts = _profile.get('host', hosts)
        if not hosts:
            hosts = _profile.get('hosts', hosts)
        proxies = _profile.get('proxies', None)
        use_ssl = _profile.get('use_ssl', False)
        ca_certs = _profile.get('ca_certs', None)
        verify_certs = _profile.get('verify_certs', True)
        username = _profile.get('username', None)
        password = _profile.get('password', None)
        timeout = _profile.get('timeout', 10)

        if username and password:
            http_auth = (username, password)

    if not hosts:
        hosts = ['127.0.0.1:9200']
    if isinstance(hosts, six.string_types):
        hosts = [hosts]
    try:
        if proxies:
            # Custom connection class to use requests module with proxies
            class ProxyConnection(RequestsHttpConnection):
                def __init__(self, *args, **kwargs):
                    proxies = kwargs.pop('proxies', {})
                    super(ProxyConnection, self).__init__(*args, **kwargs)
                    self.session.proxies = proxies

            es = elasticsearch.Elasticsearch(
                hosts,
                connection_class=ProxyConnection,
                proxies=proxies,
                use_ssl=use_ssl,
                ca_certs=ca_certs,
                verify_certs=verify_certs,
                http_auth=http_auth,
                timeout=timeout,
            )
        else:
            es = elasticsearch.Elasticsearch(
                    hosts,
                    use_ssl=use_ssl,
                    ca_certs=ca_certs,
                    verify_certs=verify_certs,
                    http_auth=http_auth,
                    timeout=timeout,
                )

        # Try the connection
        es.info()
    except elasticsearch.exceptions.TransportError as err:
        raise CommandExecutionError(
            'Could not connect to Elasticsearch host/ cluster {0} due to {1}'.format(hosts, err))
    return es
184160
def connect
      unless @connected
        once('report_version', ->() do
          once('firmware_query', ->() do
            once('capability_query', ->() do
              once('analog_mapping_query', ->() do

                2.times { |i| toggle_pin_reporting(i) }

                @connected = true
                emit('ready')
              end)
              query_analog_mapping
           end)
            query_capabilities
          end)
        end)

         until connected?
          read_and_process
          delay(0.5)
        end
      end

      self
    end