code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
user_id = kwargs['user_id'] try: group_i = db.DBSession.query(AttrGroup).filter(AttrGroup.id==group_id).one() group_i.project.check_write_permission(user_id) db.DBSession.delete(group_i) db.DBSession.flush() log.info("Group %s in project %s deleted", group_i.id,...
def delete_attribute_group(group_id, **kwargs)
Delete an attribute group.
3.807904
3.767132
1.010823
user_id=kwargs.get('user_id') net_i = _get_network(network_id) net_i.check_read_permission(user_id) group_items_i = db.DBSession.query(AttrGroupItem).filter( AttrGroupItem.network_id==network_id).all() return group_items_i
def get_network_attributegroup_items(network_id, **kwargs)
Get all the group items in a network
4.796508
4.743431
1.01119
user_id=kwargs.get('user_id') network_i = _get_network(network_id) network_i.check_read_permission(user_id) group_items_i = db.DBSession.query(AttrGroupItem).filter( AttrGroupItem.network_id==network_id, AttrGroupItem.group_...
def get_group_attributegroup_items(network_id, group_id, **kwargs)
Get all the items in a specified group, within a network
3.768974
3.79298
0.993671
user_id=kwargs.get('user_id') network_i = _get_network(network_id) network_i.check_read_permission(user_id) group_items_i = db.DBSession.query(AttrGroupItem).filter( AttrGroupItem.network_id==network_id, AttrGroupIte...
def get_attribute_item_groups(network_id, attr_id, **kwargs)
Get all the group items in a network with a given attribute_id
3.7677
3.567356
1.05616
user_id=kwargs.get('user_id') log.info("Deleting %s attribute group items", len(attributegroupitems)) #if there area attributegroupitems from different networks, keep track of those #networks to ensure the user actually has permission to remove the items. network_lookup = {} if not is...
def delete_attribute_group_items(attributegroupitems, **kwargs)
remove attribute groups items . ** attributegroupitems : a list of items, of the form: ```{ 'attr_id' : X, 'group_id' : Y, 'network_id' : Z, }```
3.948344
3.79747
1.03973
user_id = kwargs.get('user_id') net_i = _get_network(network_id) net_i.check_share_permission(user_id) if read_only == 'Y': write = 'N' share = 'N' else: write = 'Y' if net_i.created_by != int(user_id) and share == 'Y': raise HydraError("Cannot share the '...
def share_network(network_id, usernames, read_only, share,**kwargs)
Share a network with a list of users, identified by their usernames. The read_only flag ('Y' or 'N') must be set to 'Y' to allow write access or sharing. The share flat ('Y' or 'N') must be set to 'Y' to allow the project to be shared with other users
4.028447
4.123905
0.976853
user_id = kwargs.get('user_id') net_i = _get_network(network_id) net_i.check_share_permission(user_id) for username in usernames: user_i = _get_user(username) #Set the owner ship on the network itself net_i.unset_owner(user_i.id, write=write, share=share) db.DBSession.flu...
def unshare_network(network_id, usernames,**kwargs)
Un-Share a network with a list of users, identified by their usernames.
5.923281
6.486551
0.913163
user_id = kwargs.get('user_id') proj_i = _get_project(project_id) #Is the sharing user allowed to share this project? proj_i.check_share_permission(int(user_id)) user_id = int(user_id) for owner in proj_i.owners: if user_id == owner.user_id: break else: ra...
def share_project(project_id, usernames, read_only, share,**kwargs)
Share an entire project with a list of users, identifed by their usernames. The read_only flag ('Y' or 'N') must be set to 'Y' to allow write access or sharing. The share flat ('Y' or 'N') must be set to 'Y' to allow the project to be shared with other users
3.624548
3.83235
0.945777
user_id = kwargs.get('user_id') proj_i = _get_project(project_id) proj_i.check_share_permission(user_id) for username in usernames: user_i = _get_user(username) #Set the owner ship on the network itself proj_i.unset_owner(user_i.id, write=write, share=share) db.DBSessi...
def unshare_project(project_id, usernames,**kwargs)
Un-share a project with a list of users, identified by their usernames.
5.794605
6.543641
0.885532
user_id = kwargs.get('user_id') proj_i = _get_project(project_id) #Is the sharing user allowed to share this project? proj_i.check_share_permission(user_id) #You cannot edit something you cannot see. if read == 'N': write = 'N' share = 'N' for username in usernames: ...
def set_project_permission(project_id, usernames, read, write, share,**kwargs)
Set permissions on a project to a list of users, identifed by their usernames. The read flag ('Y' or 'N') sets read access, the write flag sets write access. If the read flag is 'N', then there is automatically no write access or share access.
3.703398
3.843931
0.96344
user_id = kwargs.get('user_id') net_i = _get_network(network_id) #Check if the user is allowed to share this network. net_i.check_share_permission(user_id) #You cannot edit something you cannot see. if read == 'N': write = 'N' share = 'N' for username in usernames: ...
def set_network_permission(network_id, usernames, read, write, share,**kwargs)
Set permissions on a network to a list of users, identifed by their usernames. The read flag ('Y' or 'N') sets read access, the write flag sets write access. If the read flag is 'N', then there is automatically no write access or share access.
4.205387
4.244666
0.990746
user_id = kwargs.get('user_id') dataset_i = _get_dataset(dataset_id) #check that I can hide the dataset if dataset_i.created_by != int(user_id): raise HydraError('Permission denied. ' 'User %s is not the owner of dataset %s' %(user_id, datase...
def hide_dataset(dataset_id, exceptions, read, write, share,**kwargs)
Hide a particular piece of data so it can only be seen by its owner. Only an owner can hide (and unhide) data. Data with no owner cannot be hidden. The exceptions paramater lists the usernames of those with permission to view the data read, write and share indicate whether these users c...
3.644454
3.900076
0.934457
user_id = kwargs.get('user_id') dataset_i = _get_dataset(dataset_id) #check that I can unhide the dataset if dataset_i.created_by != int(user_id): raise HydraError('Permission denied. ' 'User %s is not the owner of dataset %s' %(user_id, data...
def unhide_dataset(dataset_id,**kwargs)
Hide a particular piece of data so it can only be seen by its owner. Only an owner can hide (and unhide) data. Data with no owner cannot be hidden. The exceptions paramater lists the usernames of those with permission to view the data read, write and share indicate whether these users c...
4.468766
5.35425
0.83462
projowner_qry = db.DBSession.query(ProjectOwner) if project_ids is not None: projowner_qry = projowner_qry.filter(ProjectOwner.project_id.in_(project_ids)) project_owners_i = projowner_qry.all() return [JSONObject(project_owner_i) for project_owner_i in project_owners_i]
def get_all_project_owners(project_ids=None, **kwargs)
Get the project owner entries for all the requested projects. If the project_ids argument is None, return all the owner entries for ALL projects
3.298673
3.226263
1.022444
networkowner_qry = db.DBSession.query(NetworkOwner) if network_ids is not None: networkowner_qry = networkowner_qry.filter(NetworkOwner.network_id.in_(network_ids)) network_owners_i = networkowner_qry.all() return [JSONObject(network_owner_i) for network_owner_i in network_owners_i]
def get_all_network_owners(network_ids=None, **kwargs)
Get the network owner entries for all the requested networks. If the network_ids argument is None, return all the owner entries for ALL networks
3.226022
3.278869
0.983882
project_ids = [po.project_id for po in project_owners] existing_projowners = db.DBSession.query(ProjectOwner).filter(ProjectOwner.project_id.in_(project_ids)).all() #Create a lookup based on the unique key for this table (project_id, user_id) po_lookup = {} for po in existing_projow...
def bulk_set_project_owners(project_owners, **kwargs)
Set the project owner of multiple projects at once. Accepts a list of JSONObjects which look like: { 'project_id': XX, 'user_id' : YY, 'view' : 'Y'/ 'N' 'edit' : 'Y'/ 'N' 'share' : 'Y'/ 'N' }
2.209774
2.028179
1.089536
network_ids = [no.network_id for no in network_owners] existing_projowners = db.DBSession.query(NetworkOwner).filter(NetworkOwner.network_id.in_(network_ids)).all() #Create a lookup based on the unique key for this table (network_id, user_id) no_lookup = {} for no in existing_projow...
def bulk_set_network_owners(network_owners, **kwargs)
Set the network owner of multiple networks at once. Accepts a list of JSONObjects which look like: { 'network_id': XX, 'user_id' : YY, 'view' : 'Y'/ 'N' 'edit' : 'Y'/ 'N' 'share' : 'Y'/ 'N' }
2.374457
2.172223
1.0931
user_id = int(kwargs.get('user_id')) if dataset_id is None: return None try: dataset_rs = db.DBSession.query(Dataset.id, Dataset.type, Dataset.unit_id, Dataset.name, Dataset.hidden, Dataset.cr_date, ...
def get_dataset(dataset_id,**kwargs)
Get a single dataset, by ID
3.282579
3.304367
0.993406
user_id = int(kwargs.get('user_id')) if dataset_id is None: return None dataset = db.DBSession.query(Dataset).filter( Dataset.id==dataset_id).options(joinedload_all('metadata')).first() if dataset is None: raise HydraError("Dataset %s does not exist."%(dataset_id)) ...
def clone_dataset(dataset_id,**kwargs)
Get a single dataset, by ID
2.645297
2.691774
0.982733
user_id = int(kwargs.get('user_id')) datasets = [] if len(dataset_ids) == 0: return [] try: dataset_rs = db.DBSession.query(Dataset.id, Dataset.type, Dataset.unit_id, Dataset.name, Dataset.hidden, Datas...
def get_datasets(dataset_ids,**kwargs)
Get a single dataset, by ID
3.140043
3.158937
0.994019
if dataset_id is None: raise HydraError("Dataset must have an ID to be updated.") user_id = kwargs.get('user_id') dataset = db.DBSession.query(Dataset).filter(Dataset.id==dataset_id).one() #This dataset been seen before, so it may be attached #to other scenarios, which may be locked....
def update_dataset(dataset_id, name, data_type, val, unit_id, metadata={}, flush=True, **kwargs)
Update an existing dataset
3.915093
3.961829
0.988204
d = Dataset() d.type = data_type d.value = val d.set_metadata(metadata) d.unit_id = unit_id d.name = name d.created_by = user_id d.hash = d.set_hash() try: existing_dataset = db.DBSession.query(Dataset).filter(Dataset.hash==d.hash).one() if existing_datas...
def add_dataset(data_type, val, unit_id=None, metadata={}, name="", user_id=None, flush=False)
Data can exist without scenarios. This is the mechanism whereby single pieces of data can be added without doing it through a scenario. A typical use of this would be for setting default values on types.
2.585968
2.740783
0.943514
get_timing = lambda x: datetime.datetime.now() - x start_time=datetime.datetime.now() new_data = _process_incoming_data(bulk_data, user_id, source) log.info("Incoming data processed in %s", (get_timing(start_time))) existing_data = _get_existing_data(new_data.keys()) log.info("Existing d...
def _bulk_insert_data(bulk_data, user_id=None, source=None)
Insert lots of datasets at once to reduce the number of DB interactions. user_id indicates the user adding the data source indicates the name of the app adding the data both user_id and source are added as metadata
3.174925
3.165092
1.003107
metadata = [] if len(dataset_ids) == 0: return [] if len(dataset_ids) > qry_in_threshold: idx = 0 extent = qry_in_threshold while idx < len(dataset_ids): log.info("Querying %s metadatas", len(dataset_ids[idx:extent])) rs = db.DBSession.query(Metad...
def _get_metadata(dataset_ids)
Get all the metadata for a given list of datasets
2.603458
2.566404
1.014438
dataset_dict = {} datasets = [] if len(dataset_ids) > qry_in_threshold: idx = 0 extent =qry_in_threshold while idx < len(dataset_ids): log.info("Querying %s datasets", len(dataset_ids[idx:extent])) rs = db.DBSession.query(Dataset).filter(Dataset.id.in_(...
def _get_datasets(dataset_ids)
Get all the datasets in a list of dataset IDS. This must be done in chunks of 999, as sqlite can only handle 'in' with < 1000 elements.
2.626775
2.516012
1.044023
try: collection = db.DBSession.query(DatasetCollection).filter(DatasetCollection.id==collection_id).one() return collection except NoResultFound: raise ResourceNotFoundError("No dataset collection found with id %s"%collection_id)
def _get_collection(collection_id)
Get a dataset collection by ID :param collection ID
3.248449
3.63604
0.893403
collection_item = db.DBSession.query(DatasetCollectionItem).\ filter(DatasetCollectionItem.collection_id==collection_id, DatasetCollectionItem.dataset_id==dataset_id).first() return collection_item
def _get_collection_item(collection_id, dataset_id)
Get a single dataset collection entry by collection ID and dataset ID :param collection ID :param dataset ID
2.560871
3.364134
0.761227
collection_i = _get_collection(collection_id) collection_item = _get_collection_item(collection_id, dataset_id) if collection_item is not None: raise HydraError("Dataset Collection %s already contains dataset %s", collection_id, dataset_id) new_item = DatasetCollectionItem() new_item.d...
def add_dataset_to_collection(dataset_id, collection_id, **kwargs)
Add a single dataset to a dataset collection.
3.059443
3.087229
0.991
collection_i = _get_collection(collection_id) collection_item = _get_collection_item(collection_id, dataset_id) if collection_item is None: raise HydraError("Dataset %s is not in collection %s.", dataset_id, ...
def remove_dataset_from_collection(dataset_id, collection_id, **kwargs)
Add a single dataset to a dataset collection.
3.660517
3.786163
0.966814
_get_collection(collection_id) collection_item = _get_collection_item(collection_id, dataset_id) if collection_item is None: return 'N' else: return 'Y'
def check_dataset_in_collection(dataset_id, collection_id, **kwargs)
Check whether a dataset is contained inside a collection :param dataset ID :param collection ID :returns 'Y' or 'N'
3.612715
3.165533
1.141266
try: collections = db.DBSession.query(DatasetCollection).filter(DatasetCollection.name.like("%%%s%%"%collection_name.lower())).all() except NoResultFound: raise ResourceNotFoundError("No dataset collection found with name %s"%collection_name) return collections
def get_collections_like_name(collection_name,**kwargs)
Get all the datasets from the collection with the specified name
3.658295
3.770786
0.970168
collection_datasets = db.DBSession.query(Dataset).filter(Dataset.id==DatasetCollectionItem.dataset_id, DatasetCollectionItem.collection_id==DatasetCollection.id, DatasetCollection.id==collection_id).all() return collection_data...
def get_collection_datasets(collection_id,**kwargs)
Get all the datasets from the collection with the specified name
3.786518
3.938329
0.961453
t = [] for time in timestamps: t.append(get_datetime(time)) dataset_i = db.DBSession.query(Dataset).filter(Dataset.id==dataset_id).one() #for time in t: # data.append(td.get_val(timestamp=time)) data = dataset_i.get_val(timestamp=t) if data is not None: dataset = JSO...
def get_val_at_time(dataset_id, timestamps,**kwargs)
Given a timestamp (or list of timestamps) and some timeseries data, return the values appropriate to the requested times. If the timestamp is before the start of the timeseries data, return None If the timestamp is after the end of the timeseries data, return the last value.
4.30626
4.626615
0.930758
datasets = _get_datasets(dataset_ids) datetimes = [] for time in timestamps: datetimes.append(get_datetime(time)) return_vals = {} for dataset_i in datasets.values(): data = dataset_i.get_val(timestamp=datetimes) ret_data = {} if type(data) is list: ...
def get_multiple_vals_at_time(dataset_ids, timestamps,**kwargs)
Given a timestamp (or list of timestamps) and a list of timeseries datasets, return the values appropriate to the requested times. If the timestamp is before the start of the timeseries data, return None If the timestamp is after the end of the timeseries data, return the last value.
3.016245
3.188181
0.946071
try: server_start_time = get_datetime(start_time) server_end_time = get_datetime(end_time) times = [server_start_time] next_time = server_start_time while next_time < server_end_time: if int(increment) == 0: raise HydraError("%s is not a va...
def get_vals_between_times(dataset_id, start_time, end_time, timestep,increment,**kwargs)
Retrive data between two specified times within a timeseries. The times need not be specified in the timeseries. This function will 'fill in the blanks'. Two types of data retrieval can be done. If the timeseries is timestamp-based, then start_time and end_time must be datetimes and ti...
2.782834
2.874096
0.968247
try: d = db.DBSession.query(Dataset).filter(Dataset.id==dataset_id).one() except NoResultFound: raise HydraError("Dataset %s does not exist."%dataset_id) dataset_rs = db.DBSession.query(ResourceScenario).filter(ResourceScenario.dataset_id==dataset_id).all() if len(dataset_rs) > 0: ...
def delete_dataset(dataset_id,**kwargs)
Removes a piece of data from the DB. CAUTION! Use with care, as this cannot be undone easily.
3.484736
3.517982
0.99055
notes = db.DBSession.query(Note).filter(Note.ref_key==ref_key) if ref_key == 'NETWORK': notes = notes.filter(Note.network_id == ref_id) elif ref_key == 'NODE': notes = notes.filter(Note.node_id == ref_id) elif ref_key == 'LINK': notes = notes.filter(Note.link_id == ref_id) ...
def get_notes(ref_key, ref_id, **kwargs)
Get all the notes for a resource, identifed by ref_key and ref_ido. Returns [] if no notes are found or if the resource doesn't exist.
2.076503
2.164077
0.959533
note_i = Note() note_i.ref_key = note.ref_key note_i.set_ref(note.ref_key, note.ref_id) note_i.value = note.value note_i.created_by = kwargs.get('user_id') db.DBSession.add(note_i) db.DBSession.flush() return note_i
def add_note(note, **kwargs)
Add a new note
3.357118
3.350206
1.002063
note_i = _get_note(note.id) if note.ref_key != note_i.ref_key: raise HydraError("Cannot convert a %s note to a %s note. Please create a new note instead."%(note_i.ref_key, note.ref_key)) note_i.set_ref(note.ref_key, note.ref_id) note_i.value = note.value db.DBSession.flush() re...
def update_note(note, **kwargs)
Update a note
4.486874
4.521232
0.992401
note_i = _get_note(note_id) db.DBSession.delete(note_i) db.DBSession.flush()
def purge_note(note_id, **kwargs)
Remove a note from the DB permenantly
6.024281
5.474591
1.100407
user_id = util.hdb.login_user(username, password) hydra_session = session.Session({}, #This is normally a request object, but in this case is empty validate_key=config.get('COOKIES', 'VALIDATE_KEY', 'YxaDbzUUSo08b+'), type='file', cookie_expires=True, data_...
def login(username, password, **kwargs)
Login a user, returning a dict containing their user_id and session_id This does the DB login to check the credentials, and then creates a session so that requests from apps do not need to perform a login args: username (string): The user's username password(string): Th...
7.116992
6.763116
1.052324
hydra_session_object = session.SessionObject({}, #This is normally a request object, but in this case is empty validate_key=config.get('COOKIES', 'VALIDATE_KEY', 'YxaDbzUUSo08b+'), type='file', cookie_expires=True, data_dir=config.get('COOKIES', 'DATA_DIR', '/tm...
def logout(session_id, **kwargs)
Logout a user, removing their cookie if it exists and returning 'OK' args: session_id (string): The session ID to identify the cookie to remove returns: 'OK' raises: HydraError if the logout fails
7.025902
6.747871
1.041203
hydra_session_object = session.SessionObject({}, #This is normally a request object, but in this case is empty validate_key=config.get('COOKIES', 'VALIDATE_KEY', 'YxaDbzUUSo08b+'), type='file', cookie_expires=True, data_dir=config.get('COOKIES', 'DATA_DIR', '/tm...
def get_session_user(session_id, **kwargs)
Given a session ID, get the user ID that it is associated with args: session_id (string): The user's ID to identify the cookie to remove returns: user_id (string) or None if the session does not exist
7.376037
7.126867
1.034962
dim = [] while True: try: dim.append(len(arr)) arr = arr[0] except TypeError: return dim
def array_dim(arr)
Return the size of a multidimansional array.
2.623393
2.405565
1.090552
#If a list is transformed into a numpy array and the sub elements #of this array are still lists, then numpy failed to fully convert #the list, meaning it is not symmetrical. try: arr = np.array(array) except: raise HydraError("Array %s is not valid."%(array,)) if type(arr[...
def check_array_struct(array)
Check to ensure arrays are symmetrical, for example: [[1, 2, 3], [1, 2]] is invalid
7.030289
6.3205
1.112299
dim = array_dim(arr) tmp_arr = [] for n in range(len(dim) - 1): for inner in arr: for i in inner: tmp_arr.append(i) arr = tmp_arr tmp_arr = [] return arr
def arr_to_vector(arr)
Reshape a multidimensional array to a vector.
3.882233
3.478677
1.116009
if len(dim) <= 1: return vec array = vec while len(dim) > 1: i = 0 outer_array = [] for m in range(reduce(mul, dim[0:-1])): inner_array = [] for n in range(dim[-1]): inner_array.append(array[i]) i += 1 o...
def vector_to_arr(vec, dim)
Reshape a vector to a multidimensional array with dimensions 'dim'.
2.754982
2.633644
1.046072
try: val = val.strip() except: pass logging.debug("%s, type=%s", val, type(val)) if isinstance(val, float): return val if isinstance(val, int): return val if isinstance(val, np.ndarray): return list(val) try: val = float(val) ...
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.
1.929615
1.939617
0.994843
restriction_dict = {} if restriction_xml is None: return restriction_dict if restriction_xml.find('restriction') is not None: restrictions = restriction_xml.findall('restriction') for restriction in restrictions: restriction_type = restriction.find('type').text ...
def get_restriction_as_dict(restriction_xml)
turn: :: <restrictions> <restriction> <type>MAXLEN</type> <value>3</value> </restriction> <restriction> <type>VALUERANGE</type> <value><item>1</item><item>10</item></value> ...
1.939207
1.911918
1.014273
value = _get_val(in_value) if type(value) is list: for subval in value: if type(subval) is tuple: subval = subval[1] validate_ENUM(subval, restriction) else: if value not in restriction: raise ValidationError("ENUM : %s"%(restriction))
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
3.394215
3.802758
0.892567
#Sometimes restriction values can accidentally be put in the template <item>100</items>, #Making them a list, not a number. Rather than blowing up, just get value 1 from the list. if type(restriction) is list: restriction = restriction[0] value = _get_val(in_value) if type(value) is li...
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
5.987815
6.357268
0.941885
if len(restriction) != 2: raise ValidationError("Template ERROR: Only two values can be specified in a date range.") value = _get_val(in_value) if type(value) is list: for subval in value: if type(subval) is tuple: subval = subval[1] validate_VALU...
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.
3.082993
3.110786
0.991065
if len(restriction) != 2: raise ValidationError("Template ERROR: Only two values can be specified in a date range.") if type(value) == pd.DataFrame: dates = [get_datetime(v) for v in list(value.index)] else: dates = value if type(dates) is list: for date in dates: ...
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.
3.475426
3.470581
1.001396
#Sometimes restriction values can accidentally be put in the template <item>100</items>, #Making them a list, not a number. Rather than blowing up, just get value 1 from the list. if type(restriction) is list: restriction = restriction[0] else: return if len(value) > restrictio...
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.
12.107518
12.477446
0.970352
#Sometimes restriction values can accidentally be put in the template <item>100</items>, #Making them a list, not a number. Rather than blowing up, just get value 1 from the list. if type(restriction) is list: restriction = restriction[0] value = _get_val(in_value) if type(value) is li...
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..
5.403283
5.429141
0.995237
#Sometimes restriction values can accidentally be put in the template <item>100</items>, #Making them a list, not a number. Rather than blowing up, just get value 1 from the list. if type(restriction) is list: restriction = restriction[0] value = _get_val(value) if type(value) is list:...
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..
5.369249
5.3946
0.995301
#Sometimes restriction values can accidentally be put in the template <item>100</items>, #Making them a list, not a number. Rather than blowing up, just get value 1 from the list. if type(restriction) is list: restriction = restriction[0] value = _get_val(in_value, full=True) if len(v...
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
6.975202
7.125736
0.978875
flat_list = _flatten_value(in_value) previous = None for a in flat_list: if previous is None: previous = a continue try: if a < previous: raise ValidationError("INCREASING") except TypeError: raise ValueError("IN...
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.
4.728288
5.116965
0.924041
if len(value) == 0: return if type(value) == pd.DataFrame: if str(value.index[0]).startswith('9999'): tmp_val = value.to_json().replace('9999', '1900') value = pd.read_json(tmp_val) #If the timeseries is not datetime-based, check for a consistent timestep ...
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.
2.596174
2.573179
1.008936
if type(value) == pd.DataFrame: value = value.values.tolist() if type(value) != list: raise ValidationError("Value %s cannot be processed."%(value)) if len(value) == 0: return flat_list = _flatten_list(value) return flat_list
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
3.945928
3.980705
0.991264
if not isinstance(value, dict) or len(value) == 0: return 0 elif len(value) == 0: return 0 #An emptu dict has 0 else: nextval = list(value.values())[0] return 1 + count_levels(nextval)
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...
3.904164
3.750656
1.040928
#failsafe in case someone specified null if target_depth is None: target_depth = 1 values = list(value.values()) if len(values) == 0: return {} else: if depth is None: depth = count_levels(value) if isinstance(values[0], dict) and len(values[0]) > ...
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}} ==> {'a_b': 1, 'a_c': 2} Assumes a constant structure actoss all s...
3.009192
3.075563
0.97842
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 to_named_tuple(keys, values)
Convert a sqlalchemy object into a named tuple
4.4305
3.980212
1.113132
if dataset.type == 'array': #TODO: design a mechansim to retrieve this data if it's stored externally return json.loads(dataset.value) elif dataset.type == 'descriptor': return str(dataset.value) elif dataset.type == 'scalar': return Decimal(str(dataset.value)) elif...
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* the start of the timeseries data, return None ...
3.126484
3.088234
1.012386
if isinstance(layout, dict): return json.dumps(layout) if(isinstance(layout, six.string_types)): try: return get_layout_as_string(json.loads(layout)) except: return layout
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 retrieved or until a non-json structure is identi...
2.900625
2.721919
1.065654
if isinstance(layout, dict): return layout if(isinstance(layout, six.string_types)): try: return get_layout_as_dict(json.loads(layout)) except: return layout
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 until a non-json structure is identified.
2.941068
2.812537
1.045699
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_username(uid,**kwargs)
Return the username of a given user_id
4.232377
4.17699
1.01326
checkname = "%%%s%%"%username rs = db.DBSession.query(User.username).filter(User.username.like(checkname)).all() return [r.username for r in rs]
def get_usernames_like(username,**kwargs)
Return a list of usernames like the given string.
4.016287
3.874625
1.036562
#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 username. if user_id is not None: raise HydraErr...
def add_user(user, **kwargs)
Add a user
3.688683
3.676294
1.00337
#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 NoResultFound: raise ResourceNotFoundError("User (id=%s) not found"%(user.id))
def update_user_display_name(user,**kwargs)
Update a user's display name
3.74559
3.80172
0.985236
#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).encode('utf-8'), bcrypt.gensalt()) return user_i except NoResultFound: raise ResourceNotFoundEr...
def update_user_password(new_pwd_user_id, new_password,**kwargs)
Update a user's password
3.009024
3.093998
0.972536
user_id=kwargs.get('user_id') if uid is None: uid = user_id user_i = _get_user(uid) return user_i
def get_user(uid, **kwargs)
Get a user by ID
4.537786
4.487029
1.011312
try: user_i = db.DBSession.query(User).filter(User.username==uname).one() return user_i except NoResultFound: return None
def get_user_by_name(uname,**kwargs)
Get a user by username
3.412468
3.558789
0.958885
user_id = kwargs.get('user_id') try: user_i = _get_user(uid) return user_i except NoResultFound: return None
def get_user_by_id(uid,**kwargs)
Get a user by username
3.96572
4.034032
0.983066
#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("User (user_id=%s) does not exist"%(deleted_user_id)) return 'OK'
def delete_user(deleted_user_id,**kwargs)
Delete a user
3.943258
4.072933
0.968162
#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 add_role(role,**kwargs)
Add a new role
4.364951
4.549859
0.95936
#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 (role_id=%s) does not exist"%(role_id)) return 'OK'
def delete_role(role_id,**kwargs)
Delete a role
4.088363
4.325965
0.945075
#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 add_perm(perm,**kwargs)
Add a permission
4.436745
4.865619
0.911856
#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("Permission (id=%s) does not exist"%(perm_id)) return 'OK'
def delete_perm(perm_id,**kwargs)
Delete a permission
4.298235
4.7355
0.907662
#check_perm(kwargs.get('user_id'), 'edit_role') try: _get_user(new_user_id) role_i = _get_role(role_id) roleuser_i = RoleUser(user_id=new_user_id, role_id=role_id) role_i.roleusers.append(roleuser_i) db.DBSession.flush() except Exception as e: # Will occur if the...
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`
3.881148
4.09602
0.947541
#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, RoleUser.role_id==role_id).one() db.DBSession.delete(roleuser_i) except NoResultFound: ...
def delete_user_role(deleted_user_id, role_id,**kwargs)
Remove a user from a role
3.207879
3.237818
0.990754
#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.DBSession.flush() return role_i
def set_role_perm(role_id, perm_id,**kwargs)
Insert a permission into a role
3.793119
3.999081
0.948498
#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_id).one() db.DBSession.delete(roleperm_i) except NoResultFound: raise ResourceNo...
def delete_role_perm(role_id, perm_id,**kwargs)
Remove a permission from a role
3.229331
3.31766
0.973376
#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.code except NoResultFound: raise ResourceNotFoundError("Role (role_id=%s) does not exist"%(role.id)) for ...
def update_role(role,**kwargs)
Update the role. Used to add permissions and users to a role.
2.773524
2.787993
0.99481
users_qry = db.DBSession.query(User) filter_type = kwargs.get('filter_type') filter_value = kwargs.get('filter_value') if filter_type is not None: # Filtering the search of users if filter_type == "id": if isinstance(filter_value, str): # Trying to read...
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
2.434349
2.433915
1.000178
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_role(role_id,**kwargs)
Get a role by its ID.
3.143013
3.334672
0.942525
try: user_roles = db.DBSession.query(Role).filter(Role.id==RoleUser.role_id, RoleUser.user_id==uid).all() return user_roles except NoResultFound: raise HydraError("Roles not found for user (user_id={})".format(uid))
def get_user_roles(uid,**kwargs)
Get the roles for a user. @param user_id
4.128008
4.780786
0.863458
try: _get_user(uid) user_perms = db.DBSession.query(Perm).filter(Perm.id==RolePerm.perm_id, RolePerm.role_id==Role.id, Role.id==RoleUser.role_id, ...
def get_user_permissions(uid, **kwargs)
Get the roles for a user. @param user_id
4.197094
4.740116
0.885441
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_role_by_code(role_code,**kwargs)
Get a role by its code
2.810796
2.866144
0.980689
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(perm_id,**kwargs)
Get all permissions
3.211802
3.51394
0.914017
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 get_perm_by_code(perm_code,**kwargs)
Get a permission by its code
3.145534
3.283769
0.957904
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 and put it into the dataframe manually to maintain the order. cols = list(ordered_...
def _create_dataframe(cls, value)
Builds a dataframe from the value
4.315798
4.291279
1.005714
try: if self.value is None: log.warning("Cannot parse dataset. No value specified.") return None # attr_data.value is a dictionary but the keys have namespaces which must be stripped data = six.text_type(self.value) if da...
def parse_value(self)
Turn the value of an incoming dataset into a hydra-friendly value.
6.811912
6.01564
1.132367
if self.metadata is None or self.metadata == "": return {} metadata_dict = self.metadata if isinstance(self.metadata, dict) else json.loads(self.metadata) # These should be set on all datasets by default, but we don't enforce this rigidly metadata_keys = [m.lower(...
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 metadata if necessary. Returns: dict: THe metadata as a p...
2.781493
2.930149
0.949267
group_i = ResourceGroup() group_i.name = group.name group_i.description = group.description group_i.status = group.status group_i.network_id = network_id db.DBSession.add(group_i) db.DBSession.flush() return group_i
def add_resourcegroup(group, network_id,**kwargs)
Add a new group to a network.
2.679331
2.631736
1.018085
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 delete_resourcegroup(group_id,**kwargs)
Add a new group to a scenario.
8.320023
7.865077
1.057844
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 group_i
def update_resourcegroup(group,**kwargs)
Add a new group to a network.
4.097943
4.455978
0.919651
#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") except Exception as e: logging.warn(e) try: aux_dir = config.ge...
def create_sqlite_backup_db(audit_tables)
return an inspector object
3.154934
3.163594
0.997263
user = get_session().query(User).filter(User.id==user_id).one() if user.is_admin(): return True else: return False
def _is_admin(user_id)
Is the specified user an admin
2.900604
2.767699
1.04802
if metadata_dict is None: return existing_metadata = [] for m in self.metadata: existing_metadata.append(m.key) if m.key in metadata_dict: if m.value != metadata_dict[m.key]: m.value = metadata_dict[m.key] ...
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.
2.228548
2.26706
0.983012