sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def cubic_bucket_warp(x, n, l1, l2, l3, x0, w1, w2, w3): """Warps the length scale with a piecewise cubic "bucket" shape. Parameters ---------- x : float or array-like of float Locations to evaluate length scale at. n : non-negative int Derivative order to evaluate. Only first d...
Warps the length scale with a piecewise cubic "bucket" shape. Parameters ---------- x : float or array-like of float Locations to evaluate length scale at. n : non-negative int Derivative order to evaluate. Only first derivatives are supported. l1 : positive float Length...
entailment
def quintic_bucket_warp(x, n, l1, l2, l3, x0, w1, w2, w3): """Warps the length scale with a piecewise quintic "bucket" shape. Parameters ---------- x : float or array-like of float Locations to evaluate length scale at. n : non-negative int Derivative order to evaluate. Only first d...
Warps the length scale with a piecewise quintic "bucket" shape. Parameters ---------- x : float or array-like of float Locations to evaluate length scale at. n : non-negative int Derivative order to evaluate. Only first derivatives are supported. l1 : positive float Length s...
entailment
def exp_gauss_warp(X, n, l0, *msb): """Length scale function which is an exponential of a sum of Gaussians. The centers and widths of the Gaussians are free parameters. The length scale function is given by .. math:: l = l_0 \exp\left ( \sum_{i=1}^{N}\beta_i\exp\left ( -\...
Length scale function which is an exponential of a sum of Gaussians. The centers and widths of the Gaussians are free parameters. The length scale function is given by .. math:: l = l_0 \exp\left ( \sum_{i=1}^{N}\beta_i\exp\left ( -\frac{(x-\mu_i)^2}{2\sigma_i^2} \right ) \ri...
entailment
def get_multiple_choices_required(self): """ Add only the required message, but no 'ng-required' attribute to the input fields, otherwise all Checkboxes of a MultipleChoiceField would require the property "checked". """ errors = [] if self.required: for key, m...
Add only the required message, but no 'ng-required' attribute to the input fields, otherwise all Checkboxes of a MultipleChoiceField would require the property "checked".
entailment
def sso(user, desired_username, name, email, profile_fields=None): """ Create a user, if the provided `user` is None, from the parameters. Then log the user in, and return it. """ if not user: if not settings.REGISTRATION_OPEN: raise SSOError('Account registration is closed') ...
Create a user, if the provided `user` is None, from the parameters. Then log the user in, and return it.
entailment
def parallel_compute_ll_matrix(gp, bounds, num_pts, num_proc=None): """Compute matrix of the log likelihood over the parameter space in parallel. Parameters ---------- bounds : 2-tuple or list of 2-tuples with length equal to the number of free parameters Bounds on the range to use for each...
Compute matrix of the log likelihood over the parameter space in parallel. Parameters ---------- bounds : 2-tuple or list of 2-tuples with length equal to the number of free parameters Bounds on the range to use for each of the parameters. If a single 2-tuple is given, it will be used f...
entailment
def slice_plot(*args, **kwargs): """Constructs a plot that lets you look at slices through a multidimensional array. Parameters ---------- vals : array, (`M`, `D`, `P`, ...) Multidimensional array to visualize. x_vals_1 : array, (`M`,) Values along the first dimension. x_val...
Constructs a plot that lets you look at slices through a multidimensional array. Parameters ---------- vals : array, (`M`, `D`, `P`, ...) Multidimensional array to visualize. x_vals_1 : array, (`M`,) Values along the first dimension. x_vals_2 : array, (`D`,) Values along...
entailment
def arrow_respond(slider, event): """Event handler for arrow key events in plot windows. Pass the slider object to update as a masked argument using a lambda function:: lambda evt: arrow_respond(my_slider, evt) Parameters ---------- slider : Slider instance associated with...
Event handler for arrow key events in plot windows. Pass the slider object to update as a masked argument using a lambda function:: lambda evt: arrow_respond(my_slider, evt) Parameters ---------- slider : Slider instance associated with this handler. event : Event to be ha...
entailment
def debit(self, amount, credit_account, description, debit_memo="", credit_memo="", datetime=None): """ Post a debit of 'amount' and a credit of -amount against this account and credit_account respectively. note amount must be non-negative. """ assert amount >= 0 return self.po...
Post a debit of 'amount' and a credit of -amount against this account and credit_account respectively. note amount must be non-negative.
entailment
def credit(self, amount, debit_account, description, debit_memo="", credit_memo="", datetime=None): """ Post a credit of 'amount' and a debit of -amount against this account and credit_account respectively. note amount must be non-negative. """ assert amount >= 0 return self.pos...
Post a credit of 'amount' and a debit of -amount against this account and credit_account respectively. note amount must be non-negative.
entailment
def post(self, amount, other_account, description, self_memo="", other_memo="", datetime=None): """ Post a transaction of 'amount' against this account and the negative amount against 'other_account'. This will show as a debit or credit against this account when amount > 0 or amount < 0 respectively. ...
Post a transaction of 'amount' against this account and the negative amount against 'other_account'. This will show as a debit or credit against this account when amount > 0 or amount < 0 respectively.
entailment
def balance(self, date=None): """ returns the account balance as of 'date' (datetime stamp) or now(). """ qs = self._entries() if date: qs = qs.filter(transaction__t_stamp__lt=date) r = qs.aggregate(b=Sum('amount')) b = r['b'] flip = self._DEBIT_IN_DB() ...
returns the account balance as of 'date' (datetime stamp) or now().
entailment
def totals(self, start=None, end=None): """Returns a Totals object containing the sum of all debits, credits and net change over the period of time from start to end. 'start' is inclusive, 'end' is exclusive """ qs = self._entries_range(start=start, end=end) qs_positive...
Returns a Totals object containing the sum of all debits, credits and net change over the period of time from start to end. 'start' is inclusive, 'end' is exclusive
entailment
def ledger(self, start=None, end=None): """Returns a list of entries for this account. Ledger returns a sequence of LedgerEntry's matching the criteria in chronological order. The returned sequence can be boolean-tested (ie. test that nothing was returned). If 'start' is given,...
Returns a list of entries for this account. Ledger returns a sequence of LedgerEntry's matching the criteria in chronological order. The returned sequence can be boolean-tested (ie. test that nothing was returned). If 'start' is given, only entries on or after that datetime are ...
entailment
def get_third_party(self, third_party): """Return the account for the given third-party. Raise <something> if the third party doesn't belong to this bookset.""" actual_account = third_party.get_account() assert actual_account.get_bookset() == self return ThirdPartySubAccount(actual_acco...
Return the account for the given third-party. Raise <something> if the third party doesn't belong to this bookset.
entailment
def get_third_party(self, third_party): """Return the account for the given third-party. Raise <something> if the third party doesn't belong to this bookset.""" actual_account = third_party.get_account() assert actual_account.get_bookset() == self.get_bookset() return ProjectAccount(ac...
Return the account for the given third-party. Raise <something> if the third party doesn't belong to this bookset.
entailment
def find_overlapping_slots(all_slots): """Find any slots that overlap""" overlaps = set([]) for slot in all_slots: # Because slots are ordered, we can be more efficient than this # N^2 loop, but this is simple and, since the number of slots # should be low, this should be "fast enoug...
Find any slots that overlap
entailment
def find_non_contiguous(all_items): """Find any items that have slots that aren't contiguous""" non_contiguous = [] for item in all_items: if item.slots.count() < 2: # No point in checking continue last_slot = None for slot in item.slots.all().order_by('end_ti...
Find any items that have slots that aren't contiguous
entailment
def validate_items(all_items): """Find errors in the schedule. Check for: - pending / rejected talks in the schedule - items with both talks and pages assigned - items with neither talks nor pages assigned """ validation = [] for item in all_items: if item.talk is...
Find errors in the schedule. Check for: - pending / rejected talks in the schedule - items with both talks and pages assigned - items with neither talks nor pages assigned
entailment
def find_duplicate_schedule_items(all_items): """Find talks / pages assigned to mulitple schedule items""" duplicates = [] seen_talks = {} for item in all_items: if item.talk and item.talk in seen_talks: duplicates.append(item) if seen_talks[item.talk] not in duplicates: ...
Find talks / pages assigned to mulitple schedule items
entailment
def find_clashes(all_items): """Find schedule items which clash (common slot and venue)""" clashes = {} seen_venue_slots = {} for item in all_items: for slot in item.slots.all(): pos = (item.venue, slot) if pos in seen_venue_slots: if seen_venue_slots[pos]...
Find schedule items which clash (common slot and venue)
entailment
def find_invalid_venues(all_items): """Find venues assigned slots that aren't on the allowed list of days.""" venues = {} for item in all_items: valid = False item_days = list(item.venue.days.all()) for slot in item.slots.all(): for day in item_days: ...
Find venues assigned slots that aren't on the allowed list of days.
entailment
def check_schedule(): """Helper routine to easily test if the schedule is valid""" all_items = prefetch_schedule_items() for validator, _type, _msg in SCHEDULE_ITEM_VALIDATORS: if validator(all_items): return False all_slots = prefetch_slots() for validator, _type, _msg in SLOT_...
Helper routine to easily test if the schedule is valid
entailment
def validate_schedule(): """Helper routine to report issues with the schedule""" all_items = prefetch_schedule_items() errors = [] for validator, _type, msg in SCHEDULE_ITEM_VALIDATORS: if validator(all_items): errors.append(msg) all_slots = prefetch_slots() for validator, _...
Helper routine to report issues with the schedule
entailment
def get_form(self, request, obj=None, **kwargs): """Change the form depending on whether we're adding or editing the slot.""" if obj is None: # Adding a new Slot kwargs['form'] = SlotAdminAddForm return super(SlotAdmin, self).get_form(request, obj, **kwargs)
Change the form depending on whether we're adding or editing the slot.
entailment
def get_cached_menus(): """Return the menus from the cache or generate them if needed.""" items = cache.get(CACHE_KEY) if items is None: menu = generate_menu() cache.set(CACHE_KEY, menu.items) else: menu = Menu(items) return menu
Return the menus from the cache or generate them if needed.
entailment
def maybe_obj(str_or_obj): """If argument is not a string, return it. Otherwise import the dotted name and return that. """ if not isinstance(str_or_obj, six.string_types): return str_or_obj parts = str_or_obj.split(".") mod, modname = None, None for p in parts: modname = p ...
If argument is not a string, return it. Otherwise import the dotted name and return that.
entailment
def generate_menu(): """Generate a new list of menus.""" root_menu = Menu(list(copy.deepcopy(settings.WAFER_MENUS))) for dynamic_menu_func in settings.WAFER_DYNAMIC_MENUS: dynamic_menu_func = maybe_obj(dynamic_menu_func) dynamic_menu_func(root_menu) return root_menu
Generate a new list of menus.
entailment
def lock(self): ''' Try to get locked the file - the function will wait until the file is unlocked if 'wait' was defined as locktype - the funciton will raise AlreadyLocked exception if 'lock' was defined as locktype ''' # Open file self.__fd = open(self.__lockfi...
Try to get locked the file - the function will wait until the file is unlocked if 'wait' was defined as locktype - the funciton will raise AlreadyLocked exception if 'lock' was defined as locktype
entailment
def _make_handler(state_token, done_function): ''' Makes a a handler class to use inside the basic python HTTP server. state_token is the expected state token. done_function is a function that is called, with the code passed to it. ''' class LocalServerHandler(BaseHTTPServer.BaseHTTPRequestHan...
Makes a a handler class to use inside the basic python HTTP server. state_token is the expected state token. done_function is a function that is called, with the code passed to it.
entailment
def configuration(): 'Loads configuration from the file system.' defaults = ''' [oauth2] hostname = localhost port = 9876 api_endpoint = https://api.coursera.org auth_endpoint = https://accounts.coursera.org/oauth2/v1/auth token_endpoint = https://accounts.coursera.org/oauth2/v1/token verify_tls = True token_ca...
Loads configuration from the file system.
entailment
def _load_token_cache(self): 'Reads the local fs cache for pre-authorized access tokens' try: logging.debug('About to read from local file cache file %s', self.token_cache_file) with open(self.token_cache_file, 'rb') as f: fs_cached = cPi...
Reads the local fs cache for pre-authorized access tokens
entailment
def _save_token_cache(self, new_cache): 'Write out to the filesystem a cache of the OAuth2 information.' logging.debug('Looking to write to local authentication cache...') if not self._check_token_cache_type(new_cache): logging.error('Attempt to save a bad value: %s', new_cache) ...
Write out to the filesystem a cache of the OAuth2 information.
entailment
def _check_token_cache_type(self, cache_value): ''' Checks the cache_value for appropriate type correctness. Pass strict=True for strict validation to ensure the latest types are being written. Returns true is correct type, False otherwise. ''' def check_string_...
Checks the cache_value for appropriate type correctness. Pass strict=True for strict validation to ensure the latest types are being written. Returns true is correct type, False otherwise.
entailment
def _authorize_new_tokens(self): ''' Stands up a new localhost http server and retrieves new OAuth2 access tokens from the Coursera OAuth2 server. ''' logging.info('About to request new OAuth2 tokens from Coursera.') # Attempt to request new tokens from Coursera via the b...
Stands up a new localhost http server and retrieves new OAuth2 access tokens from the Coursera OAuth2 server.
entailment
def _exchange_refresh_tokens(self): 'Exchanges a refresh token for an access token' if self.token_cache is not None and 'refresh' in self.token_cache: # Attempt to use the refresh token to get a new access token. refresh_form = { 'grant_type': 'refresh_token', ...
Exchanges a refresh token for an access token
entailment
def foreignkey(element, exceptions): ''' function to determine if each select field needs a create button or not ''' label = element.field.__dict__['label'] try: label = unicode(label) except NameError: pass if (not label) or (label in exceptions): return False el...
function to determine if each select field needs a create button or not
entailment
def deserialize_by_field(value, field): """ Some types get serialized to JSON, as strings. If we know what they are supposed to be, we can deserialize them """ if isinstance(field, forms.DateTimeField): value = parse_datetime(value) elif isinstance(field, forms.DateField): value ...
Some types get serialized to JSON, as strings. If we know what they are supposed to be, we can deserialize them
entailment
def hyperprior(self): """Combined hyperprior for the kernel, noise kernel and (if present) mean function. """ hp = self.k.hyperprior * self.noise_k.hyperprior if self.mu is not None: hp *= self.mu.hyperprior return hp
Combined hyperprior for the kernel, noise kernel and (if present) mean function.
entailment
def fixed_params(self): """Combined fixed hyperparameter flags for the kernel, noise kernel and (if present) mean function. """ fp = CombinedBounds(self.k.fixed_params, self.noise_k.fixed_params) if self.mu is not None: fp = CombinedBounds(fp, self.mu.fixed_params) re...
Combined fixed hyperparameter flags for the kernel, noise kernel and (if present) mean function.
entailment
def params(self): """Combined hyperparameters for the kernel, noise kernel and (if present) mean function. """ p = CombinedBounds(self.k.params, self.noise_k.params) if self.mu is not None: p = CombinedBounds(p, self.mu.params) return p
Combined hyperparameters for the kernel, noise kernel and (if present) mean function.
entailment
def param_names(self): """Combined names for the hyperparameters for the kernel, noise kernel and (if present) mean function. """ pn = CombinedBounds(self.k.param_names, self.noise_k.param_names) if self.mu is not None: pn = CombinedBounds(pn, self.mu.param_names) ret...
Combined names for the hyperparameters for the kernel, noise kernel and (if present) mean function.
entailment
def free_params(self): """Combined free hyperparameters for the kernel, noise kernel and (if present) mean function. """ p = CombinedBounds(self.k.free_params, self.noise_k.free_params) if self.mu is not None: p = CombinedBounds(p, self.mu.free_params) return p
Combined free hyperparameters for the kernel, noise kernel and (if present) mean function.
entailment
def free_params(self, value): """Set the free parameters. Note that this bypasses enforce_bounds. """ value = scipy.asarray(value, dtype=float) self.K_up_to_date = False self.k.free_params = value[:self.k.num_free_params] self.noise_k.free_params = value[self.k.num_free_p...
Set the free parameters. Note that this bypasses enforce_bounds.
entailment
def free_param_bounds(self): """Combined free hyperparameter bounds for the kernel, noise kernel and (if present) mean function. """ fpb = CombinedBounds(self.k.free_param_bounds, self.noise_k.free_param_bounds) if self.mu is not None: fpb = CombinedBounds(fpb, self.mu.free_p...
Combined free hyperparameter bounds for the kernel, noise kernel and (if present) mean function.
entailment
def free_param_names(self): """Combined free hyperparameter names for the kernel, noise kernel and (if present) mean function. """ p = CombinedBounds(self.k.free_param_names, self.noise_k.free_param_names) if self.mu is not None: p = CombinedBounds(p, self.mu.free_param_names...
Combined free hyperparameter names for the kernel, noise kernel and (if present) mean function.
entailment
def add_data(self, X, y, err_y=0, n=0, T=None): """Add data to the training data set of the GaussianProcess instance. Parameters ---------- X : array, (`M`, `D`) `M` input values of dimension `D`. y : array, (`M`,) `M` target values. er...
Add data to the training data set of the GaussianProcess instance. Parameters ---------- X : array, (`M`, `D`) `M` input values of dimension `D`. y : array, (`M`,) `M` target values. err_y : array, (`M`,) or scalar float, optional Non-...
entailment
def condense_duplicates(self): """Condense duplicate points using a transformation matrix. This is useful if you have multiple non-transformed points at the same location or multiple transformed points that use the same quadrature points. Won't change the GP if ...
Condense duplicate points using a transformation matrix. This is useful if you have multiple non-transformed points at the same location or multiple transformed points that use the same quadrature points. Won't change the GP if all of the rows of [X, n] are unique. Will...
entailment
def remove_outliers(self, thresh=3, **predict_kwargs): """Remove outliers from the GP with very simplistic outlier detection. Removes points that are more than `thresh` * `err_y` away from the GP mean. Note that this is only very rough in that it ignores the uncertainty in the G...
Remove outliers from the GP with very simplistic outlier detection. Removes points that are more than `thresh` * `err_y` away from the GP mean. Note that this is only very rough in that it ignores the uncertainty in the GP mean at any given point. But you should only be using th...
entailment
def optimize_hyperparameters(self, method='SLSQP', opt_kwargs={}, verbose=False, random_starts=None, num_proc=None, max_tries=1): r"""Optimize the hyperparameters by maximizing the log-posterior. Leaves the :py:class:`GaussianPro...
r"""Optimize the hyperparameters by maximizing the log-posterior. Leaves the :py:class:`GaussianProcess` instance in the optimized state. If :py:func:`scipy.optimize.minimize` is not available (i.e., if your :py:mod:`scipy` version is older than 0.11.0) then :py:func:`fmin_slsq...
entailment
def predict(self, Xstar, n=0, noise=False, return_std=True, return_cov=False, full_output=False, return_samples=False, num_samples=1, samp_kwargs={}, return_mean_func=False, use_MCMC=False, full_MC=False, rejection_func=None, ddof=1, output_transform=None, ...
Predict the mean and covariance at the inputs `Xstar`. The order of the derivative is given by `n`. The keyword `noise` sets whether or not noise is included in the prediction. Parameters ---------- Xstar : array, (`M`, `D`) `M` test input values of ...
entailment
def plot(self, X=None, n=0, ax=None, envelopes=[1, 3], base_alpha=0.375, return_prediction=False, return_std=True, full_output=False, plot_kwargs={}, **kwargs): """Plots the Gaussian process using the current hyperparameters. Only for num_dim <= 2. Parameters -...
Plots the Gaussian process using the current hyperparameters. Only for num_dim <= 2. Parameters ---------- X : array-like (`M`,) or (`M`, `num_dim`), optional The values to evaluate the Gaussian process at. If None, then 100 points between the minimum and maximum...
entailment
def draw_sample(self, Xstar, n=0, num_samp=1, rand_vars=None, rand_type='standard normal', diag_factor=1e3, method='cholesky', num_eig=None, mean=None, cov=None, modify_sign=None, **kwargs): """Draw a sample evaluated at the given points `Xstar`. ...
Draw a sample evaluated at the given points `Xstar`. Note that this function draws samples from the GP given the current values for the hyperparameters (which may be in a nonsense state if you just created the instance or called a method that performs MCMC sampling). If you want...
entailment
def update_hyperparameters(self, new_params, hyper_deriv_handling='default', exit_on_bounds=True, inf_on_error=True): r"""Update the kernel's hyperparameters to the new parameters. This will call :py:meth:`compute_K_L_alpha_ll` to update the state accordingly. Note that...
r"""Update the kernel's hyperparameters to the new parameters. This will call :py:meth:`compute_K_L_alpha_ll` to update the state accordingly. Note that if this method crashes and the `hyper_deriv_handling` keyword was used, it may leave :py:attr:`use_hyper_deriv` in th...
entailment
def compute_K_L_alpha_ll(self): r"""Compute `K`, `L`, `alpha` and log-likelihood according to the first part of Algorithm 2.1 in R&W. Computes `K` and the noise portion of `K` using :py:meth:`compute_Kij`, computes `L` using :py:func:`scipy.linalg.cholesky`, then computes `alpha...
r"""Compute `K`, `L`, `alpha` and log-likelihood according to the first part of Algorithm 2.1 in R&W. Computes `K` and the noise portion of `K` using :py:meth:`compute_Kij`, computes `L` using :py:func:`scipy.linalg.cholesky`, then computes `alpha` as `L.T\\(L\\y)`. Onl...
entailment
def compute_Kij(self, Xi, Xj, ni, nj, noise=False, hyper_deriv=None, k=None): r"""Compute covariance matrix between datasets `Xi` and `Xj`. Specify the orders of derivatives at each location with the `ni`, `nj` arrays. The `include_noise` flag is passed to the covariance kernel to ...
r"""Compute covariance matrix between datasets `Xi` and `Xj`. Specify the orders of derivatives at each location with the `ni`, `nj` arrays. The `include_noise` flag is passed to the covariance kernel to indicate whether noise is to be included (i.e., for evaluation of :math:`K+...
entailment
def compute_ll_matrix(self, bounds, num_pts): """Compute the log likelihood over the (free) parameter space. Parameters ---------- bounds : 2-tuple or list of 2-tuples with length equal to the number of free parameters Bounds on the range to use for each of the param...
Compute the log likelihood over the (free) parameter space. Parameters ---------- bounds : 2-tuple or list of 2-tuples with length equal to the number of free parameters Bounds on the range to use for each of the parameters. If a single 2-tuple is given, it will ...
entailment
def _compute_ll_matrix(self, idx, param_vals, num_pts): """Recursive helper function for compute_ll_matrix. Parameters ---------- idx : int The index of the parameter for this layer of the recursion to work on. `idx` == len(`num_pts`) is the base case tha...
Recursive helper function for compute_ll_matrix. Parameters ---------- idx : int The index of the parameter for this layer of the recursion to work on. `idx` == len(`num_pts`) is the base case that terminates the recursion. param_vals : List o...
entailment
def sample_hyperparameter_posterior(self, nwalkers=200, nsamp=500, burn=0, thin=1, num_proc=None, sampler=None, plot_posterior=False, plot_chains=False, sampler_type='ensemble', ...
Produce samples from the posterior for the hyperparameters using MCMC. Returns the sampler created, because storing it stops the GP from being pickleable. To add more samples to a previous sampler, pass the sampler instance in the `sampler` keyword. Parameters -...
entailment
def compute_from_MCMC(self, X, n=0, return_mean=True, return_std=True, return_cov=False, return_samples=False, return_mean_func=False, num_samples=1, noise=False, samp_kwargs={}, sampler=None, flat_trace=None, burn=0, ...
Compute desired quantities from MCMC samples of the hyperparameter posterior. The return will be a list with a number of rows equal to the number of hyperparameter samples. The columns depend on the state of the boolean flags, but will be some subset of (mean, stddev, cov, samples), in ...
entailment
def compute_l_from_MCMC(self, X, n=0, sampler=None, flat_trace=None, burn=0, thin=1, **kwargs): """Compute desired quantities from MCMC samples of the hyperparameter posterior. The return will be a list with a number of rows equal to the number of hyperparameter samples. The columns wil...
Compute desired quantities from MCMC samples of the hyperparameter posterior. The return will be a list with a number of rows equal to the number of hyperparameter samples. The columns will contain the covariance length scale function. Parameters ---------- ...
entailment
def predict_MCMC(self, X, ddof=1, full_MC=False, rejection_func=None, **kwargs): """Make a prediction using MCMC samples. This is essentially a convenient wrapper of :py:meth:`compute_from_MCMC`, designed to act more or less interchangeably with :py:meth:`predict`. Comp...
Make a prediction using MCMC samples. This is essentially a convenient wrapper of :py:meth:`compute_from_MCMC`, designed to act more or less interchangeably with :py:meth:`predict`. Computes the mean of the GP posterior marginalized over the hyperparameters using iterat...
entailment
def build_parser(): "Build an argparse argument parser to parse the command line." parser = argparse.ArgumentParser( description="""Coursera OAuth2 client CLI. This tool helps users of the Coursera App Platform to programmatically access Coursera APIs.""", epilog="""Please file ...
Build an argparse argument parser to parse the command line.
entailment
def main(): "Boots up the command line tool" logging.captureWarnings(True) args = build_parser().parse_args() # Configure logging args.setup_logging(args) # Dispatch into the appropriate subcommand function. try: return args.func(args) except SystemExit: raise except:...
Boots up the command line tool
entailment
def sponsor_menu( root_menu, menu="sponsors", label=_("Sponsors"), sponsors_item=_("Our sponsors"), packages_item=_("Sponsorship packages")): """Add sponsor menu links.""" root_menu.add_menu(menu, label, items=[]) for sponsor in ( Sponsor.objects.all() .order_...
Add sponsor menu links.
entailment
def objectatrib(instance, atrib): ''' this filter is going to be useful to execute an object method or get an object attribute dynamically. this method is going to take into account the atrib param can contains underscores ''' atrib = atrib.replace("__", ".") atribs = [] atribs = atrib.s...
this filter is going to be useful to execute an object method or get an object attribute dynamically. this method is going to take into account the atrib param can contains underscores
entailment
def as_widget(self, widget=None, attrs=None, only_initial=False): """ Renders the field. """ attrs = attrs or {} attrs.update(self.form.get_widget_attrs(self)) if hasattr(self.field, 'widget_css_classes'): css_classes = self.field.widget_css_classes el...
Renders the field.
entailment
def convert_widgets(self): """ During form initialization, some widgets have to be replaced by a counterpart suitable to be rendered the AngularJS way. """ for field in self.base_fields.values(): try: new_widget = field.get_converted_widget() ...
During form initialization, some widgets have to be replaced by a counterpart suitable to be rendered the AngularJS way.
entailment
def epochdate(timestamp): ''' Convet an epoch date to a tuple in format ("yyyy-mm-dd","hh:mm:ss") Example: "1023456427" -> ("2002-06-07","15:27:07") Parameters: - `timestamp`: date in epoch format ''' dt = datetime.fromtimestamp(float(timestamp)).timetuple() fecha = "{0:d}-{1:02d}-{2:0...
Convet an epoch date to a tuple in format ("yyyy-mm-dd","hh:mm:ss") Example: "1023456427" -> ("2002-06-07","15:27:07") Parameters: - `timestamp`: date in epoch format
entailment
def model_inspect(obj): ''' Analize itself looking for special information, right now it returns: - Application name - Model name ''' # Prepare the information object info = {} if hasattr(obj, '_meta'): info['verbose_name'] = getattr(obj._meta,...
Analize itself looking for special information, right now it returns: - Application name - Model name
entailment
def upload_path(instance, filename): ''' This method is created to return the path to upload files. This path must be different from any other to avoid problems. ''' path_separator = "/" date_separator = "-" ext_separator = "." empty_string = "" # get the model name model_name = ...
This method is created to return the path to upload files. This path must be different from any other to avoid problems.
entailment
def remove_getdisplay(field_name): ''' for string 'get_FIELD_NAME_display' return 'FIELD_NAME' ''' str_ini = 'get_' str_end = '_display' if str_ini == field_name[0:len(str_ini)] and str_end == field_name[(-1) * len(str_end):]: field_name = field_name[len(str_ini):(-1) * len(str_end)] ...
for string 'get_FIELD_NAME_display' return 'FIELD_NAME'
entailment
def JSONEncoder_newdefault(kind=['uuid', 'datetime', 'time', 'decimal']): ''' JSON Encoder newdfeault is a wrapper capable of encoding several kinds Usage: from codenerix.helpers import JSONEncoder_newdefault JSONEncoder_newdefault() ''' JSONEncoder_olddefault = json.JSONEncoder.defa...
JSON Encoder newdfeault is a wrapper capable of encoding several kinds Usage: from codenerix.helpers import JSONEncoder_newdefault JSONEncoder_newdefault()
entailment
def context_processors_update(context, request): ''' Update context with context_processors from settings Usage: from codenerix.helpers import context_processors_update context_processors_update(context, self.request) ''' for template in settings.TEMPLATES: for context_proces...
Update context with context_processors from settings Usage: from codenerix.helpers import context_processors_update context_processors_update(context, self.request)
entailment
def append(self, filename_in_zip, file_contents): ''' Appends a file with name filename_in_zip and contents of file_contents to the in-memory zip. ''' # Set the file pointer to the end of the file self.in_memory_zip.seek(-1, io.SEEK_END) # Get a handle to the in-...
Appends a file with name filename_in_zip and contents of file_contents to the in-memory zip.
entailment
def writetofile(self, filename): '''Writes the in-memory zip to a file.''' f = open(filename, "w") f.write(self.read()) f.close()
Writes the in-memory zip to a file.
entailment
def sponsor_image_url(sponsor, name): """Returns the corresponding url from the sponsors images""" if sponsor.files.filter(name=name).exists(): # We avoid worrying about multiple matches by always # returning the first one. return sponsor.files.filter(name=name).first().item.url retu...
Returns the corresponding url from the sponsors images
entailment
def sponsor_tagged_image(sponsor, tag): """returns the corresponding url from the tagged image list.""" if sponsor.files.filter(tag_name=tag).exists(): return sponsor.files.filter(tag_name=tag).first().tagged_file.item.url return ''
returns the corresponding url from the tagged image list.
entailment
def ifusergroup(parser, token): """ Check to see if the currently logged in user belongs to a specific group. Requires the Django authentication contrib app and middleware. Usage: {% ifusergroup Admins %} ... {% endifusergroup %}, or {% ifusergroup Admins Clients Sellers %} ... {% else %} ... {%...
Check to see if the currently logged in user belongs to a specific group. Requires the Django authentication contrib app and middleware. Usage: {% ifusergroup Admins %} ... {% endifusergroup %}, or {% ifusergroup Admins Clients Sellers %} ... {% else %} ... {% endifusergroup %}
entailment
def OpenHandle(self): '''Gets a handle for use with other vSphere Guest API functions. The guest library handle provides a context for accessing information about the virtual machine. Virtual machine statistics and state data are associated with a particular guest library handl...
Gets a handle for use with other vSphere Guest API functions. The guest library handle provides a context for accessing information about the virtual machine. Virtual machine statistics and state data are associated with a particular guest library handle, so using one handle does not a...
entailment
def CloseHandle(self): '''Releases a handle acquired with VMGuestLib_OpenHandle''' if hasattr(self, 'handle'): ret = vmGuestLib.VMGuestLib_CloseHandle(self.handle.value) if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret) del(self.handle)
Releases a handle acquired with VMGuestLib_OpenHandle
entailment
def UpdateInfo(self): '''Updates information about the virtual machine. This information is associated with the VMGuestLibHandle. VMGuestLib_UpdateInfo requires similar CPU resources to a system call and therefore can affect performance. If you are concerned about performance, ...
Updates information about the virtual machine. This information is associated with the VMGuestLibHandle. VMGuestLib_UpdateInfo requires similar CPU resources to a system call and therefore can affect performance. If you are concerned about performance, minimize the number of...
entailment
def GetSessionId(self): '''Retrieves the VMSessionID for the current session. Call this function after calling VMGuestLib_UpdateInfo. If VMGuestLib_UpdateInfo has never been called, VMGuestLib_GetSessionId returns VMGUESTLIB_ERROR_NO_INFO.''' sid = c_void_p() ret = vmGuestL...
Retrieves the VMSessionID for the current session. Call this function after calling VMGuestLib_UpdateInfo. If VMGuestLib_UpdateInfo has never been called, VMGuestLib_GetSessionId returns VMGUESTLIB_ERROR_NO_INFO.
entailment
def GetCpuLimitMHz(self): '''Retrieves the upperlimit of processor use in MHz available to the virtual machine. For information about setting the CPU limit, see "Limits and Reservations" on page 14.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetCpuLimitMHz(self.handl...
Retrieves the upperlimit of processor use in MHz available to the virtual machine. For information about setting the CPU limit, see "Limits and Reservations" on page 14.
entailment
def GetCpuReservationMHz(self): '''Retrieves the minimum processing power in MHz reserved for the virtual machine. For information about setting a CPU reservation, see "Limits and Reservations" on page 14.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetCpuReservationM...
Retrieves the minimum processing power in MHz reserved for the virtual machine. For information about setting a CPU reservation, see "Limits and Reservations" on page 14.
entailment
def GetCpuShares(self): '''Retrieves the number of CPU shares allocated to the virtual machine. For information about how an ESX server uses CPU shares to manage virtual machine priority, see the vSphere Resource Management Guide.''' counter = c_uint() ret = vmGuestLib.VMGu...
Retrieves the number of CPU shares allocated to the virtual machine. For information about how an ESX server uses CPU shares to manage virtual machine priority, see the vSphere Resource Management Guide.
entailment
def GetCpuStolenMs(self): '''Retrieves the number of milliseconds that the virtual machine was in a ready state (able to transition to a run state), but was not scheduled to run.''' counter = c_uint64() ret = vmGuestLib.VMGuestLib_GetCpuStolenMs(self.handle.value, byref(counter)) ...
Retrieves the number of milliseconds that the virtual machine was in a ready state (able to transition to a run state), but was not scheduled to run.
entailment
def GetCpuUsedMs(self): '''Retrieves the number of milliseconds during which the virtual machine has used the CPU. This value includes the time used by the guest operating system and the time used by virtualization code for tasks for this virtual machine. You can combine this va...
Retrieves the number of milliseconds during which the virtual machine has used the CPU. This value includes the time used by the guest operating system and the time used by virtualization code for tasks for this virtual machine. You can combine this value with the elapsed time ...
entailment
def GetElapsedMs(self): '''Retrieves the number of milliseconds that have passed in the virtual machine since it last started running on the server. The count of elapsed time restarts each time the virtual machine is powered on, resumed, or migrated using VMotion. This value cou...
Retrieves the number of milliseconds that have passed in the virtual machine since it last started running on the server. The count of elapsed time restarts each time the virtual machine is powered on, resumed, or migrated using VMotion. This value counts milliseconds, regardless of ...
entailment
def GetHostCpuUsedMs(self): '''Undocumented.''' counter = c_uint64() ret = vmGuestLib.VMGuestLib_GetHostCpuUsedMs(self.handle.value, byref(counter)) if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret) return counter.value
Undocumented.
entailment
def GetHostMemKernOvhdMB(self): '''Undocumented.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetHostMemKernOvhdMB(self.handle.value, byref(counter)) if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret) return counter.value
Undocumented.
entailment
def GetHostMemMappedMB(self): '''Undocumented.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetHostMemMappedMB(self.handle.value, byref(counter)) if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret) return counter.value
Undocumented.
entailment
def GetHostMemPhysFreeMB(self): '''Undocumented.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetHostMemPhysFreeMB(self.handle.value, byref(counter)) if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret) return counter.value
Undocumented.
entailment
def GetHostMemPhysMB(self): '''Undocumented.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetHostMemPhysMB(self.handle.value, byref(counter)) if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret) return counter.value
Undocumented.
entailment
def GetHostMemSharedMB(self): '''Undocumented.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetHostMemSharedMB(self.handle.value, byref(counter)) if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret) return counter.value
Undocumented.
entailment
def GetHostMemSwappedMB(self): '''Undocumented.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetHostMemSwappedMB(self.handle.value, byref(counter)) if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret) return counter.value
Undocumented.
entailment
def GetHostMemUnmappedMB(self): '''Undocumented.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetHostMemUnmappedMB(self.handle.value, byref(counter)) if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret) return counter.value
Undocumented.
entailment
def GetHostMemUsedMB(self): '''Undocumented.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetHostMemUsedMB(self.handle.value, byref(counter)) if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret) return counter.value
Undocumented.
entailment
def GetHostNumCpuCores(self): '''Undocumented.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetHostNumCpuCores(self.handle.value, byref(counter)) if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret) return counter.value
Undocumented.
entailment
def GetHostProcessorSpeed(self): '''Retrieves the speed of the ESX system's physical CPU in MHz.''' counter = c_uint() ret = vmGuestLib.VMGuestLib_GetHostProcessorSpeed(self.handle.value, byref(counter)) if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret) return co...
Retrieves the speed of the ESX system's physical CPU in MHz.
entailment