Submit Ising-formulated problem and return samples.
553579
def sample(config_file, profile, solver_def, biases, couplings, random_problem,
           num_reads, verbose):
    """"""

    # TODO: de-dup wrt ping

    def echo(s, maxlen=100):
        click.echo(s if verbose else strtrunc(s, maxlen))

    try:
        client = Client.from_config(
            config_file=config_file, profile=profile, solver=solver_def)
    except Exception as e:
        click.echo("Invalid configuration: {}".format(e))
        return 1
    if config_file:
        echo("Using configuration file: {}".format(config_file))
    if profile:
        echo("Using profile: {}".format(profile))
    echo("Using endpoint: {}".format(client.endpoint))

    try:
        solver = client.get_solver()
    except SolverAuthenticationError:
        click.echo("Authentication error. Check credentials in your configuration file.")
        return 1
    except (InvalidAPIResponseError, UnsupportedSolverError):
        click.echo("Invalid or unexpected API response.")
        return 2
    except SolverNotFoundError:
        click.echo("Solver with the specified features does not exist.")
        return 3

    echo("Using solver: {}".format(solver.id))

    if random_problem:
        linear, quadratic = generate_random_ising_problem(solver)
    else:
        try:
            linear = ast.literal_eval(biases) if biases else []
        except Exception as e:
            click.echo("Invalid biases: {}".format(e))
        try:
            quadratic = ast.literal_eval(couplings) if couplings else {}
        except Exception as e:
            click.echo("Invalid couplings: {}".format(e))

    echo("Using qubit biases: {!r}".format(linear))
    echo("Using qubit couplings: {!r}".format(quadratic))
    echo("Number of samples: {}".format(num_reads))

    try:
        result = solver.sample_ising(linear, quadratic, num_reads=num_reads).result()
    except Exception as e:
        click.echo(e)
        return 4

    if verbose:
        click.echo("Result: {!r}".format(result))

    echo("Samples: {!r}".format(result['samples']))
    echo("Occurrences: {!r}".format(result['occurrences']))
    echo("Energies: {!r}".format(result['energies']))
119159
function(ts, val) {
      var sample = new PowerSample(this, ts, val);
      this.samples_.push(sample);
      return sample;
    }
1014852
def Sample(self):
    """"""
    self._profiling_sample += 1

    if self._profiling_sample >= self._profiling_sample_rate:
      if self._heapy:
        heap = self._heapy.heap()
        heap.dump(self._sample_file)

      self._profiling_sample = 0
341406
public final void sample()
  {
    long sum = _sum.getAndSet(0);
    int count = _count.getAndSet(0);

    if (count != 0)
      _value =sum / (double) count;
    else
      _value = 0;
  }
1138867
def _model(self, t, theta, period, tmpid):
        """"""
        template = self.templates[tmpid]
        phase = (t / period - theta[2]) % 1
        return theta[0] + theta[1] * template(phase)
948686
def sample_bitstrings(self, n_samples):
        
        if self.rs is None:
            raise ValueError("You have tried to perform a stochastic operation without setting the "
                             "random state of the simulator. Might I suggest using a PyQVM object?")

        # note on reshape: it puts bitstrings in lexicographical order.
        # would you look at that .. _all_bitstrings returns things in lexicographical order!
        # reminder: qubit 0 is on the left in einsum simulator.
        probabilities = np.abs(self.wf.reshape(-1)) ** 2
        possible_bitstrings = all_bitstrings(self.n_qubits)
        inds = self.rs.choice(2 ** self.n_qubits, n_samples, p=probabilities)
        return possible_bitstrings[inds, :]
510014
def sample_bitstrings(self, n_samples):
        
        if self.rs is None:
            raise ValueError("You have tried to perform a stochastic operation without setting the "
                             "random state of the simulator. Might I suggest using a PyQVM object?")
        probabilities = np.abs(self.wf) ** 2
        possible_bitstrings = all_bitstrings(self.n_qubits)
        inds = self.rs.choice(2 ** self.n_qubits, n_samples, p=probabilities)
        bitstrings = possible_bitstrings[inds, :]
        bitstrings = np.flip(bitstrings, axis=1)  # qubit ordering: 0 on the left.
        return bitstrings
