Collect a random sample of the values in a particular
    field based on the reservoir sampling technique.
973208
def random_sample(value, field, row, num=10):
    
    # TODO: Could become a more general DQ piece.
    if value is None:
        field['has_nulls'] = True
        return
    if value in field['samples']:
        return
    if isinstance(value, basestring) and not len(value.strip()):
        field['has_empty'] = True
        return
    if len(field['samples']) < num:
        field['samples'].append(value)
        return
    j = random.randint(0, row)
    if j < (num - 1):
        field['samples'][j] = value
799247
def sample(args):
    
    from random import random

    p = OptionParser(sample.__doc__)
    opts, args = p.parse_args(args)

    if len(args) != 2:
        sys.exit(not p.print_help())

    vcffile, ratio = args
    ratio = float(ratio)
    fp = open(vcffile)
    pf = vcffile.rsplit(".", 1)[0]
    kept = pf + ".kept.vcf"
    withheld = pf + ".withheld.vcf"
    fwk = open(kept, "w")
    fww = open(withheld, "w")
    nkept = nwithheld = 0
    for row in fp:
        if row[0] == '#':
            print(row.strip(), file=fwk)
            continue
        if random() < ratio:
            nkept += 1
            print(row.strip(), file=fwk)
        else:
            nwithheld += 1
            print(row.strip(), file=fww)
    logging.debug("{0} records kept to `{1}`".format(nkept, kept))
    logging.debug("{0} records withheld to `{1}`".format(nwithheld, withheld))
804954
def random_sample(self, k=1):
        
        # k == 0: no work to do
        if k == 0:
            results = []
        # k == 1: same behavior on all versions of Redis
        elif k == 1:
            results = [self.redis.srandmember(self.key)]
        # k != 1, Redis version >= 2.6: compute in Redis
        else:
            results = self.redis.srandmember(self.key, k)

        return [self._unpickle(x) for x in results]
1023978
def _sample_item(self, **kwargs):
        """"""
        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=self.replace)
        else:
            loc, stratum_idx = self.strata.sample(pmf = self.strata.weights_,
                                                  replace=self.replace)

        return loc, 1, {'stratum': stratum_idx}
597114
protected boolean sample() {
        if (curr.increment() >= freq) {
            curr.set(0);
            target.set(rand.nextInt(freq));
        }
        return curr.get() == target.get();
    }
696478
def sample_random(self):
        
        if self.sampling_mode['volume']:  
            # Choose a leaf weighted by volume, randomly
            if self.leafnode:
                return self.sample_bounds()
            else:
                split_ratio = ((self.split_value - self.bounds_x[0,self.split_dim]) / 
                               (self.bounds_x[1,self.split_dim] - self.bounds_x[0,self.split_dim]))
                if split_ratio > np.random.random():
                    return self.lower.sample(sampling_mode=['random'])
                else:
                    return self.greater.sample(sampling_mode=['random'])
        else: 
            # Choose a leaf randomly
            return np.random.choice(self.get_leaves()).sample_bounds()
321070
def get_random_values(fields):
    
    values = {}

    for field in fields:
        try:
            value = get_random_value(field)
        except AttributeError:
            # this can only really occur if the field is not implemented yet.
            # Silencing the exception during the prototype phase
            value = None

        values.update({field: value})

    return values
870477
def sample_wr(population, k):
    ""
    n = len(population)
    _random, _int = random.random, int  # speed hack 
    result = [None] * k
    for i in xrange(k):
        j = _int(_random() * n)
        result[i] = population[j]
    return result
440427
def _sample_without_replacement(n, r, out):
    
    k = r.shape[0]

    # Logic taken from random.sample in the standard library
    pool = np.arange(n)
    for j in range(k):
        idx = int(np.floor(r[j] * (n-j)))  # np.floor returns a float
        out[j] = pool[idx]
        pool[idx] = pool[n-j-1]
155809
def _sampleFromEdges(self):
    
    dimensionsToChooseFrom = range(self.dimension)
    random.shuffle(dimensionsToChooseFrom)
    dim1, dim2 = dimensionsToChooseFrom[0], dimensionsToChooseFrom[1]
    coordinates = [random.uniform(-1, 1) * dim / 2. for dim in self.dimensions]
    coordinates[dim1] = self.dimensions[dim1] / 2. * random.choice([-1, 1])
    coordinates[dim2] = self.dimensions[dim2] / 2. * random.choice([-1, 1])
    return coordinates
80043
def sampleset(self, factor_bbox=10.0, num=1000):
        
        w1, w2 = self.bounding_box(factor=factor_bbox)

        if self._n_models == 1:
            w = np.logspace(w1, w2, num)
        else:
            w = list(map(partial(np.logspace, num=num), w1, w2))

        return np.asarray(w)
269029
def sample(self, logits, argmax_sampling=False):
        
        if argmax_sampling:
            return torch.argmax(logits, dim=-1)
        else:
            u = torch.rand_like(logits)
            return torch.argmax(logits - torch.log(-torch.log(u)), dim=-1)
312432
def sample(self, num_samples=1):
        
        self.check_fit()
        return np.random.normal(self.mean, self.std, num_samples)
15452
def fetch_sampling_target(self, rules):
        
        now = int(time.time())
        report_docs = self._generate_reporting_docs(rules, now)
        resp = self._xray_client.get_sampling_targets(
            SamplingStatisticsDocuments=report_docs
        )
        new_docs = resp['SamplingTargetDocuments']

        targets_mapping = {}
        for doc in new_docs:
            TTL = self._dt_to_epoch(doc['ReservoirQuotaTTL']) if doc.get('ReservoirQuotaTTL', None) else None
            target = {
                'rate': doc['FixedRate'],
                'quota': doc.get('ReservoirQuota', None),
                'TTL': TTL,
                'interval': doc.get('Interval', None),
            }
            targets_mapping[doc['RuleName']] = target

        return targets_mapping, self._dt_to_epoch(resp['LastRuleModification'])
566644
def fetch_sample(list, options = {})
      if (count = options.delete(:count))
        list.sample(count, random: FFaker::Random)
      else
        list.sample(random: FFaker::Random)
      end
    end
348861
def setSample(self, sample):
        """"""
        if not isinstance(sample, RDD):
            raise TypeError("samples should be a RDD, received %s" % type(sample))
        self._sample = sample
707920
private void growReservoir() {
    currItemsAlloc_ = SamplingUtil.getAdjustedSize(reservoirSize_, currItemsAlloc_ * rf_.getValue());
    data_ = java.util.Arrays.copyOf(data_, currItemsAlloc_);
  }