Connect is only called after creation
164454
void connect(boolean reconnectOnConnect) throws InterruptedException, IOException {
        if (options.getServers().size() == 0) {
            throw new IllegalArgumentException("No servers provided in options");
        }

        for (String serverURI : getServers()) {

            if (isClosed()) {
                break;
            }

            updateStatus(Status.CONNECTING);

            tryToConnect(serverURI);

            if (isConnected()) {
                break;
            } else {
                updateStatus(Status.DISCONNECTED);
            }
        }

        if (!isConnected() && !isClosed()) {
            if (reconnectOnConnect) {
                reconnect();
            } else {
                close();
                throw new IOException("Unable to connect to gnatsd server.");
            }
        }
    }
721101
def connect_or_create(self, overwrite=False):
        
        connection = self._get_connection()
        if connection:
            return connection
        else:
            return self.create(overwrite=overwrite)
865328
def connect(self, protocolFactory):
        
        deferred = self._startProcess()
        deferred.addCallback(self._connectRelay, protocolFactory)
        deferred.addCallback(self._startRelay)
        return deferred
102617
@Override
    public void connectAsynch(Object _udpRequestContextObject) {
        try {
            connectCommon(_udpRequestContextObject);
            getApplicationCallback().ready(vc);
        } catch (IOException e) {
            getApplicationCallback().destroy(e);
        }
    }
1131868
public void createConnection(ICredentials credentials, ConnectorClusterConfig config) throws ConnectionException {
        logger.info("Creating new connection...");
        Connection connection = createNativeConnection(credentials, config);

        String connectionName = config.getName().getName();

        synchronized (connections) {
            if (!connections.containsKey(connectionName)) {
                connections.put(connectionName, connection);
                logger.info("Connected to [" + connectionName + "]");

            } else {
                String msg = "The connection [" + connectionName + "] already exists";
                logger.error(msg);
                throw new ConnectionException(msg);
            }
        }

    }
810721
private void connect(String host, int port) throws SQLException, IOException {
    try {
      socket = Utils.createSocket(urlParser, host);
      if (options.socketTimeout != null) {
        socket.setSoTimeout(options.socketTimeout);
      }

      initializeSocketOption();

      // Bind the socket to a particular interface if the connection property
      // localSocketAddress has been defined.
      if (options.localSocketAddress != null) {
        InetSocketAddress localAddress = new InetSocketAddress(options.localSocketAddress, 0);
        socket.bind(localAddress);
      }

      if (!socket.isConnected()) {
        InetSocketAddress sockAddr =
            urlParser.getOptions().pipe == null ? new InetSocketAddress(host, port) : null;
        if (options.connectTimeout != 0) {
          socket.connect(sockAddr, options.connectTimeout);
        } else {
          socket.connect(sockAddr);
        }
      }

      handleConnectionPhases(host);

      connected = true;

      if (options.useCompression) {
        writer = new CompressPacketOutputStream(writer.getOutputStream(),
            options.maxQuerySizeToLog);
        reader = new DecompressPacketInputStream(
            ((StandardPacketInputStream) reader).getInputStream(),
            options.maxQuerySizeToLog);
        if (options.enablePacketDebug) {
          writer.setTraceCache(traceCache);
          reader.setTraceCache(traceCache);
        }
      }

      boolean mustLoadAdditionalInfo = true;
      if (globalInfo != null) {
        if (globalInfo.isAutocommit() == options.autocommit) {
          mustLoadAdditionalInfo = false;
        }
      }

      if (mustLoadAdditionalInfo) {
        Map<String, String> serverData = new TreeMap<>();
        if (options.usePipelineAuth && !options.createDatabaseIfNotExist) {
          try {
            sendPipelineAdditionalData();
            readPipelineAdditionalData(serverData);
          } catch (SQLException sqle) {
            if ("08".equals(sqle.getSQLState())) {
              throw sqle;
            }
            //in case pipeline is not supported
            //(proxy flush socket after reading first packet)
            additionalData(serverData);
          }
        } else {
          additionalData(serverData);
        }

        writer.setMaxAllowedPacket(Integer.parseInt(serverData.get("max_allowed_packet")));
        autoIncrementIncrement = Integer.parseInt(serverData.get("auto_increment_increment"));
        loadCalendar(serverData.get("time_zone"), serverData.get("system_time_zone"));

      } else {

        writer.setMaxAllowedPacket((int) globalInfo.getMaxAllowedPacket());
        autoIncrementIncrement = globalInfo.getAutoIncrementIncrement();
        loadCalendar(globalInfo.getTimeZone(), globalInfo.getSystemTimeZone());
      }

      reader.setServerThreadId(this.serverThreadId, isMasterConnection());
      writer.setServerThreadId(this.serverThreadId, isMasterConnection());

      activeStreamingResult = null;
      hostFailed = false;
    } catch (IOException | SQLException ioException) {
      ensureClosingSocketOnException();
      throw ioException;
    }
  }