1013670
def _generate_examples(self, filepath):
    """"""
    rows_per_pair_id = collections.defaultdict(list)

    with tf.io.gfile.GFile(filepath) as f:
      reader = csv.DictReader(f, delimiter='\t', quoting=csv.QUOTE_NONE)
      for row in reader:
        rows_per_pair_id[row['pairID']].append(row)

    for rows in six.itervalues(rows_per_pair_id):
      premise = {row['language']: row['sentence1'] for row in rows}
      hypothesis = {row['language']: row['sentence2'] for row in rows}
      yield {
          'premise': premise,
          'hypothesis': hypothesis,
          'label': rows[0]['gold_label'],
      }
509936
def create_model(samples_x, samples_y_aggregation,
                 n_restarts_optimizer=250, is_white_kernel=False):
    '''
    
    '''
    kernel = gp.kernels.ConstantKernel(constant_value=1,
                                       constant_value_bounds=(1e-12, 1e12)) * \
                                                gp.kernels.Matern(nu=1.5)
    if is_white_kernel is True:
        kernel += gp.kernels.WhiteKernel(noise_level=1, noise_level_bounds=(1e-12, 1e12))
    regressor = gp.GaussianProcessRegressor(kernel=kernel,
                                            n_restarts_optimizer=n_restarts_optimizer,
                                            normalize_y=True,
                                            alpha=1e-10)
    regressor.fit(numpy.array(samples_x), numpy.array(samples_y_aggregation))

    model = {}
    model['model'] = regressor
    model['kernel_prior'] = str(kernel)
    model['kernel_posterior'] = str(regressor.kernel_)
    model['model_loglikelihood'] = regressor.log_marginal_likelihood(regressor.kernel_.theta)

    return model
128016
def generateAmplitudes(k):
    """"""
    res = np.array([np.random.random() for i in range(k)])
    return res/res.sum()
160313
def random_real_solution(solution_size, lower_bounds, upper_bounds):
    """"""
    return [
        random.uniform(lower_bounds[i], upper_bounds[i])
        for i in range(solution_size)
    ]
1316567
def potential_physical_input(method):
    """"""
    @wraps(method)
    def wrapper(*args,**kwargs):
        from galpy.potential import flatten as flatten_potential
        Pot= flatten_potential(args[0])
        ro= kwargs.get('ro',None)
        if ro is None and hasattr(Pot,'_ro'):
            ro= Pot._ro
        if ro is None and isinstance(Pot,list) \
                and hasattr(Pot[0],'_ro'):
            # For lists of Potentials
            ro= Pot[0]._ro
        if _APY_LOADED and isinstance(ro,units.Quantity):
            ro= ro.to(units.kpc).value
        if 't' in kwargs or 'M' in kwargs:
            vo= kwargs.get('vo',None)
            if vo is None and hasattr(Pot,'_vo'):
                vo= Pot._vo
            if vo is None and isinstance(Pot,list) \
                    and hasattr(Pot[0],'_vo'):
                # For lists of Potentials
                vo= Pot[0]._vo
            if _APY_LOADED and isinstance(vo,units.Quantity):
                vo= vo.to(units.km/units.s).value
        # Loop through args
        newargs= (Pot,)
        for ii in range(1,len(args)):
            if _APY_LOADED and isinstance(args[ii],units.Quantity):
                newargs= newargs+(args[ii].to(units.kpc).value/ro,)
            else:
                newargs= newargs+(args[ii],)
        args= newargs
        # phi and t kwargs
        if 'phi' in kwargs and _APY_LOADED \
                and isinstance(kwargs['phi'],units.Quantity):
            kwargs['phi']= kwargs['phi'].to(units.rad).value
        if 't' in kwargs and _APY_LOADED \
                and isinstance(kwargs['t'],units.Quantity):
            kwargs['t']= kwargs['t'].to(units.Gyr).value\
                /time_in_Gyr(vo,ro)
        # v kwarg for dissipative forces
        if 'v' in kwargs and _APY_LOADED \
                and isinstance(kwargs['v'],units.Quantity):
            kwargs['v']= kwargs['v'].to(units.km/units.s).value/vo
        # Mass kwarg for rtide
        if 'M' in kwargs and _APY_LOADED \
                and isinstance(kwargs['M'],units.Quantity):
            try:
                kwargs['M']= kwargs['M'].to(units.Msun).value\
                    /mass_in_msol(vo,ro)
            except units.UnitConversionError:
                kwargs['M']= kwargs['M'].to(units.pc*units.km**2/units.s**2)\
                    .value/mass_in_msol(vo,ro)/_G
        # kwargs that come up in quasiisothermaldf    
        if 'z' in kwargs and _APY_LOADED \
                and isinstance(kwargs['z'],units.Quantity):
            kwargs['z']= kwargs['z'].to(units.kpc).value/ro
        if 'dz' in kwargs and _APY_LOADED \
                and isinstance(kwargs['dz'],units.Quantity):
            kwargs['dz']= kwargs['dz'].to(units.kpc).value/ro
        if 'dR' in kwargs and _APY_LOADED \
                and isinstance(kwargs['dR'],units.Quantity):
            kwargs['dR']= kwargs['dR'].to(units.kpc).value/ro
        if 'zmax' in kwargs and _APY_LOADED \
                and isinstance(kwargs['zmax'],units.Quantity):
            kwargs['zmax']= kwargs['zmax'].to(units.kpc).value/ro
        return method(*args,**kwargs)
    return wrapper
