Returns (NewConnectionStatus, NewLastConnectionError, NewUptime)
334971
async def get_status_info(self) -> Tuple[str, str, int]:
        """"""
        return await self.gateway.commands.GetStatusInfo()
964540
def _check_connection(self):
        
        # check if connection is expired
        reset = False
        if self._force_recon:
            self.logger.warning(
                "[%s:%s] Error communicating with socket, resetting "
                "connection",
                self.fn or self.host, self.port)
            reset = True

        elif self.heartbeat_controller.is_expired():
            self.logger.warning(
                "[%s:%s] Heartbeat timeout, resetting connection",
                self.fn or self.host, self.port)
            reset = True

        if reset:
            for channel in self._open_channels:
                self.disconnect_channel(channel)
            self._report_connection_status(
                ConnectionStatus(CONNECTION_STATUS_LOST,
                                 NetworkAddress(self.host, self.port)))
            try:
                self.initialize_connection()
            except ChromecastConnectionError:
                self.stop.set()
            return False
        return True
794175
def _ReturnConnection(self):
		
		if self.conn is not None:
			if self.connInfo.commitOnEnd is True or self.commitOnEnd is True:
				self.conn.Commit()
					
			Pool().returnConnection(self.conn)
			self.conn = None
640134
def new(cls, func, args, mon, count=0):
        
        try:
            with mon:
                val = func(*args)
        except StopIteration:
            res = Result(None, mon, msg='TASK_ENDED')
        except Exception:
            _etype, exc, tb = sys.exc_info()
            res = Result(exc, mon, ''.join(traceback.format_tb(tb)),
                         count=count)
        else:
            res = Result(val, mon, count=count)
        return res
704994
def get_new_connection(self, conn_params):
        """"""
        connection = ldap.ldapobject.ReconnectLDAPObject(
            uri=conn_params['uri'],
            retry_max=conn_params['retry_max'],
            retry_delay=conn_params['retry_delay'],
            bytes_mode=False)

        options = conn_params['options']
        for opt, value in options.items():
            if opt == 'query_timeout':
                connection.timeout = int(value)
            elif opt == 'page_size':
                self.page_size = int(value)
            else:
                connection.set_option(opt, value)

        if conn_params['tls']:
            connection.start_tls_s()

        connection.simple_bind_s(
            conn_params['bind_dn'],
            conn_params['bind_pw'],
        )
        return connection
1257954
async def _reconnect(self, last_error):
        
        self._log.debug('Closing current connection...')
        await self._connection.disconnect()

        await helpers._cancel(
            self._log,
            send_loop_handle=self._send_loop_handle,
            recv_loop_handle=self._recv_loop_handle
        )

        # TODO See comment in `_start_reconnect`
        # Perhaps this should be the last thing to do?
        # But _connect() creates tasks which may run and,
        # if they see that reconnecting is True, they will end.
        # Perhaps that task creation should not belong in connect?
        self._reconnecting = False

        # Start with a clean state (and thus session ID) to avoid old msgs
        self._state.reset()

        retries = self._retries if self._auto_reconnect else 0
        for attempt in retry_range(retries):
            try:
                await self._connect()
            except (IOError, asyncio.TimeoutError) as e:
                last_error = e
                self._log.info('Failed reconnection attempt %d with %s',
                               attempt, e.__class__.__name__)

                await asyncio.sleep(self._delay)
            except Exception as e:
                last_error = e
                self._log.exception('Unexpected exception reconnecting on '
                                    'attempt %d', attempt)

                await asyncio.sleep(self._delay)
            else:
                self._send_queue.extend(self._pending_state.values())
                self._pending_state.clear()

                if self._auto_reconnect_callback:
                    self._loop.create_task(self._auto_reconnect_callback())

                break
        else:
            self._log.error('Automatic reconnection failed {} time(s)'
                            .format(attempt))
            await self._disconnect(error=last_error.with_traceback(None))
1226022
function(self) {
  return function(err) {
    if (connectionAccounting) deleteConnection(self.id);
    // Debug information
    if (self.logger.isDebug())
      self.logger.debug(
        f(
          'connection %s for [%s:%s] errored out with [%s]',
          self.id,
          self.host,
          self.port,
          JSON.stringify(err)
        )
      );
    // Emit the error
    if (self.listeners('error').length > 0) self.emit('error', new MongoNetworkError(err), self);
  };
}
1018886
def _check_connection(self):
        """"""
        try:
            super()._check_connection()
        except OSError as exc:
            _LOGGER.error(exc)
            self.protocol.transport.close()
            self.protocol.conn_lost_callback()
            return
        task = self.loop.call_later(
            self.reconnect_timeout + 0.1, self._check_connection)
        self.cancel_check_conn = task.cancel
843670
function doConnect() {
            attemptCount++;
            attemptTimestamp = new Date();
            attemptSingleConnect().then(
                registerHandlersAndDomains, // succeded
                function () { // failed this attempt, possibly try again
                    if (attemptCount < CONNECTION_ATTEMPTS) { //try again
                        // Calculate how long we should wait before trying again
                        var now = new Date();
                        var delay = Math.max(
                            RETRY_DELAY - (now - attemptTimestamp),
                            1
                        );
                        setTimeout(doConnect, delay);
                    } else { // too many attempts, give up
                        deferred.reject("Max connection attempts reached");
                    }
                }
            );
        }
