Calculate the sampling query distribution
178426
def calc_query(self):
        """"""
        # initial query
        if self.query_dist is None:
            self.query_dist = self.exp4p_.next(-1, None, None)
        else:
            self.query_dist = self.exp4p_.next(
                self.calc_reward_fn(),
                self.queried_hist_[-1],
                self.dataset.data[self.queried_hist_[-1]][1]
            )
        return
296299
def _sample_aAt(self,n):
        """"""
        #Sample frequency along largest eigenvalue using ARS
        dO1s=\
            bovy_ars.bovy_ars([0.,0.],[True,False],
                              [self._meandO-numpy.sqrt(self._sortedSigOEig[2]),
                               self._meandO+numpy.sqrt(self._sortedSigOEig[2])],
                              _h_ars,_hp_ars,nsamples=n,
                              hxparams=(self._meandO,self._sortedSigOEig[2]),
                              maxn=100)
        dO1s= numpy.array(dO1s)*self._sigMeanSign
        dO2s= numpy.random.normal(size=n)*numpy.sqrt(self._sortedSigOEig[1])
        dO3s= numpy.random.normal(size=n)*numpy.sqrt(self._sortedSigOEig[0])
        #Rotate into dOs in R,phi,z coordinates
        dO= numpy.vstack((dO3s,dO2s,dO1s))
        dO= numpy.dot(self._sigomatrixEig[1][:,self._sigomatrixEigsortIndx],
                      dO)
        Om= dO+numpy.tile(self._progenitor_Omega.T,(n,1)).T
        #Also generate angles
        da= numpy.random.normal(size=(3,n))*self._sigangle
        #And a random time
        dt= self.sample_t(n)
        #Integrate the orbits relative to the progenitor
        da+= dO*numpy.tile(dt,(3,1))
        angle= da+numpy.tile(self._progenitor_angle.T,(n,1)).T
        return (Om,angle,dt)
915894
def sample_cc(self, nsamples=1, weighted=True):
        
        weights = self.areas / np.sum(self.areas) if weighted else None
        for index in np.random.choice(a=len(self.geometries), size=nsamples, p=weights):
            yield self.geometries[index]
1201604
def sample(N, D):
    """"""
    scale = 31
    result = np.zeros([N, D])
    
    if D > len(directions) + 1:
        raise ValueError("Error in Sobol sequence: not enough dimensions")

    L = int(math.ceil(math.log(N) / math.log(2)))

    if L > scale:
        raise ValueError("Error in Sobol sequence: not enough bits")

    for i in range(D):
        V = np.zeros(L + 1, dtype=long)

        if i == 0:
            for j in range(1, L + 1):
                V[j] = 1 << (scale - j)  # all m's = 1
        else:
            m = np.array(directions[i - 1], dtype=int)
            a = m[0]
            s = len(m) - 1

            # The following code discards the first row of the ``m`` array
            # Because it has floating point errors, e.g. values of 2.24e-314
            if L <= s:
                for j in range(1, L + 1):
                    V[j] = m[j] << (scale - j)
            else:
                for j in range(1, s + 1):
                    V[j] = m[j] << (scale - j)
                for j in range(s + 1, L + 1):
                    V[j] = V[j - s] ^ (V[j - s] >> s)
                    for k in range(1, s):
                        V[j] ^= ((a >> (s - 1 - k)) & 1) * V[j - k]

        X = long(0)
        for j in range(1, N):
            X ^= V[index_of_least_significant_zero_bit(j - 1)]
            result[j][i] = float(X / math.pow(2, scale))

    return result
128016
def generateAmplitudes(k):
    """"""
    res = np.array([np.random.random() for i in range(k)])
    return res/res.sum()
982387
def sample_discrete(distn,size=[],dtype=np.int32):
    ''
    distn = np.atleast_1d(distn)
    assert (distn >=0).all() and distn.ndim == 1
    if (0 == distn).all():
        return np.random.randint(distn.shape[0],size=size)
    cumvals = np.cumsum(distn)
    return np.sum(np.array(random(size))[...,na] * cumvals[-1] > cumvals, axis=-1,dtype=dtype)
