Samples nh ids from each strata by using Stratified Sampling

@param strataIdList
@param nh
@param withReplacement
@return
545786
public static TransposeDataCollection randomSampling(TransposeDataList strataIdList, AssociativeArray nh, boolean withReplacement) {
        TransposeDataCollection sampledIds = new TransposeDataCollection();
    
        for(Map.Entry<Object, FlatDataList> entry : strataIdList.entrySet()) {
            Object strata = entry.getKey();
            
            Number sampleN =  ((Number)nh.get(strata));
            if(sampleN==null) {
                continue;
            }
            
            sampledIds.put(strata, SimpleRandomSampling.randomSampling(entry.getValue(), sampleN.intValue(), withReplacement));
        }
        
        return sampledIds;
    }
139150
public ParallelTaskBuilder setReplaceVarMapToSingleTargetSingleVar(
            String variable, List<String> replaceList, String uniformTargetHost) {

        if (Strings.isNullOrEmpty(uniformTargetHost)) {
            logger.error("uniform target host is empty or null. skil setting.");
            return this;
        }
        this.replacementVarMapNodeSpecific.clear();
        this.targetHosts.clear();
        int i = 0;
        for (String replace : replaceList) {
            if (replace == null){
                logger.error("null replacement.. skip");
                continue;
            }
            String hostName = PcConstants.API_PREFIX + i;

            replacementVarMapNodeSpecific.put(
                    hostName,
                    new StrStrMap().addPair(variable, replace).addPair(
                            PcConstants.UNIFORM_TARGET_HOST_VAR,
                            uniformTargetHost));
            targetHosts.add(hostName);
            ++i;
        }
        this.requestReplacementType = RequestReplacementType.TARGET_HOST_SPECIFIC_VAR_REPLACEMENT;
        logger.info(
                "Set requestReplacementType as {} for single target. Will disable the set target hosts."
                        + "Also Simulated "
                        + "Now Already set targetHost list with size {}. \nPLEASE NOT TO SET TARGET HOSTS AGAIN WITH THIS API.",
                requestReplacementType.toString(), targetHosts.size());

        return this;
    }
343230
public ParallelTaskBuilder setReplacementVarMapNodeSpecific(
            Map<String, StrStrMap> replacementVarMapNodeSpecific) {
        this.replacementVarMapNodeSpecific.clear();
        this.replacementVarMapNodeSpecific
                .putAll(replacementVarMapNodeSpecific);

        this.requestReplacementType = RequestReplacementType.TARGET_HOST_SPECIFIC_VAR_REPLACEMENT;
        logger.info("Set requestReplacementType as {}"
                + requestReplacementType.toString());
        return this;
    }
113745
public Task<DocumentT> findOneAndReplace(final Bson filter, final Bson replacement) {
    return dispatcher.dispatchTask(new Callable<DocumentT>() {
      @Override
      public DocumentT call() {
        return proxy.findOneAndReplace(filter, replacement);
      }
    });
  }
1128275
public static <E> Collection<E> sampleWithoutReplacement(Collection<E> c, int n, Random r) {
    if (n < 0)
      throw new IllegalArgumentException("n < 0: " + n);
    if (n > c.size())
      throw new IllegalArgumentException("n > size of collection: " + n + ", " + c.size());
    List<E> copy = new ArrayList<E>(c.size());
    copy.addAll(c);
    Collection<E> result = new ArrayList<E>(n);
    for (int k = 0; k < n; k++) {
      double d = r.nextDouble();
      int x = (int) (d * copy.size());
      result.add(copy.remove(x));
    }
    return result;
  }
1055328
@SuppressWarnings("unchecked")
    private IDataSet performReplacements(IDataSet dataSet) {
        if (!dbUnitConfig.getProperties().containsKey("replacers")) {
            return dataSet;
        }
        return performReplacements(dataSet, (List<Replacer>) dbUnitConfig.getProperties().get("replacers"));
    }
1088467
def _sample_item(self, **kwargs):
        
        t = self.t_
        if 'fixed_stratum' in kwargs:
            stratum_idx = kwargs['fixed_stratum']
        else:
            stratum_idx = None
        if stratum_idx is not None:
            # Sample in given stratum
            loc = self.strata._sample_in_stratum(stratum_idx, replace=False)
            # Record instrumental distribution
            if self.record_inst_hist:
                self.inst_pmf_[stratum_idx,t] = 1
        else:
            # Choose stratum based on instrumental distribution
            self._calc_inst_pmf()

            if self.record_inst_hist:
                inst_pmf = self.inst_pmf_[:,t]
            else:
                inst_pmf = self.inst_pmf_

            loc, stratum_idx = self.strata.sample(pmf = inst_pmf, replace=False)

        return loc, 1, {'stratum': stratum_idx}
386863
@Override
    public DataSet sample(int numSamples, org.nd4j.linalg.api.rng.Random rng, boolean withReplacement) {
        Set<Integer> added = new HashSet<>();
        List<DataSet> toMerge = new ArrayList<>();
        boolean terminate = false;
        for (int i = 0; i < numSamples && !terminate; i++) {
            int picked = rng.nextInt(numExamples());
            if (!withReplacement) {
                while (added.contains(picked)) {
                    picked = rng.nextInt(numExamples());
                    if(added.size() == numExamples()){
                        terminate = true;
                        break;
                    }
                }
            }
            added.add(picked);
            toMerge.add(get(picked));
        }
        return DataSet.merge(toMerge);
    }