1144536
def get_input(problem):
    "
    input_data = load_input()
    pbsplit = problem.split(":")
    problem_input = input_data['input'][pbsplit[0]]
    if isinstance(problem_input, dict) and "filename" in problem_input and "value" in problem_input:
        if len(pbsplit) > 1 and pbsplit[1] == 'filename':
            return problem_input["filename"]
        else:
            return open(problem_input["value"], 'rb').read()
    else:
        return problem_input
1184225
def sample(self, size=(), rule="R", antithetic=None, verbose=False, **kws):
        
        size_ = numpy.prod(size, dtype=int)
        dim = len(self)
        if dim > 1:
            if isinstance(size, (tuple,list,numpy.ndarray)):
                shape = (dim,) + tuple(size)
            else:
                shape = (dim, size)
        else:
            shape = size

        out = self.kernel.resample(size_)[0]
        try:
            out = out.reshape(shape)
        except:
            if len(self) == 1:
                out = out.flatten()
            else:
                out = out.reshape(dim, out.size/dim)

        return out
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
1214940
def generate_samples(self):
        """"""
        filenames = glob_all(self.args.random_data_folder, '*.wav')
        shuffle(filenames)
        while True:
            for fn in filenames:
                for x, y in self.vectors_from_fn(fn):
                    yield x, y
1096549
@Override
	public Iterator<T> sample(final Iterator<T> input) {
		if (fraction == 0) {
			return emptyIterable;
		}

		return new SampledIterator<T>() {
			T current = null;

			@Override
			public boolean hasNext() {
				if (current == null) {
					current = getNextSampledElement();
				}

				return current != null;
			}

			@Override
			public T next() {
				if (current == null) {
					return getNextSampledElement();
				} else {
					T result = current;
					current = null;

					return result;
				}
			}

			private T getNextSampledElement() {
				if (fraction <= THRESHOLD) {
					double rand = random.nextDouble();
					double u = Math.max(rand, EPSILON);
					int gap = (int) (Math.log(u) / Math.log(1 - fraction));
					int elementCount = 0;
					if (input.hasNext()) {
						T element = input.next();
						while (input.hasNext() && elementCount < gap) {
							element = input.next();
							elementCount++;
						}
						if (elementCount < gap) {
							return null;
						} else {
							return element;
						}
					} else {
						return null;
					}
				} else {
					while (input.hasNext()) {
						T element = input.next();

						if (random.nextDouble() <= fraction) {
							return element;
						}
					}
					return null;
				}
			}
		};
	}