http://stats.stackexchange.com/questions/68274/how-to-sample-from-an-exponential-distribution-using-rejection-sampling-in-php
509654
public function gaussian($max, $lambda = 0.2) {
    $tau = $max;
    $u = 1.0 * $this->getNext(0, self::MAX) / self::MAX;
    $x = - log(1 - (1 - exp(- $lambda * $tau)) * $u) / $lambda;
    $ran = (int) $x;
    if ( $ran >= $max ) $ran=$max-1; // If $tao and $lambda are wack
    return $ran;
  }
1274399
function encodeSample(sample) {
  /** @type {number} */
  let compandedValue; 
  sample = (sample ==-32768) ? -32767 : sample;
  /** @type {number} */
  let sign = ((~sample) >> 8) & 0x80; 
  if (!sign) {
    sample = sample * -1; 
  }
  if (sample > 32635) {
    sample = 32635; 
  }
  if (sample >= 256)  {
    /** @type {number} */
    let exponent = LOG_TABLE[(sample >> 8) & 0x7F];
    /** @type {number} */
    let mantissa = (sample >> (exponent + 3) ) & 0x0F; 
    compandedValue = ((exponent << 4) | mantissa); 
  } else {
    compandedValue = sample >> 4; 
  } 
  return compandedValue ^ (sign ^ 0x55);
}
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]
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)
835894
def sample(self, nsamples=100, seed=None):
        
        if nsamples < 1:
            raise ValueError("Number of samples must be larger than 0, got '%g'" % nsamples)

        if seed is None:
            seed = random.randint(0, 2 ** 32)

        if self.mode == 'spark':
            result = asarray(self.values.tordd().values().takeSample(False, nsamples, seed))

        else:
            inds = [int(k) for k in random.rand(nsamples) * self.shape[0]]
            result = asarray([self.values[i] for i in inds])

        return self._constructor(result)
615564
def sample(generator, min=-1, max=1, width=SAMPLE_WIDTH):
	''''''
	# select signed char, short, or in based on sample width
	fmt = { 1: '<B', 2: '<h', 4: '<i' }[width]
	return (struct.pack(fmt, int(sample)) for sample in \
			normalize(hard_clip(generator, min, max),\
				min, max, -2**(width * 8 - 1), 2**(width * 8 - 1) - 1))
81292
protected function generateSamples(): void
    {
        $module = str_after($this->getNameInput(), '/');

        $this->call('make:config', ['name' => 'config', '--module' => $this->getNameInput()]);
        $this->call('make:model', ['name' => 'Example', '--module' => $this->getNameInput()]);
        $this->call('make:policy', ['name' => 'ExamplePolicy', '--module' => $this->getNameInput()]);
        $this->call('make:provider', ['name' => ucfirst($module).'ServiceProvider', '--module' => $this->getNameInput()]);
        $this->call('make:command', ['name' => 'ExampleCommand', '--module' => $this->getNameInput()]);
        $this->call('make:controller', ['name' => 'ExampleController', '--module' => $this->getNameInput()]);
        $this->call('make:request', ['name' => 'ExampleRequest', '--module' => $this->getNameInput()]);
        $this->call('make:middleware', ['name' => 'ExampleMiddleware', '--module' => $this->getNameInput()]);
        $this->call('make:transformer', ['name' => 'ExampleTransformer', '--model' => 'Example', '--module' => $this->getNameInput()]);
        $this->call('make:datatable', ['name' => 'ExampleDatatable', '--model' => 'Example', '--transformer' => 'ExampleTransformer', '--module' => $this->getNameInput()]);

        $this->warn('Optionally create migrations and seeds (it may take some time):');
        $this->warn("artisan make:migration create_{$module}_example_table --module {$this->getNameInput()}");
        $this->warn("artisan make:seeder ExampleSeeder --module {$this->getNameInput()}");
    }
