text
stringlengths
81
112k
Print the results of validating a file. Args: file_result: A FileValidationResults instance. def print_file_results(file_result): """Print the results of validating a file. Args: file_result: A FileValidationResults instance. """ print_results_header(file_result.filepath, file_re...
Print `results` (the results of validation) to stdout. Args: results: A list of FileValidationResults or ObjectValidationResults instances. def print_results(results): """Print `results` (the results of validation) to stdout. Args: results: A list of FileValidationResults...
Ensure file objects' 'encryption_algorithm' property is from the encryption-algo-ov vocabulary. def vocab_encryption_algo(instance): """Ensure file objects' 'encryption_algorithm' property is from the encryption-algo-ov vocabulary. """ for key, obj in instance['objects'].items(): if 'type' ...
Ensures that all SDOs being referenced by the SRO are contained within the same bundle def enforce_relationship_refs(instance): """Ensures that all SDOs being referenced by the SRO are contained within the same bundle""" if instance['type'] != 'bundle' or 'objects' not in instance: return ...
Ensure timestamp properties with a comparison requirement are valid. E.g. `modified` must be later or equal to `created`. def timestamp_compare(instance): """Ensure timestamp properties with a comparison requirement are valid. E.g. `modified` must be later or equal to `created`. """ compares = [(...
Ensure cyber observable timestamp properties with a comparison requirement are valid. def observable_timestamp_compare(instance): """Ensure cyber observable timestamp properties with a comparison requirement are valid. """ for key, obj in instance['objects'].items(): compares = enums.TIMEST...
Ensure keys in Language Content's 'contents' dictionary are valid language codes, and that the keys in the sub-dictionaries match the rules for object property names. def language_contents(instance): """Ensure keys in Language Content's 'contents' dictionary are valid language codes, and that the keys ...
Construct the list of 'MUST' validators to be run by the validator. def list_musts(options): """Construct the list of 'MUST' validators to be run by the validator. """ validator_list = [ timestamp, timestamp_compare, observable_timestamp_compare, object_marking_circular_refs...
Determines the exit status code to be returned from a script by inspecting the results returned from validating file(s). Status codes are binary OR'd together, so exit codes can communicate multiple error conditions. def get_code(results): """Determines the exit status code to be returned from a script...
Parses a list of command line arguments into a ValidationOptions object. Args: cmd_args (list of str): The list of command line arguments to be parsed. is_script: Whether the arguments are intended for use in a stand-alone script or imported into another tool. Returns: Inst...
Decorator for functions that require cyber observable data. def cyber_observable_check(original_function): """Decorator for functions that require cyber observable data. """ def new_function(*args, **kwargs): if not has_cyber_observable_data(args[0]): return func = original_func...
Initializes a cache which the ``requests`` library will consult for responses, before making network requests. :param refresh_cache: Whether the cache should be cleared out def init_requests_cache(refresh_cache=False): """ Initializes a cache which the ``requests`` library will consult for respons...
render content with "active" urls logic def render_tag(self, context, kwargs, nodelist): '''render content with "active" urls logic''' # load configuration from passed options self.load_configuration(**kwargs) # get request from context request = context['request'] # g...
parse content of extension def parse(self, parser): '''parse content of extension''' # line number of token that started the tag lineno = next(parser.stream).lineno # template context context = nodes.ContextReference() # parse keyword arguments kwargs = [] ...
render content with "active" urls logic def render_tag(self, context, caller, **kwargs): '''render content with "active" urls logic''' # load configuration from passed options self.load_configuration(**kwargs) # get request from context request = context['request'] # g...
generate cache key def get_cache_key(content, **kwargs): '''generate cache key''' cache_key = '' for key in sorted(kwargs.keys()): cache_key = '{cache_key}.{key}:{value}'.format( cache_key=cache_key, key=key, value=kwargs[key], ) cache_key = '{conten...
Return True/False from "yes"/"no". :param value: template keyword argument value :type value: string :param varname: name of the variable, for use on exception raising :type varname: string :raises: :exc:`ImproperlyConfigured` Django > 1.5 template boolean/None variables feature. def yesno_to...
check "active" url, apply css_class def check_active(url, element, **kwargs): '''check "active" url, apply css_class''' menu = yesno_to_bool(kwargs['menu'], 'menu') ignore_params = yesno_to_bool(kwargs['ignore_params'], 'ignore_params') # check missing href parameter if not url.attrib.get('href', ...
check content for "active" urls def check_content(content, **kwargs): '''check content for "active" urls''' # valid html root tag try: # render elements tree from content tree = fragment_fromstring(content) # flag for prevent content rerendering, when no "active" urls found ...
check content for "active" urls, store results to django cache def render_content(content, **kwargs): '''check content for "active" urls, store results to django cache''' # try to take pre rendered content from django cache, if caching is enabled if settings.ACTIVE_URL_CACHE: cache_key = get_cache_...
load configuration, merge with default settings def load_configuration(self, **kwargs): '''load configuration, merge with default settings''' # update passed arguments with default values for key in settings.ACTIVE_URL_KWARGS: kwargs.setdefault(key, settings.ACTIVE_URL_KWARGS[key]) ...
Parse a Marathon response into an object or list of objects. def _parse_response(response, clazz, is_list=False, resource_name=None): """Parse a Marathon response into an object or list of objects.""" target = response.json()[ resource_name] if resource_name else response.json() if ...
Query Marathon server. def _do_request(self, method, path, params=None, data=None): """Query Marathon server.""" headers = { 'Content-Type': 'application/json', 'Accept': 'application/json'} if self.auth_token: headers['Authorization'] = "token={}".format(self.auth_toke...
Query Marathon server for events. def _do_sse_request(self, path, params=None): """Query Marathon server for events.""" urls = [''.join([server.rstrip('/'), path]) for server in self.servers] while urls: url = urls.pop() try: # Requests does not set the o...
Create and start an app. :param str app_id: application ID :param :class:`marathon.models.app.MarathonApp` app: the application to create :param bool minimal: ignore nulls and empty collections :returns: the created app (on success) :rtype: :class:`marathon.models.app.MarathonA...
List all apps. :param str cmd: if passed, only show apps with a matching `cmd` :param bool embed_tasks: embed tasks in result :param bool embed_counts: embed all task counts :param bool embed_deployments: embed all deployment identifier :param bool embed_readiness: embed all rea...
Get a single app. :param str app_id: application ID :param bool embed_tasks: embed tasks in result :param bool embed_counts: embed all task counts :param bool embed_deployments: embed all deployment identifier :param bool embed_readiness: embed all readiness check results ...
Update an app. Applies writable settings in `app` to `app_id` Note: this method can not be used to rename apps. :param str app_id: target application ID :param app: application settings :type app: :class:`marathon.models.app.MarathonApp` :param bool force: apply even if...
Update multiple apps. Applies writable settings in elements of apps either by upgrading existing ones or creating new ones :param apps: sequence of application settings :param bool force: apply even if a deployment is in progress :param bool minimal: ignore nulls and empty collections ...
Roll an app back to a previous version. :param str app_id: application ID :param str version: application version :param bool force: apply even if a deployment is in progress :returns: a dict containing the deployment id and version :rtype: dict def rollback_app(self, app_id, ...
Stop and destroy an app. :param str app_id: application ID :param bool force: apply even if a deployment is in progress :returns: a dict containing the deployment id and version :rtype: dict def delete_app(self, app_id, force=False): """Stop and destroy an app. :param...
Scale an app. Scale an app to a target number of instances (with `instances`), or scale the number of instances up or down by some delta (`delta`). If the resulting number of instances would be negative, desired instances will be set to zero. If both `instances` and `delta` are passed,...
Create and start a group. :param :class:`marathon.models.group.MarathonGroup` group: the group to create :returns: success :rtype: dict containing the version ID def create_group(self, group): """Create and start a group. :param :class:`marathon.models.group.MarathonGroup` gr...
List all groups. :param kwargs: arbitrary search filters :returns: list of groups :rtype: list[:class:`marathon.models.group.MarathonGroup`] def list_groups(self, **kwargs): """List all groups. :param kwargs: arbitrary search filters :returns: list of groups ...
Get a single group. :param str group_id: group ID :returns: group :rtype: :class:`marathon.models.group.MarathonGroup` def get_group(self, group_id): """Get a single group. :param str group_id: group ID :returns: group :rtype: :class:`marathon.models.group.Ma...
Update a group. Applies writable settings in `group` to `group_id` Note: this method can not be used to rename groups. :param str group_id: target group ID :param group: group settings :type group: :class:`marathon.models.group.MarathonGroup` :param bool force: apply ev...
Roll a group back to a previous version. :param str group_id: group ID :param str version: group version :param bool force: apply even if a deployment is in progress :returns: a dict containing the deployment id and version :rtype: dict def rollback_group(self, group_id, versi...
Stop and destroy a group. :param str group_id: group ID :param bool force: apply even if a deployment is in progress :returns: a dict containing the deleted version :rtype: dict def delete_group(self, group_id, force=False): """Stop and destroy a group. :param str gro...
Scale a group by a factor. :param str group_id: group ID :param int scale_by: factor to scale by :returns: a dict containing the deployment id and version :rtype: dict def scale_group(self, group_id, scale_by): """Scale a group by a factor. :param str group_id: group ...
List running tasks, optionally filtered by app_id. :param str app_id: if passed, only show tasks for this application :param kwargs: arbitrary search filters :returns: list of tasks :rtype: list[:class:`marathon.models.task.MarathonTask`] def list_tasks(self, app_id=None, **kwargs): ...
Kill a list of given tasks. :param list[str] task_ids: tasks to kill :param bool scale: if true, scale down the app by the number of tasks killed :param bool force: if true, ignore any current running deployments :return: True on success :rtype: bool def kill_given_tasks(self,...
Kill all tasks belonging to app. :param str app_id: application ID :param bool scale: if true, scale down the app by the number of tasks killed :param str host: if provided, only terminate tasks on this Mesos slave :param int batch_size: if non-zero, terminate tasks in groups of this si...
Kill a task. :param str app_id: application ID :param str task_id: the task to kill :param bool scale: if true, scale down the app by one if the task exists :returns: the killed task :rtype: :class:`marathon.models.task.MarathonTask` def kill_task(self, app_id, task_id, scale=...
List the versions of an app. :param str app_id: application ID :returns: list of versions :rtype: list[str] def list_versions(self, app_id): """List the versions of an app. :param str app_id: application ID :returns: list of versions :rtype: list[str] ...
Get the configuration of an app at a specific version. :param str app_id: application ID :param str version: application version :return: application configuration :rtype: :class:`marathon.models.app.MarathonApp` def get_version(self, app_id, version): """Get the configuration...
Register a callback URL as an event subscriber. :param str url: callback URL :returns: the created event subscription :rtype: dict def create_event_subscription(self, url): """Register a callback URL as an event subscriber. :param str url: callback URL :returns: the ...
Deregister a callback URL as an event subscriber. :param str url: callback URL :returns: the deleted event subscription :rtype: dict def delete_event_subscription(self, url): """Deregister a callback URL as an event subscriber. :param str url: callback URL :returns: ...
List all running deployments. :returns: list of deployments :rtype: list[:class:`marathon.models.deployment.MarathonDeployment`] def list_deployments(self): """List all running deployments. :returns: list of deployments :rtype: list[:class:`marathon.models.deployment.MarathonD...
List all the tasks queued up or waiting to be scheduled. :returns: list of queue items :rtype: list[:class:`marathon.models.queue.MarathonQueueItem`] def list_queue(self, embed_last_unused_offers=False): """List all the tasks queued up or waiting to be scheduled. :returns: list of que...
Cancel a deployment. :param str deployment_id: deployment id :param bool force: if true, don't create a rollback deployment to restore the previous configuration :returns: a dict containing the deployment id and version (empty dict if force=True) :rtype: dict def delete_deployment(sel...
Polls event bus using /v2/events :param bool raw: if true, yield raw event text, else yield MarathonEvent object :param event_types: a list of event types to consume :type event_types: list[type] or list[str] :returns: iterator with events :rtype: iterator def event_stream(self...
Checks if a path is a correct format that Marathon expects. Raises ValueError if not valid. :param str path: The app id. :rtype: str def assert_valid_path(path): """Checks if a path is a correct format that Marathon expects. Raises ValueError if not valid. :param str path: The app id. :rtype: s...
Checks if an id is the correct format that Marathon expects. Raises ValueError if not valid. :param str id: App or group id. :rtype: str def assert_valid_id(id): """Checks if an id is the correct format that Marathon expects. Raises ValueError if not valid. :param str id: App or group id. :rtyp...
Construct a JSON-friendly representation of the object. :param bool minimal: Construct a minimal representation of the object (ignore nulls and empty collections) :rtype: dict def json_repr(self, minimal=False): """Construct a JSON-friendly representation of the object. :param bool m...
Construct an object from a parsed response. :param dict attributes: object attributes from parsed response def from_json(cls, attributes): """Construct an object from a parsed response. :param dict attributes: object attributes from parsed response """ return cls(**{to_snake_c...
Encode an object as a JSON string. :param bool minimal: Construct a minimal representation of the object (ignore nulls and empty collections) :rtype: str def to_json(self, minimal=True): """Encode an object as a JSON string. :param bool minimal: Construct a minimal representation of ...
Construct a JSON-friendly representation of the object. :param bool minimal: [ignored] :rtype: list def json_repr(self, minimal=False): """Construct a JSON-friendly representation of the object. :param bool minimal: [ignored] :rtype: list """ if self.value: ...
Construct a MarathonConstraint from a parsed response. :param dict attributes: object attributes from parsed response :rtype: :class:`MarathonConstraint` def from_json(cls, obj): """Construct a MarathonConstraint from a parsed response. :param dict attributes: object attributes from ...
:param str constraint: The string representation of a constraint :rtype: :class:`MarathonConstraint` def from_string(cls, constraint): """ :param str constraint: The string representation of a constraint :rtype: :class:`MarathonConstraint` """ obj = constraint.split(':...
Construct a list of MarathonEndpoints from a list of tasks. :param list[:class:`marathon.models.MarathonTask`] tasks: list of tasks to parse :rtype: list[:class:`MarathonEndpoint`] def from_tasks(cls, tasks): """Construct a list of MarathonEndpoints from a list of tasks. :param list[...
Convert newlines into U+23EC characters, followed by an actual newline and then a tree prefix so as to position the remaining text under the previous line. def _format_newlines(prefix, formatted_node, options): """ Convert newlines into U+23EC characters, followed by an actual newline and then a tr...
Gets a band. Gets a band with specified tag. If no tag is specified, the request will fail. If the tag is invalid, a brawlstars.InvalidTag will be raised. If the data is missing, a ValueError will be raised. If the connection times out, a brawlstars.Timeout will be raised. If th...
Gets a player. Gets a player with specified tag. If no tag is specified, the request will fail. If the tag is invalid, a brawlstars.InvalidTag will be raised. If the data is missing, a ValueError will be raised. If the connection times out, a brawlstars.Timeout will be raised. I...
Gets a band. Gets a band with specified tag. If no tag is specified, the request will fail. If the tag is invalid, a brawlstars.InvalidTag will be raised. If the data is missing, a ValueError will be raised. If the connection times out, a brawlstars.Timeout will be raised. If th...
Function allowing lazy importing of a module into the namespace. A lazy module object is created, registered in `sys.modules`, and returned. This is a hollow module; actual loading, and `ImportErrors` if not found, are delayed until an attempt is made to access attributes of the lazy module. A han...
Performs lazy importing of one or more callables. :func:`lazy_callable` creates functions that are thin wrappers that pass any and all arguments straight to the target module's callables. These can be functions or classes. The full loading of that module is only actually triggered when the returned laz...
Ensures that a module, and its parents, are properly loaded def _load_module(module): """Ensures that a module, and its parents, are properly loaded """ modclass = type(module) # We only take care of our own LazyModule instances if not issubclass(modclass, LazyModule): raise TypeError("Pas...
Like dict.setdefault but sets the default value also if None is present. def _setdef(argdict, name, defaultvalue): """Like dict.setdefault but sets the default value also if None is present. """ if not name in argdict or argdict[name] is None: argdict[name] = defaultvalue return argdict[name]
Removes all lazy behavior from a module's class, for loading. Also removes all module attributes listed under the module's class deletion dictionaries. Deletion dictionaries are class attributes with names specified in `_DELETION_DICT`. Parameters ---------- module: LazyModule Returns ...
Resets a module's lazy state from cached data. def _reset_lazymodule(module, cls_attrs): """Resets a module's lazy state from cached data. """ modclass = type(module) del modclass.__getattribute__ del modclass.__setattr__ try: del modclass._LOADING except AttributeError: pa...
A decorator that defines __unicode__ and __str__ methods under Python 2. Under Python 3 it does nothing. To support Python 2 and 3 with a single code base, define a __str__ method returning text and apply this decorator to the class. def python_2_unicode_compatible(klass): """ A decorator that def...
Compute timestamp from a datetime object that could be timezone aware or unaware. def timestamp_from_datetime(dt): """ Compute timestamp from a datetime object that could be timezone aware or unaware. """ try: utc_dt = dt.astimezone(pytz.utc) except ValueError: utc_dt = dt.r...
Similar to smart_bytes, except that lazy instances are resolved to strings, rather than kept as lazy objects. If strings_only is True, don't convert (some) non-string-like objects. def force_bytes(s, encoding='utf-8', strings_only=False, errors='strict'): """ Similar to smart_bytes, except that lazy i...
Wrap a function so that results for any argument tuple are stored in 'cache'. Note that the args to the function must be usable as dictionary keys. Only the first num_args are considered when creating the key. def memoize(func, cache, num_args): """ Wrap a function so that results for any argument ...
Obtained from https://github.com/dcramer/reraise/blob/master/src/reraise.py >>> try: >>> do_something_crazy() >>> except Exception: >>> reraise_as(UnhandledException) def reraise_as(new_exception_or_type): """ Obtained from https://github.com/dcramer/reraise/blob/master/src/reraise.py ...
Remove sensitive information from msg. def hide_auth(msg): """Remove sensitive information from msg.""" for pattern, repl in RE_HIDE_AUTH: msg = pattern.sub(repl, msg) return msg
Prepare the HTTP handler, URL, and HTTP headers for all subsequent requests def init(self): """Prepare the HTTP handler, URL, and HTTP headers for all subsequent requests""" self.debug('Initializing %r', self) proto = self.server.split('://')[0] if proto == 'https': if hasa...
Convert unix timestamp to human readable date/time string def timestamp_to_datetime(cls, dt, dt_format=DATETIME_FORMAT): """Convert unix timestamp to human readable date/time string""" return cls.convert_datetime(cls.get_datetime(dt), dt_format=dt_format)
Calculate delta between current time and datetime and return a human readable form of the delta object def get_age(dt): """Calculate delta between current time and datetime and return a human readable form of the delta object""" delta = datetime.now() - dt days = delta.days hours, rem =...
Return JSON object expected by the Zabbix API def json_obj(self, method, params=None, auth=True): """Return JSON object expected by the Zabbix API""" if params is None: params = {} obj = { 'jsonrpc': '2.0', 'method': method, 'params': params, ...
Perform one HTTP request to Zabbix API def do_request(self, json_obj): """Perform one HTTP request to Zabbix API""" self.debug('Request: url="%s" headers=%s', self._api_url, self._http_headers) self.debug('Request: body=%s', json_obj) self.r_query.append(json_obj) request = url...
Perform a user.login API request def login(self, user=None, password=None, save=True): """Perform a user.login API request""" if user and password: if save: self.__username = user self.__password = password elif self.__username and self.__password: ...
Perform a re-login def relogin(self): """Perform a re-login""" try: self.__auth = None # reset auth before relogin self.login() except ZabbixAPIException as e: self.log(ERROR, 'Zabbix API relogin error (%s)', e) self.__auth = None # logged_in() ...
Perform a re-login if not signed in or raise an exception def check_auth(self): """Perform a re-login if not signed in or raise an exception""" if not self.logged_in: if self.relogin_interval and self.last_login and (time() - self.last_login) > self.relogin_interval: self.lo...
Check authentication and perform actual API request and relogin if needed def call(self, method, params=None): """Check authentication and perform actual API request and relogin if needed""" start_time = time() self.check_auth() self.log(INFO, '[%s-%05d] Calling Zabbix API method "%s"',...
download function to download parallely def download_parallel(url, directory, idx, min_file_size = 0, max_file_size = -1, no_redirects = False, pos = 0, mode = 's'): """ download function to download parallely """ global main_it global exit_flag global total_chunks global file_name global i_max file_na...
called when paralled downloading is true def download_parallel_gui(root, urls, directory, min_file_size, max_file_size, no_redirects): """ called when paralled downloading is true """ global parallel # create directory to save files if not os.path.exists(directory): os.makedirs(directory) parallel = True ap...
called when user wants serial downloading def download_series_gui(frame, urls, directory, min_file_size, max_file_size, no_redirects): """ called when user wants serial downloading """ # create directory to save files if not os.path.exists(directory): os.makedirs(directory) app = progress_class(frame, urls, d...
function called when thread is started def run(self): """ function called when thread is started """ global parallel if parallel: download_parallel(self.url, self.directory, self.idx, self.min_file_size, self.max_file_size, self.no_redirects) else: download(self.url, self.directory, self.i...
function to initialize thread for downloading def start(self): """ function to initialize thread for downloading """ global parallel for self.i in range(0, self.length): if parallel: self.thread.append(myThread(self.url[ self.i ], self.directory, self.i, self.min_file_size, self.max_file_s...
reading bytes; update progress bar after 1 ms def read_bytes(self): """ reading bytes; update progress bar after 1 ms """ global exit_flag for self.i in range(0, self.length) : self.bytes[self.i] = i_max[self.i] self.maxbytes[self.i] = total_chunks[self.i] self.progress[self.i]["maximum"] = total_c...
Add this type to our collection, if needed. def declare_type(self, declared_type): # type: (TypeDef) -> TypeDef """Add this type to our collection, if needed.""" if declared_type not in self.collected_types: self.collected_types[declared_type.name] = declared_type return declared_t...
Instantiate the metaschema. def get_metaschema(): # type: () -> Tuple[Names, List[Dict[Text, Any]], Loader] """Instantiate the metaschema.""" loader = ref_resolver.Loader({ "Any": "https://w3id.org/cwl/salad#Any", "ArraySchema": "https://w3id.org/cwl/salad#ArraySchema", "Array_symbol":...
Collect the provided namespaces, checking for conflicts. def add_namespaces(metadata, namespaces): # type: (Mapping[Text, Any], MutableMapping[Text, Text]) -> None """Collect the provided namespaces, checking for conflicts.""" for key, value in metadata.items(): if key not in namespaces: ...
Walk through the metadata object, collecting namespace declarations. def collect_namespaces(metadata): # type: (Mapping[Text, Any]) -> Dict[Text, Text] """Walk through the metadata object, collecting namespace declarations.""" namespaces = {} # type: Dict[Text, Text] if "$import_metadata" in metadata:...
Load a schema that can be used to validate documents using load_and_validate. return: document_loader, avsc_names, schema_metadata, metaschema_loader def load_schema(schema_ref, # type: Union[CommentedMap, CommentedSeq, Text] cache=None # type: Dict ): # type: (...) -> Tuple...
Load a document and validate it with the provided schema. return data, metadata def load_and_validate(document_loader, # type: Loader avsc_names, # type: Names document, # type: Union[CommentedMap, Text] ...
Validate a document using the provided schema. def validate_doc(schema_names, # type: Names doc, # type: Union[Dict[Text, Any], List[Dict[Text, Any]], Text, None] loader, # type: Loader strict, # type: bool strict_foreign_prop...
Calculate a reproducible name for anonymous types. def get_anon_name(rec): # type: (MutableMapping[Text, Any]) -> Text """Calculate a reproducible name for anonymous types.""" if "name" in rec: return rec["name"] anon_name = "" if rec['type'] in ('enum', 'https://w3id.org/cwl/salad#enum'): ...
Go through and replace types in the 'spec' mapping def replace_type(items, spec, loader, found, find_embeds=True, deepen=True): # type: (Any, Dict[Text, Any], Loader, Set[Text], bool, bool) -> Any """ Go through and replace types in the 'spec' mapping""" if isinstance(items, MutableMapping): # rec...