text
stringlengths
81
112k
Process value for writing into a cell. Args: value: any type of variable Returns: json serialized value if value is list or dict, else value def normalize_cell_value(value): """Process value for writing into a cell. Args: value: any type of variable Returns: json...
Read addresses from input file into list of tuples. This only supports address and zipcode headers def get_addresses_from_input_file(input_file_name): """Read addresses from input file into list of tuples. This only supports address and zipcode headers """ mode = 'r' if sys.version_info[0...
Read identifiers from input file into list of dicts with the header row values as keys, and the rest of the rows as values. def get_identifiers_from_input_file(input_file_name): """Read identifiers from input file into list of dicts with the header row values as keys, and the rest of the rows as valu...
function takes the ipAddress of a specific host and issues a RESTFUL call to get the device and interface that the target host is currently connected to. Note: Although intended to return a single location, Multiple locations may be returned for a single host due to a partially discovered network or misconfigur...
function takes devid of specific device and issues a RESTFUL call to get the IP/MAC/ARP list from the target device. :param devId: int or str value of the target device. :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually a...
function requires no inputs and returns all IP address scopes currently configured on the HPE IMC server. If the optional scopeId parameter is included, this will automatically return only the desired scope id. :param scopeId: integer of the desired scope id ( optional ) :param auth: requests auth object #...
Function to delete an entire IP segment from the IMC IP Address management under terminal access :param network_address :param auth :param url >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.termaccess import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") ...
Function to add new host IP address allocation to existing scope ID :param ipaddress: :param name: name of the owner of this host :param description: Description of the host :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interf...
Function to add remove IP address allocation :param hostid: Host id of the host to be deleted :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: String of HTTP response c...
Function requires input of scope ID and returns list of allocated IP address for the specified scope :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :param scopeId: Interger of teh ...
Function to abstract existing add_scope_ip_function. Allows for use of network address rather than forcing human to learn the scope_id :param ipaddress: :param name: name of the owner of this host :param description: Description of the host :param: network_address: network address of the target s...
Function to abstract def delete_host_from_segment(ipaddress, networkaddress, auth, url): '''Function to abstract ''' host_id = get_host_id(ipaddress, networkaddress, auth, url) remove_scope_ip(host_id, auth.creds, auth.url)
Generates the API request signature from the given parameters. def generate_signature(method, version, endpoint, date, rel_url, content_type, content, access_key, secret_key, hash_type): ''' Generates the API request signature from the given parameters. ''' ...
Fetches the list of agents with the given status with limit and offset for pagination. :param limit: number of agents to get :param offset: offset index of agents to get :param status: An upper-cased string constant representing agent status (one of ``'ALIVE'``, ``'TERMINATE...
Sets the content of the request. def set_content(self, value: RequestContent, *, content_type: str = None): ''' Sets the content of the request. ''' assert self._attached_files is None, \ 'cannot set content because you already attached files.' ...
A shortcut for set_content() with JSON objects. def set_json(self, value: object): ''' A shortcut for set_content() with JSON objects. ''' self.set_content(modjson.dumps(value, cls=ExtendedJSONEncoder), content_type='application/json')
Attach a list of files represented as AttachedFile. def attach_files(self, files: Sequence[AttachedFile]): ''' Attach a list of files represented as AttachedFile. ''' assert not self._content, 'content must be empty to attach files.' self.content_type = 'multipart/form-data' ...
Calculates the signature of the given request and adds the Authorization HTTP header. It should be called at the very end of request preparation and before sending the request to the server. def _sign(self, rel_url, access_key=None, secret_key=None, hash_type=None): ''' Calculat...
Sends the request to the server and reads the response. You may use this method either with plain synchronous Session or AsyncSession. Both the followings patterns are valid: .. code-block:: python3 from ai.backend.client.request import Request from ai.backend.client.sess...
Creates a WebSocket connection. .. warning:: This method only works with :class:`~ai.backend.client.session.AsyncSession`. def connect_websocket(self, **kwargs) -> 'WebSocketContextManager': ''' Creates a WebSocket connection. .. warning:: This method o...
Main function. :return: None. def main(): """ Main function. :return: None. """ try: # Get the `src` directory's absolute path src_path = os.path.dirname( # `aoiklivereload` directory's absolute path os.path.dirname( # `d...
function takes the a python dict containing all necessary fields for a performance tasks, transforms the dict into JSON and issues a RESTFUL call to create the performance task. device. :param task: dictionary containing all required fields for performance tasks :param auth: requests auth object #usually ...
function takes the a str object containing the name of an existing performance tasks and issues a RESTFUL call to the IMC REST service. It will return a list :param task_name: str containing the name of the performance task :param auth: requests auth object #usually auth.creds from auth pyhpei...
Function takes a str of the target task_name to be deleted and retrieves task_id using the get_perf_task function. Once the task_id has been successfully retrieved it is populated into the task_id variable and an DELETE call is made against the HPE IMC REST interface to delete the target task. :param ta...
For a json response, check if there was any error and throw exception. Otherwise, create a housecanary.response.Response. def process_json_response(self, response): """For a json response, check if there was any error and throw exception. Otherwise, create a housecanary.response.Response.""" ...
Start watcher thread. :return: Watcher thread object. def start_watcher_thread(self): """ Start watcher thread. :return: Watcher thread object. """ # Create watcher thread watcher_thread = threading.Thread(target=self.run_watcher) ...
Watcher thread's function. :return: None. def run_watcher(self): """ Watcher thread's function. :return: None. """ # Create observer observer = Observer() # Start observer observer.start() # Dict that maps file ...
Find paths to watch. :return: Paths to watch. def _find_watch_paths(self): """ Find paths to watch. :return: Paths to watch. """ # Add directory paths in `sys.path` to watch paths watch_path_s = set(os.path.abspath(x) for x in sys.path) ...
Find short paths of given paths. E.g. if both `/home` and `/home/aoik` exist, only keep `/home`. :param paths: Paths. :return: Set of short paths. def _find_short_paths(self, paths): """ Find short paths of given paths. E.g. if both `/home` an...
Collect paths of leaf nodes. :param node: Starting node. Type is dict. Key is child node's path part. Value is child node. :param path_parts: The starting node's path parts. Type is tuple. :param leaf_paths: Leaf path list. :return: ...
Dispatch file system event. Callback called when there is a file system event. Hooked at 2KGRW. This function overrides `FileSystemEventHandler.dispatch`. :param event: File system event object. :return: None. def dispatch(self, event): """ Di...
Reload the program. :return: None. def reload(self): """ Reload the program. :return: None. """ # Get reload mode reload_mode = self._reload_mode # If reload mode is `exec` if self._reload_mode == self.RELOAD_MODE_V_EXEC...
Reload the program process. :return: None. def reload_using_exec(self): """ Reload the program process. :return: None. """ # Create command parts cmd_parts = [sys.executable] + sys.argv # Get env dict copy env_copy = os....
Spawn a subprocess and exit the current process. :return: None. def reload_using_spawn_exit(self): """ Spawn a subprocess and exit the current process. :return: None. """ # Create command parts cmd_parts = [sys.executable] + sys.argv ...
Spawn a subprocess and wait until it finishes. :return: None. def reload_using_spawn_wait(self): """ Spawn a subprocess and wait until it finishes. :return: None. """ # Create command parts cmd_parts = [sys.executable] + sys.argv ...
Show the information about the given agent. def agent(agent_id): ''' Show the information about the given agent. ''' fields = [ ('ID', 'id'), ('Status', 'status'), ('Region', 'region'), ('First Contact', 'first_contact'), ('CPU Usage (%)', 'cpu_cur_pct'), ...
List and manage agents. (admin privilege required) def agents(status, all): ''' List and manage agents. (admin privilege required) ''' fields = [ ('ID', 'id'), ('Status', 'status'), ('Region', 'region'), ('First Contact', 'first_contact'), ('CPU Usage (%)...
Show details about a keypair resource policy. When `name` option is omitted, the resource policy for the current access_key will be returned. def resource_policy(name): """ Show details about a keypair resource policy. When `name` option is omitted, the resource policy for the current access_key will b...
List and manage resource policies. (admin privilege required) def resource_policies(ctx): ''' List and manage resource policies. (admin privilege required) ''' if ctx.invoked_subcommand is not None: return fields = [ ('Name', 'name'), ('Created At', 'created_at'), ...
Add a new keypair resource policy. NAME: NAME of a new keypair resource policy. def add(name, default_for_unspecified, total_resource_slots, max_concurrent_sessions, max_containers_per_session, max_vfolder_count, max_vfolder_size, idle_timeout, allowed_vfolder_hosts): ''' Add a new keypair...
Delete a keypair resource policy. NAME: NAME of a keypair resource policy to delete. def delete(name): """ Delete a keypair resource policy. NAME: NAME of a keypair resource policy to delete. """ with Session() as session: if input('Are you sure? (y/n): ').lower().strip()[:1] != 'y': ...
Run a local proxy to a service provided by Backend.AI compute sessions. The type of proxy depends on the app definition: plain TCP or HTTP. \b SESSID: The compute session ID. APP: The name of service provided by the given session. def app(session_id, app, bind, port): """ Run a local proxy to...
Retrieves a configuration value from the environment variables. The given *key* is uppercased and prefixed by ``"BACKEND_"`` and then ``"SORNA_"`` if the former does not exist. :param key: The key name. :param default: The default value returned when there is no corresponding environment variab...
Shows the output logs of a running container. \b SESSID: Session ID or its alias given when creating the session. def logs(sess_id_or_alias): ''' Shows the output logs of a running container. \b SESSID: Session ID or its alias given when creating the session. ''' with Session() as ses...
get the key from the function input. def _wrap_key(function, args, kws): ''' get the key from the function input. ''' return hashlib.md5(pickle.dumps((_from_file(function) + function.__name__, args, kws))).hexdigest()
get the cache value def get(key, adapter = MemoryAdapter): ''' get the cache value ''' try: return pickle.loads(adapter().get(key)) except CacheExpiredException: return None
set cache by code, must set timeout length def set(key, value, timeout = -1, adapter = MemoryAdapter): ''' set cache by code, must set timeout length ''' if adapter(timeout = timeout).set(key, pickle.dumps(value)): return value else: return None
the Decorator to cache Function. def wrapcache(timeout = -1, adapter = MemoryAdapter): ''' the Decorator to cache Function. ''' def _wrapcache(function): @wraps(function) def __wrapcache(*args, **kws): hash_key = _wrap_key(function, args, kws) try: adapter_instance = adapter() return pickle.loads...
Creates an Excel file containing data returned by the Analytics API Args: data: Analytics API data as a list of dicts output_file_name: File name for output Excel file (use .xlsx extension). def export_analytics_data_to_excel(data, output_file_name, result_info_key, identifier_keys): """Create...
Creates CSV files containing data returned by the Analytics API. Creates one file per requested endpoint and saves it into the specified output_folder Args: data: Analytics API data as a list of dicts output_folder: Path to a folder to save the CSV files into def export_analytics_dat...
Creates an Excel file made up of combining the Value Report or Rental Report Excel output for the provided addresses. Args: addresses: A list of (address, zipcode) tuples output_file_name: A file name for the Excel output endpoint: One of 'value_report' or 'rental_report' rep...
Calls the analytics_data_excel module to create the Workbook def create_excel_workbook(data, result_info_key, identifier_keys): """Calls the analytics_data_excel module to create the Workbook""" workbook = analytics_data_excel.get_excel_workbook(data, result_info_key, identifier_keys) adjust_column_width_w...
Adjust column width in worksheet. Args: worksheet: worksheet to be adjusted def adjust_column_width(worksheet): """Adjust column width in worksheet. Args: worksheet: worksheet to be adjusted """ dims = {} padding = 1 for row in worksheet.rows: for cell in row: ...
function takes input of ipaddress to RESTFUL call to HP IMC :param ipaddress: The current IP address of the Access Point at time of query. :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.auth...
List and manage compute sessions. def sessions(status, access_key, id_only, all): ''' List and manage compute sessions. ''' fields = [ ('Session ID', 'sess_id'), ] with Session() as session: if is_admin(session): fields.append(('Owner', 'access_key')) if not id_o...
Show detailed information for a running compute session. SESSID: Session id or its alias. def session(sess_id_or_alias): ''' Show detailed information for a running compute session. SESSID: Session id or its alias. ''' fields = [ ('Session ID', 'sess_id'), ('Role', 'role'), ...
Factory for creating the correct type of Response based on the data. Args: endpoint_name (str) - The endpoint of the request, such as "property/value" json_body - The response body in json format. original_response (response object) - server response returned from an http req...
Gets a list of business error message strings for each of the requested objects that had a business error. If there was no error, returns an empty list Returns: List of strings def get_object_errors(self): """Gets a list of business error message strings for each of...
Returns true if any requested object had a business logic error, otherwise returns false Returns: boolean def has_object_error(self): """Returns true if any requested object had a business logic error, otherwise returns false Returns: boolean ""...
Returns a list of rate limit details. def rate_limits(self): """Returns a list of rate limit details.""" if not self._rate_limits: self._rate_limits = utilities.get_rate_limits(self.response) return self._rate_limits
Function takes input of auth class object auth object and URL and returns a BOOL of TRUE if the authentication was successful. >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> check_imc_creds(auth.creds, auth.url) True def check_imc_creds(auth, url): """Function takes ...
Function takes in object of type str, list, or dict and prints out to current working directory as pyoutput.txt :param: Object: object of type str, list, or dict :return: No return. Just prints out to file handler and save to current working directory as pyoutput.txt def print_to_file(object_name): ...
This method requests an authentication object from the HPE IMC NMS and returns an HTTPDigest Auth Object :return: def get_auth(self): """ This method requests an authentication object from the HPE IMC NMS and returns an HTTPDigest Auth Object :return: """ ...
Print title like ``----- {title} -----`` or ``===== {title} =====``. :param title: Title. :param is_end: Whether is end title. End title use ``=`` instead of ``-``. :return: None. def print_title(title, is_end=False): """ Print title like ``----- {title} -----`` or ``===== {title} =====``. ...
Get full Python version. E.g. - `2.7.11.final.0.32bit` - `3.5.1.final.0.64bit` :return: Full Python version. def get_full_python_version(): """ Get full Python version. E.g. - `2.7.11.final.0.32bit` - `3.5.1.final.0.64bit` :return: Full Python version. ""...
Get given virtual environment's `python` program path. :param venv_path: Virtual environment directory path. :return: `python` program path. def get_python_path(venv_path): """ Get given virtual environment's `python` program path. :param venv_path: Virtual environment directory path. :retu...
Add command line options. :return: None. def add_options(ctx): """ Add command line options. :return: None. """ # Add option ctx.add_option( '--always', action='store_true', default=False, dest='always', help='whether always run tasks.', ) ...
Prepend given path to environment variable PYTHONPATH. :param path: Path to add to PYTHONPATH. :return: New PYTHONPATH value. def add_pythonpath(path): """ Prepend given path to environment variable PYTHONPATH. :param path: Path to add to PYTHONPATH. :return: New PYTHONPATH value. """ ...
Wrap given path as relative path relative to top directory. Wrapper object will be handled specially in \ :paramref:`create_cmd_task.parts`. :param path: Relative path relative to top directory. :return: Wrapper object. def mark_path(path): """ Wrap given path as relative path relative to to...
Wrap given item as input or output target that should be added to task. Wrapper object will be handled specially in \ :paramref:`create_cmd_task.parts`. :param type: Target type. Allowed values: - 'input' - 'output' :param item: Item to mark as input or output target....
Create node for given relative path. :param ctx: BuildContext object. :param path: Relative path relative to top directory. :return: Created Node. def create_node(ctx, path): """ Create node for given relative path. :param ctx: BuildContext object. :param path: Relative path relative t...
Normalize given items. Do several things: - Ignore None. - Flatten list. - Unwrap wrapped item in `_ItemWrapper`. :param ctx: BuildContext object. :param items: Items list to normalize. :param str_to_node: Convert string to node. :param node_to_str: Convert node to absol...
Update touch file at given path. Do two things: - Create touch file if it not exists. - Update touch file if import checking fails. The returned touch file node is used as task's output target for dirty checking. Task will run if the touch file changes. :param ctx: BuildContext instan...
Chain given tasks. Set each task to run after its previous task. :param tasks: Tasks list. :return: Given tasks list. def chain_tasks(tasks): """ Chain given tasks. Set each task to run after its previous task. :param tasks: Tasks list. :return: Given tasks list. """ # If given task...
Create task that runs given command. :param ctx: BuildContext object. :param parts: Command parts list. Each part can be: - **None**: Will be ignored. - **String**: Will be used as-is. - **Node object**: Will be converted to absolute path. - **List of t...
Decorator that makes decorated function use BuildContext instead of \ Context instance. BuildContext instance has more methods. :param pythonpath: Path or list of paths to add to environment variable PYTHONPATH. Each path can be absolute path, or relative path relative to top directory. ...
Decorator that makes decorated function use ConfigurationContext instead \ of Context instance. :param func: Decorated function. :return: Decorated function. def config_ctx(func): """ Decorator that makes decorated function use ConfigurationContext instead \ of Context instance. :param f...
Print given context's info. :param ctx: Context object. :return: None. def print_ctx(ctx): """ Print given context's info. :param ctx: Context object. :return: None. """ # Print title print_title('ctx attributes') # Print context object's attributes print_text(dir(ctx))...
Create task that sets up `virtualenv` package. :param ctx: BuildContext object. :param python: Python program path. :param inputs: Input items list to add to created task. See :paramref:`create_cmd_task.inputs` for allowed item types. :param outputs: Output items list to add to created task...
Create task that sets up virtual environment. :param ctx: BuildContext object. :param python: Python program path. :param venv_path: Virtual environment directory relative path relative to top directory. :param inputs: Input items list to add to created task. See :paramref:`create_c...
Create task that uses given virtual environment's `pip` to sets up \ packages listed in given requirements file. :param ctx: BuildContext object. :param python: Python program path used to set up `pip` and `virtualenv`. :param req_path: Requirements file relative path relative to top directory. ...
Delete all files untracked by git. :param ctx: Context object. :return: None. def git_clean(ctx): """ Delete all files untracked by git. :param ctx: Context object. :return: None. """ # Get command parts cmd_part_s = [ # Program path 'git', # Clean untra...
Run command. :return: Command exit code. def run(self): """ Run command. :return: Command exit code. """ # Print task title print_title(self._task_name_title) # Get context object ctx = self._ctx # Get command parts cmd_part_s ...
function takes no input as input to RESTFUL call to HP IMC :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: list of dictionaries where each element of the list represents a ...
Function operates on the IMCDev object. Takes input of vlanid (1-4094), str of vlan_name, auth and url to execute the create_dev_vlan method on the IMCDev object. Device must be supported in the HPE IMC Platform VLAN Manager module. :param vlanid: str of VLANId ( valid 1-4094 ) :param vl...
Function operates on the IMCDev object. Takes input of vlanid (1-4094), auth and url to execute the delete_dev_vlans method on the IMCDev object. Device must be supported in the HPE IMC Platform VLAN Manager module. :param vlanid: str of VLANId ( valid 1-4094 ) :return: def delvlan(self...
Function operates on the IMCDev object and updates the ipmacarp attribute :return: def getipmacarp(self): """ Function operates on the IMCDev object and updates the ipmacarp attribute :return: """ self.ipmacarp = get_ip_mac_arp_list(self.auth, self.url, devid = self.devi...
Function operates on the IMCInterface object and configures the interface into an administratively down state and refreshes contents of self.adminstatus :return: def down(self): """ Function operates on the IMCInterface object and configures the interface into an administrativel...
Function operates on the IMCInterface object and configures the interface into an administratively up state and refreshes contents of self.adminstatus :return: def up(self): """ Function operates on the IMCInterface object and configures the interface into an ...
Object method takes in input of hostipaddress, name and description and adds them to the parent ip scope. :param hostipaddress: str of ipv4 address of the target host ip record :param name: str of the name of the owner of the target host ip record :param description: str of a description...
Object method takes in input of hostip address,removes them from the parent ip scope. :param hostid: str of the hostid of the target host ip record :return: def deallocate_ip(self, hostipaddress): """ Object method takes in input of hostip address,removes them from the parent ip scope...
Method gets all hosts currently allocated to the target scope and refreashes the self.hosts attributes of the object :return: def gethosts(self): """ Method gets all hosts currently allocated to the target scope and refreashes the self.hosts attributes of the object :ret...
Method searches for the next free ip address in the scope object and returns it as a str value. :return: def nextfreeip(self): """ Method searches for the next free ip address in the scope object and returns it as a str value. :return: """ allocated_ips =...
Method takes inpur of str startip, str endip, name, and description and adds a child scope. The startip and endip MUST be in the IP address range of the parent scope. :param startip: str of ipv4 address of the first address in the child scope :param endip: str of ipv4 address of the last address...
Takes no input, or template_name as input to issue RESTUL call to HP IMC :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :param template_name: str value of template name :retur...
Function takes input of a dictionry containing the required key/value pair for the modification of a telnet template. :param auth: :param url: :param telnet_template: Human readable label which is the name of the specific telnet template :param template_id Internal IMC number which designates the s...
Takes template_name as input to issue RESTUL call to HP IMC which will delete the specific telnet template from the IMC system :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :p...
Function takes input of a dictionry containing the required key/value pair for the creation of a ssh template. :param auth: :param url: :param ssh: dictionary of valid JSON which complains to API schema :return: int value of HTTP response code 201 for proper creation or 404 for failed creation ...
Takes no input, or template_name as input to issue RESTUL call to HP IMC :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :param template_name: str value of template name :retur...
Function takes input of a dictionry containing the required key/value pair for the modification of a ssh template. :param auth: :param url: :param ssh_template: Human readable label which is the name of the specific ssh template :param template_id Internal IMC number which designates the specific s...