805549
function (successCallback, errorCallback, deviceId) {
		winble.logger.logApiEntry("connect");
		winble.deviceManager.connectToDevice(successCallback, errorCallback, deviceId);
		winble.logger.logApiExit("connect");
	}
323782
def _start_connect(self, connect_type):
        
        if self._connect_state.value != self.CS_NOT_CONNECTED:
            # already done or in process, assume success
            return

        self._connected.value = 0
        self._connect_state.value = self.CS_ATTEMPTING_CONNECT
        # tell comm process to attempt connection
        self._attempting_connect.value = connect_type

        # EXTREMELY IMPORTANT - for this to work at all in Windows,
        # where the above processes are spawned (vs forked in Unix),
        # the thread objects (as sattributes of this object) must be
        # assigned to this object AFTER we have spawned the processes.
        # That way, multiprocessing can pickle the freshroastsr700
        # successfully. (It can't pickle thread-related stuff.)
        if self.update_data_func is not None:
            # Need to launch the thread that will listen to the event
            self._create_update_data_system(
                None, setFunc=False, createThread=True)
            self.update_data_thread.start()
        if self.state_transition_func is not None:
            # Need to launch the thread that will listen to the event
            self._create_state_transition_system(
                None, setFunc=False, createThread=True)
            self.state_transition_thread.start()
905515
function connect() {
      var props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
      var callback = arguments[1];

      this.host = props.host || '127.0.0.1';
      this.port = props.port || 21000;
      this.resultType = props.resultType || null;
      this.timeout = props.timeout || 1000;
      this.transport = props.transport || _thrift2.default.TBufferedTransport;
      this.protocol = props.protocol || _thrift2.default.TBinaryProtocol;
      this.options = {
        transport: this.transport,
        protocol: this.protocol,
        timeout: this.timeout
      };

      var deferred = _thrift.Q.defer();

      var connection = _thrift2.default.createConnection(this.host, this.port, this.options);
      var client = _thrift2.default.createClient(_ImpalaService2.default, connection);

      connection.on('error', ImpalaClient.onErrorDeferred(deferred));

      connection.on('connect', function () {
        deferred.resolve('Connection is established.');
      });

      this.client = client;
      this.connection = connection;

      deferred.promise.nodeify(callback);
      return deferred.promise;
    }
1188738
def _do_connect(self):
        """"""
        _, self._protocol = yield from self._loop.create_connection(
            lambda: SnapcastProtocol(self._callbacks), self._host, self._port)
765870
function Connect()
	{
		$this->handler->Log(DBH_LOG_INFO, "Opening Connection...");
		if ($this->dbopen)
		{
			$this->handler->Log(DBH_LOG_WARNING, "Connection Already Open");
		}
		else
		{
			$this->adapter = new DataAdapter($this->csetting);
			
			try {
				$this->adapter->Open();
			}
			catch (Exception $ex) {
				$this->handler->Crash(DatabaseException::$CONNECTION_ERROR,$ex->getMessage());
			}

			$this->handler->Log(DBH_LOG_INFO, "Connection Open");
			$this->dbopen = true;
		}
	}