1044176
function sample(array, n, randomSource) {
        // shuffle the original array using a fisher-yates shuffle
        var shuffled = shuffle(array, randomSource);

        // and then return a subset of it - the first `n` elements.
        return shuffled.slice(0, n);
    }
94507
def samples(self, gp, Y_metadata=None):
        
        orig_shape = gp.shape
        gp = gp.flatten()
        ns = np.ones_like(gp, dtype=int)
        Ysim = np.random.binomial(ns, self.gp_link.transf(gp))
        return Ysim.reshape(orig_shape)
51751
public function calculate_sample($sampleid, $sampleorigin, $notusedstarttime = false, $notusedendtime = false) {

        $course = $this->retrieve('course', $sampleid);

        // It may not be available, but if it is the indicator checks if completion is enabled for the cm.
        $cm = $this->retrieve('course_modules', $sampleid);

        $completion = new \completion_info($course);

        if (!$completion->is_enabled($cm)) {
            $value = self::get_min_value();
        } else if (!$cm && !$completion->has_criteria()) {
            // Course completion enabled with no criteria counts as nothing.
            $value = self::get_min_value();
        } else {
            $value = self::get_max_value();
        }
        return $value;
    }
1152912
public function getSampleData() {
        $excelReader = $this->_getReader();
        $worksheet = $excelReader->getActiveSheet();
        $maxRows = 3;
        $out = array();

        foreach ($worksheet->getRowIterator() as $i => $row) {
            // workaround cause those PHPExcel assholes start their arrays at index 1
            $n = $i-1;
            if ($n >= $maxRows) {
                break;
            }

            $cellData = array();
            $cellIterator = $row->getCellIterator();
            $cellIterator->setIterateOnlyExistingCells(false);
            foreach ($cellIterator as $cell) {
                $cellData[] = $cell->getValue();
            }
            $out[] = $cellData;
        }
        return $out;
    }
253137
public function random($min = false, $max = false)
    {
        if ($min === false) {
            $min = new BigInteger(0);
        }
        if ($max === false) {
            $max = new BigInteger(0x7FFFFFFF);
        }
        $compare = $max->compare($min);
        if (! $compare) {
            return $this->protectedNormalize($min);
        } elseif ($compare < 0) {
            // if $min is bigger then $max, swap $min and $max
            $temp = $max;
            $max = $min;
            $min = $temp;
        }
        static $one;
        if (! isset($one)) {
            $one = new BigInteger(1);
        }
        $max = $max->subtract($min->subtract($one));
        $size = strlen(ltrim($max->toBytes(), chr(0)));
        /*
         * doing $random % $max doesn't work because some numbers will be more likely to occur than others.
         * eg. if $max is 140 and $random's max is 255 then that'd mean both $random = 5 and $random = 145
         * would produce 5 whereas the only value of random that could produce 139 would be 139. ie.
         * not all numbers would be equally likely. some would be more likely than others.
         *
         * creating a whole new random number until you find one that is within the range doesn't work
         * because, for sufficiently small ranges, the likelihood that you'd get a number within that range
         * would be pretty small. eg. with $random's max being 255 and if your $max being 1 the probability
         * would be pretty high that $random would be greater than $max.
         *
         * phpseclib works around this using the technique described here:
         *
         *
         */
        $random_max = new BigInteger(chr(1) . str_repeat("\0", $size), 256);
        $random = $this->protectedRandomNumberHelper($size);
        list ($max_multiple) = $random_max->divide($max);
        $max_multiple = $max_multiple->multiply($max);
        while ($random->compare($max_multiple) >= 0) {
            $random = $random->subtract($max_multiple);
            $random_max = $random_max->subtract($max_multiple);
            $random = $random->bitwiseLeftShift(8);
            $random = $random->add($this->protectedRandomNumberHelper(1));
            $random_max = $random_max->bitwiseLeftShift(8);
            list ($max_multiple) = $random_max->divide($max);
            $max_multiple = $max_multiple->multiply($max);
        }
        list ($random) = $random->divide($max);
        return $this->protectedNormalize($random->add($min));
    }