786473
def get_nowait(self):
        
        new_get = Future()

        with self._lock:
            if not self._get.done():
                raise QueueEmpty
            get, self._get = self._get, new_get

        hole = get.result()
        if not hole.done():
            # Restore the unfinished hole.
            new_get.set_result(hole)
            raise QueueEmpty

        node = hole.result()
        value = node.value
        new_hole, node.next = node.next, None
        new_get.set_result(new_hole)
        return value
545491
def _check_connection(self):
        """"""
        if ((self.tcp_disconnect_timer + 2 * self.reconnect_timeout) <
                time.time()):
            self.tcp_disconnect_timer = time.time()
            raise OSError('No response from {}. Disconnecting'.format(
                self.server_address))
        if (self.tcp_check_timer + self.reconnect_timeout) >= time.time():
            return
        msg = Message().modify(
            child_id=255, type=self.const.MessageType.internal,
            sub_type=self.const.Internal.I_VERSION)
        self.add_job(msg.encode)
        self.tcp_check_timer = time.time()
463346
def _check_connectivity(self, err):

        '''  '''
        
        try:
            import requests
            requests.get(self.uptime_ssl)
        except:
            from requests import Request
            request_object = Request(method='GET', url=self.uptime_ssl)
            request_details = self.handle_requests(request_object)
            self.printer('ERROR.')
            raise ConnectionError(request_details['error'])
        self.printer('ERROR.')
        raise err
1247383
private int getNewReconnectIvl()
    {
        //  The new interval is the current interval + random value.
        int interval = currentReconnectIvl + (Utils.randomInt() % options.reconnectIvl);

        //  Only change the current reconnect interval  if the maximum reconnect
        //  interval was set and if it's larger than the reconnect interval.
        if (options.reconnectIvlMax > 0 && options.reconnectIvlMax > options.reconnectIvl) {
            //  Calculate the next interval
            currentReconnectIvl = Math.min(currentReconnectIvl * 2, options.reconnectIvlMax);
        }
        return interval;
    }
1348277
protected void postConnection(ConnectionHandle handle, long statsObtainTime){

		handle.renewConnection(); // mark it as being logically "open"

		// Give an application a chance to do something with it.
		if (handle.getConnectionHook() != null){
			handle.getConnectionHook().onCheckOut(handle);
		}

		if (this.pool.closeConnectionWatch){ // a debugging tool
			this.pool.watchConnection(handle);
		}

		if (this.pool.statisticsEnabled){
			this.pool.statistics.addCumulativeConnectionWaitTime(System.nanoTime()-statsObtainTime);
		}
	}
168674
protected void checkIfAlreadyConnected(DeviceProxy device, String attribute, String event_name, CallBack callback, int max_size, boolean stateless)
            throws DevFailed {
        if (device == null || (callback == null && max_size < 0)) {
            Except.throw_wrong_syntax_exception("API_InvalidArgs",
                    "Device or callback pointer NULL and  event queue not used !!",
                    "EventConsumer.subscribe_event()");
        }

        if (device == null || device.name() == null)
            Except.throw_event_system_failed("API_NotificationServiceFailed",
                    "Failed to connect to device",
                    "EventConsumer.subscribe_event()");
        else {
            //	Check if already connected (exists in map)
            String callback_key = device.name().toLowerCase() + "/" + attribute + "." + event_name;
            if (event_callback_map.containsKey(callback_key))
                Except.throw_event_system_failed("API_MethodArgument",
                        "Already connected to event " + callback_key,
                        "EventConsumer.subscribe_event()");

            //	Check if already trying to connects (exists in map)
            if (stateless && failed_event_callback_map.containsKey(callback_key))
                Except.throw_event_system_failed("API_MethodArgument",
                        "Already trying to connect to event " + callback_key,
                        "EventConsumer.subscribe_event()");
        }
    }
101830
def _fetch(self):
        
        if self.closed():
            raise self.Error("Failed to read from closed connection {!r}".format(self.server.address))
        if self.defunct():
            raise self.Error("Failed to read from defunct connection {!r}".format(self.server.address))
        if not self.responses:
            return 0, 0

        self._receive()

        details, summary_signature, summary_metadata = self._unpack()

        if details:
            log_debug("[#%04X]  S: RECORD * %d", self.local_port, len(details))  # TODO
            self.responses[0].on_records(details)

        if summary_signature is None:
            return len(details), 0

        response = self.responses.popleft()
        response.complete = True
        if summary_signature == b"\x70":
            log_debug("[#%04X]  S: SUCCESS %r", self.local_port, summary_metadata)
            response.on_success(summary_metadata or {})
        elif summary_signature == b"\x7E":
            self._last_run_statement = None
            log_debug("[#%04X]  S: IGNORED", self.local_port)
            response.on_ignored(summary_metadata or {})
        elif summary_signature == b"\x7F":
            self._last_run_statement = None
            log_debug("[#%04X]  S: FAILURE %r", self.local_port, summary_metadata)
            response.on_failure(summary_metadata or {})
        else:
            self._last_run_statement = None
            raise ProtocolError("Unexpected response message with signature %02X" % summary_signature)

        return len(details), 1
