INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
r Convert tau to: math: y = \ sqrt { 2 \ nu \ sum_i ( \ tau_i^2/ l_i^2 ) }. Takes tau as an argument list for compatibility with: py: func: mpmath. diff. Parameters ---------- tau [ 0 ]: scalar float First element of tau. tau [ 1 ]: And so on... Returns ------- y: scalar float Inner part of Matern kernel at the given t... | def _compute_y_wrapper(self, *args):
r"""Convert tau to :math:`y=\sqrt{2\nu\sum_i(\tau_i^2/l_i^2)}`.
Takes `tau` as an argument list for compatibility with :py:func:`mpmath.diff`.
Parameters
----------
tau[0] : scalar float
First element of `tau`.
... |
r Evaluate the derivative of the outer form of the Matern kernel. Uses the general Leibniz rule to compute the n - th derivative of:.. math:: f ( y ) = \ frac { 2^ { 1 - \ nu }} { \ Gamma ( \ nu ) } y^ { \ nu/ 2 } K_ \ nu ( y^ { 1/ 2 } ) Parameters ---------- y:: py: class: Array ( M ) M inputs to evaluate at. n: non -... | def _compute_dk_dy(self, y, n):
r"""Evaluate the derivative of the outer form of the Matern kernel.
Uses the general Leibniz rule to compute the n-th derivative of:
.. math::
f(y) = \frac{2^{1-\nu}}{\Gamma(\nu)} y^{\nu/2} K_\nu(y^{1/2})
Par... |
r Evaluate the derivative of the inner argument of the Matern kernel. Take the derivative of.. math:: y = 2 \ nu \ sum_i ( \ tau_i^2/ l_i^2 ) Parameters ---------- tau:: py: class: Matrix ( M D ) M inputs with dimension D. b:: py: class: Array ( P ) Block specifying derivatives to be evaluated. r2l2:: py: class: Array ... | def _compute_dy_dtau(self, tau, b, r2l2):
r"""Evaluate the derivative of the inner argument of the Matern kernel.
Take the derivative of
.. math::
y = 2 \nu \sum_i(\tau_i^2 / l_i^2)
Parameters
----------
tau : :py:class:`Mat... |
Evaluate the term inside the sum of Faa di Bruno s formula for the given partition. Overrides the version from: py: class: gptools. kernel. core. ChainRuleKernel in order to get the correct behavior at the origin. Parameters ---------- tau:: py: class: Matrix ( M D ) M inputs with dimension D. p: list of: py: class: Ar... | def _compute_dk_dtau_on_partition(self, tau, p):
"""Evaluate the term inside the sum of Faa di Bruno's formula for the given partition.
Overrides the version from :py:class:`gptools.kernel.core.ChainRuleKernel`
in order to get the correct behavior at the origin.
Paramet... |
Build an argparse argument parser to parse the command line. | def add_logging_parser(main_parser):
"Build an argparse argument parser to parse the command line."
main_parser.set_defaults(setup_logging=set_logging_level)
verbosity_group = main_parser.add_mutually_exclusive_group(required=False)
verbosity_group.add_argument(
'--verbose',
'-v',
... |
Computes and sets the logging level from the parsed arguments. | def set_logging_level(args):
"Computes and sets the logging level from the parsed arguments."
root_logger = logging.getLogger()
level = logging.INFO
logging.getLogger('requests.packages.urllib3').setLevel(logging.WARNING)
if "verbose" in args and args.verbose is not None:
logging.getLogger('... |
Check if the user should or shouldn t be inside the system: - If the user is staff or superuser: LOGIN GRANTED - If the user has a Person and it is not disabled: LOGIN GRANTED - Elsewhere: LOGIN DENIED | def check_auth(user):
'''
Check if the user should or shouldn't be inside the system:
- If the user is staff or superuser: LOGIN GRANTED
- If the user has a Person and it is not "disabled": LOGIN GRANTED
- Elsewhere: LOGIN DENIED
'''
# Initialize authentication
auth = None
person = ... |
Handle the debugging to a file | def debug(self, msg):
'''
Handle the debugging to a file
'''
# If debug is not disabled
if self.__debug is not False:
# If never was set, try to set it up
if self.__debug is None:
# Check what do we have inside settings
de... |
Authenticate the user agains LDAP | def authenticate(self, *args, **kwargs):
'''
Authenticate the user agains LDAP
'''
# Get config
username = kwargs.get("username", None)
password = kwargs.get("password", None)
# Check user in Active Directory (authorization == None if can not connect to Active D... |
Get or create the given user | def get_or_create_user(self, username, password):
'''
Get or create the given user
'''
# Get the groups for this user
info = self.get_ad_info(username, password)
self.debug("INFO found: {}".format(info))
# Find the user
try:
user = User.objec... |
It tries to do a group synchronization if possible This methods should be redeclared by the developer | def synchronize(self, user, info):
'''
It tries to do a group synchronization if possible
This methods should be redeclared by the developer
'''
self.debug("Synchronize!")
# Remove all groups from this user
user.groups.clear()
# For all domains found fo... |
Sets the free hyperparameters to the new parameter values in new_params. Parameters ---------- new_params:: py: class: Array or other Array - like ( len (: py: attr: self. free_params ) ) New parameter values ordered as dictated by the docstring for the class. | def set_hyperparams(self, new_params):
"""Sets the free hyperparameters to the new parameter values in new_params.
Parameters
----------
new_params : :py:class:`Array` or other Array-like, (len(:py:attr:`self.free_params`),)
New parameter values, ordered as dictated ... |
r Compute the anisotropic: math: r^2/ l^2 term for the given tau. Here: math: \ tau = X_i - X_j is the difference vector. Computes.. math:: \ frac { r^2 } { l^2 } = \ sum_i \ frac { \ tau_i^2 } { l_ { i } ^ { 2 }} Assumes that the length parameters are the last num_dim elements of: py: attr: self. params. Where l and t... | def _compute_r2l2(self, tau, return_l=False):
r"""Compute the anisotropic :math:`r^2/l^2` term for the given `tau`.
Here, :math:`\tau=X_i-X_j` is the difference vector. Computes
.. math::
\frac{r^2}{l^2} = \sum_i\frac{\tau_i^2}{l_{i}^{2}}
Assume... |
Set enforce_bounds for both of the kernels to a new value. | def enforce_bounds(self, v):
"""Set `enforce_bounds` for both of the kernels to a new value.
"""
self._enforce_bounds = v
self.k1.enforce_bounds = v
self.k2.enforce_bounds = v |
Returns the bounds of the free hyperparameters. Returns ------- free_param_bounds:: py: class: Array Array of the bounds of the free parameters in order. | def free_param_bounds(self):
"""Returns the bounds of the free hyperparameters.
Returns
-------
free_param_bounds : :py:class:`Array`
Array of the bounds of the free parameters, in order.
"""
return scipy.concatenate((self.k1.free_param_bounds, self.k... |
Returns the names of the free hyperparameters. Returns ------- free_param_names:: py: class: Array Array of the names of the free parameters in order. | def free_param_names(self):
"""Returns the names of the free hyperparameters.
Returns
-------
free_param_names : :py:class:`Array`
Array of the names of the free parameters, in order.
"""
return scipy.concatenate((self.k1.free_param_names, self.k2.fre... |
Set the ( free ) hyperparameters. Parameters ---------- new_params:: py: class: Array or other Array - like New values of the free parameters. Raises ------ ValueError If the length of new_params is not consistent with: py: attr: self. params. | def set_hyperparams(self, new_params):
"""Set the (free) hyperparameters.
Parameters
----------
new_params : :py:class:`Array` or other Array-like
New values of the free parameters.
Raises
------
ValueError
If the length o... |
r Evaluate: math: dk/ d \ tau at the specified locations with the specified derivatives. Parameters ---------- tau:: py: class: Matrix ( M D ) M inputs with dimension D. n:: py: class: Array ( D ) Degree of derivative with respect to each dimension. Returns ------- dk_dtau:: py: class: Array ( M ) Specified derivative ... | def _compute_dk_dtau(self, tau, n):
r"""Evaluate :math:`dk/d\tau` at the specified locations with the specified derivatives.
Parameters
----------
tau : :py:class:`Matrix`, (`M`, `D`)
`M` inputs with dimension `D`.
n : :py:class:`Array`, (`D`,)
De... |
Evaluate the term inside the sum of Faa di Bruno s formula for the given partition. Parameters ---------- tau:: py: class: Matrix ( M D ) M inputs with dimension D. p: list of: py: class: Array Each element is a block of the partition representing the derivative orders to use. Returns ------- dk_dtau:: py: class: Array... | def _compute_dk_dtau_on_partition(self, tau, p):
"""Evaluate the term inside the sum of Faa di Bruno's formula for the given partition.
Parameters
----------
tau : :py:class:`Matrix`, (`M`, `D`)
`M` inputs with dimension `D`.
p : list of :py:class:`Array`
... |
Masks the covariance function into a form usable by: py: func: mpmath. diff. Parameters ---------- * args: num_dim * 2 floats The individual elements of Xi and Xj to be passed to: py: attr: cov_func. | def _mask_cov_func(self, *args):
"""Masks the covariance function into a form usable by :py:func:`mpmath.diff`.
Parameters
----------
*args : `num_dim` * 2 floats
The individual elements of Xi and Xj to be passed to :py:attr:`cov_func`.
"""
# Have to ... |
Function implementing a constant mean suitable for use with: py: class: MeanFunction. | def constant(X, n, mu, hyper_deriv=None):
"""Function implementing a constant mean suitable for use with :py:class:`MeanFunction`.
"""
if (n == 0).all():
if hyper_deriv is not None:
return scipy.ones(X.shape[0])
else:
return mu * scipy.ones(X.shape[0])
else:
... |
Modified hyperbolic tangent function mtanh ( z ; alpha ). Parameters ---------- alpha: float The core slope of the mtanh. z: float or array The coordinate of the mtanh. | def mtanh(alpha, z):
"""Modified hyperbolic tangent function mtanh(z; alpha).
Parameters
----------
alpha : float
The core slope of the mtanh.
z : float or array
The coordinate of the mtanh.
"""
z = scipy.asarray(z)
ez = scipy.exp(z)
enz = 1.0 / ez
return ((1... |
Profile used with the mtanh function to fit profiles suitable for use with: py: class: MeanFunction. Only supports univariate data! Parameters ---------- X: array ( M 1 ) The points to evaluate at. n: array ( 1 ) The order of derivative to compute. Only up to first derivatives are supported. x0: float Pedestal center d... | def mtanh_profile(X, n, x0, delta, alpha, h, b, hyper_deriv=None):
"""Profile used with the mtanh function to fit profiles, suitable for use with :py:class:`MeanFunction`.
Only supports univariate data!
Parameters
----------
X : array, (`M`, 1)
The points to evaluate at.
n : ar... |
Linear mean function of arbitrary dimension suitable for use with: py: class: MeanFunction. The form is: math: m_0 * X [: 0 ] + m_1 * X [: 1 ] + \ dots + b. Parameters ---------- X: array ( M D ) The points to evaluate the model at. n: array of non - negative int ( D ) The derivative order to take specified as an integ... | def linear(X, n, *args, **kwargs):
"""Linear mean function of arbitrary dimension, suitable for use with :py:class:`MeanFunction`.
The form is :math:`m_0 * X[:, 0] + m_1 * X[:, 1] + \dots + b`.
Parameters
----------
X : array, (`M`, `D`)
The points to evaluate the model at.
n :... |
We save all the schedule items associated with this slot so the last_update time is updated to reflect any changes to the timing of the slots | def update_schedule_items(*args, **kw):
"""We save all the schedule items associated with this slot, so
the last_update time is updated to reflect any changes to the
timing of the slots"""
slot = kw.pop('instance', None)
if not slot:
return
for item in slot.scheduleitem_set.all():
... |
Create the difference between the current revision and a previous version | def make_diff(current, revision):
"""Create the difference between the current revision and a previous version"""
the_diff = []
dmp = diff_match_patch()
for field in (set(current.field_dict.keys()) | set(revision.field_dict.keys())):
# These exclusions really should be configurable
if f... |
Actually compare two versions. | def compare_view(self, request, object_id, version_id, extra_context=None):
"""Actually compare two versions."""
opts = self.model._meta
object_id = unquote(object_id)
# get_for_object's ordering means this is always the latest revision.
# The reversion we want to compare to
... |
Allow selecting versions to compare. | def comparelist_view(self, request, object_id, extra_context=None):
"""Allow selecting versions to compare."""
opts = self.model._meta
object_id = unquote(object_id)
current = get_object_or_404(self.model, pk=object_id)
# As done by reversion's history_view
action_list = ... |
This function helps to convert date information for showing proper filtering | def grv(struct, position):
'''
This function helps to convert date information for showing proper filtering
'''
if position == 'year':
size = 4
else:
size = 2
if (struct[position][2]):
rightnow = str(struct[position][0]).zfill(size)
else:
if position == 'year... |
Entry point for this class here we decide basic stuff | def _setup(self, request):
'''
Entry point for this class, here we decide basic stuff
'''
# Get details from self
info = model_inspect(self)
self._appname = getattr(self, 'appname', info['appname'])
self._modelname = getattr(self, 'modelname', info['modelname'])
... |
Build the list of templates related to this user | def get_template_names(self):
'''
Build the list of templates related to this user
'''
# Get user template
template_model = getattr(self, 'template_model', "{0}/{1}_{2}".format(self._appname.lower(), self._modelname.lower(), self.get_template_names_key))
template_model_e... |
Set a base context | def get_context_data(self, **kwargs):
'''
Set a base context
'''
# Call the base implementation first to get a context
context = super(GenBase, self).get_context_data(**kwargs)
# Update general context with the stuff we already calculated
if hasattr(self, 'html_... |
Entry point for this class here we decide basic stuff | def dispatch(self, *args, **kwargs):
'''
Entry point for this class, here we decide basic stuff
'''
# Get if this class is working as only a base render and List funcionality shouldn't be enabled
onlybase = getattr(self, "onlybase", False)
# REST not available when only... |
raise Exception ( FOUND: {} -- __foreignkeys: {} -- __columns: {} -- autorules_keys: {} -- \ query_select_related: {} -- query_renamed: {} -- query_optimizer: {} | use_extra: {} | -- \ query: {} -- meta. fields: {} -- fields_related_model: {} -- query_verifier: {} \ -- ??? {} == {}. format ( found self. __foreignkeys s... | def get_queryset(self, raw_query=False):
# Call the base implementation
if not self.haystack:
queryset = super(GenList, self).get_queryset()
else:
queryset = SearchQuerySet().models(self.model)
# Optional tweak methods
Mfields = None
MlimitQ = Non... |
Generic list view with validation included and object transfering support | def get_context_data(self, **kwargs):
'''
Generic list view with validation included and object transfering support
'''
# Call the base implementation first to get a context
context = super(GenList, self).get_context_data(**kwargs)
# Update general context with the stuff... |
Return a base answer for a json answer | def get_context_json(self, context):
'''
Return a base answer for a json answer
'''
# Initialize answer
answer = {}
# Metadata builder
answer['meta'] = self.__jcontext_metadata(context)
# Filter builder
answer['filter'] = self.__jcontext_filter(c... |
Get a json parameter and rebuild the context back to a dictionary ( probably kwargs ) | def set_context_json(self, jsonquery):
'''
Get a json parameter and rebuild the context back to a dictionary (probably kwargs)
'''
# Make sure we are getting dicts
if type(jsonquery) != dict:
raise IOError("set_json_context() method can be called only with dictionari... |
Entry point for this class here we decide basic stuff | def dispatch(self, request, **kwargs):
'''
Entry point for this class, here we decide basic stuff
'''
# Check if this is a webservice request
self.json_worker = (bool(getattr(self.request, "authtoken", False))) or (self.json is True)
self.__authtoken = (bool(getattr(self... |
Set form groups to the groups specified in the view if defined | def get_form(self, form_class=None):
'''
Set form groups to the groups specified in the view if defined
'''
formobj = super(GenModify, self).get_form(form_class)
# Set requested group to this form
selfgroups = getattr(self, "form_groups", None)
if selfgroups:
... |
Entry point for this class here we decide basic stuff | def dispatch(self, request, **kwargs):
'''
Entry point for this class, here we decide basic stuff
'''
# Delete method must happen with POST not with GET
if request.method == 'POST':
# Check if this is a webservice request
self.__authtoken = (bool(getattr(... |
Entry point for this class here we decide basic stuff | def dispatch(self, request, **kwargs):
'''
Entry point for this class, here we decide basic stuff
'''
# Check if this is a REST query to pusth the answer to responde in JSON
if bool(self.request.META.get('HTTP_X_REST', False)):
self.json = True
# Check if th... |
method in charged of filling an structure containing the object fields values taking into account the group attribute from the corresponding form object which is necesary to fill the details form as it is configured in the group attribute | def get_filled_structure(self, subgroup=None):
'''
method in charged of filling an structure containing the object fields
values taking into account the 'group' attribute from the corresponding
form object, which is necesary to fill the details form as it is configured
in the 'gr... |
Pilfered from django. forms. utils: Convert a dictionary of attributes to a single string. The returned string will contain a leading space followed by key = value XML - style pairs. In the case of a boolean value the key will appear without a value. Otherwise the value is formatted through its own dict of attrs which ... | def flatatt(attrs):
"""
Pilfered from `django.forms.utils`:
Convert a dictionary of attributes to a single string.
The returned string will contain a leading space followed by key="value",
XML-style pairs. In the case of a boolean value, the key will appear
without a value. Otherwise, the value ... |
r Evaluate the kernel directly at the given values of tau. Parameters ---------- tau:: py: class: Matrix ( M D ) M inputs with dimension D. Returns ------- k:: py: class: Array ( M ): math: k ( \ tau ) ( less the: math: \ sigma^2 prefactor ). | def _compute_k(self, tau):
r"""Evaluate the kernel directly at the given values of `tau`.
Parameters
----------
tau : :py:class:`Matrix`, (`M`, `D`)
`M` inputs with dimension `D`.
Returns
-------
k : :py:class:`Array`, (`M`,)
... |
Evaluate the derivative of the outer form of the RQ kernel. Parameters ---------- y:: py: class: Array ( M ) M inputs to evaluate at. n: non - negative scalar int Order of derivative to compute. Returns ------- dk_dy:: py: class: Array ( M ) Specified derivative at specified locations. | def _compute_dk_dy(self, y, n):
"""Evaluate the derivative of the outer form of the RQ kernel.
Parameters
----------
y : :py:class:`Array`, (`M`,)
`M` inputs to evaluate at.
n : non-negative scalar int
Order of derivative to compute.
... |
Given a directory name return the Page representing it in the menu heirarchy. | def get_parent(self, directory):
"""
Given a directory name, return the Page representing it in the menu
heirarchy.
"""
assert settings.PAGE_DIR.startswith('/')
assert settings.PAGE_DIR.endswith('/')
parents = directory[len(settings.PAGE_DIR):]
page = No... |
Return the correct URL to SSO with the given method. | def wafer_sso_url(context, sso_method):
'''
Return the correct URL to SSO with the given method.
'''
request = context.request
url = reverse(getattr(views, '%s_login' % sso_method))
if 'next' in request.GET:
url += '?' + urlencode({'next': request.GET['next']})
return url |
Authorizes Coursera s OAuth2 client for using coursera. org API servers for a specific application | def authorize(args):
"""
Authorizes Coursera's OAuth2 client for using coursera.org API servers for
a specific application
"""
oauth2_instance = oauth2.build_oauth2(args.app, args)
oauth2_instance.build_authorizer()
logging.info('Application "%s" authorized!', args.app) |
Checks courseraoauth2client s connectivity to the coursera. org API servers for a specific application | def check_auth(args):
"""
Checks courseraoauth2client's connectivity to the coursera.org API servers
for a specific application
"""
oauth2_instance = oauth2.build_oauth2(args.app, args)
auth = oauth2_instance.build_authorizer()
my_profile_url = (
'https://api.coursera.org/api/externa... |
Writes to the screen the state of the authentication cache. ( For debugging authentication issues. ) BEWARE: DO NOT email the output of this command!!! You must keep the tokens secure. Treat them as passwords. | def display_auth_cache(args):
'''
Writes to the screen the state of the authentication cache. (For debugging
authentication issues.) BEWARE: DO NOT email the output of this command!!!
You must keep the tokens secure. Treat them as passwords.
'''
oauth2_instance = oauth2.build_oauth2(args.app, ar... |
r Warps the X coordinate with the tanh model.. math:: l = \ frac { l_1 + l_2 } { 2 } - \ frac { l_1 - l_2 } { 2 } \ tanh \ frac { x - x_0 } { l_w } Parameters ---------- X:: py: class: Array ( M ) or scalar float M locations to evaluate length scale at. l1: positive float Small - X saturation value of the length scale.... | def tanh_warp_arb(X, l1, l2, lw, x0):
r"""Warps the `X` coordinate with the tanh model
.. math::
l = \frac{l_1 + l_2}{2} - \frac{l_1 - l_2}{2}\tanh\frac{x-x_0}{l_w}
Parameters
----------
X : :py:class:`Array`, (`M`,) or scalar float
`M` locations to evaluate length sca... |
r Warps the X coordinate with a Gaussian - shaped divot... math:: l = l_1 - ( l_1 - l_2 ) \ exp \ left ( - 4 \ ln 2 \ frac { ( X - x_0 ) ^2 } { l_ { w } ^ { 2 }} \ right ) Parameters ---------- X:: py: class: Array ( M ) or scalar float M locations to evaluate length scale at. l1: positive float Global value of the len... | def gauss_warp_arb(X, l1, l2, lw, x0):
r"""Warps the `X` coordinate with a Gaussian-shaped divot.
.. math::
l = l_1 - (l_1 - l_2) \exp\left ( -4\ln 2\frac{(X-x_0)^2}{l_{w}^{2}} \right )
Parameters
----------
X : :py:class:`Array`, (`M`,) or scalar float
`M` locatio... |
r Implements a tanh warping function and its derivative... math:: l = \ frac { l_1 + l_2 } { 2 } - \ frac { l_1 - l_2 } { 2 } \ tanh \ frac { x - x_0 } { l_w } Parameters ---------- x: float or array of float Locations to evaluate the function at. n: int Derivative order to take. Used for ALL of the points. l1: positiv... | def tanh_warp(x, n, l1, l2, lw, x0):
r"""Implements a tanh warping function and its derivative.
.. math::
l = \frac{l_1 + l_2}{2} - \frac{l_1 - l_2}{2}\tanh\frac{x-x_0}{l_w}
Parameters
----------
x : float or array of float
Locations to evaluate the function at.
n ... |
r Implements a sum - of - tanh warping function and its derivative... math:: l = a \ tanh \ frac { x - x_a } { l_a } + b \ tanh \ frac { x - x_b } { l_b } Parameters ---------- x: float or array of float Locations to evaluate the function at. n: int Derivative order to take. Used for ALL of the points. lcore: float Cor... | def double_tanh_warp(x, n, lcore, lmid, ledge, la, lb, xa, xb):
r"""Implements a sum-of-tanh warping function and its derivative.
.. math::
l = a\tanh\frac{x-x_a}{l_a} + b\tanh\frac{x-x_b}{l_b}
Parameters
----------
x : float or array of float
Locations to evaluate the... |
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 scale to the left of the bucket. l2: positive flo... | 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 quintic bucket shape. | 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... |
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 ) \ right ) Th... | 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 ( -\... |
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. | 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... |
Create a user if the provided user is None from the parameters. Then log the user in and return it. | 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')
... |
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 for each of the parameters. nu... | 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... |
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 the second dimension. x_vals_3: array ( P ) Values along the thi... | 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... |
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 handled. | 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... |
Post a debit of amount and a credit of - amount against this account and credit_account respectively. | 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 credit of amount and a debit of - amount against this account and credit_account respectively. | 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 transaction of amount against this account and the negative amount against other_account. | 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.
... |
returns the account balance as of date ( datetime stamp ) or now (). | 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 a Totals object containing the sum of all debits credits and net change over the period of time from start to end. | 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 list of entries for this account. | 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,... |
Return the account for the given third - party. Raise <something > if the third party doesn t belong to this bookset. | 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. | 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... |
Find any slots that overlap | 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 items that have slots that aren t contiguous | 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 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 | 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 talks/ pages assigned to mulitple schedule items | 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 schedule items which clash ( common slot and venue ) | 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 venues assigned slots that aren t on the allowed list of days. | 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:
... |
Helper routine to easily test if the schedule is valid | 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 report issues with the schedule | 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, _... |
Change the form depending on whether we re adding or editing the slot. | 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) |
Return the menus from the cache or generate them if needed. | 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 |
If argument is not a string return it. | 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 ... |
Generate a new list of menus. | 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 |
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 | 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... |
Makes a a handler class to use inside the basic python HTTP server. | 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... |
Loads configuration from the file system. | 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... |
Reads the local fs cache for pre - authorized access tokens | 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... |
Write out to the filesystem a cache of the OAuth2 information. | 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)
... |
Checks the cache_value for appropriate type correctness. | 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_... |
Stands up a new localhost http server and retrieves new OAuth2 access tokens from the Coursera OAuth2 server. | 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... |
Exchanges a refresh token for an access token | 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',
... |
function to determine if each select field needs a create button or not | 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... |
Some types get serialized to JSON as strings. If we know what they are supposed to be we can deserialize them | 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 ... |
Combined hyperprior for the kernel noise kernel and ( if present ) mean function. | 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 fixed hyperparameter flags for the kernel noise kernel and ( if present ) mean function. | 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 hyperparameters for the kernel noise kernel and ( if present ) mean function. | 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 names for the hyperparameters for the kernel noise kernel and ( if present ) mean function. | 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 free hyperparameters for the kernel noise kernel and ( if present ) mean function. | 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 |
Set the free parameters. Note that this bypasses enforce_bounds. | 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... |
Combined free hyperparameter bounds for the kernel noise kernel and ( if present ) mean function. | 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 names for the kernel noise kernel and ( if present ) mean function. | 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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.