Samples n ids by using SimpleRandomSampling (Simple Random Sampling).

@param idList
@param n
@param withReplacement
@return
323245
public static FlatDataCollection randomSampling(FlatDataList idList, int n, boolean withReplacement) {
        FlatDataList sampledIds = new FlatDataList();
        
        int populationN = idList.size();
        
        for(int i=0;i<n;) {
            if(withReplacement==false && populationN<=n) {
                /* if replacement is not allowed and we already sampled everything that it can stop */
                break;
            }
            
            int randomPosition = PHPMethods.mt_rand(0, populationN-1);
            
            Object pointID = idList.get(randomPosition);
            
            if(withReplacement==false && sampledIds.contains(pointID)) {
                continue;
            }

            sampledIds.add(pointID);
            ++i;
            
            
        }
    
        return sampledIds.toFlatDataCollection();
    }
576537
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;

        $subset = [];

        for ($i = 0; $i < $n; $i++) {
            $subset[] = $this->samples[rand(0, $max)];
        }

        return self::quick($subset);
    }
899003
public List<T> apply(List<T> selectedCandidates, Random rng)
    {
        return new ArrayList<T>(selectedCandidates);
    }
250595
public static FlatDataCollection randomSampling(FlatDataList idList, int n, boolean randomizeRecords) {
        FlatDataList sampledIds = new FlatDataList();
        
        int populationN = idList.size();
        
        Object[] keys = idList.toArray();
        if(randomizeRecords) {
            PHPMethods.<Object>shuffle(keys);
        }
        
        int k = populationN/n; //number of systematics
        if(k<2) {
            throw new IllegalArgumentException("The number of systematics is too small.");
        }
        
        int randomSystematic = PHPMethods.mt_rand(0,k-1);
        
        for(int i=randomSystematic;i<keys.length;i+=k) {
            Object pointID = keys[i];
            sampledIds.add(pointID);
        }
    
        return sampledIds.toFlatDataCollection();
    }
431107
def rnumlistwithreplacement(howmany, max, min=0):
    """"""
    if checkquota() < 1:
        raise Exception("Your www.random.org quota has already run out.")
    requestparam = build_request_parameterWR(howmany, min, max)
    request = urllib.request.Request(requestparam)
    request.add_header('User-Agent', 'randomwrapy/0.1 very alpha')
    opener = urllib.request.build_opener()
    numlist = opener.open(request).read()
    return numlist.split()
1146290
def sample(self, n_to_sample, **kwargs):
        
        n_to_sample = verify_positive(int(n_to_sample))

        n_remaining = self._max_iter - self.t_

        if n_remaining == 0:
            if (not self.replace) and (self._n_items == self._max_iter):
                raise Exception("All items have already been sampled")
            else:
                raise Exception("No more space available to continue sampling. "
                                "Consider re-initialising with a larger value "
                                "of max_iter.")

        if n_to_sample > n_remaining:
            warnings.warn("Space only remains for {} more iteration(s). "
                          "Setting n_to_sample = {}.".format(n_remaining, \
                          n_remaining))
            n_to_sample = n_remaining

        for _ in range(n_to_sample):
            self._iterate(**kwargs)
371364
public static <T extends EurekaEndpoint> List<T> randomize(List<T> list) {
        List<T> randomList = new ArrayList<>(list);
        if (randomList.size() < 2) {
            return randomList;
        }
        Random random = new Random(LOCAL_IPV4_ADDRESS.hashCode());
        int last = randomList.size() - 1;
        for (int i = 0; i < last; i++) {
            int pos = random.nextInt(randomList.size() - i);
            if (pos != i) {
                Collections.swap(randomList, i, pos);
            }
        }
        return randomList;
    }
1338705
public void pollNToList(int n, List<T> retList) {
    if (n >= size) {
      // if we need to remove all elements then do fast polling
      pollAllToList(retList);
    }
    while (n-- > 0 && head != null) {
      T curr = head.element;
      this.removeElem(curr);
      retList.add(curr);
    }
    shrinkIfNecessary();
  }