817431
function() {
                var asyncGetReadyTime = new Date().getTime();

                asyncClient = new Async({
                    protocol: protocol,
                    queueHost: queueHost,
                    queuePort: queuePort,
                    queueUsername: queueUsername,
                    queuePassword: queuePassword,
                    queueReceive: queueReceive,
                    queueSend: queueSend,
                    queueConnectionTimeout: queueConnectionTimeout,
                    socketAddress: socketAddress,
                    serverName: serverName,
                    deviceId: deviceId,
                    wsConnectionWaitTime: wsConnectionWaitTime,
                    connectionRetryInterval: connectionRetryInterval,
                    connectionCheckTimeout: connectionCheckTimeout,
                    connectionCheckTimeoutThreshold: connectionCheckTimeoutThreshold,
                    messageTtl: messageTtl,
                    reconnectOnClose: reconnectOnClose,
                    asyncLogging: asyncLogging
                });

                asyncClient.on('asyncReady', function() {
                    if (actualTimingLog) {
                        Utility.chatStepLogger('Async Connection ', new Date().getTime() - asyncGetReadyTime);
                    }

                    peerId = asyncClient.getPeerId();

                    if (!userInfo) {
                        var getUserInfoTime = new Date().getTime();

                        getUserInfo(function(userInfoResult) {
                            if (actualTimingLog) {
                                Utility.chatStepLogger('Get User Info ', new Date().getTime() - getUserInfoTime);
                            }
                            if (!userInfoResult.hasError) {
                                userInfo = userInfoResult.result.user;

                                /**
                                 * Check if user has KeyId stored in their cache or not?
                                 */
                                if (canUseCache) {
                                    if (db) {
                                        db.users
                                            .where('id')
                                            .equals(userInfo.id)
                                            .toArray()
                                            .then(function(users) {
                                                if (users.length > 0 && typeof users[0].keyId != 'undefined') {
                                                    var user = users[0];

                                                    getEncryptionKey({
                                                        keyId: user.keyId
                                                    }, function(result) {
                                                        if (!result.hasError) {
                                                            cacheSecret = result.secretKey;
                                                        }
                                                        else {
                                                            if (result.message != '') {
                                                                try {
                                                                    var response = JSON.parse(result.message);
                                                                    if (response.error == 'invalid_param') {
                                                                        generateEncryptionKey({
                                                                            keyAlgorithm: 'AES',
                                                                            keySize: 256
                                                                        });
                                                                    }
                                                                }
                                                                catch (e) {
                                                                    console.log(e);
                                                                }
                                                            }
                                                        }
                                                    });
                                                }
                                                else {
                                                    generateEncryptionKey({
                                                        keyAlgorithm: 'AES',
                                                        keySize: 256
                                                    });
                                                }
                                            })
                                            .catch(function(error) {
                                                fireEvent('error', {
                                                    code: error.errorCode,
                                                    message: error.errorMessage,
                                                    error: error
                                                });
                                            });
                                    }
                                    else {
                                        fireEvent('error', {
                                            code: 6601,
                                            message: CHAT_ERRORS[6601],
                                            error: null
                                        });
                                    }
                                }

                                chatState = true;
                                fireEvent('chatReady');
                                chatSendQueueHandler();
                            }
                        });
                    }
                    else if (userInfo.id > 0) {
                        chatState = true;
                        fireEvent('chatReady');
                        chatSendQueueHandler();
                    }
                });

                asyncClient.on('stateChange', function(state) {
                    fireEvent('chatState', state);
                    chatFullStateObject = state;

                    switch (state.socketState) {
                        case 1: // CONNECTED
                            if (state.deviceRegister && state.serverRegister) {
                                chatState = true;
                                ping();
                            }
                            break;
                        case 0: // CONNECTING
                        case 2: // CLOSING
                        case 3: // CLOSED
                            chatState = false;
                            break;
                    }
                });

                asyncClient.on('connect', function(newPeerId) {
                    asyncGetReadyTime = new Date().getTime();
                    peerId = newPeerId;
                    fireEvent('connect');
                    ping();
                });

                asyncClient.on('disconnect', function(event) {
                    oldPeerId = peerId;
                    peerId = undefined;
                    fireEvent('disconnect', event);
                });

                asyncClient.on('reconnect', function(newPeerId) {
                    peerId = newPeerId;
                    fireEvent('reconnect');
                });

                asyncClient.on('message', function(params, ack) {
                    receivedAsyncMessageHandler(params);
                    ack && ack();
                });

                asyncClient.on('error', function(error) {
                    fireEvent('error', {
                        code: error.errorCode,
                        message: error.errorMessage,
                        error: error.errorEvent
                    });
                });
            }