215961
private CmsUUID maybeReplaceFormatter(CmsUUID formatterId) {

        if (m_customReplacements != null) {
            CmsUUID replacement = m_customReplacements.get(formatterId);
            if (replacement != null) {
                return replacement;
            }
        }
        return formatterId;
    }
359332
public ParallelTaskBuilder setReplaceVarMapToSingleTargetFromMap(
            Map<String, StrStrMap> replacementVarMapNodeSpecific,
            String uniformTargetHost) {
        setReplacementVarMapNodeSpecific(replacementVarMapNodeSpecific);

        if (Strings.isNullOrEmpty(uniformTargetHost)) {
            logger.error("uniform target host is empty or null. skip setting.");
            return this;
        }
        for (Entry<String, StrStrMap> entry : replacementVarMapNodeSpecific
                .entrySet()) {

            if (entry.getValue() != null) {
                entry.getValue().addPair(PcConstants.UNIFORM_TARGET_HOST_VAR,
                        uniformTargetHost);
            }
        }
        return this;
    }
342697
public List<StepCandidate> collectCandidates(List<CandidateSteps> candidateSteps) {
        List<StepCandidate> collected = new ArrayList<>();
        for (CandidateSteps steps : candidateSteps) {
            collected.addAll(steps.listCandidates());
        }
        return collected;
    }
1057310
def representative_sample(X, num_samples, save=False):
    
    X = X.values if hasattr(X, 'values') else np.array(X)
    N, M = X.shape
    rownums = np.arange(N)
    np.random.shuffle(rownums)

    idx = AnnoyIndex(M)
    for i, row in enumerate(X):
        idx.add_item(i, row)
    idx.build(int(np.log2(N)) + 1)

    if save:
        if isinstance(save, basestring):
            idxfilename = save
        else:
            idxfile = tempfile.NamedTemporaryFile(delete=False)
            idxfile.close()
            idxfilename = idxfile.name
        idx.save(idxfilename)
        idx = AnnoyIndex(M)
        idx.load(idxfile.name)

    samples = -1 * np.ones(shape=(num_samples,), dtype=int)
    samples[0] = rownums[0]
    # FIXME: some integer determined by N and num_samples and distribution
    j, num_nns = 0, min(1000, int(num_samples / 2. + 1))
    for i in rownums:
        if i in samples:
            continue
        nns = idx.get_nns_by_item(i, num_nns)
        # FIXME: pick vector furthest from past K (K > 1) points or outside of a hypercube
        #        (sized to uniformly fill the space) around the last sample
        samples[j + 1] = np.setdiff1d(nns, samples)[-1]
        if len(num_nns) < num_samples / 3.:
            num_nns = min(N, 1.3 * num_nns)
        j += 1
    return samples
968292
private IDataSet performReplacements(IDataSet dataSet, List<Replacer> replacersList) {

        if (replacersList == null || replacersList.isEmpty())
            return dataSet;

        ReplacementDataSet replacementSet = new ReplacementDataSet(dataSet);
        // convert to set to remove duplicates
        Set<Replacer> replacers = new HashSet<>((List<Replacer>) replacersList);
        for (Replacer replacer : replacers) {
            replacer.addReplacements(replacementSet);
        }

        return replacementSet;
    }
999679
public function randomSubsetWithReplacement(int $n) : self
    {
        if ($n < 1) {
            throw new InvalidArgumentException('Cannot generate a'
                . " subset of less than 1 sample, $n given.");
        }

        $max = $this->numRows() - 1;

        $samples = $labels = [];

        for ($i = 0; $i < $n; $i++) {
            $index = rand(0, $max);

            $samples[] = $this->samples[$index];
            $labels[] = $this->labels[$index];
        }

        return self::quick($samples, $labels);
    }
728339
private void cascadeInsertFor(ObjectEnvelope mod, List alreadyPrepared)
    {
        // avoid endless recursion, so use List for registration
        if(alreadyPrepared.contains(mod.getIdentity())) return;
        alreadyPrepared.add(mod.getIdentity());

        ClassDescriptor cld = getTransaction().getBroker().getClassDescriptor(mod.getObject().getClass());

        List refs = cld.getObjectReferenceDescriptors(true);
        cascadeInsertSingleReferences(mod, refs, alreadyPrepared);

        List colls = cld.getCollectionDescriptors(true);
        cascadeInsertCollectionReferences(mod, colls, alreadyPrepared);
    }
855161
public List<T> apply(List<T> selectedCandidates, Random rng)
    {
        List<T> population = selectedCandidates;
        for (EvolutionaryOperator<T> operator : pipeline)
        {
            population = operator.apply(population, rng);
        }
        return population;
    }
119574
public static TransposeDataCollection weightedProbabilitySampling(AssociativeArray2D strataFrequencyTable, AssociativeArray nh, boolean withReplacement) {
        TransposeDataCollection sampledIds = new TransposeDataCollection(); 
    
        for(Map.Entry<Object, AssociativeArray> entry : strataFrequencyTable.entrySet()) {
            Object strata = entry.getKey();
            
            Number sampleN =  ((Number)nh.get(strata));
            if(sampleN==null) {
                continue;
            }
            
            sampledIds.put(strata, SimpleRandomSampling.weightedSampling(entry.getValue(), sampleN.intValue(), withReplacement));
        }
        
        return sampledIds;
    }