force database reconnector to connect to the (host, port, name)
168066
def reconfigure_database(self, host, port, name='feat'):
        ''''''
        self._database.reconfigure(host, port, name)
1008690
function connStr(conn) {
  var conf = mergeDefaults(conn);
  var connString = conf.driver + '://' + conf.username + (conf.password ? ':' + conf.password : '') + '@' + conf.host
    + (conf.port ? ':' + conf.port : '') + '/' + conf.database;
  return connString;
}
1283907
def ida_connect(host='localhost', port=18861, retry=10):
    
    for i in range(retry):
        try:
            LOG.debug('Connectint to %s:%d, try %d...', host, port, i + 1)
            link = rpyc_classic.connect(host, port)
            link.eval('2 + 2')
        except socket.error:
            time.sleep(1)
            continue
        else:
            LOG.debug('Connected to %s:%d', host, port)
            return link

    raise IDALinkError("Could not connect to %s:%d after %d tries" % (host, port, retry))
1291622
private java.sql.Connection connectToDB(String strJDBCDriver, String strJDBCURL,
        String strUsername, String strPassword)
        throws java.sql.SQLException, java.lang.ClassNotFoundException
    {
        Class.forName(strJDBCDriver);
        java.sql.Connection conn =
        java.sql.DriverManager.getConnection(strJDBCURL,
                strUsername, strPassword);  
        return conn;
    }
1158569
def _connect(host=None, port=None, db=None, password=None):
    '''
    
    '''
    if not host:
        host = __salt__['config.option']('redis.host')
    if not port:
        port = __salt__['config.option']('redis.port')
    if not db:
        db = __salt__['config.option']('redis.db')
    if not password:
        password = __salt__['config.option']('redis.password')

    return redis.StrictRedis(host, port, db, password, decode_responses=True)
664468
def _try_connect(self, connection_string):
        """"""
        if self._parse_conn_string(connection_string):
            self._trigger_callback('on_disconnect', self.id, self._connection_id)

            self.stop_sync()

            if self._mux_func is not None:
                self._mux_func(self._channel)

            if self._device_info is None:
                raise ArgumentError("Missing device name or alias, specify using device=name in port string "
                                    "or -c device=name in connect_direct or debug command",
                                    known_devices=[x for x in DEVICE_ALIASES.keys()])

            try:
                self.jlink = pylink.JLink()
                self.jlink.open(serial_no=self._jlink_serial)
                self.jlink.set_tif(pylink.enums.JLinkInterfaces.SWD)
                self.jlink.connect(self._device_info.jlink_name)
                self.jlink.set_little_endian()
            except pylink.errors.JLinkException as exc:
                if exc.code == exc.VCC_FAILURE:
                    raise HardwareError("No target power detected", code=exc.code,
                                        suggestion="Check jlink connection and power wiring")

                raise
            except:
                raise

            self._control_thread = JLinkControlThread(self.jlink)
            self._control_thread.start()

            self.set_config('probe_required', True)
            self.set_config('probe_supported', True)
828799
private void actuallyReconnect() {
        if (((null == signalingChannel) || !signalingChannel.connected) && reconnect) {
            if (connectionInProgress) {
                // The client app must have initiated a connection manually during the timeout period. Try again later
                performReconnect();
            } else {
                Log.d(TAG, "Trying to reconnect...");
                connect(localEndpointID, applicationID, reconnect, presence, appContext, new ConnectCompletionListener() {
                    @Override
                    public void onError(final String errorMessage) {
                        // A REST API call failed. Socket errors are handled in the onError callback
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                Listener listener = listenerReference.get();
                                if (null != listener) {
                                    listener.onError(RespokeClient.this, errorMessage);
                                }
                            }
                        });

                        // Try again later
                        performReconnect();
                    }
                });
            }
        }
    }
1235845
def new_conn(self):
        
        """
        :return:
        """
        logger.debug("Opening new connection to rethinkdb with args=%s" % self._conn_args)
        return ConnectionWrapper(self._pool, **self._conn_args)
459908
def reconnect(self, conn_retries=None):
        '''  '''
        if conn_retries is None:
            conn_retries = self.conn_retries

        count = 0
        if self.logger:
            self.logger.info('Connecting to Redis..')
        while count < conn_retries:
            super(redis.client.Redis, self).__init__(*self.args, **self.kwargs)

            if self.ping():
                if self.logger:
                    self.logger.info('Connected to Redis!')
                return True
            else:
                sl = min(3 ** count, self.max_sleep)
                if self.logger:
                    self.logger.info('Connecting failed, retrying in {0} seconds'.format(sl))
                time.sleep(sl)
                count += 1
        raise ConnectionError
