Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def _repr__base(self, rich_output=False):
# Make a dictionary which will then be transformed in a list
repr_dict = collections.OrderedDict()
key = '%s (point source)' % self.name
repr_dict[key] = collections.OrderedDict()
... | [
"\n Representation of the object\n\n :param rich_output: if True, generates HTML, otherwise text\n :return: the representation\n "
] |
Please provide a description of the function:def get_flux(self, energies):
results = [component.shape(energies) for component in self.components.values()]
return numpy.sum(results, 0) | [
"Get the total flux of this particle source at the given energies (summed over the components)"
] |
Please provide a description of the function:def free_parameters(self):
free_parameters = collections.OrderedDict()
for component in self._components.values():
for par in component.shape.parameters.values():
if par.free:
free_parameters[par.pa... | [
"\n Returns a dictionary of free parameters for this source.\n We use the parameter path as the key because it's \n guaranteed to be unique, unlike the parameter name.\n\n :return:\n "
] |
Please provide a description of the function:def parameters(self):
all_parameters = collections.OrderedDict()
for component in self._components.values():
for par in component.shape.parameters.values():
all_parameters[par.path] = par
return all_parameters | [
"\n Returns a dictionary of all parameters for this source.\n We use the parameter path as the key because it's \n guaranteed to be unique, unlike the parameter name.\n\n :return:\n "
] |
Please provide a description of the function:def get_total_spatial_integral(self, z=None):
if isinstance( z, u.Quantity):
z = z.value
return np.ones_like( z ) | [
"\n Returns the total integral (for 2D functions) or the integral over the spatial components (for 3D functions).\n needs to be implemented in subclasses.\n\n :return: an array of values of the integral (same dimension as z).\n "
] |
Please provide a description of the function:def get_function(function_name, composite_function_expression=None):
# Check whether this is a composite function or a simple function
if composite_function_expression is not None:
# Composite function
return _parse_function_expression(composi... | [
"\n Returns the function \"name\", which must be among the known functions or a composite function.\n\n :param function_name: the name of the function (use 'composite' if the function is a composite function)\n :param composite_function_expression: composite function specification such as\n ((((powerlaw... |
Please provide a description of the function:def get_function_class(function_name):
if function_name in _known_functions:
return _known_functions[function_name]
else:
raise UnknownFunction("Function %s is not known. Known functions are: %s" %
(function_name... | [
"\n Return the type for the requested function\n\n :param function_name: the function to return\n :return: the type for that function (i.e., this is a class, not an instance)\n "
] |
Please provide a description of the function:def _parse_function_expression(function_specification):
# NOTE FOR SECURITY
# This function has some security concerns. Security issues could arise if the user tries to read a model
# file which has been maliciously formatted to contain harmful code. In thi... | [
"\n Parse a complex function expression like:\n\n ((((powerlaw{1} + (sin{2} * 3)) + (sin{2} * 25)) - (powerlaw{1} * 16)) + (sin{2} ** 3.0))\n\n and return a composite function instance\n\n :param function_specification:\n :return: a composite function instance\n "
] |
Please provide a description of the function:def check_calling_sequence(name, function_name, function, possible_variables):
# Get calling sequence
# If the function has been memoized, it will have a "input_object" member
try:
calling_sequence = inspect.getargspec(functio... | [
"\n Check the calling sequence for the function looking for the variables specified.\n One or more of the variables can be in the calling sequence. Note that the\n order of the variables will be enforced.\n It will also enforce that the first parameter in the calling sequence is called '... |
Please provide a description of the function:def free_parameters(self):
free_parameters = collections.OrderedDict([(k,v) for k, v in self.parameters.iteritems() if v.free])
return free_parameters | [
"\n Returns a dictionary of free parameters for this function\n\n :return: dictionary of free parameters\n "
] |
Please provide a description of the function:def evaluate_at(self, *args, **parameter_specification): # pragma: no cover
# Set the parameters to the provided values
for parameter in parameter_specification:
self._get_child(parameter).value = parameter_specification[parameter]
... | [
"\n Evaluate the function at the given x(,y,z) for the provided parameters, explicitly provided as part of the\n parameter_specification keywords.\n\n :param *args:\n :param **parameter_specification:\n :return:\n "
] |
Please provide a description of the function:def from_unit_cube(self, x):
mu = self.mu.value
sigma = self.sigma.value
sqrt_two = 1.414213562
if x < 1e-16 or (1 - x) < 1e-16:
res = -1e32
else:
res = mu + sigma * sqrt_two * erfcinv(2 * (1 - x)... | [
"\n Used by multinest\n\n :param x: 0 < x < 1\n :param lower_bound:\n :param upper_bound:\n :return:\n "
] |
Please provide a description of the function:def from_unit_cube(self, x):
x0 = self.x0.value
gamma = self.gamma.value
half_pi = 1.57079632679
res = np.tan(np.pi * x - half_pi) * gamma + x0
return res | [
"\n Used by multinest\n\n :param x: 0 < x < 1\n :param lower_bound:\n :param upper_bound:\n :return:\n "
] |
Please provide a description of the function:def from_unit_cube(self, x):
cosdec_min = np.cos(deg2rad*(90.0 + self.lower_bound.value))
cosdec_max = np.cos(deg2rad*(90.0 + self.upper_bound.value))
v = x * (cosdec_max - cosdec_min)
v += cosdec_min
v = np.clip(v, -1.0, 1.... | [
"\n Used by multinest\n\n :param x: 0 < x < 1\n :param lower_bound:\n :param upper_bound:\n :return:\n "
] |
Please provide a description of the function:def from_unit_cube(self, x):
lower_bound = self.lower_bound.value
upper_bound = self.upper_bound.value
low = lower_bound
spread = float(upper_bound - lower_bound)
par = x * spread + low
return par | [
"\n Used by multinest\n\n :param x: 0 < x < 1\n :param lower_bound:\n :param upper_bound:\n :return:\n "
] |
Please provide a description of the function:def from_unit_cube(self, x):
low = math.log10(self.lower_bound.value)
up = math.log10(self.upper_bound.value)
spread = up - low
par = 10 ** (x * spread + low)
return par | [
"\n Used by multinest\n\n :param x: 0 < x < 1\n :param lower_bound:\n :param upper_bound:\n :return:\n "
] |
Please provide a description of the function:def _get_data_file_path(data_file):
try:
file_path = pkg_resources.resource_filename("astromodels", 'data/%s' % data_file)
except KeyError:
raise IOError("Could not read or find data file %s. Try reinstalling astromodels. If this does not fix... | [
"\n Returns the absolute path to the required data files.\n\n :param data_file: relative path to the data file, relative to the astromodels/data path.\n So to get the path to data/dark_matter/gammamc_dif.dat you need to use data_file=\"dark_matter/gammamc_dif.dat\"\n :return: absolute path of the data f... |
Please provide a description of the function:def _setup(self):
tablepath = _get_data_file_path("dark_matter/gammamc_dif.dat")
self._data = np.loadtxt(tablepath)
channel_index_mapping = {
1: 8, # ee
2: 6, # mumu
3: 3, # tautau
4: 1, ... | [
"\n Mapping between the channel codes and the rows in the gammamc file\n\n 1 : 8, # ee\n 2 : 6, # mumu\n 3 : 3, # tautau\n 4 : 1, # bb\n 5 : 2, # tt\n 6 : 7, # gg\n 7 : 4, # ww\n 8 : 5, # zz\n 9 : 0, # cc\n... |
Please provide a description of the function:def _setup(self):
# Get and open the two data files
tablepath_h = _get_data_file_path("dark_matter/dmSpecTab.npy")
self._data_h = np.load(tablepath_h)
tablepath_f = _get_data_file_path("dark_matter/gammamc_dif.dat")
self._data_f = n... | [
"\n Mapping between the channel codes and the rows in the gammamc file\n dmSpecTab.npy created to match this mapping too\n\n 1 : 8, # ee\n 2 : 6, # mumu\n 3 : 3, # tautau\n 4 : 1, # bb\n 5 : 2, # tt\n 6 : 7, # gg\n 7 ... |
Please provide a description of the function:def vincenty(lon0, lat0, a1, s):
lon0 = np.deg2rad(lon0)
lat0 = np.deg2rad(lat0)
a1 = np.deg2rad(a1)
s = np.deg2rad(s)
sina = np.cos(lat0) * np.sin(a1)
num1 = np.sin(lat0)*np.cos(s) + np.cos(lat0)*np.sin(s)*np.cos(a1)
den1 = np.sqrt(sina**2 + (np.sin... | [
"\n Returns the coordinates of a new point that is a given angular distance s away from a starting point (lon0, lat0) at bearing (angle from north) a1), to within a given precision\n\n Note that this calculation is a simplified version of the full vincenty problem, which solves for the coordinates on the surface ... |
Please provide a description of the function:def is_valid_variable_name(string_to_check):
try:
parse('{} = None'.format(string_to_check))
return True
except (SyntaxError, ValueError, TypeError):
return False | [
"\n Returns whether the provided name is a valid variable name in Python\n\n :param string_to_check: the string to be checked\n :return: True or False\n "
] |
Please provide a description of the function:def _check_unit(new_unit, old_unit):
try:
new_unit.physical_type
except AttributeError:
raise UnitMismatch("The provided unit (%s) has no physical type. Was expecting a unit for %s"
% (new_unit, old_unit.physical_ty... | [
"\n Check that the new unit is compatible with the old unit for the quantity described by variable_name\n\n :param new_unit: instance of astropy.units.Unit\n :param old_unit: instance of astropy.units.Unit\n :return: nothin\n "
] |
Please provide a description of the function:def peak_energy(self):
# Eq. 6 in Massaro et al. 2004
# (http://adsabs.harvard.edu/abs/2004A%26A...413..489M)
return self.piv.value * pow(10, ((2 + self.alpha.value) * np.log(10)) / (2 * self.beta.value)) | [
"\n Returns the peak energy in the nuFnu spectrum\n\n :return: peak energy in keV\n "
] |
Please provide a description of the function:def get_spatially_integrated_flux( self, energies):
if not isinstance(energies, np.ndarray):
energies = np.array(energies, ndmin=1)
# Get the differential flux from the spectral components
results = [self.spatial_sh... | [
"\n Returns total flux of source at the given energy\n :param energies: energies (array or float)\n :return: differential flux at given energy\n "
] |
Please provide a description of the function:def get_ra(self):
try:
return self.ra.value
except AttributeError:
# Transform from L,B to R.A., Dec
return self.sky_coord.transform_to('icrs').ra.value | [
"\n Get R.A. corresponding to the current position (ICRS, J2000)\n\n :return: Right Ascension\n "
] |
Please provide a description of the function:def get_dec(self):
try:
return self.dec.value
except AttributeError:
# Transform from L,B to R.A., Dec
return self.sky_coord.transform_to('icrs').dec.value | [
"\n Get Dec. corresponding to the current position (ICRS, J2000)\n\n :return: Declination\n "
] |
Please provide a description of the function:def get_l(self):
try:
return self.l.value
except AttributeError:
# Transform from L,B to R.A., Dec
return self.sky_coord.transform_to('galactic').l.value | [
"\n Get Galactic Longitude (l) corresponding to the current position\n\n :return: Galactic Longitude\n "
] |
Please provide a description of the function:def get_b(self):
try:
return self.b.value
except AttributeError:
# Transform from L,B to R.A., Dec
return self.sky_coord.transform_to('galactic').b.value | [
"\n Get Galactic latitude (b) corresponding to the current position\n\n :return: Latitude\n "
] |
Please provide a description of the function:def parameters(self):
if self._coord_type == 'galactic':
return collections.OrderedDict((('l', self.l), ('b', self.b)))
else:
return collections.OrderedDict((('ra', self.ra), ('dec', self.dec))) | [
"\n Get the dictionary of parameters (either ra,dec or l,b)\n\n :return: dictionary of parameters\n "
] |
Please provide a description of the function:def fix(self):
if self._coord_type == 'equatorial':
self.ra.fix = True
self.dec.fix = True
else:
self.l.fix = True
self.b.fix = True | [
"\n Fix the parameters with the coordinates (either ra,dec or l,b depending on how the class\n has been instanced)\n \n "
] |
Please provide a description of the function:def free(self):
if self._coord_type == 'equatorial':
self.ra.fix = False
self.dec.fix = False
else:
self.l.fix = False
self.b.fix = False | [
"\n Free the parameters with the coordinates (either ra,dec or l,b depending on how the class\n has been instanced)\n \n "
] |
Please provide a description of the function:def _custom_init_(self, model_name, other_name=None,log_interp = True):
# Get the data directory
data_dir_path = get_user_data_path()
# Sanitize the data file
filename_sanitized = os.path.abspath(os.path.join(data_dir_path, '%s.h... | [
"\n Custom initialization for this model\n \n :param model_name: the name of the model, corresponding to the root of the .h5 file in the data directory\n :param other_name: (optional) the name to be used as name of the model when used in astromodels. If None \n (default), use the ... |
Please provide a description of the function:def accept_quantity(input_type=float, allow_none=False):
def accept_quantity_wrapper(method):
def handle_quantity(instance, value, *args, **kwargs):
# For speed reasons, first run the case where the input is not a quantity, and fall back to th... | [
"\n A class-method decorator which allow a given method (typically the set_value method) to receive both a\n astropy.Quantity or a simple float, but to be coded like it's always receiving a pure float in the right units.\n This is to give a way to avoid the huge bottleneck that are astropy.unit... |
Please provide a description of the function:def in_unit_of(self, unit, as_quantity=False):
new_unit = u.Unit(unit)
new_quantity = self.as_quantity.to(new_unit)
if as_quantity:
return new_quantity
else:
return new_quantity.value | [
"\n Return the current value transformed to the new units\n\n :param unit: either an astropy.Unit instance, or a string which can be converted to an astropy.Unit\n instance, like \"1 / (erg cm**2 s)\"\n :param as_quantity: if True, the method return an astropy.Quantity, if False just... |
Please provide a description of the function:def internal_to_external_delta(self, internal_value, internal_delta):
external_value = self.transformation.backward(internal_value)
bound_internal = internal_value + internal_delta
bound_external = self.transformation.backward(bound_internal... | [
"\n Transform an interval from the internal to the external reference (through the transformation). It is useful\n if you have for example a confidence interval in internal reference and you want to transform it to the\n external reference\n\n :param interval_value: value in internal ref... |
Please provide a description of the function:def _get_value(self):
# This is going to be true (possibly) only for derived classes. It is here to make the code cleaner
# and also to avoid infinite recursion
if self._aux_variable:
return self._aux_variable['law'](self._aux_... | [
"Return current parameter value"
] |
Please provide a description of the function:def _set_value(self, new_value):
if self.min_value is not None and new_value < self.min_value:
raise SettingOutOfBounds(
"Trying to set parameter {0} = {1}, which is less than the minimum allowed {2}".format(
... | [
"Sets the current value of the parameter, ensuring that it is within the allowed range."
] |
Please provide a description of the function:def _set_internal_value(self, new_internal_value):
if new_internal_value != self._internal_value:
self._internal_value = new_internal_value
# Call callbacks if any
for callback in self._callbacks:
call... | [
"\n This is supposed to be only used by fitting engines\n\n :param new_internal_value: new value in internal representation\n :return: none\n "
] |
Please provide a description of the function:def _set_min_value(self, min_value):
# Check that the min value can be transformed if a transformation is present
if self._transformation is not None:
if min_value is not None:
try:
_ = self._trans... | [
"Sets current minimum allowed value"
] |
Please provide a description of the function:def _get_internal_min_value(self):
if self.min_value is None:
# No minimum set
return None
else:
# There is a minimum. If there is a transformation, use it, otherwise just return the minimum
if se... | [
"\n This is supposed to be only used by fitting engines to get the minimum value in internal representation.\n It is supposed to be called only once before doing the minimization/sampling, to set the range of the parameter\n\n :return: minimum value in internal representation (or None if there ... |
Please provide a description of the function:def _set_max_value(self, max_value):
self._external_max_value = max_value
# Check that the current value of the parameter is still within the boundaries. If not, issue a warning
if self._external_max_value is not None and self.value > self... | [
"Sets current maximum allowed value"
] |
Please provide a description of the function:def _get_internal_max_value(self):
if self.max_value is None:
# No minimum set
return None
else:
# There is a minimum. If there is a transformation, use it, otherwise just return the minimum
if se... | [
"\n This is supposed to be only used by fitting engines to get the maximum value in internal representation.\n It is supposed to be called only once before doing the minimization/sampling, to set the range of the parameter\n\n :return: maximum value in internal representation (or None if there ... |
Please provide a description of the function:def _set_bounds(self, bounds):
# Use the properties so that the checks and the handling of units are made automatically
min_value, max_value = bounds
# Remove old boundaries to avoid problems with the new one, if the current value was with... | [
"Sets the boundaries for this parameter to min_value and max_value"
] |
Please provide a description of the function:def to_dict(self, minimal=False):
data = collections.OrderedDict()
if minimal:
# In the minimal representation we just output the value
data['value'] = self._to_python_type(self.value)
else:
# In the... | [
"Returns the representation for serialization"
] |
Please provide a description of the function:def _get_internal_delta(self):
if self._transformation is None:
return self._delta
else:
delta_int = None
for i in range(2):
# Try using the low bound
low_bound_ext = self.val... | [
"\n This is only supposed to be used by fitting/sampling engine, to get the initial step in internal representation\n\n :return: initial delta in internal representation\n "
] |
Please provide a description of the function:def _set_prior(self, prior):
if prior is None:
# Removing prior
self._prior = None
else:
# Try and call the prior with the current value of the parameter
try:
_ = prior(self.value)... | [
"Set prior for this parameter. The prior must be a function accepting the current value of the parameter\n as input and giving the probability density as output."
] |
Please provide a description of the function:def set_uninformative_prior(self, prior_class):
prior_instance = prior_class()
if self.min_value is None:
raise ParameterMustHaveBounds("Parameter %s does not have a defined minimum. Set one first, then re-run "
... | [
"\n Sets the prior for the parameter to a uniform prior between the current minimum and maximum, or a\n log-uniform prior between the current minimum and maximum.\n\n NOTE: if the current minimum and maximum are not defined, the default bounds for the prior class will be used.\n\n :param... |
Please provide a description of the function:def remove_auxiliary_variable(self):
if not self.has_auxiliary_variable():
# do nothing, but print a warning
warnings.warn("Cannot remove a non-existing auxiliary variable", RuntimeWarning)
else:
# Remove the ... | [
"\n Remove an existing auxiliary variable\n\n :return:\n "
] |
Please provide a description of the function:def to_dict(self, minimal=False):
data = super(Parameter, self).to_dict()
# Add wether is a normalization or not
data['is_normalization'] = self._is_normalization
if minimal:
# No need to add anything
pass... | [
"Returns the representation for serialization"
] |
Please provide a description of the function:def get_total_spatial_integral(self, z=None):
dL= self.l_max.value-self.l_min.value if self.l_max.value > self.l_min.value else 360 + self.l_max.value - self.l_max.value
#integral -inf to inf exp(-b**2 / 2*sigma_b**2 ) db = sqrt(2pi)*sigma_b
... | [
"\n Returns the total integral (for 2D functions) or the integral over the spatial components (for 3D functions).\n needs to be implemented in subclasses.\n\n :return: an array of values of the integral (same dimension as z).\n "
] |
Please provide a description of the function:def _get_child_from_path(self, path):
keys = path.split(".")
this_child = self
for key in keys:
try:
this_child = this_child._get_child(key)
except KeyError:
raise KeyError("Child... | [
"\n Return a children below this level, starting from a path of the kind \"this_level.something.something.name\"\n\n :param path: the key\n :return: the child\n "
] |
Please provide a description of the function:def _find_instances(self, cls):
instances = collections.OrderedDict()
for child_name, child in self._children.iteritems():
if isinstance(child, cls):
key_name = ".".join(child._get_path())
instances[ke... | [
"\n Find all the instances of cls below this node.\n\n :return: a dictionary of instances of cls\n "
] |
Please provide a description of the function:def clone_model(model_instance):
data = model_instance.to_dict_with_types()
parser = ModelParser(model_dict=data)
return parser.get_model() | [
"\n Returns a copy of the given model with all objects cloned. This is equivalent to saving the model to\n a file and reload it, but it doesn't require writing or reading to/from disk. The original model is not touched.\n\n :param model: model to be cloned\n :return: a cloned copy of the given model\n ... |
Please provide a description of the function:def sanitize_lib_name(library_path):
lib_name = os.path.basename(library_path)
# Some regexp magic needed to extract in a system-independent (mac/linux) way the library name
tokens = re.findall("lib(.+)(\.so|\.dylib|\.a)(.+)?", lib_name)
if not token... | [
"\n Get a fully-qualified library name, like /usr/lib/libgfortran.so.3.0, and returns the lib name needed to be\n passed to the linker in the -l option (for example gfortran)\n\n :param library_path:\n :return:\n "
] |
Please provide a description of the function:def find_library(library_root, additional_places=None):
# find_library searches for all system paths in a system independent way (but NOT those defined in
# LD_LIBRARY_PATH or DYLD_LIBRARY_PATH)
first_guess = ctypes.util.find_library(library_root)
if ... | [
"\n Returns the name of the library without extension\n\n :param library_root: root of the library to search, for example \"cfitsio_\" will match libcfitsio_1.2.3.4.so\n :return: the name of the library found (NOTE: this is *not* the path), and a directory path if the library is not\n in the system path... |
Please provide a description of the function:def dict_to_table(dictionary, list_of_keys=None):
# assert len(dictionary.values()) > 0, "Dictionary cannot be empty"
# Create an empty table
table = Table()
# If the dictionary is not empty, fill the table
if len(dictionary) > 0:
# Add... | [
"\n Return a table representing the dictionary.\n\n :param dictionary: the dictionary to represent\n :param list_of_keys: optionally, only the keys in this list will be inserted in the table\n :return: a Table instance\n "
] |
Please provide a description of the function:def _base_repr_(self, html=False, show_name=True, **kwargs):
table_id = 'table{id}'.format(id=id(self))
data_lines, outs = self.formatter._pformat_table(self,
tableid=table_id, html=html, max... | [
"\n Override the method in the astropy.Table class\n to avoid displaying the description, and the format\n of the columns\n "
] |
Please provide a description of the function:def fetch_cache_key(request):
m = hashlib.md5()
m.update(request.body)
return m.hexdigest() | [
" Returns a hashed cache key. "
] |
Please provide a description of the function:def dispatch(self, request, *args, **kwargs):
if not graphql_api_settings.CACHE_ACTIVE:
return self.super_call(request, *args, **kwargs)
cache = caches["default"]
operation_ast = self.get_operation_ast(request)
if operati... | [
" Fetches queried data from graphql and returns cached & hashed key. "
] |
Please provide a description of the function:def _parse(partial_dt):
dt = None
try:
if isinstance(partial_dt, datetime):
dt = partial_dt
if isinstance(partial_dt, date):
dt = _combine_date_time(partial_dt, time(0, 0, 0))
if isinstance(partial_dt, time):
... | [
"\n parse a partial datetime object to a complete datetime object\n "
] |
Please provide a description of the function:def get_obj(app_label, model_name, object_id):
try:
model = apps.get_model("{}.{}".format(app_label, model_name))
assert is_valid_django_model(model), ("Model {}.{} do not exist.").format(
app_label, model_name
)
obj = ge... | [
"\n Function used to get a object\n :param app_label: A valid Django Model or a string with format: <app_label>.<model_name>\n :param model_name: Key into kwargs that contains de data: new_person\n :param object_id:\n :return: instance\n "
] |
Please provide a description of the function:def create_obj(django_model, new_obj_key=None, *args, **kwargs):
try:
if isinstance(django_model, six.string_types):
django_model = apps.get_model(django_model)
assert is_valid_django_model(django_model), (
"You need to pass ... | [
"\n Function used by my on traditional Mutations to create objs\n :param django_model: A valid Django Model or a string with format:\n <app_label>.<model_name>\n :param new_obj_key: Key into kwargs that contains de data: new_person\n :param args:\n :param kwargs: Dict with model attributes values\... |
Please provide a description of the function:def clean_dict(d):
if not isinstance(d, (dict, list)):
return d
if isinstance(d, list):
return [v for v in (clean_dict(v) for v in d) if v]
return OrderedDict(
[(k, v) for k, v in ((k, clean_dict(v)) for k, v in list(d.items())) if v... | [
"\n Remove all empty fields in a nested dict\n "
] |
Please provide a description of the function:def _get_queryset(klass):
if isinstance(klass, QuerySet):
return klass
elif isinstance(klass, Manager):
manager = klass
elif isinstance(klass, ModelBase):
manager = klass._default_manager
else:
if isinstance(klass, type):
... | [
"\n Returns a QuerySet from a Model, Manager, or QuerySet. Created to make\n get_object_or_404 and get_list_or_404 more DRY.\n\n Raises a ValueError if klass is not a Model, Manager, or QuerySet.\n "
] |
Please provide a description of the function:def get_Object_or_None(klass, *args, **kwargs):
queryset = _get_queryset(klass)
try:
if args:
return queryset.using(args[0]).get(**kwargs)
else:
return queryset.get(*args, **kwargs)
except queryset.model.DoesNotExist:
... | [
"\n Uses get() to return an object, or None if the object does not exist.\n\n klass may be a Model, Manager, or QuerySet object. All other passed\n arguments and keyword arguments are used in the get() query.\n\n Note: Like with get(), an MultipleObjectsReturned will be raised\n if more than one obje... |
Please provide a description of the function:def find_schema_paths(schema_files_path=DEFAULT_SCHEMA_FILES_PATH):
paths = []
for path in schema_files_path:
if os.path.isdir(path):
paths.append(path)
if paths:
return paths
raise SchemaFilesNotFound("Searched " + os.pathsep... | [
"Searches the locations in the `SCHEMA_FILES_PATH` to\n try to find where the schema SQL files are located.\n "
] |
Please provide a description of the function:def execute(self, cmd, *args, **kwargs):
self.cursor.execute(cmd, *args, **kwargs) | [
" Execute the SQL command and return the data rows as tuples\n "
] |
Please provide a description of the function:def select(self, cmd, *args, **kwargs):
self.cursor.execute(cmd, *args, **kwargs)
return self.cursor.fetchall() | [
" Execute the SQL command and return the data rows as tuples\n "
] |
Please provide a description of the function:def run():
# create a arg parser and configure it.
parser = argparse.ArgumentParser(description='SharQ Server.')
parser.add_argument('-c', '--config', action='store', required=True,
help='Absolute path of the SharQ configuration file.... | [
"Exposes a CLI to configure the SharQ Server and runs the server.",
"\n ___ _ ___ ___\n / __| |_ __ _ _ _ / _ \\ / __| ___ _ ___ _____ _ _\n \\__ \\ ' \\/ _` | '_| (_) | \\__ \\/ -_) '_\\ V / -_) '_|\n |___/_||_\\__,_|_| \\__\\_\\ |___/\\___|_| \\_/\\___|_|\n\n Version: %s\... |
Please provide a description of the function:def setup_server(config_path):
# configure the SharQ server
server = SharQServer(config_path)
# start the requeue loop
gevent.spawn(server.requeue)
return server | [
"Configure SharQ server, start the requeue loop\n and return the server."
] |
Please provide a description of the function:def requeue(self):
job_requeue_interval = float(
self.config.get('sharq', 'job_requeue_interval'))
while True:
self.sq.requeue()
gevent.sleep(job_requeue_interval / 1000.00) | [
"Loop endlessly and requeue expired jobs."
] |
Please provide a description of the function:def _view_enqueue(self, queue_type, queue_id):
response = {
'status': 'failure'
}
try:
request_data = json.loads(request.data)
except Exception, e:
response['message'] = e.message
return... | [
"Enqueues a job into SharQ."
] |
Please provide a description of the function:def _view_dequeue(self, queue_type):
response = {
'status': 'failure'
}
request_data = {
'queue_type': queue_type
}
try:
response = self.sq.dequeue(**request_data)
if response['... | [
"Dequeues a job from SharQ."
] |
Please provide a description of the function:def _view_finish(self, queue_type, queue_id, job_id):
response = {
'status': 'failure'
}
request_data = {
'queue_type': queue_type,
'queue_id': queue_id,
'job_id': job_id
}
try:... | [
"Marks a job as finished in SharQ."
] |
Please provide a description of the function:def _view_interval(self, queue_type, queue_id):
response = {
'status': 'failure'
}
try:
request_data = json.loads(request.data)
interval = request_data['interval']
except Exception, e:
r... | [
"Updates the queue interval in SharQ."
] |
Please provide a description of the function:def _view_metrics(self, queue_type, queue_id):
response = {
'status': 'failure'
}
request_data = {}
if queue_type:
request_data['queue_type'] = queue_type
if queue_id:
request_data['queue_id... | [
"Gets SharQ metrics based on the params."
] |
Please provide a description of the function:def _view_clear_queue(self, queue_type, queue_id):
response = {
'status': 'failure'
}
try:
request_data = json.loads(request.data)
except Exception, e:
response['message'] = e.message
re... | [
"remove queueu from SharQ based on the queue_type and queue_id."
] |
Please provide a description of the function:def _get_from_path(import_path):
# type: (str) -> Callable
module_name, obj_name = import_path.rsplit('.', 1)
module = import_module(module_name)
return getattr(module, obj_name) | [
"\n Kwargs:\n import_path: full import path (to a mock factory function)\n\n Returns:\n (the mock factory function)\n "
] |
Please provide a description of the function:def register(func_path, factory=mock.MagicMock):
# type: (str, Callable) -> Callable
global _factory_map
_factory_map[func_path] = factory
def decorator(decorated_factory):
_factory_map[func_path] = decorated_factory
return decorated_fac... | [
"\n Kwargs:\n func_path: import path to mock (as you would give to `mock.patch`)\n factory: function that returns a mock for the patched func\n\n Returns:\n (decorator)\n\n Usage:\n\n automock.register('path.to.func.to.mock') # default MagicMock\n automock.register('path... |
Please provide a description of the function:def start_patching(name=None):
# type: (Optional[str]) -> None
global _factory_map, _patchers, _mocks
if _patchers and name is None:
warnings.warn('start_patching() called again, already patched')
_pre_import()
if name is not None:
... | [
"\n Initiate mocking of the functions listed in `_factory_map`.\n\n For this to work reliably all mocked helper functions should be imported\n and used like this:\n\n import dp_paypal.client as paypal\n res = paypal.do_paypal_express_checkout(...)\n\n (i.e. don't use `from dp_paypal.client... |
Please provide a description of the function:def stop_patching(name=None):
# type: (Optional[str]) -> None
global _patchers, _mocks
if not _patchers:
warnings.warn('stop_patching() called again, already stopped')
if name is not None:
items = [(name, _patchers[name])]
else:
... | [
"\n Finish the mocking initiated by `start_patching`\n\n Kwargs:\n name (Optional[str]): if given, only unpatch the specified path, else all\n defined default mocks\n "
] |
Please provide a description of the function:def standardize_back(xs, offset, scale):
try:
offset = float(offset)
except:
raise ValueError('The argument offset is not None or float.')
try:
scale = float(scale)
except:
raise ValueError('The argument scale is not None... | [
"\n This is function for de-standarization of input series.\n\n **Args:**\n\n * `xs` : standardized input (1 dimensional array)\n\n * `offset` : offset to add (float).\n\n * `scale` : scale (float).\n \n **Returns:**\n\n * `x` : original (destandardised) series\n\n "
] |
Please provide a description of the function:def standardize(x, offset=None, scale=None):
if offset == None:
offset = np.array(x).mean()
else:
try:
offset = float(offset)
except:
raise ValueError('The argument offset is not None or float')
if scale == No... | [
" \n This is function for standarization of input series.\n\n **Args:**\n\n * `x` : series (1 dimensional array)\n\n **Kwargs:**\n\n * `offset` : offset to remove (float). If not given, \\\n the mean value of `x` is used.\n\n * `scale` : scale (float). If not given, \\\n the standa... |
Please provide a description of the function:def input_from_history(a, n, bias=False):
if not type(n) == int:
raise ValueError('The argument n must be int.')
if not n > 0:
raise ValueError('The argument n must be greater than 0')
try:
a = np.array(a, dtype="float64")
except:... | [
"\n This is function for creation of input matrix.\n\n **Args:**\n\n * `a` : series (1 dimensional array)\n\n * `n` : size of input matrix row (int). It means how many samples \\\n of previous history you want to use \\\n as the filter input. It also represents the filter length.\n\n **... |
Please provide a description of the function:def init_weights(self, w, n=-1):
if n == -1:
n = self.n
if type(w) == str:
if w == "random":
w = np.random.normal(0, 0.5, n)
elif w == "zeros":
w = np.zeros(n)
else:
... | [
"\n This function initialises the adaptive weights of the filter.\n\n **Args:**\n\n * `w` : initial weights of filter. Possible values are:\n \n * array with initial weights (1 dimensional array) of filter size\n \n * \"random\" : create random weights\n ... |
Please provide a description of the function:def predict(self, x):
y = np.dot(self.w, x)
return y | [
"\n This function calculates the new output value `y` from input array `x`.\n\n **Args:**\n\n * `x` : input vector (1 dimension array) in length of filter.\n\n **Returns:**\n\n * `y` : output value (float) calculated from input array.\n\n "
] |
Please provide a description of the function:def pretrained_run(self, d, x, ntrain=0.5, epochs=1):
Ntrain = int(len(d)*ntrain)
# train
for epoch in range(epochs):
self.run(d[:Ntrain], x[:Ntrain])
# test
y, e, w = self.run(d[Ntrain:], x[Ntrain:])
retur... | [
"\n This function sacrifices part of the data for few epochs of learning.\n \n **Args:**\n\n * `d` : desired value (1 dimensional array)\n\n * `x` : input matrix (2-dimensional array). Rows are samples,\n columns are input arrays.\n \n **Kwargs:**\n\n ... |
Please provide a description of the function:def explore_learning(self, d, x, mu_start=0, mu_end=1., steps=100,
ntrain=0.5, epochs=1, criteria="MSE", target_w=False):
mu_range = np.linspace(mu_start, mu_end, steps)
errors = np.zeros(len(mu_range))
for i, mu in enumerate(mu_r... | [
"\n Test what learning rate is the best.\n\n **Args:**\n\n * `d` : desired value (1 dimensional array)\n\n * `x` : input matrix (2-dimensional array). Rows are samples,\n columns are input arrays.\n \n **Kwargs:**\n \n * `mu_start` : starting learning ... |
Please provide a description of the function:def check_float_param(self, param, low, high, name):
try:
param = float(param)
except:
raise ValueError(
'Parameter {} is not float or similar'.format(name)
)
if low != None ... | [
"\n Check if the value of the given parameter is in the given range\n and a float.\n Designed for testing parameters like `mu` and `eps`.\n To pass this function the variable `param` must be able to be converted\n into a float with a value between `low` and `high`.\n\n **Ar... |
Please provide a description of the function:def check_int(self, param, error_msg):
if type(param) == int:
return int(param)
else:
raise ValueError(error_msg) | [
"\n This function check if the parameter is int.\n If yes, the function returns the parameter,\n if not, it raises error message.\n \n **Args:**\n \n * `param` : parameter to check (int or similar)\n\n * `error_ms` : lowest allowed value (int), or None ... |
Please provide a description of the function:def check_int_param(self, param, low, high, name):
try:
param = int(param)
except:
raise ValueError(
'Parameter {} is not int or similar'.format(name)
)
if low != None or hig... | [
"\n Check if the value of the given parameter is in the given range\n and an int.\n Designed for testing parameters like `mu` and `eps`.\n To pass this function the variable `param` must be able to be converted\n into a float with a value between `low` and `high`.\n\n **Arg... |
Please provide a description of the function:def adapt(self, d, x):
y = np.dot(self.w, x)
e = d - y
nu = self.mu / (self.eps + np.dot(x, x))
self.w += nu * x * e**3 | [
"\n Adapt weights according one desired value and its input.\n\n **Args:**\n\n * `d` : desired value (float)\n\n * `x` : input array (1-dimensional array)\n "
] |
Please provide a description of the function:def run(self, d, x):
# measure the data and check if the dimmension agree
N = len(x)
if not len(d) == N:
raise ValueError('The length of vector d and matrix x must agree.')
self.n = len(x[0])
# prepare data
... | [
"\n This function filters multiple samples in a row.\n\n **Args:**\n\n * `d` : desired value (1 dimensional array)\n\n * `x` : input matrix (2-dimensional array). Rows are samples,\n columns are input arrays.\n\n **Returns:**\n\n * `y` : output value (1 dimensional... |
Please provide a description of the function:def get_valid_error(x1, x2=-1):
# just error
if type(x2) == int and x2 == -1:
try:
e = np.array(x1)
except:
raise ValueError('Impossible to convert series to a numpy array')
# two series
else:
t... | [
"\n Function that validates:\n\n * x1 is possible to convert to numpy array\n\n * x2 is possible to convert to numpy array (if exists)\n\n * x1 and x2 have the same length (if both exist)\n "
] |
Please provide a description of the function:def logSE(x1, x2=-1):
e = get_valid_error(x1, x2)
return 10*np.log10(e**2) | [
"\n 10 * log10(e**2) \n This function accepts two series of data or directly\n one series with error.\n\n **Args:**\n\n * `x1` - first data series or error (1d array)\n\n **Kwargs:**\n\n * `x2` - second series (1d array) if first series was not error directly,\\\\\n then this should b... |
Please provide a description of the function:def MAE(x1, x2=-1):
e = get_valid_error(x1, x2)
return np.sum(np.abs(e)) / float(len(e)) | [
"\n Mean absolute error - this function accepts two series of data or directly\n one series with error.\n\n **Args:**\n\n * `x1` - first data series or error (1d array)\n\n **Kwargs:**\n\n * `x2` - second series (1d array) if first series was not error directly,\\\\\n then this should be th... |
Please provide a description of the function:def MSE(x1, x2=-1):
e = get_valid_error(x1, x2)
return np.dot(e, e) / float(len(e)) | [
"\n Mean squared error - this function accepts two series of data or directly\n one series with error.\n\n **Args:**\n\n * `x1` - first data series or error (1d array)\n\n **Kwargs:**\n\n * `x2` - second series (1d array) if first series was not error directly,\\\\\n then this should be the... |
Please provide a description of the function:def RMSE(x1, x2=-1):
e = get_valid_error(x1, x2)
return np.sqrt(np.dot(e, e) / float(len(e))) | [
"\n Root-mean-square error - this function accepts two series of data\n or directly one series with error.\n\n **Args:**\n\n * `x1` - first data series or error (1d array)\n\n **Kwargs:**\n\n * `x2` - second series (1d array) if first series was not error directly,\\\\\n then this should be... |
Please provide a description of the function:def get_mean_error(x1, x2=-1, function="MSE"):
if function == "MSE":
return MSE(x1, x2)
elif function == "MAE":
return MAE(x1, x2)
elif function == "RMSE":
return RMSE(x1, x2)
else:
raise ValueError('The provided error fun... | [
"\n This function returns desired mean error. Options are: MSE, MAE, RMSE\n \n **Args:**\n\n * `x1` - first data series or error (1d array)\n\n **Kwargs:**\n\n * `x2` - second series (1d array) if first series was not error directly,\\\\\n then this should be the second series\n\n **Retu... |
Please provide a description of the function:def ELBND(w, e, function="max"):
# check if the function is known
if not function in ["max", "sum"]:
raise ValueError('Unknown output function')
# get length of data and number of parameters
N = w.shape[0]
n = w.shape[1]
# get abs dw from... | [
"\n This function estimates Error and Learning Based Novelty Detection measure\n from given data.\n\n **Args:**\n\n * `w` : history of adaptive parameters of an adaptive model (2d array),\n every row represents parameters in given time index.\n\n * `e` : error of adaptive model (1d array)\n\n ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.