699422
function sample(test, asap, minDuration, sampleSize, done) {
    var count = 0;
    var totalDuration = 0;
    var sampleDurations = [];
    next();
    function next() {
        measure(function (done) {
            test(asap, done);
        }, function (error, results, duration) {
            if (error) {
                done(error);
            }
            if (sampleDurations.length < sampleSize) {
                sampleDurations.push(duration);
            } else if (Math.random() < 1 / count) {
                sampleDurations.splice(Math.floor(Math.random() * sampleDurations.length), 1);
                sampleDurations.push(duration);
            }
            totalDuration += duration;
            count++;
            if (totalDuration >= minDuration) {
                done(null, {
                    name: test.name,
                    subjectName: asap.name,
                    count: count,
                    totalDuration: totalDuration,
                    averageFrequency: count / totalDuration,
                    averageDuration: totalDuration / count,
                    averageOpsHz: count / totalDuration,
                    sampleDurations: sampleDurations
                });
            } else {
                next();
            }
        });
    }
}
709032
def sample_uniform(in_range, seed_coins):
    """"""
    if isinstance(seed_coins, list):
        seed_coins.append(None)
        seed_coins = iter(seed_coins)
    cur_range = in_range.copy()
    assert cur_range.size() != 0
    while cur_range.size() > 1:
        mid = (cur_range.start + cur_range.end) // 2
        bit = next(seed_coins)
        if bit == 0:
            cur_range.end = mid
        elif bit == 1:
            cur_range.start = mid + 1
        elif bit is None:
            raise NotEnoughCoinsError()
        else:
            raise InvalidCoinError()
    assert cur_range.size() == 1
    return cur_range.start
1197615
def sample(self, num_rows=1):
        
        self.check_fit()

        res = {}
        means = np.zeros(self.covariance.shape[0])
        size = (num_rows,)

        clean_cov = np.nan_to_num(self.covariance)
        samples = np.random.multivariate_normal(means, clean_cov, size=size)

        for i, (label, distrib) in enumerate(self.distribs.items()):
            cdf = stats.norm.cdf(samples[:, i])
            res[label] = distrib.percent_point(cdf)

        return pd.DataFrame(data=res)
232639
def _sample_points(X, centers, oversampling_factor, random_state):
    

    """
    # re-implement evaluate_cost here, to avoid redundant computation
    distances = pairwise_distances(X, centers).min(1) ** 2
    denom = distances.sum()
    p = oversampling_factor * distances / denom

    draws = random_state.uniform(size=len(p), chunks=p.chunks)
    picked = p > draws

    new_idxs, = da.where(picked)
    return new_idxs
983805
def _sampler_n_samples(self, n_samples):
        
        sampler_indices = self.rng_.choice(range(len(self.samplers)),
                                           size=n_samples,
                                           replace=True,
                                           p=self.weights)
        return [
            (self.samplers[idx], freq)
            for idx, freq in itemfreq(sampler_indices)
        ]
1072559
def _sample_batch():
    
    if _sample_probability == 1.0 or random.random() < _sample_probability:
        return True

    # Pop off all the metrics for the batch
    for database in _measurements:
        _measurements[database] = _measurements[database][_max_batch_size:]
    return False
1332325
function (sampleQuery) {
        var q = $q.defer();
        $window.plugins.healthkit.querySampleType(sampleQuery,
          function (success) {
            q.resolve(success);
          },
          function (err) {
            q.resolve(err);
          }
        );
        return q.promise;
      }
1082401
private void transformRollupQueryToDownSampler()  {
    
    if (rollup_query != null) {
      // TODO - clean up and handle fill
      downsampler = new DownsamplingSpecification(
          rollup_query.getRollupInterval().getIntervalSeconds() * 1000, 
          rollup_query.getRollupAgg(),
          (downsampler != null ? downsampler.getFillPolicy() : 
            FillPolicy.ZERO));
      rollup_query = null;
    }
  }
847121
def samples(self, anystring, limit=None, offset=None, sortby=None):
        ''''''

        uri = self._uris['samples'].format(anystring)
        params = {'limit': limit, 'offset': offset, 'sortby': sortby}

        return self.get_parse(uri, params)
1166025
def compute_samples(self):
        
        eps = tf.random_normal([self.batch_size, self.eq_samples, self.iw_samples, self.num_latent])
        z = tf.reshape(eps * self.std + self.mu, [-1, self.num_latent])
        return z
486726
def randomPairs(n_records, sample_size):
    
    n = int(n_records * (n_records - 1) / 2)

    if sample_size >= n:
        random_pairs = numpy.arange(n, dtype='uint')
    else:
        try:
            random_pairs = numpy.array(random.sample(range(n), sample_size),
                                       dtype='uint')
        except OverflowError:
            return randomPairsWithReplacement(n_records, sample_size)

    b = 1 - 2 * n_records

    root = (-b - 2 * numpy.sqrt(2 * (n - random_pairs) + 0.25)) / 2

    i = numpy.floor(root).astype('uint')
    j = numpy.rint(random_pairs + i * (b + i + 2) / 2 + 1).astype('uint')

    return zip(i, j)