967499
static function randtime($rand_length = 6)
    {
        list($usec, $sec) = explode(" ", microtime());
        $min = intval('1' . str_repeat('0', $rand_length - 1));
        $max = intval(str_repeat('9', $rand_length));
        return substr($sec, -5) . ((int)$usec * 100) . rand($min, $max);
    }
1340858
def samples(self, gp, Y_metadata):
        
        N1, N2 = gp.shape
        Ysim = np.zeros((N1,N2))
        ind = Y_metadata['output_index'].flatten()
        for j in np.unique(ind):
            flt = ind==j
            gp_filtered = gp[flt,:]
            n1 = gp_filtered.shape[0]
            lik = self.likelihoods_list[j]
            _ysim = np.array([np.random.normal(lik.gp_link.transf(gpj), scale=np.sqrt(lik.variance), size=1) for gpj in gp_filtered.flatten()])
            Ysim[flt,:] = _ysim.reshape(n1,N2)
        return Ysim
65545
def get_sample_stats(fit, log_likelihood=None):
    """"""
    dtypes = {"divergent__": bool, "n_leapfrog__": np.int64, "treedepth__": np.int64}

    ndraws = [s - w for s, w in zip(fit.sim["n_save"], fit.sim["warmup2"])]

    extraction = OrderedDict()
    for chain, (pyholder, ndraws) in enumerate(zip(fit.sim["samples"], ndraws)):
        if chain == 0:
            for key in pyholder["sampler_param_names"]:
                extraction[key] = []
        for key, values in zip(pyholder["sampler_param_names"], pyholder["sampler_params"]):
            extraction[key].append(values[-ndraws:])

    data = OrderedDict()
    for key, values in extraction.items():
        values = np.stack(values, axis=0)
        dtype = dtypes.get(key)
        values = values.astype(dtype)
        name = re.sub("__$", "", key)
        name = "diverging" if name == "divergent" else name
        data[name] = values

    # log_likelihood
    if log_likelihood is not None:
        log_likelihood_data = get_draws(fit, variables=log_likelihood)
        data["log_likelihood"] = log_likelihood_data[log_likelihood]

    # lp__
    stat_lp = get_draws(fit, variables="lp__")
    data["lp"] = stat_lp["lp__"]

    return data
1033285
public final void sample()
  {
    long count = _count.get();
    long lastCount = _lastAvgCount.getAndSet(count);
    long time = _time.get();
    long lastTime = _lastAvgTime.getAndSet(time);

    if (count == lastCount)
      _value = 0;
    else
      _value = _scale * (time - lastTime) / (double) (count - lastCount);
  }
1132197
protected function calculate_sample($sampleid, $sampleorigin, $starttime = false, $endtime = false) {
        global $DB;

        if (!$logstore = \core_analytics\manager::get_analytics_logstore()) {
            throw new \coding_exception('No available log stores');
        }

        // Filter by context to use the logstore_standard_log db table index.
        $course = $this->retrieve('course', $sampleid);
        $select = "courseid = :courseid AND anonymous = :anonymous AND (crud = 'c' OR crud = 'u')";
        $params = array('courseid' => $course->id, 'anonymous' => '0');

        if ($user = $this->retrieve('user', $sampleid)) {
            $select .= " AND userid = :userid";
            $params['userid'] = $user->id;
        }

        if ($starttime) {
            $select .= " AND timecreated > :starttime";
            $params['starttime'] = $starttime;
        }
        if ($endtime) {
            $select .= " AND timecreated <= :endtime";
            $params['endtime'] = $endtime;
        }

        $nlogs = $logstore->get_events_select_count($select, $params);
        if ($nlogs) {
            return self::get_max_value();
        } else {
            return self::get_min_value();
        }
    }