49502
public static int[] sampleWithoutReplacement(int sampleSize, int n) {
        // This implements a modified form of the genshuf() function from
        // Programming Pearls pg. 129.
        
        // TODO: Design a faster method that only generates min(m, n-m) integers.
        
        int[] array = IntSort.getIndexArray(n);
        for (int i=0; i<sampleSize; i++) {
            int j = Prng.nextInt(n - i) + i;
            // Swap array[i] and array[j]
            int tmp = array[i];
            array[i] = array[j];
            array[j] = tmp;
        }
        return Arrays.copyOf(array, sampleSize);
    }
1118266
public UpdatableSketchBuilder<U, S> setSamplingProbability(final float samplingProbability) {
    if ((samplingProbability < 0) || (samplingProbability > 1f)) {
      throw new SketchesArgumentException("sampling probability must be between 0 and 1");
    }
    samplingProbability_ = samplingProbability;
    return this;
  }
954688
def resample(self,N):
        
        return rand.random(size=N)*(self.maxval - self.minval) + self.minval
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;
    }
1374333
public static ModifiableDBIDs randomSampleExcept(DBIDs source, DBIDRef except, int k, Random random) {
    if(k < 0 || k > source.size()) {
      throw new IllegalArgumentException("Illegal value for size of random sample: " + k + " > " + source.size() + " or < 0");
    }
    // Fast, and we're single-threaded here anyway.
    random = (random != null) ? random : new FastNonThreadsafeRandom();

    // TODO: better balancing for different sizes
    // Two methods: constructive vs. destructive
    if(k < source.size() >> 2) {
      ArrayDBIDs aids = DBIDUtil.ensureArray(source);
      DBIDArrayIter iter = aids.iter();
      int size = aids.size();
      HashSetModifiableDBIDs sample = DBIDUtil.newHashSet(k);
      while(sample.size() < k) {
        if(!equal(iter.seek(random.nextInt(size)), except)) {
          sample.add(iter);
        }
      }
      return sample;
    }
    else {
      ArrayModifiableDBIDs sample = DBIDUtil.newArray(source);
      randomShuffle(sample, random, k);
      // Avoid excluded object:
      for(DBIDArrayIter iter = sample.iter(); iter.valid() && iter.getOffset() < k; iter.advance()) {
        if(equal(iter, except)) {
          sample.swap(iter.getOffset(), k);
          break; // Assuming that except occurrs only once!
        }
      }
      // Delete trailing elements
      for(int i = sample.size() - 1; i >= k; i--) {
        sample.remove(i);
      }
      return sample;
    }
  }
231430
public static <E> ImmutableList<E> shuffledCopy(List<? extends E> list, Random rng) {
    final ArrayList<E> shuffled = Lists.newArrayList(list);
    Collections.shuffle(shuffled, rng);
    return ImmutableList.copyOf(shuffled);
  }
119019
private int sampleNew(DBIDs ids, WritableDataStore<HashSetModifiableDBIDs> sampleNewNeighbors, WritableDataStore<HashSetModifiableDBIDs> newNeighborHash, int items) {
    int t = 0;
    for(DBIDIter iditer = ids.iter(); iditer.valid(); iditer.advance()) {
      KNNHeap realNeighbors = store.get(iditer);
      HashSetModifiableDBIDs newNeighbors = newNeighborHash.get(iditer);
      HashSetModifiableDBIDs realNewNeighbors = sampleNewNeighbors.get(iditer);
      realNewNeighbors.clear(); // Reuse
      for(DoubleDBIDListIter heapiter = realNeighbors.unorderedIterator(); heapiter.valid(); heapiter.advance()) {
        if(newNeighbors.contains(heapiter)) {
          realNewNeighbors.add(heapiter);
          t++;
        }
      }
      boundSize(realNewNeighbors, items);

      newNeighbors.removeDBIDs(realNewNeighbors);
      newNeighborHash.put(iditer, newNeighbors);
    }
    return t;
  }
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
424350
public void sampleSequenceRepeatedly(SequenceModel model, int numSamples) {
    int[] sequence = getRandomSequence(model);
    sampleSequenceRepeatedly(model, sequence, numSamples);
  }