idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
46,000
def add_resourcegroupitems ( scenario_id , items , scenario = None , ** kwargs ) : user_id = int ( kwargs . get ( 'user_id' ) ) if scenario is None : scenario = _get_scenario ( scenario_id , user_id ) _check_network_ownership ( scenario . network_id , user_id ) newitems = [ ] for group_item in items : group_item_i = _a...
Get all the items in a group in a scenario .
46,001
def get_plugins ( ** kwargs ) : plugins = [ ] plugin_paths = [ ] base_plugin_dir = config . get ( 'plugin' , 'default_directory' ) plugin_xsd_path = config . get ( 'plugin' , 'plugin_xsd_path' ) base_plugin_dir_contents = os . listdir ( base_plugin_dir ) for directory in base_plugin_dir_contents : if directory [ 0 ] ==...
Get all available plugins
46,002
def run_plugin ( plugin , ** kwargs ) : args = [ sys . executable ] home = os . path . expanduser ( '~' ) path_to_plugin = os . path . join ( home , 'svn/HYDRA/HydraPlugins' , plugin . location ) args . append ( path_to_plugin ) plugin_params = " " for p in plugin . params : param = "--%s=%s " % ( p . name , p . value ...
Run a plugin
46,003
def create_mysql_db ( db_url ) : db_url = db_url . strip ( ) . strip ( '/' ) if db_url . find ( 'mysql' ) >= 0 : db_name = config . get ( 'mysqld' , 'db_name' , 'hydradb' ) if db_url . find ( db_name ) >= 0 : no_db_url = db_url . rsplit ( "/" , 1 ) [ 0 ] else : if db_url . find ( '@' ) == - 1 : raise HydraError ( "No H...
To simplify deployment create the mysql DB if it s not there . Accepts a URL with or without a DB name stated and returns a db url containing the db name for use in the main sqlalchemy engine .
46,004
def add_project ( project , ** kwargs ) : user_id = kwargs . get ( 'user_id' ) existing_proj = get_project_by_name ( project . name , user_id = user_id ) if len ( existing_proj ) > 0 : raise HydraError ( "A Project with the name \"%s\" already exists" % ( project . name , ) ) proj_i = Project ( ) proj_i . name = projec...
Add a new project returns a project complexmodel
46,005
def update_project ( project , ** kwargs ) : user_id = kwargs . get ( 'user_id' ) proj_i = _get_project ( project . id ) proj_i . check_write_permission ( user_id ) proj_i . name = project . name proj_i . description = project . description attr_map = hdb . add_resource_attributes ( proj_i , project . attributes ) proj...
Update a project returns a project complexmodel
46,006
def get_project_by_network_id ( network_id , ** kwargs ) : user_id = kwargs . get ( 'user_id' ) projects_i = db . DBSession . query ( Project ) . join ( ProjectOwner ) . join ( Network , Project . id == Network . project_id ) . filter ( Network . id == network_id , ProjectOwner . user_id == user_id ) . order_by ( 'name...
get a project complexmodel by a network_id
46,007
def get_projects ( uid , include_shared_projects = True , projects_ids_list_filter = None , ** kwargs ) : req_user_id = kwargs . get ( 'user_id' ) projects_qry = db . DBSession . query ( Project ) log . info ( "Getting projects for %s" , uid ) if include_shared_projects is True : projects_qry = projects_qry . join ( Pr...
Get all the projects owned by the specified user . These include projects created by the user but also ones shared with the user . For shared projects only include networks in those projects which are accessible to the user .
46,008
def get_networks ( project_id , include_data = 'N' , ** kwargs ) : log . info ( "Getting networks for project %s" , project_id ) user_id = kwargs . get ( 'user_id' ) project = _get_project ( project_id ) project . check_read_permission ( user_id ) rs = db . DBSession . query ( Network . id , Network . status ) . filter...
Get all networks in a project Returns an array of network objects .
46,009
def get_network_project ( network_id , ** kwargs ) : net_proj = db . DBSession . query ( Project ) . join ( Network , and_ ( Project . id == Network . id , Network . id == network_id ) ) . first ( ) if net_proj is None : raise HydraError ( "Network %s not found" % network_id ) return net_proj
get the project that a network is in
46,010
def add_resource_types ( resource_i , types ) : if types is None : return [ ] existing_type_ids = [ ] if resource_i . types : for t in resource_i . types : existing_type_ids . append ( t . type_id ) new_type_ids = [ ] for templatetype in types : if templatetype . id in existing_type_ids : continue rt_i = ResourceType (...
Save a reference to the types used for this resource .
46,011
def create_default_units_and_dimensions ( ) : default_units_file_location = os . path . realpath ( os . path . join ( os . path . dirname ( os . path . realpath ( __file__ ) ) , '../' , 'static' , 'default_units_and_dimensions.json' ) ) d = None with open ( default_units_file_location ) as json_data : d = json . load (...
Adds the units and the dimensions reading a json file . It adds only dimensions and units that are not inside the db It is possible adding new dimensions and units to the DB just modifiyin the json file
46,012
def get_dimension_from_db_by_name ( dimension_name ) : try : dimension = db . DBSession . query ( Dimension ) . filter ( Dimension . name == dimension_name ) . one ( ) return JSONObject ( dimension ) except NoResultFound : raise ResourceNotFoundError ( "Dimension %s not found" % ( dimension_name ) )
Gets a dimension from the DB table .
46,013
def get_rules ( scenario_id , ** kwargs ) : rules = db . DBSession . query ( Rule ) . filter ( Rule . scenario_id == scenario_id , Rule . status == 'A' ) . all ( ) return rules
Get all the rules for a given scenario .
46,014
def get_attribute_by_name_and_dimension ( name , dimension_id = None , ** kwargs ) : try : attr_i = db . DBSession . query ( Attr ) . filter ( and_ ( Attr . name == name , Attr . dimension_id == dimension_id ) ) . one ( ) log . debug ( "Attribute retrieved" ) return attr_i except NoResultFound : return None
Get a specific attribute by its name . dimension_id can be None because in attribute the dimension_id is not anymore mandatory
46,015
def add_attributes ( attrs , ** kwargs ) : all_attrs = db . DBSession . query ( Attr ) . all ( ) attr_dict = { } for attr in all_attrs : attr_dict [ ( attr . name . lower ( ) , attr . dimension_id ) ] = JSONObject ( attr ) attrs_to_add = [ ] existing_attrs = [ ] for potential_new_attr in attrs : if potential_new_attr i...
Add a list of generic attributes which can then be used in creating a resource attribute and put into a type .
46,016
def get_attributes ( ** kwargs ) : attrs = db . DBSession . query ( Attr ) . order_by ( Attr . name ) . all ( ) return attrs
Get all attributes
46,017
def add_resource_attribute ( resource_type , resource_id , attr_id , is_var , error_on_duplicate = True , ** kwargs ) : attr = db . DBSession . query ( Attr ) . filter ( Attr . id == attr_id ) . first ( ) if attr is None : raise ResourceNotFoundError ( "Attribute with ID %s does not exist." % attr_id ) resource_i = _ge...
Add a resource attribute attribute to a resource .
46,018
def add_resource_attrs_from_type ( type_id , resource_type , resource_id , ** kwargs ) : type_i = _get_templatetype ( type_id ) resource_i = _get_resource ( resource_type , resource_id ) resourceattr_qry = db . DBSession . query ( ResourceAttr ) . filter ( ResourceAttr . ref_key == resource_type ) if resource_type == '...
adds all the attributes defined by a type to a node .
46,019
def get_all_resource_attributes ( ref_key , network_id , template_id = None , ** kwargs ) : user_id = kwargs . get ( 'user_id' ) resource_attr_qry = db . DBSession . query ( ResourceAttr ) . outerjoin ( Node , Node . id == ResourceAttr . node_id ) . outerjoin ( Link , Link . id == ResourceAttr . link_id ) . outerjoin (...
Get all the resource attributes for a given resource type in the network . That includes all the resource attributes for a given type within the network . For example if the ref_key is NODE then it will return all the attirbutes of all nodes in the network . This function allows a front end to pre - load an entire netw...
46,020
def get_resource_attributes ( ref_key , ref_id , type_id = None , ** kwargs ) : user_id = kwargs . get ( 'user_id' ) resource_attr_qry = db . DBSession . query ( ResourceAttr ) . filter ( ResourceAttr . ref_key == ref_key , or_ ( ResourceAttr . network_id == ref_id , ResourceAttr . node_id == ref_id , ResourceAttr . li...
Get all the resource attributes for a given resource . If type_id is specified only return the resource attributes within the type .
46,021
def check_attr_dimension ( attr_id , ** kwargs ) : attr_i = _get_attr ( attr_id ) datasets = db . DBSession . query ( Dataset ) . filter ( Dataset . id == ResourceScenario . dataset_id , ResourceScenario . resource_attr_id == ResourceAttr . id , ResourceAttr . attr_id == attr_id ) . all ( ) bad_datasets = [ ] for d in ...
Check that the dimension of the resource attribute data is consistent with the definition of the attribute . If the attribute says volume make sure every dataset connected with this attribute via a resource attribute also has a dimension of volume .
46,022
def get_resource_attribute ( resource_attr_id , ** kwargs ) : resource_attr_qry = db . DBSession . query ( ResourceAttr ) . filter ( ResourceAttr . id == resource_attr_id , ) resource_attr = resource_attr_qry . first ( ) if resource_attr is None : raise ResourceNotFoundError ( "Resource attribute %s does not exist" , r...
Get a specific resource attribte by ID If type_id is Gspecified only return the resource attributes within the type .
46,023
def delete_mappings_in_network ( network_id , network_2_id = None , ** kwargs ) : qry = db . DBSession . query ( ResourceAttrMap ) . filter ( or_ ( ResourceAttrMap . network_a_id == network_id , ResourceAttrMap . network_b_id == network_id ) ) if network_2_id is not None : qry = qry . filter ( or_ ( ResourceAttrMap . n...
Delete all the resource attribute mappings in a network . If another network is specified only delete the mappings between the two networks .
46,024
def get_network_mappings ( network_id , network_2_id = None , ** kwargs ) : qry = db . DBSession . query ( ResourceAttrMap ) . filter ( or_ ( and_ ( ResourceAttrMap . resource_attr_id_a == ResourceAttr . id , ResourceAttr . network_id == network_id ) , and_ ( ResourceAttrMap . resource_attr_id_b == ResourceAttr . id , ...
Get all the mappings of network resource attributes NOT ALL THE MAPPINGS WITHIN A NETWORK . For that use get_mappings_in_network . If another network is specified only return the mappings between the two networks .
46,025
def check_attribute_mapping_exists ( resource_attr_id_source , resource_attr_id_target , ** kwargs ) : qry = db . DBSession . query ( ResourceAttrMap ) . filter ( ResourceAttrMap . resource_attr_id_a == resource_attr_id_source , ResourceAttrMap . resource_attr_id_b == resource_attr_id_target ) . all ( ) if len ( qry ) ...
Check whether an attribute mapping exists between a source and target resource attribute . returns Y if a mapping exists . Returns N in all other cases .
46,026
def get_attribute_group ( group_id , ** kwargs ) : user_id = kwargs . get ( 'user_id' ) try : group_i = db . DBSession . query ( AttrGroup ) . filter ( AttrGroup . id == group_id ) . one ( ) group_i . project . check_read_permission ( user_id ) except NoResultFound : raise HydraError ( "Group %s not found" % ( group_id...
Get a specific attribute group
46,027
def delete_attribute_group ( group_id , ** kwargs ) : 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 ( "...
Delete an attribute group .
46,028
def get_network_attributegroup_items ( network_id , ** kwargs ) : 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...
Get all the group items in a network
46,029
def get_group_attributegroup_items ( network_id , group_id , ** kwargs ) : 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 , AttrGroupIt...
Get all the items in a specified group within a network
46,030
def get_attribute_item_groups ( network_id , attr_id , ** kwargs ) : 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 . a...
Get all the group items in a network with a given attribute_id
46,031
def share_network ( network_id , usernames , read_only , share , ** kwargs ) : 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' : ...
Share a network with a list of users identified by their usernames .
46,032
def unshare_network ( network_id , usernames , ** kwargs ) : 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 ) net_i . unset_owner ( user_i . id , write = write , share = share ) db . DBSession ...
Un - Share a network with a list of users identified by their usernames .
46,033
def share_project ( project_id , usernames , read_only , share , ** kwargs ) : user_id = kwargs . get ( 'user_id' ) proj_i = _get_project ( project_id ) 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 : raise HydraEr...
Share an entire project with a list of users identifed by their usernames .
46,034
def unshare_project ( project_id , usernames , ** kwargs ) : 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 ) proj_i . unset_owner ( user_i . id , write = write , share = share ) db . DBSessi...
Un - share a project with a list of users identified by their usernames .
46,035
def set_project_permission ( project_id , usernames , read , write , share , ** kwargs ) : user_id = kwargs . get ( 'user_id' ) proj_i = _get_project ( project_id ) proj_i . check_share_permission ( user_id ) if read == 'N' : write = 'N' share = 'N' for username in usernames : user_i = _get_user ( username ) if proj_i ...
Set permissions on a project to a list of users identifed by their usernames .
46,036
def get_all_project_owners ( project_ids = None , ** kwargs ) : 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...
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
46,037
def get_all_network_owners ( network_ids = None , ** kwargs ) : 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 ( net...
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
46,038
def add_dataset ( data_type , val , unit_id = None , metadata = { } , name = "" , user_id = None , flush = False ) : 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 ....
Data can exist without scenarios . This is the mechanism whereby single pieces of data can be added without doing it through a scenario .
46,039
def _bulk_insert_data ( bulk_data , user_id = None , source = None ) : 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 ) ) ) ex...
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
46,040
def _get_metadata ( dataset_ids ) : 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 ( Metadata...
Get all the metadata for a given list of datasets
46,041
def _get_datasets ( dataset_ids ) : 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 . ...
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 .
46,042
def get_vals_between_times ( dataset_id , start_time , end_time , timestep , increment , ** kwargs ) : 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 ) ==...
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 .
46,043
def delete_dataset ( dataset_id , ** kwargs ) : 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 . data...
Removes a piece of data from the DB . CAUTION! Use with care as this cannot be undone easily .
46,044
def add_note ( note , ** kwargs ) : 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
Add a new note
46,045
def update_note ( note , ** kwargs ) : 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 = not...
Update a note
46,046
def purge_note ( note_id , ** kwargs ) : note_i = _get_note ( note_id ) db . DBSession . delete ( note_i ) db . DBSession . flush ( )
Remove a note from the DB permenantly
46,047
def login ( username , password , ** kwargs ) : user_id = util . hdb . login_user ( username , password ) hydra_session = session . Session ( { } , validate_key = config . get ( 'COOKIES' , 'VALIDATE_KEY' , 'YxaDbzUUSo08b+' ) , type = 'file' , cookie_expires = True , data_dir = config . get ( 'COOKIES' , 'DATA_DIR' , '...
Login a user returning a dict containing their user_id and session_id
46,048
def logout ( session_id , ** kwargs ) : hydra_session_object = session . SessionObject ( { } , validate_key = config . get ( 'COOKIES' , 'VALIDATE_KEY' , 'YxaDbzUUSo08b+' ) , type = 'file' , cookie_expires = True , data_dir = config . get ( 'COOKIES' , 'DATA_DIR' , '/tmp' ) , file_dir = config . get ( 'COOKIES' , 'FILE...
Logout a user removing their cookie if it exists and returning OK
46,049
def get_session_user ( session_id , ** kwargs ) : hydra_session_object = session . SessionObject ( { } , validate_key = config . get ( 'COOKIES' , 'VALIDATE_KEY' , 'YxaDbzUUSo08b+' ) , type = 'file' , cookie_expires = True , data_dir = config . get ( 'COOKIES' , 'DATA_DIR' , '/tmp' ) , file_dir = config . get ( 'COOKIE...
Given a session ID get the user ID that it is associated with
46,050
def array_dim ( arr ) : dim = [ ] while True : try : dim . append ( len ( arr ) ) arr = arr [ 0 ] except TypeError : return dim
Return the size of a multidimansional array .
46,051
def arr_to_vector ( arr ) : 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
Reshape a multidimensional array to a vector .
46,052
def vector_to_arr ( vec , dim ) : 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 outer_array . append ( inner_array ) array =...
Reshape a vector to a multidimensional array with dimensions dim .
46,053
def validate_ENUM ( in_value , restriction ) : 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 ) )
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
46,054
def validate_NUMPLACES ( in_value , restriction ) : if type ( restriction ) is list : restriction = restriction [ 0 ] value = _get_val ( in_value ) if type ( value ) is list : for subval in value : if type ( subval ) is tuple : subval = subval [ 1 ] validate_NUMPLACES ( subval , restriction ) else : restriction = int (...
the value parameter must be either a single value or a 1 - dimensional list . All the values in this list must satisfy the condition
46,055
def validate_EQUALTIMESTEPS ( value , restriction ) : 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 type ( value . index ) == pd . Int64Index ...
Ensure that the timesteps in a timeseries are equal . If a restriction is provided they must be equal to the specified restriction .
46,056
def flatten_dict ( value , target_depth = 1 , depth = None ) : 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 ] ) > 0 : subval = list (...
Take a hashtable with multiple nested dicts and return a dict where the keys are a concatenation of each sub - key .
46,057
def to_named_tuple ( keys , values ) : values = [ dbobject . __dict__ [ key ] for key in dbobject . keys ( ) ] tuple_object = namedtuple ( 'DBObject' , dbobject . keys ( ) ) tuple_instance = tuple_object . _make ( values ) return tuple_instance
Convert a sqlalchemy object into a named tuple
46,058
def get_val ( dataset , timestamp = None ) : if dataset . type == 'array' : return json . loads ( dataset . value ) elif dataset . type == 'descriptor' : return str ( dataset . value ) elif dataset . type == 'scalar' : return Decimal ( str ( dataset . value ) ) elif dataset . type == 'timeseries' : val = dataset . valu...
Turn the string value of a dataset into an appropriate value be it a decimal value array or time series .
46,059
def get_layout_as_string ( layout ) : 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
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 identified .
46,060
def get_layout_as_dict ( layout ) : if isinstance ( layout , dict ) : return layout if ( isinstance ( layout , six . string_types ) ) : try : return get_layout_as_dict ( json . loads ( layout ) ) except : return 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 .
46,061
def get_username ( uid , ** kwargs ) : 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
Return the username of a given user_id
46,062
def get_usernames_like ( username , ** kwargs ) : checkname = "%%%s%%" % username rs = db . DBSession . query ( User . username ) . filter ( User . username . like ( checkname ) ) . all ( ) return [ r . username for r in rs ]
Return a list of usernames like the given string .
46,063
def update_user_display_name ( user , ** kwargs ) : 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 ) )
Update a user s display name
46,064
def update_user_password ( new_pwd_user_id , new_password , ** kwargs ) : 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...
Update a user s password
46,065
def get_user ( uid , ** kwargs ) : user_id = kwargs . get ( 'user_id' ) if uid is None : uid = user_id user_i = _get_user ( uid ) return user_i
Get a user by ID
46,066
def add_role ( role , ** kwargs ) : role_i = Role ( name = role . name , code = role . code ) db . DBSession . add ( role_i ) db . DBSession . flush ( ) return role_i
Add a new role
46,067
def add_perm ( perm , ** kwargs ) : perm_i = Perm ( name = perm . name , code = perm . code ) db . DBSession . add ( perm_i ) db . DBSession . flush ( ) return perm_i
Add a permission
46,068
def delete_perm ( perm_id , ** kwargs ) : 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'
Delete a permission
46,069
def set_user_role ( new_user_id , role_id , ** kwargs ) : 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 : log . exception ( e ) raise ResourceN...
Apply role_id to new_user_id
46,070
def delete_user_role ( deleted_user_id , role_id , ** kwargs ) : 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 NoResultF...
Remove a user from a role
46,071
def set_role_perm ( role_id , perm_id , ** kwargs ) : _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
Insert a permission into a role
46,072
def delete_role_perm ( role_id , perm_id , ** kwargs ) : _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 ResourceNot...
Remove a permission from a role
46,073
def update_role ( role , ** kwargs ) : 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 perm in role . permiss...
Update the role . Used to add permissions and users to a role .
46,074
def get_all_users ( ** kwargs ) : users_qry = db . DBSession . query ( User ) filter_type = kwargs . get ( 'filter_type' ) filter_value = kwargs . get ( 'filter_value' ) if filter_type is not None : if filter_type == "id" : if isinstance ( filter_value , str ) : log . info ( "[HB.users] Getting user by Filter ID : %s" ...
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
46,075
def get_role ( role_id , ** kwargs ) : 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 ) )
Get a role by its ID .
46,076
def get_role_by_code ( role_code , ** kwargs ) : 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 ) )
Get a role by its code
46,077
def get_perm ( perm_id , ** kwargs ) : 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 ) )
Get all permissions
46,078
def get_perm_by_code ( perm_code , ** kwargs ) : 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 ) )
Get a permission by its code
46,079
def _create_dataframe ( cls , value ) : try : ordered_jo = json . loads ( six . text_type ( value ) , object_pairs_hook = collections . OrderedDict ) cols = list ( ordered_jo . keys ( ) ) if len ( cols ) == 0 : raise ValueError ( "Dataframe has no columns" ) if isinstance ( ordered_jo [ cols [ 0 ] ] , list ) : index = ...
Builds a dataframe from the value
46,080
def parse_value ( self ) : try : if self . value is None : log . warning ( "Cannot parse dataset. No value specified." ) return None data = six . text_type ( self . value ) if data . upper ( ) . strip ( ) in ( "NULL" , "" ) : return "NULL" data = data [ 0 : 100 ] log . info ( "[Dataset.parse_value] Parsing %s (%s)" , d...
Turn the value of an incoming dataset into a hydra - friendly value .
46,081
def get_metadata_as_dict ( self , user_id = None , source = None ) : if self . metadata is None or self . metadata == "" : return { } metadata_dict = self . metadata if isinstance ( self . metadata , dict ) else json . loads ( self . metadata ) metadata_keys = [ m . lower ( ) for m in metadata_dict ] if user_id is not ...
Convert a metadata json string into a dictionary .
46,082
def delete_resourcegroup ( group_id , ** kwargs ) : group_i = _get_group ( group_id ) db . DBSession . delete ( group_i ) db . DBSession . flush ( ) return 'OK'
Add a new group to a scenario .
46,083
def _is_admin ( user_id ) : user = get_session ( ) . query ( User ) . filter ( User . id == user_id ) . one ( ) if user . is_admin ( ) : return True else : return False
Is the specified user an admin
46,084
def set_metadata ( self , metadata_dict ) : 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 ] for k , v in metadata_dict . items ( ) :...
Set the metadata on a dataset
46,085
def check_user ( self , user_id ) : if self . hidden == 'N' : return True for owner in self . owners : if int ( owner . user_id ) == int ( user_id ) : if owner . view == 'Y' : return True return False
Check whether this user can read this dataset
46,086
def get_network ( self ) : ref_key = self . ref_key if ref_key == 'NETWORK' : return self . network elif ref_key == 'NODE' : return self . node . network elif ref_key == 'LINK' : return self . link . network elif ref_key == 'GROUP' : return self . group . network elif ref_key == 'PROJECT' : return None
Get the network that this resource attribute is in .
46,087
def check_read_permission ( self , user_id , do_raise = True ) : return self . get_resource ( ) . check_read_permission ( user_id , do_raise = do_raise )
Check whether this user can read this resource attribute
46,088
def check_write_permission ( self , user_id , do_raise = True ) : return self . get_resource ( ) . check_write_permission ( user_id , do_raise = do_raise )
Check whether this user can write this node
46,089
def add_link ( self , name , desc , layout , node_1 , node_2 ) : existing_link = get_session ( ) . query ( Link ) . filter ( Link . name == name , Link . network_id == self . id ) . first ( ) if existing_link is not None : raise HydraError ( "A link with name %s is already in network %s" % ( name , self . id ) ) l = Li...
Add a link to a network . Links are what effectively define the network topology by associating two already existing nodes .
46,090
def add_node ( self , name , desc , layout , node_x , node_y ) : 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 already in network %s" % ( name , self . id ) ) node =...
Add a node to a network .
46,091
def check_read_permission ( self , user_id , do_raise = True ) : if _is_admin ( user_id ) : return True if int ( self . created_by ) == int ( user_id ) : return True for owner in self . owners : if int ( owner . user_id ) == int ( user_id ) : if owner . view == 'Y' : break else : if do_raise is True : raise PermissionE...
Check whether this user can read this network
46,092
def check_share_permission ( self , user_id ) : 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 ( user_id ) : if owner . view == 'Y' and owner . share == 'Y' : break else : raise PermissionError ( "Permission denied. User ...
Check whether this user can write this project
46,093
def check_read_permission ( self , user_id , do_raise = True ) : return self . network . check_read_permission ( user_id , do_raise = do_raise )
Check whether this user can read this link
46,094
def check_write_permission ( self , user_id , do_raise = True ) : return self . network . check_write_permission ( user_id , do_raise = do_raise )
Check whether this user can write this link
46,095
def get_items ( self , scenario_id ) : items = get_session ( ) . query ( ResourceGroupItem ) . filter ( ResourceGroupItem . group_id == self . id ) . filter ( ResourceGroupItem . scenario_id == scenario_id ) . all ( ) return items
Get all the items in this group in the given scenario
46,096
def set_ref ( self , ref_key , ref_id ) : if ref_key == 'NETWORK' : self . network_id = ref_id elif ref_key == 'NODE' : self . node_id = ref_id elif ref_key == 'LINK' : self . link_id = ref_id elif ref_key == 'GROUP' : self . group_id = ref_id elif ref_key == 'SCENARIO' : self . scenario_id = ref_id elif ref_key == 'PR...
Using a ref key and ref id set the reference to the appropriate resource type .
46,097
def roles ( self ) : roles = [ ] for ur in self . roleusers : roles . append ( ur . role ) return set ( roles )
Return a set with all roles granted to the user .
46,098
def is_admin ( self ) : for ur in self . roleusers : if ur . role . code == 'admin' : return True return False
Check that the user has a role with the code admin
46,099
def _check_dimension ( typeattr , unit_id = None ) : if unit_id is None : unit_id = typeattr . unit_id dimension_id = _get_attr ( typeattr . attr_id ) . dimension_id if unit_id is not None and dimension_id is None : unit_dimension_id = units . get_dimension_by_unit_id ( unit_id ) . id raise HydraError ( "Unit %s (abbre...
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