the associated ConnectFuture from the map of preconnect futures.
439312
private void addConnectFuture(ConnectFuture future) {
        Object key = connectFutures.add(future);
        future.getSession().setAttributeIfAbsent(CONNECT_FUTURE_KEY, key);
    }
1349516
@SuppressWarnings("unchecked")
  private void setupConnection(Address address, Connection connection, CompletableFuture<Connection> future) {
    LOGGER.debug("{} - Setting up connection to {}", id, address);

    this.connection = connection;

    connection.onClose(c -> {
      if (c.equals(this.connection)) {
        LOGGER.debug("{} - Connection closed", id);
        this.connection = null;
      }
    });
    connection.onException(c -> {
      if (c.equals(this.connection)) {
        LOGGER.debug("{} - Connection lost", id);
        this.connection = null;
      }
    });

    for (Map.Entry<Class<?>, Function> entry : handlers.entrySet()) {
      connection.handler(entry.getKey(), entry.getValue());
    }

    // When we first connect to a new server, first send a ConnectRequest to the server to establish
    // the connection with the server-side state machine.
    ConnectRequest request = ConnectRequest.builder()
      .withClientId(id)
      .build();

    LOGGER.trace("{} - Sending {}", id, request);
    connection.<ConnectRequest, ConnectResponse>sendAndReceive(request).whenComplete((r, e) -> handleConnectResponse(r, e, future));
  }
1101966
private CompletableFuture<Void> listen() {
    CompletableFuture<Void> future = new CompletableFuture<>();
    context.getThreadContext().executor().execute(() -> {
      internalServer.listen(cluster().member().serverAddress(), context::connectServer).whenComplete((internalResult, internalError) -> {
        if (internalError == null) {
          // If the client address is different than the server address, start a separate client server.
          if (clientServer != null) {
            clientServer.listen(cluster().member().clientAddress(), context::connectClient).whenComplete((clientResult, clientError) -> {
              started = true;
              future.complete(null);
            });
          } else {
            started = true;
            future.complete(null);
          }
        } else {
          future.completeExceptionally(internalError);
        }
      });
    });

    return future;
  }
426022
public static <T> Future<T> of(final Supplier<T> s) {
        return Future.of(CompletableFuture.supplyAsync(s));
    }
54446
def get_future(self):
        """"""
        now = dt.now()
        four_days = now + timedelta(hours=96)
        now = now.timestamp()
        four_days = four_days.timestamp()
        url = build_url(self.api_key, self.spot_id, self.fields,
                        self.unit, now, four_days)
        return get_msw(url)
1082818
private List<ConnectionFuture<StatefulRedisPubSubConnection<String, String>>> potentiallyConnectSentinels() {

        List<ConnectionFuture<StatefulRedisPubSubConnection<String, String>>> connectionFutures = new ArrayList<>();
        for (RedisURI sentinel : sentinels) {

            if (pubSubConnections.containsKey(sentinel)) {
                continue;
            }

            ConnectionFuture<StatefulRedisPubSubConnection<String, String>> future = redisClient.connectPubSubAsync(CODEC,
                    sentinel);
            pubSubConnections.put(sentinel, future);

            future.whenComplete((connection, throwable) -> {

                if (throwable != null || closed) {
                    pubSubConnections.remove(sentinel);
                }

                if (closed) {
                    connection.closeAsync();
                }
            });

            connectionFutures.add(future);
        }

        return connectionFutures;
    }
