text
stringlengths
18
773k
def _get_val(val, full=False): """ Get the value(s) of a dataset as a single value or as 1-d list of values. In the special case of timeseries, when a check is for time-based criteria, you can return the entire timeseries. """ try: val = val.strip() except: pass ...
def get_restriction_as_dict(restriction_xml): """ turn: :: <restrictions> <restriction> <type>MAXLEN</type> <value>3</value> </restriction> <restriction> <type>VALUERANGE</type> ...
def validate_ENUM(in_value, restriction): """ Test to ensure that the given value is contained in the provided list. the value parameter must be either a single value or a 1-dimensional list. All the values in this list must satisfy the ENUM """ value = _get_val(in_value) if type...
def validate_NUMPLACES(in_value, restriction): """ the value parameter must be either a single value or a 1-dimensional list. All the values in this list must satisfy the condition """ #Sometimes restriction values can accidentally be put in the template <item>100</items>, #Making them a...
def validate_VALUERANGE(in_value, restriction): """ Test to ensure that a value sits between a lower and upper bound. Parameters: A Decimal value and a tuple, containing a lower and upper bound, both as Decimal values. """ if len(restriction) != 2: raise ValidationError("Temp...
def validate_DATERANGE(value, restriction): """ Test to ensure that the times in a timeseries fall between a lower and upper bound Parameters: A timeseries in the form [(datetime, val), (datetime, val)..] and a tuple containing the lower and upper bound as datetime objects. """ if le...
def validate_MAXLEN(value, restriction): """ Test to ensure that a list has the prescribed length. Parameters: A list and an integer, which defines the required length of the list. """ #Sometimes restriction values can accidentally be put in the template <item>100</items>, #Makin...
def validate_LESSTHAN(in_value, restriction): """ Test to ensure that a value is less than a prescribed value. Parameter: Two values, which will be compared for the difference.. """ #Sometimes restriction values can accidentally be put in the template <item>100</items>, #Making them a li...
def validate_LESSTHANEQ(value, restriction): """ Test to ensure that a value is less than or equal to a prescribed value. Parameter: Two values, which will be compared for the difference.. """ #Sometimes restriction values can accidentally be put in the template <item>100</items>, #Makin...
def validate_SUMTO(in_value, restriction): """ Test to ensure the values of a list sum to a specified value: Parameters: a list of numeric values and a target to which the values in the list must sum """ #Sometimes restriction values can accidentally be put in the template <item>100<...
def validate_INCREASING(in_value, restriction): """ Test to ensure the values in a list are increasing. Parameters: a list of values and None. The none is there simply to conform with the rest of the validation routines. """ flat_list = _flatten_value(in_value) previous = None ...
def validate_EQUALTIMESTEPS(value, restriction): """ Ensure that the timesteps in a timeseries are equal. If a restriction is provided, they must be equal to the specified restriction. Value is a pandas dataframe. """ if len(value) == 0: return if type(value) == pd.Data...
def _flatten_value(value): """ 1: Turn a multi-dimensional array into a 1-dimensional array 2: Turn a timeseries of values into a single 1-dimensional array """ if type(value) == pd.DataFrame: value = value.values.tolist() if type(value) != list: raise ValidationError("...
def count_levels(value): """ Count how many levels are in a dict: scalar, list etc = 0 {} = 0 {'a':1} = 1 {'a' : {'b' : 1}} = 2 etc... """ if not isinstance(value, dict) or len(value) == 0: return 0 elif len(value) == 0: return 0 #An emptu ...
def flatten_dict(value, target_depth=1, depth=None): """ Take a hashtable with multiple nested dicts and return a dict where the keys are a concatenation of each sub-key. The depth of the returned array is dictated by target_depth, defaulting to 1 ex: {'a' : {'b':1, 'c': 2}} ==> {'...
def to_named_tuple(keys, values): """ Convert a sqlalchemy object into a named tuple """ values = [dbobject.__dict__[key] for key in dbobject.keys()] tuple_object = namedtuple('DBObject', dbobject.keys()) tuple_instance = tuple_object._make(values) return tuple_instance
def get_val(dataset, timestamp=None): """ Turn the string value of a dataset into an appropriate value, be it a decimal value, array or time series. If a timestamp is passed to this function, return the values appropriate to the requested times. If the timestamp is *before*...
def get_layout_as_string(layout): """ Take a dict or string and return a string. The dict will be json dumped. The string will json parsed to check for json validity. In order to deal with strings which have been json encoded multiple times, keep json decoding until a dict is...
def get_layout_as_dict(layout): """ Take a dict or string and return a dict if the data is json-encoded. The string will json parsed to check for json validity. In order to deal with strings which have been json encoded multiple times, keep json decoding until a dict is retrieved or ...
def get_username(uid,**kwargs): """ Return the username of a given user_id """ rs = db.DBSession.query(User.username).filter(User.id==uid).one() if rs is None: raise ResourceNotFoundError("User with ID %s not found"%uid) return rs.username
def get_usernames_like(username,**kwargs): """ Return a list of usernames like the given string. """ checkname = "%%%s%%"%username rs = db.DBSession.query(User.username).filter(User.username.like(checkname)).all() return [r.username for r in rs]
def add_user(user, **kwargs): """ Add a user """ #check_perm(kwargs.get('user_id'), 'add_user') u = User() u.username = user.username u.display_name = user.display_name user_id = _get_user_id(u.username) #If the user is already there, cannot add another with #the same ...
def update_user_display_name(user,**kwargs): """ Update a user's display name """ #check_perm(kwargs.get('user_id'), 'edit_user') try: user_i = db.DBSession.query(User).filter(User.id==user.id).one() user_i.display_name = user.display_name return user_i except NoResul...
def update_user_password(new_pwd_user_id, new_password,**kwargs): """ Update a user's password """ #check_perm(kwargs.get('user_id'), 'edit_user') try: user_i = db.DBSession.query(User).filter(User.id==new_pwd_user_id).one() user_i.password = bcrypt.hashpw(str(new_password).encod...
def get_user(uid, **kwargs): """ Get a user by ID """ user_id=kwargs.get('user_id') if uid is None: uid = user_id user_i = _get_user(uid) return user_i
def get_user_by_name(uname,**kwargs): """ Get a user by username """ try: user_i = db.DBSession.query(User).filter(User.username==uname).one() return user_i except NoResultFound: return None
def get_user_by_id(uid,**kwargs): """ Get a user by username """ user_id = kwargs.get('user_id') try: user_i = _get_user(uid) return user_i except NoResultFound: return None
def delete_user(deleted_user_id,**kwargs): """ Delete a user """ #check_perm(kwargs.get('user_id'), 'edit_user') try: user_i = db.DBSession.query(User).filter(User.id==deleted_user_id).one() db.DBSession.delete(user_i) except NoResultFound: raise ResourceNotFoundError...
def add_role(role,**kwargs): """ Add a new role """ #check_perm(kwargs.get('user_id'), 'add_role') role_i = Role(name=role.name, code=role.code) db.DBSession.add(role_i) db.DBSession.flush() return role_i
def delete_role(role_id,**kwargs): """ Delete a role """ #check_perm(kwargs.get('user_id'), 'edit_role') try: role_i = db.DBSession.query(Role).filter(Role.id==role_id).one() db.DBSession.delete(role_i) except InvalidRequestError: raise ResourceNotFoundError("Role (ro...
def add_perm(perm,**kwargs): """ Add a permission """ #check_perm(kwargs.get('user_id'), 'add_perm') perm_i = Perm(name=perm.name, code=perm.code) db.DBSession.add(perm_i) db.DBSession.flush() return perm_i
def delete_perm(perm_id,**kwargs): """ Delete a permission """ #check_perm(kwargs.get('user_id'), 'edit_perm') try: perm_i = db.DBSession.query(Perm).filter(Perm.id==perm_id).one() db.DBSession.delete(perm_i) except InvalidRequestError: raise ResourceNotFoundError("P...
def set_user_role(new_user_id, role_id, **kwargs): """ Apply `role_id` to `new_user_id` Note this function returns the `Role` instance associated with `role_id` """ #check_perm(kwargs.get('user_id'), 'edit_role') try: _get_user(new_user_id) role_i = _get_role(role_id) ...
def delete_user_role(deleted_user_id, role_id,**kwargs): """ Remove a user from a role """ #check_perm(kwargs.get('user_id'), 'edit_role') try: _get_user(deleted_user_id) _get_role(role_id) roleuser_i = db.DBSession.query(RoleUser).filter(RoleUser.user_id==deleted_user_id...
def set_role_perm(role_id, perm_id,**kwargs): """ Insert a permission into a role """ #check_perm(kwargs.get('user_id'), 'edit_perm') _get_perm(perm_id) role_i = _get_role(role_id) roleperm_i = RolePerm(role_id=role_id, perm_id=perm_id) role_i.roleperms.append(roleperm_i) db.D...
def delete_role_perm(role_id, perm_id,**kwargs): """ Remove a permission from a role """ #check_perm(kwargs.get('user_id'), 'edit_perm') _get_perm(perm_id) _get_role(role_id) try: roleperm_i = db.DBSession.query(RolePerm).filter(RolePerm.role_id==role_id, RolePerm.perm_id==perm_...
def update_role(role,**kwargs): """ Update the role. Used to add permissions and users to a role. """ #check_perm(kwargs.get('user_id'), 'edit_role') try: role_i = db.DBSession.query(Role).filter(Role.id==role.id).one() role_i.name = role.name role_i.code = role.c...
def get_all_users(**kwargs): """ Get the username & ID of all users. Use the the filter if it has been provided The filter has to be a list of values """ users_qry = db.DBSession.query(User) filter_type = kwargs.get('filter_type') filter_value = kwargs.get('filter_value') ...
def get_role(role_id,**kwargs): """ Get a role by its ID. """ try: role = db.DBSession.query(Role).filter(Role.id==role_id).one() return role except NoResultFound: raise HydraError("Role not found (role_id={})".format(role_id))
def get_user_roles(uid,**kwargs): """ Get the roles for a user. @param user_id """ try: user_roles = db.DBSession.query(Role).filter(Role.id==RoleUser.role_id, RoleUser.user_id==uid).all() return user_roles except NoResult...
def get_user_permissions(uid, **kwargs): """ Get the roles for a user. @param user_id """ try: _get_user(uid) user_perms = db.DBSession.query(Perm).filter(Perm.id==RolePerm.perm_id, RolePerm.role_id==Role.id, ...
def get_role_by_code(role_code,**kwargs): """ Get a role by its code """ try: role = db.DBSession.query(Role).filter(Role.code==role_code).one() return role except NoResultFound: raise ResourceNotFoundError("Role not found (role_code={})".format(role_code))
def get_perm(perm_id,**kwargs): """ Get all permissions """ try: perm = db.DBSession.query(Perm).filter(Perm.id==perm_id).one() return perm except NoResultFound: raise ResourceNotFoundError("Permission not found (perm_id={})".format(perm_id))
def get_perm_by_code(perm_code,**kwargs): """ Get a permission by its code """ try: perm = db.DBSession.query(Perm).filter(Perm.code==perm_code).one() return perm except NoResultFound: raise ResourceNotFoundError("Permission not found (perm_code={})".format(perm_code))
def _create_dataframe(cls, value): """ Builds a dataframe from the value """ try: ordered_jo = json.loads(six.text_type(value), object_pairs_hook=collections.OrderedDict) #Pandas does not maintain the order of dicts, so we must break the dict #up...
def parse_value(self): """ Turn the value of an incoming dataset into a hydra-friendly value. """ try: if self.value is None: log.warning("Cannot parse dataset. No value specified.") return None # attr_data.value is a dictionar...
def get_metadata_as_dict(self, user_id=None, source=None): """ Convert a metadata json string into a dictionary. Args: user_id (int): Optional: Insert user_id into the metadata if specified source (string): Optional: Insert source (the name of the app typically) into the...
def add_resourcegroup(group, network_id,**kwargs): """ Add a new group to a network. """ group_i = ResourceGroup() group_i.name = group.name group_i.description = group.description group_i.status = group.status group_i.network_id ...
def delete_resourcegroup(group_id,**kwargs): """ Add a new group to a scenario. """ group_i = _get_group(group_id) #This should cascaded to delete all the group items. db.DBSession.delete(group_i) db.DBSession.flush() return 'OK'
def update_resourcegroup(group,**kwargs): """ Add a new group to a network. """ group_i = _get_group(group.id) group_i.name = group.name group_i.description = group.description group_i.status = group.status db.DBSession.flush() return gr...
def create_sqlite_backup_db(audit_tables): """ return an inspector object """ #we always want to create a whole new DB, so delete the old one first #if it exists. try: Popen("rm %s"%(config.get('sqlite', 'backup_url')), shell=True) logging.warn("Old sqlite backup DB removed")...
def _is_admin(user_id): """ Is the specified user an admin """ user = get_session().query(User).filter(User.id==user_id).one() if user.is_admin(): return True else: return False
def set_metadata(self, metadata_dict): """ Set the metadata on a dataset **metadata_dict**: A dictionary of metadata key-vals. Transforms this dict into an array of metadata objects for storage in the DB. """ if metadata_dict is None: ...
def check_user(self, user_id): """ Check whether this user can read this dataset """ if self.hidden == 'N': return True for owner in self.owners: if int(owner.user_id) == int(user_id): if owner.view == 'Y': return ...
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.network elif ref_key == 'LINK': ret...
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)
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)
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, by associating two already existing nodes. """ existing_link = get_session().query(Link).filter(Link.name==name, Link....
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 node with name %s is alre...
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: raise HydraError("A resou...
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 for owner in self.owners: if in...
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.owners: if owner.user_id == int(use...
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)
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)
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).\ filter(ResourceGroupItem.scenario_id==scenario_id).all() ...
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 = ref_id elif ref_key == 'NODE': self.node_id = ref_id elif ref_key ...
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_id elif self.ref_key == 'LINK': return sel...
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 elif self.ref_key == 'LINK': return self.link ...
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
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)
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
def _check_dimension(typeattr, unit_id=None): """ 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 """ if unit_id is None: unit_id = typeattr.unit_id dimension_id = _g...
def get_types_by_attr(resource, template_id=None): """ 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_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. """ attr = db.DBSession.query(Attr).filter(Attr.name==name, Attr.dimension_id==dimension_id).first() if attr is No...
def get_template_as_json(template_id, **kwargs): """ Get a template (including attribute and dataset definitions) as a JSON string. This is just a wrapper around the get_template_as_dict function. """ user_id = kwargs['user_id'] return json.dumps(get_template_as_dict(template_id, user_id...
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( #joinedload_all('templatetypes.typeatt...
def import_template_json(template_json_string,allow_update=True, **kwargs): """ 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 require...
def import_template_xml(template_xml, allow_update=True, **kwargs): """ 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 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. If so, assign the type to the node / link. """ net_i = db.DBSession.query(Network).filter(Network.id==network_id).one() #There ...
def set_network_template(template_id, network_id, **kwargs): """ Apply an existing template to a network. Used when a template has changed, and additional attributes must be added to the network's elements. """ resource_types = [] #There should only ever be one matching type, but if ther...
def remove_template_from_network(network_id, template_id, remove_attrs, **kwargs): """ 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 ...
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 for tmpltype in template.templatetypes] node_attr_ids = dict([(ra.attr_id, ra) for ra in resource.attrib...
def get_matching_resource_types(resource_type, resource_id,**kwargs): """ Get the possible types of a resource by checking its attributes against all available types. @returns A list of TypeSummary objects. """ resource_i = None if resource_type == 'NETWORK': resource_i ...
def assign_types_to_resources(resource_types,**kwargs): """ 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 ...
def check_type_compatibility(type_1_id, type_2_id): """ 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 templa...
def assign_type_to_resource(type_id, resource_type, resource_id,**kwargs): """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 a...
def set_resource_type(resource, type_id, types={}, **kwargs): """ 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 ar...
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 = resource_id if resource_type == 'GROUP...
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_layout_as_string(template.layout) d...
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 = template.description #Lazy load the rest of ...
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("Template %s not found"%(template_id,)) db.DBSess...
def get_templates(load_all=True, **kwargs): """ 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 """ if load_all is False: templa...
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.metadata')).one() #Load the attributes. ...
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() return tmpl_i except NoResultFoun...
def add_templatetype(templatetype,**kwargs): """ Add a template type with typeattrs. """ type_i = _update_templatetype(templatetype) db.DBSession.flush() return type_i
def update_templatetype(templatetype,**kwargs): """ Update a resource type and its typeattrs. New typeattrs will be added. typeattrs not sent will be ignored. To delete typeattrs, call delete_typeattr """ tmpltype_i = db.DBSession.query(TemplateType).filter(TemplateType.id == templa...
def _set_typeattr(typeattr, existing_ta = None): """ 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. ...
def _update_templatetype(templatetype, existing_tt=None): """ 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. """ if existing_tt is None: if "id" in templatetype and templatetype.id is ...
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 ResourceNotFoundError("Template Type %s not found"...
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() return templatetype