text
stringlengths
81
112k
Get the network that this resource attribute is in. def get_network(self): """ Get the network that this resource attribute is in. """ ref_key = self.ref_key if ref_key == 'NETWORK': return self.network elif ref_key == 'NODE': return self.node.ne...
Check whether this user can read this resource attribute def check_read_permission(self, user_id, do_raise=True): """ Check whether this user can read this resource attribute """ return self.get_resource().check_read_permission(user_id, do_raise=do_raise)
Check whether this user can write this node def check_write_permission(self, user_id, do_raise=True): """ Check whether this user can write this node """ return self.get_resource().check_write_permission(user_id, do_raise=do_raise)
Add a link to a network. Links are what effectively define the network topology, by associating two already existing nodes. def add_link(self, name, desc, layout, node_1, node_2): """ Add a link to a network. Links are what effectively define the network topology...
Add a node to a network. def add_node(self, name, desc, layout, node_x, node_y): """ Add a node to a network. """ existing_node = get_session().query(Node).filter(Node.name==name, Node.network_id==self.id).first() if existing_node is not None: raise HydraError("A...
Add a new group to a network. def add_group(self, name, desc, status): """ Add a new group to a network. """ existing_group = get_session().query(ResourceGroup).filter(ResourceGroup.name==name, ResourceGroup.network_id==self.id).first() if existing_group is not None: ...
Check whether this user can read this network def check_read_permission(self, user_id, do_raise=True): """ Check whether this user can read this network """ if _is_admin(user_id): return True if int(self.created_by) == int(user_id): return True ...
Check whether this user can write this project def check_share_permission(self, user_id): """ Check whether this user can write this project """ if _is_admin(user_id): return if int(self.created_by) == int(user_id): return for owner in self...
Check whether this user can read this link def check_read_permission(self, user_id, do_raise=True): """ Check whether this user can read this link """ return self.network.check_read_permission(user_id, do_raise=do_raise)
Check whether this user can write this link def check_write_permission(self, user_id, do_raise=True): """ Check whether this user can write this link """ return self.network.check_write_permission(user_id, do_raise=do_raise)
Get all the items in this group, in the given scenario def get_items(self, scenario_id): """ Get all the items in this group, in the given scenario """ items = get_session().query(ResourceGroupItem)\ .filter(ResourceGroupItem.group_id==self.id).\ filt...
Using a ref key and ref id set the reference to the appropriate resource type. def set_ref(self, ref_key, ref_id): """ Using a ref key and ref id set the reference to the appropriate resource type. """ if ref_key == 'NETWORK': self.network_id = re...
Return the ID of the resource to which this not is attached def get_ref_id(self): """ Return the ID of the resource to which this not is attached """ if self.ref_key == 'NETWORK': return self.network_id elif self.ref_key == 'NODE': return self.node_i...
Return the ID of the resource to which this not is attached def get_ref(self): """ Return the ID of the resource to which this not is attached """ if self.ref_key == 'NETWORK': return self.network elif self.ref_key == 'NODE': return self.node ...
Return a set with all permissions granted to the user. def permissions(self): """Return a set with all permissions granted to the user.""" perms = set() for r in self.roles: perms = perms | set(r.permissions) return perms
Return a set with all roles granted to the user. def roles(self): """Return a set with all roles granted to the user.""" roles = [] for ur in self.roleusers: roles.append(ur.role) return set(roles)
Check that the user has a role with the code 'admin' def is_admin(self): """ Check that the user has a role with the code 'admin' """ for ur in self.roleusers: if ur.role.code == 'admin': return True return False
Check that the unit and dimension on a type attribute match. Alternatively, pass in a unit manually to check against the dimension of the type attribute def _check_dimension(typeattr, unit_id=None): """ Check that the unit and dimension on a type attribute match. Alternatively, pass...
Using the attributes of the resource, get all the types that this resource matches. @returns a dictionary, keyed on the template name, with the value being the list of type names which match the resources attributes. def get_types_by_attr(resource, template_id=None): """ Usi...
Search for an attribute with the given name and dimension_id. If such an attribute does not exist, create one. def _get_attr_by_name_and_dimension(name, dimension_id): """ Search for an attribute with the given name and dimension_id. If such an attribute does not exist, create one. """ ...
Get a template (including attribute and dataset definitions) as a JSON string. This is just a wrapper around the get_template_as_dict function. def get_template_as_json(template_id, **kwargs): """ Get a template (including attribute and dataset definitions) as a JSON string. This is just a ...
Turn a template into an xml template def get_template_as_xml(template_id,**kwargs): """ Turn a template into an xml template """ template_xml = etree.Element("template_definition") template_i = db.DBSession.query(Template).filter( Template.id==template_id).options( ...
Add the template, type and typeattrs described in a JSON file. Delete type, typeattr entries in the DB that are not in the XML file The assumption is that they have been deleted and are no longer required. The allow_update indicates whether an existing template of the same name should ...
Add the template, type and typeattrs described in an XML file. Delete type, typeattr entries in the DB that are not in the XML file The assumption is that they have been deleted and are no longer required. def import_template_xml(template_xml, allow_update=True, **kwargs): """ Add ...
For each node and link in a network, check whether it matches a type in a given template. If so, assign the type to the node / link. def apply_template_to_network(template_id, network_id, **kwargs): """ For each node and link in a network, check whether it matches a type in a given template...
Apply an existing template to a network. Used when a template has changed, and additional attributes must be added to the network's elements. def set_network_template(template_id, network_id, **kwargs): """ Apply an existing template to a network. Used when a template has changed, and additional attr...
Remove all resource types in a network relating to the specified template. remove_attrs Flag to indicate whether the attributes associated with the template types should be removed from the resources in the network. These will only be removed if they are not shared wi...
Given a resource and a template being removed, identify the resource attribtes which can be removed. def _get_resources_to_remove(resource, template): """ Given a resource and a template being removed, identify the resource attribtes which can be removed. """ type_ids = [tmpltype.id...
Get the possible types of a resource by checking its attributes against all available types. @returns A list of TypeSummary objects. def get_matching_resource_types(resource_type, resource_id,**kwargs): """ Get the possible types of a resource by checking its attributes against all...
Assign new types to list of resources. This function checks if the necessary attributes are present and adds them if needed. Non existing attributes are also added when the type is already assigned. This means that this function can also be used to update resources, when a resource type ...
When applying a type to a resource, it may be the case that the resource already has an attribute specified in the new type, but the template which defines this pre-existing attribute has a different unit specification to the new template. This function checks for any situations where different...
Assign new type to a resource. This function checks if the necessary attributes are present and adds them if needed. Non existing attributes are also added when the type is already assigned. This means that this function can also be used to update resources, when a resource type has changed. def assign...
Set this resource to be a certain type. Type objects (a dictionary keyed on type_id) may be passed in to save on loading. This function does not call save. It must be done afterwards. New resource attributes are added to the resource if the template requires them. Resource attrib...
Remove a resource type trom a resource def remove_type_from_resource( type_id, resource_type, resource_id,**kwargs): """ Remove a resource type trom a resource """ node_id = resource_id if resource_type == 'NODE' else None link_id = resource_id if resource_type == 'LINK' else None group_id ...
Add template and a type and typeattrs. def add_template(template, **kwargs): """ Add template and a type and typeattrs. """ tmpl = Template() tmpl.name = template.name if template.description: tmpl.description = template.description if template.layout: tmpl.layout = get_...
Update template and a type and typeattrs. def update_template(template,**kwargs): """ Update template and a type and typeattrs. """ tmpl = db.DBSession.query(Template).filter(Template.id==template.id).one() tmpl.name = template.name if template.description: tmpl.description = templa...
Delete a template and its type and typeattrs. def delete_template(template_id,**kwargs): """ Delete a template and its type and typeattrs. """ try: tmpl = db.DBSession.query(Template).filter(Template.id==template_id).one() except NoResultFound: raise ResourceNotFoundError("Templ...
Get all templates. Args: load_all Boolean: Returns just the template entry or the full template structure (template types and type attrs) Returns: List of Template objects def get_templates(load_all=True, **kwargs): """ Get all templates. Args: lo...
Get a specific resource template template, by ID. def get_template(template_id,**kwargs): """ Get a specific resource template template, by ID. """ try: tmpl_i = db.DBSession.query(Template).filter(Template.id==template_id).options(joinedload_all('templatetypes.typeattrs.default_dataset.met...
Get a specific resource template, by name. def get_template_by_name(name,**kwargs): """ Get a specific resource template, by name. """ try: tmpl_i = db.DBSession.query(Template).filter(Template.name == name).options(joinedload_all('templatetypes.typeattrs.default_dataset.metadata')).one() ...
Add a template type with typeattrs. def add_templatetype(templatetype,**kwargs): """ Add a template type with typeattrs. """ type_i = _update_templatetype(templatetype) db.DBSession.flush() return type_i
Update a resource type and its typeattrs. New typeattrs will be added. typeattrs not sent will be ignored. To delete typeattrs, call delete_typeattr def update_templatetype(templatetype,**kwargs): """ Update a resource type and its typeattrs. New typeattrs will be added. typeattrs n...
Add or updsate a type attribute. If an existing type attribute is provided, then update. Checks are performed to ensure that the dimension provided on the type attr (not updateable) is the same as that on the referring attribute. The unit provided (stored on tattr) must conform to the d...
Add or update a templatetype. If an existing template type is passed in, update that one. Otherwise search for an existing one. If not found, add. def _update_templatetype(templatetype, existing_tt=None): """ Add or update a templatetype. If an existing template type is passed in, update th...
Delete a template type and its typeattrs. def delete_templatetype(type_id,template_i=None, **kwargs): """ Delete a template type and its typeattrs. """ try: tmpltype_i = db.DBSession.query(TemplateType).filter(TemplateType.id == type_id).one() except NoResultFound: raise Resourc...
Get a specific resource type by ID. def get_templatetype(type_id,**kwargs): """ Get a specific resource type by ID. """ templatetype = db.DBSession.query(TemplateType).filter( TemplateType.id==type_id).options( joinedload_all("typeattrs")).one() ...
Get a specific resource type by name. def get_templatetype_by_name(template_id, type_name,**kwargs): """ Get a specific resource type by name. """ try: templatetype = db.DBSession.query(TemplateType).filter(TemplateType.id==template_id, TemplateType.name==type_name).one() except NoResu...
Add an typeattr to an existing type. def add_typeattr(typeattr,**kwargs): """ Add an typeattr to an existing type. """ tmpltype = get_templatetype(typeattr.type_id, user_id=kwargs.get('user_id')) ta = _set_typeattr(typeattr) tmpltype.typeattrs.append(ta) db.DBSession.flush() re...
Remove an typeattr from an existing type def delete_typeattr(typeattr,**kwargs): """ Remove an typeattr from an existing type """ tmpltype = get_templatetype(typeattr.type_id, user_id=kwargs.get('user_id')) ta = db.DBSession.query(TypeAttr).filter(TypeAttr.type_id == typeattr.type_id, ...
Check that a resource attribute satisfies the requirements of all the types of the resource. def validate_attr(resource_attr_id, scenario_id, template_id=None): """ Check that a resource attribute satisfies the requirements of all the types of the resource. """ rs = db.DBSession.que...
Check that multiple resource attribute satisfy the requirements of the types of resources to which the they are attached. def validate_attrs(resource_attr_ids, scenario_id, template_id=None): """ Check that multiple resource attribute satisfy the requirements of the types of resources to wh...
Perform a check to ensure a resource scenario's datasets are correct given what the definition of that resource (its type) specifies. def _do_validate_resourcescenario(resourcescenario, template_id=None): """ Perform a check to ensure a resource scenario's datasets are correct given what the ...
Given a network, scenario and template, ensure that all the nodes, links & groups in the network have the correct resource attributes as defined by the types in the template. Also ensure valid entries in tresourcetype. This validation will not fail if a resource has more than the required type, ...
Turn an existing network into an xml template using its attributes. If an optional scenario ID is passed in, default values will be populated from that scenario. def get_network_as_xml_template(network_id,**kwargs): """ Turn an existing network into an xml template using its...
General function to add an attribute element to a resource element. resource_attr_i can also e a type_attr if being called from get_tempalte_as_xml def _make_attr_element_from_typeattr(parent, type_attr_i): """ General function to add an attribute element to a resource element. resource_att...
General function to add an attribute element to a resource element. def _make_attr_element_from_resourceattr(parent, resource_attr_i): """ General function to add an attribute element to a resource element. """ attr = _make_attr_element(parent, resource_attr_i.attr) attr_is_var = etree.Sub...
create an attribute element from an attribute DB object def _make_attr_element(parent, attr_i): """ create an attribute element from an attribute DB object """ attr = etree.SubElement(parent, "attribute") attr_name = etree.SubElement(attr, 'name') attr_name.text = attr_i.name att...
Convert something that looks like this: <layout> <item> <name>color</name> <value>red</value> </item> <item> <name>shapefile</name> <value>blah.shp</value> </item> </layout> Into something that looks like this: { 'co...
Convert something that looks like this: { 'color' : ['red'], 'shapefile' : ['blah.shp'] } Into something that looks like this: <layout> <item> <name>color</name> <value>red</value> </item> <item> <name>shapefile</name> ...
Return the value contained by dataset argument, after casting to correct type and performing type-specific validation def valueFromDataset(cls, datatype, value, metadata=None, tmap=None): """ Return the value contained by dataset argument, after casting to correct type and perform...
Return a representation of dataset argument as an instance of the class corresponding to its datatype def fromDataset(datatype, value, metadata=None, tmap=None): """ Return a representation of dataset argument as an instance of the class corresponding to its datatype """...
Given a dimension returns True if it exists, False otherwise def exists_dimension(dimension_name,**kwargs): """ Given a dimension returns True if it exists, False otherwise """ try: dimension = db.DBSession.query(Dimension).filter(Dimension.name==dimension_name).one() # At this poin...
Helper function that extracts constant factors from unit specifications. This allows to specify units similar to this: 10^6 m^3. Return a couple (unit, factor) def _parse_unit(measure_or_unit_abbreviation): """ Helper function that extracts constant factors from unit specifications. ...
Convert a value from one unit to another one. Example:: >>> cli = PluginLib.connect() >>> cli.service.convert_units(20.0, 'm', 'km') 0.02 Parameters: values: single measure or an array of measures source_measure_or_unit_abbreviation: A measur...
Convert a value or a list of values from an unit to another one. The two units must represent the same physical dimension. def convert(values, source_measure_or_unit_abbreviation, target_measure_or_unit_abbreviation): """ Convert a value or a list of values from an unit to another one. The ...
Returns a dimension object initialized with empty values def get_empty_dimension(**kwargs): """ Returns a dimension object initialized with empty values """ dimension = JSONObject(Dimension()) dimension.id = None dimension.name = '' dimension.description = '' dimension.project_id = ...
Given a dimension id returns all its data def get_dimension(dimension_id, do_accept_dimension_id_none=False,**kwargs): """ Given a dimension id returns all its data """ if do_accept_dimension_id_none == True and dimension_id is None: # In this special case, the method returns a dimension wi...
Returns a list of objects describing all the dimensions with all the units. def get_dimensions(**kwargs): """ Returns a list of objects describing all the dimensions with all the units. """ dimensions_list = db.DBSession.query(Dimension).options(load_only("id")).all() return_list = [] for d...
Given a dimension name returns all its data. Used in convert functions def get_dimension_by_name(dimension_name,**kwargs): """ Given a dimension name returns all its data. Used in convert functions """ try: if dimension_name is None: dimension_name = '' dimension = db.DB...
Returns a single unit def get_unit(unit_id, **kwargs): """ Returns a single unit """ try: unit = db.DBSession.query(Unit).filter(Unit.id==unit_id).one() return JSONObject(unit) except NoResultFound: # The dimension does not exist raise ResourceNotFoundError("Unit...
Returns all the units def get_units(**kwargs): """ Returns all the units """ units_list = db.DBSession.query(Unit).all() units = [] for unit in units_list: new_unit = JSONObject(unit) units.append(new_unit) return units
Return the physical dimension a given unit abbreviation of a measure, or the measure itself, refers to. The search key is the abbreviation or the full measure def get_dimension_by_unit_measure_or_abbreviation(measure_or_unit_abbreviation,**kwargs): """ Return the physical dimension a given unit abb...
Return the physical dimension a given unit id refers to. if do_accept_unit_id_none is False, it raises an exception if unit_id is not valid or None if do_accept_unit_id_none is True, and unit_id is None, the function returns a Dimension with id None (unit_id can be none in some cases) def get_dimension...
Returns a single unit by abbreviation. Used as utility function to resolve string to id def get_unit_by_abbreviation(unit_abbreviation, **kwargs): """ Returns a single unit by abbreviation. Used as utility function to resolve string to id """ try: if unit_abbreviation is None: u...
Add the dimension defined into the object "dimension" to the DB If dimension["project_id"] is None it means that the dimension is global, otherwise is property of a project If the dimension exists emits an exception def add_dimension(dimension,**kwargs): """ Add the dimension defined into t...
Update a dimension in the DB. Raises and exception if the dimension does not exist. The key is ALWAYS the name and the name itself is not modificable def update_dimension(dimension,**kwargs): """ Update a dimension in the DB. Raises and exception if the dimension does not exist. ...
Delete a dimension from the DB. Raises and exception if the dimension does not exist def delete_dimension(dimension_id,**kwargs): """ Delete a dimension from the DB. Raises and exception if the dimension does not exist """ try: dimension = db.DBSession.query(Dimension).filter(Dimension.id==...
Save all the dimensions contained in the passed list. def bulk_add_dimensions(dimension_list, **kwargs): """ Save all the dimensions contained in the passed list. """ added_dimensions = [] for dimension in dimension_list: added_dimensions.append(add_dimension(dimension, **kwargs)) ...
Add the unit defined into the object "unit" to the DB If unit["project_id"] is None it means that the unit is global, otherwise is property of a project If the unit exists emits an exception A minimal example: .. code-block:: python new_unit = dict( name ...
Save all the units contained in the passed list, with the name of their dimension. def bulk_add_units(unit_list, **kwargs): """ Save all the units contained in the passed list, with the name of their dimension. """ # for unit in unit_list: # add_unit(unit, **kwargs) added_units = [] ...
Delete a unit from the DB. Raises and exception if the unit does not exist def delete_unit(unit_id, **kwargs): """ Delete a unit from the DB. Raises and exception if the unit does not exist """ try: db_unit = db.DBSession.query(Unit).filter(Unit.id==unit_id).one() ...
Update a unit in the DB. Raises and exception if the unit does not exist def update_unit(unit, **kwargs): """ Update a unit in the DB. Raises and exception if the unit does not exist """ try: db_unit = db.DBSession.query(Unit).join(Dimension).filter(Unit.id==unit["id"]).fil...
Convert a whole dataset (specified by 'dataset_id') to new unit ('target_unit_abbreviation'). Conversion ALWAYS creates a NEW dataset, so function returns the dataset ID of new dataset. def convert_dataset(dataset_id, target_unit_abbreviation,**kwargs): """ Convert a whole dataset (specified by 'da...
Validate that the resource provided matches the template. Only passes if the resource contains ONLY the attributes specified in the template. The template should take the form of a dictionary, as should the resources. *check_unit*: Makes sure that if a unit is specified in the ...
Encodes the given data using the encoding that is specified :param str encoding: encoding to use, should be one of the supported encoding :param data: data to encode :type data: str or bytes :return: multibase encoded data :rtype: bytes :raises ValueError: if the encoding is not supported def ...
Returns the codec used to encode the given data :param data: multibase encoded data :type data: str or bytes :return: the :py:obj:`multibase.Encoding` object for the data's codec :raises ValueError: if the codec is not supported def get_codec(data): """ Returns the codec used to encode the giv...
Decode the multibase decoded data :param data: multibase encoded data :type data: str or bytes :return: decoded data :rtype: str :raises ValueError: if the data is not multibase encoded def decode(data): """ Decode the multibase decoded data :param data: multibase encoded data :type...
Generate a new key pair. Args: secret (:class:`string`): A secret that serves as a seed Returns: A tuple of (private_key, public_key) encoded in base58. def ed25519_generate_key_pair_from_secret(secret): """ Generate a new key pair. Args: secret (:class:`string`): A secret t...
Generates a cryptographic key pair. Args: secret (:class:`string`): A secret that serves as a seed Returns: :class:`~bigchaindb.common.crypto.CryptoKeypair`: A :obj:`collections.namedtuple` with named fields :attr:`~bigchaindb.common.crypto.CryptoKeypair.private_key` and ...
Return role arn from X-Role-ARN header, lookup role arn from source IP, or fall back to command line default. def _get_role_arn(): """ Return role arn from X-Role-ARN header, lookup role arn from source IP, or fall back to command line default. """ role_arn = bottle.request.headers.get(...
Dynamically handle DynamoDB exceptions, returning HTTP error responses. :param exceptions.DynamoDBException error: def _on_dynamodb_exception(self, error): """Dynamically handle DynamoDB exceptions, returning HTTP error responses. :param exceptions.DynamoDBException error: ...
Collect data into fixed-length chunks or blocks def _chunk_with_padding(self, iterable, n, fillvalue=None): "Collect data into fixed-length chunks or blocks" # _chunk_with_padding('ABCDEFG', 3, 'x') --> ABC DEF Gxx" args = [iter(iterable)] * n return zip_longest(*args, fillvalue=fillval...
Marshall a `dict` into something DynamoDB likes. :param dict values: The values to marshall :rtype: dict :raises ValueError: if an unsupported type is encountered Return the values in a nested dict structure that is required for writing the values to DynamoDB. def marshall(values): """ Ma...
Transform a response payload from DynamoDB to a native dict :param dict values: The response payload from DynamoDB :rtype: dict :raises ValueError: if an unsupported type code is encountered def unmarshall(values): """ Transform a response payload from DynamoDB to a native dict :param dict va...
Recursively transform `value` into an AttributeValue `dict` :param mixed value: The value to encode :rtype: dict :raises ValueError: for unsupported types Return the value as dict indicating the data type and transform or recursively process the value if required. def _marshall_value(value): ...
Unmarshall a single dict value from a row that was returned from DynamoDB, returning the value as a normal Python dict. :param dict value: The value to unmarshall :rtype: mixed :raises ValueError: if an unsupported type code is encountered def _unmarshall_dict(value): """Unmarshall a single dict v...
Unwrap a request response and return only the response data. :param str action: The action name :param result: The result of the action :type: result: list or dict :rtype: dict | None def _unwrap_result(action, result): """Unwrap a request response and return only the response data. :param st...
Invoke the `ListTables`_ function. Returns an array of table names associated with the current account and endpoint. The output from *ListTables* is paginated, with each page returning a maximum of ``100`` table names. :param str exclusive_start_table_name: The first table name that th...
Invoke the `PutItem`_ function, creating a new item, or replaces an old item with a new item. If an item that has the same primary key as the new item already exists in the specified table, the new item completely replaces the existing item. You can perform a conditional put operation (a...
Invoke the `GetItem`_ function. :param str table_name: table to retrieve the item from :param dict key_dict: key to use for retrieval. This will be marshalled for you so a native :class:`dict` works. :param bool consistent_read: Determines the read consistency model: If ...