140843
function ConnectionCosts(forward_dimension, backward_dimension) {
    this.forward_dimension = forward_dimension;
    this.backward_dimension = backward_dimension;

    // leading 2 integers for forward_dimension, backward_dimension, respectively
    this.buffer = new Int16Array(forward_dimension * backward_dimension + 2);
    this.buffer[0] = forward_dimension;
    this.buffer[1] = backward_dimension;
}
680182
private <K, V> CompletableFuture<StatefulRedisClusterPubSubConnection<K, V>> connectClusterPubSubAsync(
            RedisCodec<K, V> codec) {

        if (partitions == null) {
            return Futures.failed(new IllegalStateException(
                    "Partitions not initialized. Initialize via RedisClusterClient.getPartitions()."));
        }

        activateTopologyRefreshIfNeeded();

        logger.debug("connectClusterPubSub(" + initialUris + ")");

        Mono<SocketAddress> socketAddressSupplier = getSocketAddressSupplier(TopologyComparators::sortByClientCount);

        PubSubClusterEndpoint<K, V> endpoint = new PubSubClusterEndpoint<K, V>(clientOptions, clientResources);
        RedisChannelWriter writer = endpoint;

        if (CommandExpiryWriter.isSupported(clientOptions)) {
            writer = new CommandExpiryWriter(writer, clientOptions, clientResources);
        }

        ClusterDistributionChannelWriter clusterWriter = new ClusterDistributionChannelWriter(clientOptions, writer,
                clusterTopologyRefreshScheduler);

        StatefulRedisClusterPubSubConnectionImpl<K, V> connection = new StatefulRedisClusterPubSubConnectionImpl<>(endpoint,
                clusterWriter, codec, timeout);

        ClusterPubSubConnectionProvider<K, V> pooledClusterConnectionProvider = new ClusterPubSubConnectionProvider<>(this,
                clusterWriter, codec, connection.getUpstreamListener(), clusterTopologyRefreshScheduler);

        clusterWriter.setClusterConnectionProvider(pooledClusterConnectionProvider);
        connection.setPartitions(partitions);

        Supplier<CommandHandler> commandHandlerSupplier = () -> new PubSubCommandHandler<>(clientOptions, clientResources,
                codec, endpoint);

        Mono<StatefulRedisClusterPubSubConnectionImpl<K, V>> connectionMono = Mono.defer(() -> connect(socketAddressSupplier,
                codec, endpoint, connection, commandHandlerSupplier));

        for (int i = 1; i < getConnectionAttempts(); i++) {
            connectionMono = connectionMono.onErrorResume(t -> connect(socketAddressSupplier, codec, endpoint, connection,
                    commandHandlerSupplier));
        }

        return connectionMono
                .flatMap(c -> c.reactive().command().collectList() //
                        .map(CommandDetailParser::parse) //
                                .doOnNext(detail -> c.setState(new RedisState(detail)))
                                .doOnError(e -> c.setState(new RedisState(Collections.emptyList()))).then(Mono.just(c))
                                .onErrorResume(RedisCommandExecutionException.class, e -> Mono.just(c)))
                .doOnNext(
                        c -> connection.registerCloseables(closeableResources, clusterWriter, pooledClusterConnectionProvider))
                .map(it -> (StatefulRedisClusterPubSubConnection<K, V>) it).toFuture();
    }
282071
def probConn (self, preCellsTags, postCellsTags, connParam):
    from .. import sim

    ''' '''
    if sim.cfg.verbose: print('Generating set of probabilistic connections (rule: %s) ...' % (connParam['label']))

    allRands = self.generateRandsPrePost(preCellsTags, postCellsTags)

    # get list of params that have a lambda function
    paramsStrFunc = [param for param in [p+'Func' for p in self.connStringFuncParams] if param in connParam]

    # copy the vars into args immediately and work out which keys are associated with lambda functions only once per method
    funcKeys = {}
    for paramStrFunc in paramsStrFunc:
        connParam[paramStrFunc + 'Args'] = connParam[paramStrFunc + 'Vars'].copy()
        funcKeys[paramStrFunc] = [key for key in connParam[paramStrFunc + 'Vars'] if callable(connParam[paramStrFunc + 'Vars'][key])]

    # probabilistic connections with disynapticBias (deprecated)
    if isinstance(connParam.get('disynapticBias', None), Number):  
        allPreGids = sim._gatherAllCellConnPreGids()
        prePreGids = {gid: allPreGids[gid] for gid in preCellsTags}
        postPreGids = {gid: allPreGids[gid] for gid in postCellsTags}
        
        probMatrix = {(preCellGid,postCellGid): connParam['probabilityFunc'][preCellGid,postCellGid] if 'probabilityFunc' in connParam else connParam['probability']
                                            for postCellGid,postCellTags in postCellsTags.items() # for each postsyn cell
                                            for preCellGid, preCellTags in preCellsTags.items()  # for each presyn cell
                                            if postCellGid in self.gid2lid}  # check if postsyn is in this node
        
        connGids = self._disynapticBiasProb2(probMatrix, allRands, connParam['disynapticBias'], prePreGids, postPreGids)
        for preCellGid, postCellGid in connGids:
            for paramStrFunc in paramsStrFunc: # call lambda functions to get weight func args
                connParam[paramStrFunc+'Args'] = {k:v if isinstance(v, Number) else v(preCellsTags[preCellGid],postCellsTags[postCellGid]) for k,v in connParam[paramStrFunc+'Vars'].items()}  
            self._addCellConn(connParam, preCellGid, postCellGid) # add connection

    # standard probabilistic conenctions   
    else:
        # calculate the conn preGids of the each pre and post cell
        # for postCellGid,postCellTags in sorted(postCellsTags.items()):  # for each postsyn cell
        for postCellGid,postCellTags in postCellsTags.items():  # for each postsyn cell  # for each postsyn cell
            if postCellGid in self.gid2lid:  # check if postsyn is in this node
                for preCellGid, preCellTags in preCellsTags.items(): # for each presyn cell
                    probability = connParam['probabilityFunc'][preCellGid,postCellGid] if 'probabilityFunc' in connParam else connParam['probability']
                    if probability >= allRands[preCellGid,postCellGid]:
                        for paramStrFunc in paramsStrFunc: # call lambda functions to get weight func args
                            # update the relevant FuncArgs dict where lambda functions are known to exist in the corresponding FuncVars dict
                            for funcKey in funcKeys[paramStrFunc]:
                                connParam[paramStrFunc + 'Args'][funcKey] = connParam[paramStrFunc + 'Vars'][funcKey](preCellTags, postCellTags)
                            # connParam[paramStrFunc+'Args'] = {k:v if isinstance(v, Number) else v(preCellTags,postCellTags) for k,v in connParam[paramStrFunc+'Vars'].items()}
                        self._addCellConn(connParam, preCellGid, postCellGid)