307064
private void addConnection() throws SQLException {

    //create new connection
    Protocol protocol = Utils.retrieveProxy(urlParser, globalInfo);
    MariaDbConnection connection = new MariaDbConnection(protocol);
    MariaDbPooledConnection pooledConnection = createPoolConnection(connection);

    if (options.staticGlobal) {
      //on first connection load initial state
      if (globalInfo == null) {
        initializePoolGlobalState(connection);
      }
      //set default transaction isolation level to permit resetting to initial state
      connection.setDefaultTransactionIsolation(globalInfo.getDefaultTransactionIsolation());
    } else {
      //set default transaction isolation level to permit resetting to initial state
      connection.setDefaultTransactionIsolation(connection.getTransactionIsolation());
    }

    if (poolState.get() == POOL_STATE_OK
        && totalConnection.incrementAndGet() <= options.maxPoolSize) {
      idleConnections.addFirst(pooledConnection);

      if (logger.isDebugEnabled()) {
        logger.debug("pool {} new physical connection created (total:{}, active:{}, pending:{})",
            poolTag, totalConnection.get(), getActiveConnections(), pendingRequestNumber.get());
      }
      return;
    }

    silentCloseConnection(pooledConnection);
  }
499919
function onConnect(err) {
    if (err) {
      DEBUG("connect error", err)
      return cb(err)
    }

    DEBUG("connected")

    channel.sendMessage({
      type: "request",
      name: "connect",
      to:   "server",
      id:   "0",
      body: {
        key: config.key
      }
    })
  }
485493
public void connectClient(Connection connection) {
    threadContext.checkThread();

    // Note we do not use method references here because the "state" variable changes over time.
    // We have to use lambdas to ensure the request handler points to the current state.
    connection.handler(RegisterRequest.class, (Function<RegisterRequest, CompletableFuture<RegisterResponse>>) request -> state.register(request));
    connection.handler(ConnectRequest.class, (Function<ConnectRequest, CompletableFuture<ConnectResponse>>) request -> state.connect(request, connection));
    connection.handler(KeepAliveRequest.class, (Function<KeepAliveRequest, CompletableFuture<KeepAliveResponse>>) request -> state.keepAlive(request));
    connection.handler(UnregisterRequest.class, (Function<UnregisterRequest, CompletableFuture<UnregisterResponse>>) request -> state.unregister(request));
    connection.handler(ResetRequest.class, (Consumer<ResetRequest>) request -> state.reset(request));
    connection.handler(CommandRequest.class, (Function<CommandRequest, CompletableFuture<CommandResponse>>) request -> state.command(request));
    connection.handler(QueryRequest.class, (Function<QueryRequest, CompletableFuture<QueryResponse>>) request -> state.query(request));

    connection.onClose(stateMachine.executor().context().sessions()::unregisterConnection);
  }
474422
def _connect(self, sock, addr, timeout):
        """"""
        if self.connection:
            raise SocketClientConnectedError()

        if self.connector:
            raise SocketClientConnectingError()

        self.connect_deferred = Deferred(self.loop)
        self.sock = sock
        self.addr = addr
        self.connector = Connector(self.loop, sock, addr, timeout)
        self.connector.deferred.add_callback(self._connected)
        self.connector.deferred.add_errback(self._connect_failed)
        self.connector.start()

        return self.connect_deferred
69838
def __start_connection(self, context, node, ccallbacks=None):
        """"""

        _logger.debug("Creating connection object: CONTEXT=[%s] NODE=[%s]", 
                      context, node)

        c = nsq.connection.Connection(
                context,
                node, 
                self.__identify, 
                self.__message_handler,
                self.__quit_ev,
                ccallbacks,
                ignore_quit=self.__connection_ignore_quit)

        g = gevent.spawn(c.run)

        # Now, wait for the thread to finish the connection.

        timeout_s = nsq.config.client.NEW_CONNECTION_NEGOTIATE_TIMEOUT_S
        if c.connected_ev.wait(timeout_s) is False:
            _logger.error("New connection to server [%s] timed-out. Cleaning-"
                          "up thread.", node)

            g.kill()
            g.join()

            # We'll try again on the next audit.

            raise EnvironmentError("Connection to server [%s] failed." % 
                                   (node,))

        self.__connections.append((node, c, g))
303130
def connect(self, name, callback):
        ''''''
        if not self._callbacks[name]:
            self._callbacks[name] = callback
        else:
            raise HookAlreadyConnectedError('Callback hook already connected.')