1021791
def __get_connection(self) -> redis.Redis:
        

        if self.__redis_use_socket:
            r = redis.from_url(
                'unix://{:s}?db={:d}'.format(
                    self.__redis_host,
                    self.__redis_db
                )
            )
        else:
            r = redis.from_url(
                'redis://{:s}:{:d}/{:d}'.format(
                    self.__redis_host,
                    self.__redis_port,
                    self.__redis_db
                )
            )

        if BlackRed.Settings.REDIS_AUTH is not None:
            r.execute_command('AUTH {:s}'.format(BlackRed.Settings.REDIS_AUTH))
        return r
536200
def reconnect(self):
        """"""
        parsed = urlparse.urlparse(self.amqp_url)
        port = parsed.port or 5672
        self.connection = amqp.Connection(host="%s:%s" % (parsed.hostname, port),
                                          userid=parsed.username or 'guest',
                                          password=parsed.password or 'guest',
                                          virtual_host=unquote(
                                              parsed.path.lstrip('/') or '%2F'))
        self.channel = self.connection.channel()
        try:
            self.channel.queue_declare(self.name)
        except amqp.exceptions.PreconditionFailed:
            pass
936967
def reconnect(self):
        
        connect_attempt = 0
        max_retries = self.config['max_reconnect_retries']
        logging.info('attempting to reconnect to crossbar')
        runner = self.setup_runner()
        while True:

            if connect_attempt == max_retries:
                logging.info('max retries reached; stopping service')
                sys.exit(1)
            self.check_event_loop()

            try:
                logging.info('waiting 5 seconds')
                time.sleep(5)
                if self.check_transport_host():
                    logging.info('waiting 10 seconds to ensure that crossbar has initialized before reconnecting')
                    time.sleep(10)
                    runner.run(Component)
                else:
                    logging.error('crossbar host port 8080 not available...')
            except RuntimeError as error:
                logging.error(error)
            except ConnectionRefusedError as error:
                logging.error(error)
            except ConnectionError as error:
                logging.error(error)
            except KeyboardInterrupt:
                logging.info('User initiated shutdown')
                loop = asyncio.get_event_loop()
                loop.stop()
                sys.exit(1)
            connect_attempt += 1