1285673
def incoming_connections(self):
        """"""

        # Incoming connections are on the left.
        return list(
            takewhile(lambda c: c.direction == INCOMING, self.connections)
        )
186388
def make_inverse_connectivity(conns, n_nod, ret_offsets=True):
    
    from itertools import chain

    iconn = [[] for ii in xrange( n_nod )]
    n_els = [0] * n_nod
    for ig, conn in enumerate( conns ):
        for iel, row in enumerate( conn ):
            for node in row:
                iconn[node].extend([ig, iel])
                n_els[node] += 1

    n_els = nm.array(n_els, dtype=nm.int32)
    iconn = nm.fromiter(chain(*iconn), nm.int32)

    if ret_offsets:
        offsets = nm.cumsum(nm.r_[0, n_els], dtype=nm.int32)
        return offsets, iconn

    else:
        return n_els, iconn
401685
@SuppressWarnings("unchecked")
    private Set<Integer> getPredecessors(Graph g, Integer vertex) {
        // The DirectedGraph cast seems to change the return type of the set
        // from Set<Integer> to just Set
        if (g instanceof DirectedGraph) {
            DirectedGraph<?> dg = (DirectedGraph)g;
            return dg.predecessors(vertex);
        }
        else {
            return g.getNeighbors(vertex);
        }
    }
534870
def connectivity_map(dset,prefix,x,y,z,radius=2):
    ''''''
    seed_series = nl.sphere_average(dset,x,y,z,radius)
    with tempfile.NamedTemporaryFile(delete=False) as temp:
        temp.write('\n'.join([str(x) for x in seed_series]))
    decon = nl.Decon()
    decon.input_dsets = dset
    decon.stim_files = {'seed':temp.name}
    decon.prefix = prefix
    decon.run()
    try:
        os.remove(temp.name)
    except:
        pass
314561
@Override
    public <R> Future<R> flatMap(final Function<? super T, ? extends MonadicValue<? extends R>> mapper) {
        return Future.<R>of(future.<R>thenCompose(t -> (CompletionStage<R>) Future.fromMonadicValue(mapper.apply(t)).getFuture()));
    }
333643
private static <V> ListenableFuture<List<V>> listFuture(
      ImmutableList<ListenableFuture<? extends V>> futures,
      boolean allMustSucceed, Executor listenerExecutor) {
    return new CombinedFuture<V, List<V>>(
        futures, allMustSucceed, listenerExecutor,
        new FutureCombiner<V, List<V>>() {
          @Override
          public List<V> combine(List<Optional<V>> values) {
            List<V> result = Lists.newArrayList();
            for (Optional<V> element : values) {
              result.add(element != null ? element.orNull() : null);
            }
            return Collections.unmodifiableList(result);
          }
        });
  }
1206061
def connectionMap(self, scene, nodes):
        
        output = {}
        connections = scene.connections()
        
        for node in nodes:
            inputs = []
            outputs = []
            
            for connection in connections:
                in_node = connection.inputNode()
                out_node = connection.outputNode()
                
                if node == in_node:
                    inputs.append(out_node)
                elif node == out_node:
                    outputs.append(in_node)
                
            output[node] = (inputs, outputs)
        
        return output
1244383
@Override
	public Iterable<OptimizerNode> getPredecessors() {
		List<OptimizerNode> allPredecessors = new ArrayList<OptimizerNode>();

		for (DagConnection dagConnection : getIncomingConnections()) {
			allPredecessors.add(dagConnection.getSource());
		}
		
		for (DagConnection conn : getBroadcastConnections()) {
			allPredecessors.add(conn.getSource());
		}
		
		return allPredecessors;
	}