35710
def reconnect(self):
        """"""
        if len(self._host) == 0:
            raise ValueError('Invalid host.')
        if self._port <= 0:
            raise ValueError('Invalid port number.')

        self._in_packet = {
            "command": 0,
            "have_remaining": 0,
            "remaining_count": [],
            "remaining_mult": 1,
            "remaining_length": 0,
            "packet": b"",
            "to_process": 0,
            "pos": 0}

        self._out_packet_mutex.acquire()
        self._out_packet = []
        self._out_packet_mutex.release()

        self._current_out_packet_mutex.acquire()
        self._current_out_packet = None
        self._current_out_packet_mutex.release()

        self._msgtime_mutex.acquire()
        self._last_msg_in = time.time()
        self._last_msg_out = time.time()
        self._msgtime_mutex.release()

        self._ping_t = 0
        self._state_mutex.acquire()
        self._state = mqtt_cs_new
        self._state_mutex.release()
        if self._ssl:
            self._ssl.close()
            self._ssl = None
            self._sock = None
        elif self._sock:
            self._sock.close()
            self._sock = None

        # Put messages in progress in a valid state.
        self._messages_reconnect_reset()

        try:
            if (sys.version_info[0] == 2 and sys.version_info[1] < 7) or (sys.version_info[0] == 3 and sys.version_info[1] < 2):
                sock = socket.create_connection((self._host, self._port))
            else:
                sock = socket.create_connection((self._host, self._port), source_address=(self._bind_address, 0))
        except socket.error as err:
            if err.errno != errno.EINPROGRESS and err.errno != errno.EWOULDBLOCK and err.errno != EAGAIN:
                raise

        verify_hostname = self._tls_insecure is False  # Decide whether we need to verify hostname

        if self._tls_ca_certs is not None:
            if self._useSecuredWebsocket:
                # Never assign to ._ssl before wss handshake is finished
                # Non-None value for ._ssl will allow ops before wss-MQTT connection is established
                rawSSL = ssl.wrap_socket(sock, ca_certs=self._tls_ca_certs, cert_reqs=ssl.CERT_REQUIRED)  # Add server certificate verification
                rawSSL.setblocking(0)  # Non-blocking socket
                self._ssl = SecuredWebSocketCore(rawSSL, self._host, self._port, self._AWSAccessKeyIDCustomConfig, self._AWSSecretAccessKeyCustomConfig, self._AWSSessionTokenCustomConfig)  # Override the _ssl socket
                # self._ssl.enableDebug()
            elif self._alpn_protocols is not None:
                # SSLContext is required to enable ALPN support
                # Assuming Python 2.7.10+/3.5+ till the end of this elif branch
                ssl_context = SSLContextBuilder()\
                    .with_ca_certs(self._tls_ca_certs)\
                    .with_cert_key_pair(self._tls_certfile, self._tls_keyfile)\
                    .with_cert_reqs(self._tls_cert_reqs)\
                    .with_check_hostname(True)\
                    .with_ciphers(self._tls_ciphers)\
                    .with_alpn_protocols(self._alpn_protocols)\
                    .build()
                self._ssl = ssl_context.wrap_socket(sock, server_hostname=self._host, do_handshake_on_connect=False)
                verify_hostname = False  # Since check_hostname in SSLContext is already set to True, no need to verify it again
                self._ssl.do_handshake()
            else:
                self._ssl = ssl.wrap_socket(
                    sock,
                    certfile=self._tls_certfile,
                    keyfile=self._tls_keyfile,
                    ca_certs=self._tls_ca_certs,
                    cert_reqs=self._tls_cert_reqs,
                    ssl_version=self._tls_version,
                    ciphers=self._tls_ciphers)

            if verify_hostname:
                if sys.version_info[0] < 3 or (sys.version_info[0] == 3 and sys.version_info[1] < 5):  # No IP host match before 3.5.x
                    self._tls_match_hostname()
                else:
                    ssl.match_hostname(self._ssl.getpeercert(), self._host)

        self._sock = sock

        if self._ssl and not self._useSecuredWebsocket:
            self._ssl.setblocking(0)  # For X.509 cert mutual auth.
        elif not self._ssl:
            self._sock.setblocking(0)  # For plain socket
        else:
            pass  # For MQTT over WebSocket

        return self._send_connect(self._keepalive, self._clean_session)
497595
def ensure_connected(self):
        """"""
        if not self.is_connected():
            if not self._auto_connect:
                raise DBALConnectionError.connection_closed()
            self.connect()
1231540
def _Connect(host=None,
             port=None,
             user=None,
             password=None,
             database=None,
             client_key_path=None,
             client_cert_path=None,
             ca_cert_path=None):
  """"""
  connection_args = _GetConnectionArgs(
      host=host,
      port=port,
      user=user,
      password=password,
      database=database,
      client_key_path=client_key_path,
      client_cert_path=client_cert_path,
      ca_cert_path=ca_cert_path)

  conn = MySQLdb.Connect(**connection_args)
  with contextlib.closing(conn.cursor()) as cursor:
    _CheckForSSL(cursor)
    _SetMariaDBMode(cursor)
    _SetSqlMode(cursor)
    _SetBinlogFormat(cursor)
    _SetPacketSizeForFollowingConnections(cursor)
    _SetEncoding(cursor)
    _CheckConnectionEncoding(cursor)
    _CheckLogFileSize(cursor)

  return conn
1144874
def _connect(self):
        """"""
        while self.protocol:
            _LOGGER.info('Trying to connect to %s', self.port)
            try:
                ser = serial.serial_for_url(
                    self.port, self.baud, timeout=self.timeout)
            except serial.SerialException:
                _LOGGER.error('Unable to connect to %s', self.port)
                _LOGGER.info(
                    'Waiting %s secs before trying to connect again',
                    self.reconnect_timeout)
                time.sleep(self.reconnect_timeout)
            else:
                transport = serial.threaded.ReaderThread(
                    ser, lambda: self.protocol)
                transport.daemon = False
                poll_thread = threading.Thread(target=self._poll_queue)
                self._stop_event.clear()
                poll_thread.start()
                transport.start()
                transport.connect()
                return
5869
def _maybe_reconnect(self):
    """"""
    with self._lock:
      if not self._connected: 
        _LOGGER.info("Connecting")
        self._do_login_locked()
        self._connected = True
        self._connect_cond.notify_all()
        _LOGGER.info("Connected")