INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Edit a job. :param resource: :class:`jobs.Job <jobs.Job>` object :return: :class:`jobs.Job <jobs.Job>` object :rtype: jobs.Job
def edit(self, resource): """Edit a job. :param resource: :class:`jobs.Job <jobs.Job>` object :return: :class:`jobs.Job <jobs.Job>` object :rtype: jobs.Job """ schema = JobSchema(exclude=('id', 'status', 'options', 'package_name', 'config_name', 'device_name', 'result_id...
Launch a new job. :param resource: :class:`jobs.Job <jobs.Job>` object :return: :class:`jobs.Job <jobs.Job>` object :rtype: jobs.Job
def launch(self, resource): """Launch a new job. :param resource: :class:`jobs.Job <jobs.Job>` object :return: :class:`jobs.Job <jobs.Job>` object :rtype: jobs.Job """ schema = JobSchema(exclude=('id', 'status', 'package_name', 'config_name', 'device_name', 'result_id', ...
Bulk launch a set of jobs. :param jobs: :class:`jobs.Job <jobs.Job>` list :param filter: (optional) Filters to apply as a string list. :param all: (optional) Apply to all if bool `True`.
def bulk_launch(self, jobs=None, filter=None, all=False): # pylint: disable=redefined-builtin """Bulk launch a set of jobs. :param jobs: :class:`jobs.Job <jobs.Job>` list :param filter: (optional) Filters to apply as a string list. :param all: (optional) Apply to all if bool `True`. ...
G square test for a binary data. Args: dm: the data matrix to be used (as a numpy.ndarray). x: the first node (as an integer). y: the second node (as an integer). s: the set of neibouring nodes of x and y (as a set()). Returns: p_val: the p-value of conditional independ...
def g_square_bin(dm, x, y, s): """G square test for a binary data. Args: dm: the data matrix to be used (as a numpy.ndarray). x: the first node (as an integer). y: the second node (as an integer). s: the set of neibouring nodes of x and y (as a set()). Returns: p_va...
Get a highlight. :param id: Result ID as an int. :param seq: TestResult sequence ID as an int. :param line: Line number in TestResult's logfile as an int. :return: :class:`highlights.Highlight <highlights.Highlight>` object
def get(self, id, seq, line): # pylint: disable=invalid-name,redefined-builtin """Get a highlight. :param id: Result ID as an int. :param seq: TestResult sequence ID as an int. :param line: Line number in TestResult's logfile as an int. :return: :class:`highlights.Highlight <hig...
Create or edit a highlight. :param id: Result ID as an int. :param seq: TestResult sequence ID as an int. :param resource: :class:`highlights.Highlight <highlights.Highlight>` object :return: :class:`highlights.Highlight <highlights.Highlight>` object :rtype: highlights.Highligh...
def create_or_edit(self, id, seq, resource): # pylint: disable=invalid-name,redefined-builtin """Create or edit a highlight. :param id: Result ID as an int. :param seq: TestResult sequence ID as an int. :param resource: :class:`highlights.Highlight <highlights.Highlight>` object ...
Create a highlight. :param id: Result ID as an int. :param seq: TestResult sequence ID as an int. :param resource: :class:`highlights.Highlight <highlights.Highlight>` object :return: :class:`highlights.Highlight <highlights.Highlight>` object :rtype: highlights.Highlight
def create(self, id, seq, resource): # pylint: disable=invalid-name,redefined-builtin """Create a highlight. :param id: Result ID as an int. :param seq: TestResult sequence ID as an int. :param resource: :class:`highlights.Highlight <highlights.Highlight>` object :return: :class...
Edit a highlight. :param id: Result ID as an int. :param seq: TestResult sequence ID as an int. :param resource: :class:`highlights.Highlight <highlights.Highlight>` object :return: :class:`highlights.Highlight <highlights.Highlight>` object :rtype: highlights.Highlight
def edit(self, id, seq, resource): # pylint: disable=invalid-name,redefined-builtin """Edit a highlight. :param id: Result ID as an int. :param seq: TestResult sequence ID as an int. :param resource: :class:`highlights.Highlight <highlights.Highlight>` object :return: :class:`hi...
Delete a highlight. :param id: Result ID as an int. :param seq: TestResult sequence ID as an int. :param line: Line number in TestResult's logfile as an int.
def delete(self, id, seq, line): # pylint: disable=invalid-name,redefined-builtin """Delete a highlight. :param id: Result ID as an int. :param seq: TestResult sequence ID as an int. :param line: Line number in TestResult's logfile as an int. """ return self.service.dele...
Setup blueprint.
def post_ext_init(state): """Setup blueprint.""" app = state.app app.config.setdefault( 'OAUTHCLIENT_SITENAME', app.config.get('THEME_SITENAME', 'Invenio')) app.config.setdefault( 'OAUTHCLIENT_BASE_TEMPLATE', app.config.get('BASE_TEMPLATE', 'inveni...
Send user to remote application for authentication.
def login(remote_app): """Send user to remote application for authentication.""" oauth = current_app.extensions['oauthlib.client'] if remote_app not in oauth.remote_apps: return abort(404) # Get redirect target in safe manner. next_param = get_safe_redirect_target(arg='next') # Redire...
Authorized handler callback.
def authorized(remote_app=None): """Authorized handler callback.""" if remote_app not in current_oauthclient.handlers: return abort(404) state_token = request.args.get('state') # Verify state parameter try: assert state_token # Checks authenticity and integrity of state and...
Extra signup step.
def signup(remote_app): """Extra signup step.""" if remote_app not in current_oauthclient.signup_handlers: return abort(404) res = current_oauthclient.signup_handlers[remote_app]['view']() return abort(404) if res is None else res
Disconnect user from remote application. Removes application as well as associated information.
def disconnect(remote_app): """Disconnect user from remote application. Removes application as well as associated information. """ if remote_app not in current_oauthclient.disconnect_handlers: return abort(404) ret = current_oauthclient.disconnect_handlers[remote_app]() db.session.comm...
Returns the checksum in bytes for an address in bytes
def address_checksum(address): """ Returns the checksum in bytes for an address in bytes """ address_bytes = address h = blake2b(digest_size=5) h.update(address_bytes) checksum = bytearray(h.digest()) checksum.reverse() return checksum
Generates a deterministic keypair from `seed` based on `index` :param seed: bytes value of seed :type seed: bytes :param index: offset from seed :type index: int :return: dict of the form: { 'private': private_key 'public': public_key }
def keypair_from_seed(seed, index=0): """ Generates a deterministic keypair from `seed` based on `index` :param seed: bytes value of seed :type seed: bytes :param index: offset from seed :type index: int :return: dict of the form: { 'private': private_key 'public': public_...
Verifies `signature` is correct for a `message` signed with `public_key` :param message: message to check :type message: bytes :param signature: signature to check :type signature: bytes :param public_key: public_key to check :type public_key: bytes :return: True if valid, False otherwis...
def verify_signature(message, signature, public_key): """ Verifies `signature` is correct for a `message` signed with `public_key` :param message: message to check :type message: bytes :param signature: signature to check :type signature: bytes :param public_key: public_key to check :...
Signs a `message` using `private_key` and `public_key` .. warning:: Not safe to use with secret keys or secret data. See module docstring. This function should be used for testing only. :param message: the message to sign :type message: bytes :param private_key: private key used to ...
def sign_message(message, private_key, public_key=None): """ Signs a `message` using `private_key` and `public_key` .. warning:: Not safe to use with secret keys or secret data. See module docstring. This function should be used for testing only. :param message: the message to sign ...
Check the CDRouter Support Lounge for eligible upgrades using your Support Lounge email & password. :param email: CDRouter Support Lounge email as a string. :param password: CDRouter Support Lounge password as a string. :return: :class:`system.Release <system.Release>` object :r...
def check_for_lounge_upgrade(self, email, password): """Check the CDRouter Support Lounge for eligible upgrades using your Support Lounge email & password. :param email: CDRouter Support Lounge email as a string. :param password: CDRouter Support Lounge password as a string. :re...
Download & install an upgrade from the CDRouter Support Lounge using your Support Lounge email & password. Please note that any running tests will be stopped. :param email: CDRouter Support Lounge email as a string. :param password: CDRouter Support Lounge password as a string. ...
def lounge_upgrade(self, email, password, release_id): """Download & install an upgrade from the CDRouter Support Lounge using your Support Lounge email & password. Please note that any running tests will be stopped. :param email: CDRouter Support Lounge email as a string. :para...
Download & install a license for your CDRouter system from the CDRouter Support Lounge. :return: :class:`system.Upgrade <system.Upgrade>` object :rtype: system.Upgrade
def lounge_update_license(self): """Download & install a license for your CDRouter system from the CDRouter Support Lounge. :return: :class:`system.Upgrade <system.Upgrade>` object :rtype: system.Upgrade """ schema = UpgradeSchema() resp = self.service.post(self....
Update the license on your CDRouter system manually by uploading a .lic license from the CDRouter Support Lounge. :param fd: File-like object to upload. :param filename: (optional) Filename to use for license as string. :return: :class:`system.Upgrade <system.Upgrade>` object :r...
def manual_update_license(self, fd, filename='cdrouter.lic'): """Update the license on your CDRouter system manually by uploading a .lic license from the CDRouter Support Lounge. :param fd: File-like object to upload. :param filename: (optional) Filename to use for license as string. ...
Get system disk space usage. :return: :class:`system.Space <system.Space>` object :rtype: system.Space
def space(self): """Get system disk space usage. :return: :class:`system.Space <system.Space>` object :rtype: system.Space """ schema = SpaceSchema() resp = self.service.get(self.base+'space/') return self.service.decode(schema, resp)
Get system interfaces. :param addresses: (optional) If bool `True`, include interface addresses. :return: :class:`system.Interface <system.Interface>` list
def interfaces(self, addresses=False): """Get system interfaces. :param addresses: (optional) If bool `True`, include interface addresses. :return: :class:`system.Interface <system.Interface>` list """ schema = InterfaceSchema() resp = self.service.get(self.base+'interfa...
Get preferences from /usr/cdrouter-data/etc/config.yml. :return: :class:`system.Preferences <system.Preferences>` object :rtype: system.Preferences
def get_preferences(self): """Get preferences from /usr/cdrouter-data/etc/config.yml. :return: :class:`system.Preferences <system.Preferences>` object :rtype: system.Preferences """ schema = PreferencesSchema() resp = self.service.get(self.base+'preferences/') re...
Edit preferences in /usr/cdrouter-data/etc/config.yml. :param resource: :class:`system.Preferences <system.Preferences>` object :return: :class:`system.Preferences <system.Preferences>` object :rtype: system.Preferences
def edit_preferences(self, resource): """Edit preferences in /usr/cdrouter-data/etc/config.yml. :param resource: :class:`system.Preferences <system.Preferences>` object :return: :class:`system.Preferences <system.Preferences>` object :rtype: system.Preferences """ schema...
Save fields value, only for non-m2m fields.
def _set_original_fields(instance): """ Save fields value, only for non-m2m fields. """ original_fields = {} def _set_original_field(instance, field): if instance.pk is None: original_fields[field] = None else: if isinstance(instance._meta.get_field(field), F...
Check if some tracked fields have changed
def _has_changed(instance): """ Check if some tracked fields have changed """ for field, value in instance._original_fields.items(): if field != 'pk' and \ not isinstance(instance._meta.get_field(field), ManyToManyField): try: if field in getattr(instance, ...
Check if some related tracked fields have changed
def _has_changed_related(instance): """ Check if some related tracked fields have changed """ tracked_related_fields = getattr( instance, '_tracked_related_fields', {} ).keys() for field, value in instance._original_fields.items(): if field != 'pk' and \ ...
Create a new event, getting the use if django-cuser is available.
def _create_event(instance, action): """ Create a new event, getting the use if django-cuser is available. """ user = None user_repr = repr(user) if CUSER: user = CuserMiddleware.get_user() user_repr = repr(user) if user is not None and user.is_anonymous: user...
Create a TrackedFieldModification for the instance. :param event: The TrackingEvent on which to add TrackingField :param instance: The instance on which the field is :param field: The field name to track :param fieldname: The displayed name for the field. Default to field.
def _create_tracked_field(event, instance, field, fieldname=None): """ Create a TrackedFieldModification for the instance. :param event: The TrackingEvent on which to add TrackingField :param instance: The instance on which the field is :param field: The field name to track :param fieldname: Th...
Create a TrackingEvent and TrackedFieldModification for a CREATE event.
def _create_create_tracking_event(instance): """ Create a TrackingEvent and TrackedFieldModification for a CREATE event. """ event = _create_event(instance, CREATE) for field in instance._tracked_fields: if not isinstance(instance._meta.get_field(field), ManyToManyField): _create...
Create a TrackingEvent and TrackedFieldModification for an UPDATE event.
def _create_update_tracking_event(instance): """ Create a TrackingEvent and TrackedFieldModification for an UPDATE event. """ event = _create_event(instance, UPDATE) for field in instance._tracked_fields: if not isinstance(instance._meta.get_field(field), ManyToManyField): try: ...
Create a TrackingEvent and TrackedFieldModification for an UPDATE event for each related model.
def _create_update_tracking_related_event(instance): """ Create a TrackingEvent and TrackedFieldModification for an UPDATE event for each related model. """ events = {} # Create a dict mapping related model field to modified fields for field, related_fields in instance._tracked_related_field...
Get the field name from a model and a sender from m2m_changed signal.
def _get_m2m_field(model, sender): """ Get the field name from a model and a sender from m2m_changed signal. """ for field in getattr(model, '_tracked_fields', []): if isinstance(model._meta.get_field(field), ManyToManyField): if getattr(model, field).through == sender: ...
Create the ``TrackedEvent`` and it's related ``TrackedFieldModification`` for a m2m modification. The first thing needed is to get the m2m field on the object being tracked. The current related objects are then taken (``old_value``). The new value is calculated in function of ``action`` (``new_value``)....
def _create_tracked_event_m2m(model, instance, sender, objects, action): """ Create the ``TrackedEvent`` and it's related ``TrackedFieldModification`` for a m2m modification. The first thing needed is to get the m2m field on the object being tracked. The current related objects are then taken (``old...
Post save, detect creation or changes and log them. We need post_save to have the object for a create.
def tracking_save(sender, instance, raw, using, update_fields, **kwargs): """ Post save, detect creation or changes and log them. We need post_save to have the object for a create. """ if _has_changed(instance): if instance._original_fields['pk'] is None: # Create _cr...
m2m_changed callback. The idea is to get the model and the instance of the object being tracked, and the different objects being added/removed. It is then send to the ``_create_tracked_field_m2m`` method to extract the proper attribute for the TrackedFieldModification.
def tracking_m2m( sender, instance, action, reverse, model, pk_set, using, **kwargs ): """ m2m_changed callback. The idea is to get the model and the instance of the object being tracked, and the different objects being added/removed. It is then send to the ``_create_tracked_field_m2m`` meth...
Perform additional setup after user have been logged in. :param remote: The remote application. :param token: The token value. :param resp: The response.
def account_setup(remote, token, resp): """Perform additional setup after user have been logged in. :param remote: The remote application. :param token: The token value. :param resp: The response. """ with db.session.begin_nested(): # Retrieve ORCID from response. orcid = resp.g...
:yield: The next LogEntry from the REST API :raise: StopIteration when there are no more log entries to show, please note that if you call this again at a later time the REST API could have different results and more data could be returned
def log_entry_generator(log_instance): """ :yield: The next LogEntry from the REST API :raise: StopIteration when there are no more log entries to show, please note that if you call this again at a later time the REST API could have different results and more data could be returned ...
This is a "constructor" for the LogEntry class. :param entry_dict: A dict we get from the REST API :return: An instance of LogEntry.
def from_entry_dict(cls, entry_dict): """ This is a "constructor" for the LogEntry class. :param entry_dict: A dict we get from the REST API :return: An instance of LogEntry. """ # Debug helper # https://circleci.com/gh/andresriancho/w3af-api-docker/30 tr...
:yield: Log entries starting from :start_id: and ending 200 entries after. In most cases easier to call than the paginate one because there is no need to keep track of the already read entries in a specific page.
def get_by_start_id(self, start_id): """ :yield: Log entries starting from :start_id: and ending 200 entries after. In most cases easier to call than the paginate one because there is no need to keep track of the already read entries in a specific page. ...
Get a list of captures. :param id: Result ID as an int. :param seq: TestResult sequence ID as an int. :return: :class:`captures.Capture <captures.Capture>` list
def list(self, id, seq): # pylint: disable=invalid-name,redefined-builtin """Get a list of captures. :param id: Result ID as an int. :param seq: TestResult sequence ID as an int. :return: :class:`captures.Capture <captures.Capture>` list """ schema = CaptureSchema(exclud...
Get a capture. :param id: Result ID as an int. :param seq: TestResult sequence ID as an int. :param intf: Interface name as string. :return: :class:`captures.Capture <captures.Capture>` object :rtype: captures.Capture
def get(self, id, seq, intf): # pylint: disable=invalid-name,redefined-builtin """Get a capture. :param id: Result ID as an int. :param seq: TestResult sequence ID as an int. :param intf: Interface name as string. :return: :class:`captures.Capture <captures.Capture>` object ...
Download a capture as a PCAP file. :param id: Result ID as an int. :param seq: TestResult sequence ID as an int. :param intf: Interface name as string. :param inline: (optional) Use inline version of capture file. :rtype: tuple `(io.BytesIO, 'filename')`
def download(self, id, seq, intf, inline=False): # pylint: disable=invalid-name,redefined-builtin """Download a capture as a PCAP file. :param id: Result ID as an int. :param seq: TestResult sequence ID as an int. :param intf: Interface name as string. :param inline: (optional) ...
Get a capture's summary. :param id: Result ID as an int. :param seq: TestResult sequence ID as an int. :param intf: Interface name as string. :param filter: (optional) PCAP filter to apply as string. :param inline: (optional) Use inline version of capture file. :return: ...
def summary(self, id, seq, intf, filter=None, inline=False): # pylint: disable=invalid-name,redefined-builtin """Get a capture's summary. :param id: Result ID as an int. :param seq: TestResult sequence ID as an int. :param intf: Interface name as string. :param filter: (optional...
Get a capture's decode. :param id: Result ID as an int. :param seq: TestResult sequence ID as an int. :param intf: Interface name as string. :param filter: (optional) PCAP filter to apply as string. :param frame: (optional) Frame number to decode. :param inline: (optiona...
def decode(self, id, seq, intf, filter=None, frame=None, inline=False): # pylint: disable=invalid-name,redefined-builtin """Get a capture's decode. :param id: Result ID as an int. :param seq: TestResult sequence ID as an int. :param intf: Interface name as string. :param filter:...
Send a capture to a CloudShark Appliance. Both cloudshark_appliance_url and cloudshark_appliance_token must be properly configured via system preferences. :param id: Result ID as an int. :param seq: TestResult sequence ID as an int. :param intf: Interface name as string. ...
def send_to_cloudshark(self, id, seq, intf, inline=False): # pylint: disable=invalid-name,redefined-builtin """Send a capture to a CloudShark Appliance. Both cloudshark_appliance_url and cloudshark_appliance_token must be properly configured via system preferences. :param id: Result ID ...
Check for errors in the response and return the resulting JSON.
def get_dict_from_response(response): """Check for errors in the response and return the resulting JSON.""" if getattr(response, '_resp') and response._resp.code > 400: raise OAuthResponseError( 'Application mis-configuration in Globus', None, response ) return response....
Get user information from Globus. See the docs here for v2/oauth/userinfo: https://docs.globus.org/api/auth/reference/
def get_user_info(remote): """Get user information from Globus. See the docs here for v2/oauth/userinfo: https://docs.globus.org/api/auth/reference/ """ response = remote.get(GLOBUS_USER_INFO_URL) user_info = get_dict_from_response(response) response.data['username'] = response.data['prefer...
Get the Globus identity for a users given email. A Globus ID is a UUID that can uniquely identify a Globus user. See the docs here for v2/api/identities https://docs.globus.org/api/auth/reference/
def get_user_id(remote, email): """Get the Globus identity for a users given email. A Globus ID is a UUID that can uniquely identify a Globus user. See the docs here for v2/api/identities https://docs.globus.org/api/auth/reference/ """ try: url = '{}?usernames={}'.format(GLOBUS_USER_ID_...
Retrieve remote account information used to find local user. It returns a dictionary with the following structure: .. code-block:: python { 'user': { 'email': '...', 'profile': { 'username': '...', 'full_name': '...',...
def account_info(remote, resp): """Retrieve remote account information used to find local user. It returns a dictionary with the following structure: .. code-block:: python { 'user': { 'email': '...', 'profile': { 'username': '...', ...
Perform additional setup after user have been logged in. :param remote: The remote application. :param token: The token value. :param resp: The response.
def account_setup(remote, token, resp): """Perform additional setup after user have been logged in. :param remote: The remote application. :param token: The token value. :param resp: The response. """ info = get_user_info(remote) user_id = get_user_id(remote, info['preferred_username']) ...
Handle unlinking of remote account. :param remote: The remote application. :returns: The HTML response.
def disconnect_handler(remote, *args, **kwargs): """Handle unlinking of remote account. :param remote: The remote application. :returns: The HTML response. """ if not current_user.is_authenticated: return current_app.login_manager.unauthorized() remote_account = RemoteAccount.get(user_...
Return the signature string of the specified function. >>> def foo(name): pass >>> get_function_signature(foo) 'foo(name)' >>> something = 'Hello' >>> get_function_signature(something) Traceback (most recent call last): ... TypeError: The argument must be a function object: None typ...
def get_function_signature(func): """ Return the signature string of the specified function. >>> def foo(name): pass >>> get_function_signature(foo) 'foo(name)' >>> something = 'Hello' >>> get_function_signature(something) Traceback (most recent call last): ... TypeError: Th...
Acquire a read lock, several threads can hold this type of lock.
def acquire_reader(self): """ Acquire a read lock, several threads can hold this type of lock. """ with self.mutex: while self.rwlock < 0 or self.rwlock == self.max_reader_concurrency or self.writers_waiting: self.readers_ok.wait() self.rwlock += 1
Acquire a write lock, only one thread can hold this lock and only when no read locks are also held.
def acquire_writer(self): """ Acquire a write lock, only one thread can hold this lock and only when no read locks are also held. """ with self.mutex: while self.rwlock != 0: self._writer_wait() self.rwlock = -1
Promote an already acquired read lock to a write lock notice: this function can easily cause a deadlock!!!!!!!!!
def promote(self): """ Promote an already acquired read lock to a write lock notice: this function can easily cause a deadlock!!!!!!!!! """ with self.mutex: self.rwlock -= 1 while self.rwlock != 0: self._writer_wait() self.rwloc...
Get a list of packages. :param filter: (optional) Filters to apply as a string list. :param type: (optional) `union` or `inter` as string. :param sort: (optional) Sort fields to apply as string list. :param limit: (optional) Limit returned list length. :param page: (optional) Pa...
def list(self, filter=None, type=None, sort=None, limit=None, page=None): # pylint: disable=redefined-builtin """Get a list of packages. :param filter: (optional) Filters to apply as a string list. :param type: (optional) `union` or `inter` as string. :param sort: (optional) Sort fields...
Get a package. :param id: Package ID as an int. :return: :class:`packages.Package <packages.Package>` object :rtype: packages.Package
def get(self, id): # pylint: disable=invalid-name,redefined-builtin """Get a package. :param id: Package ID as an int. :return: :class:`packages.Package <packages.Package>` object :rtype: packages.Package """ schema = PackageSchema() resp = self.service.get_id(se...
Create a new package. :param resource: :class:`packages.Package <packages.Package>` object :return: :class:`packages.Package <packages.Package>` object :rtype: packages.Package
def create(self, resource): """Create a new package. :param resource: :class:`packages.Package <packages.Package>` object :return: :class:`packages.Package <packages.Package>` object :rtype: packages.Package """ schema = PackageSchema(exclude=('id', 'created', 'updated',...
Get a list of tests that will be skipped for a package. :param id: Package ID as an int. :return: :class:`packages.Analysis <packages.Analysis>` object :rtype: packages.Analysis
def analyze(self, id): # pylint: disable=invalid-name,redefined-builtin """Get a list of tests that will be skipped for a package. :param id: Package ID as an int. :return: :class:`packages.Analysis <packages.Analysis>` object :rtype: packages.Analysis """ schema = Analy...
Bulk copy a set of packages. :param ids: Int list of package IDs. :return: :class:`packages.Package <packages.Package>` list
def bulk_copy(self, ids): """Bulk copy a set of packages. :param ids: Int list of package IDs. :return: :class:`packages.Package <packages.Package>` list """ schema = PackageSchema() return self.service.bulk_copy(self.base, self.RESOURCE, ids, schema)
Bulk edit a set of packages. :param _fields: :class:`packages.Package <packages.Package>` object :param ids: (optional) Int list of package IDs. :param filter: (optional) String list of filters. :param type: (optional) `union` or `inter` as string. :param all: (optional) Apply t...
def bulk_edit(self, _fields, ids=None, filter=None, type=None, all=False): # pylint: disable=redefined-builtin """Bulk edit a set of packages. :param _fields: :class:`packages.Package <packages.Package>` object :param ids: (optional) Int list of package IDs. :param filter: (optional) St...
Generate strings that are not comments or lines with only whitespace. Purpose: This function is a generator that will read in either a | plain text file of strings(IP list, command list, etc), a | comma separated string of strings, or a list of strings. It | will crop out any comme...
def clean_lines(commands): """ Generate strings that are not comments or lines with only whitespace. Purpose: This function is a generator that will read in either a | plain text file of strings(IP list, command list, etc), a | comma separated string of strings, or a list of strings. It ...
Filter xml based on an xpath expression. Purpose: This function applies an Xpath expression to the XML | supplied by source_xml. Returns a string subtree or | subtrees that match the Xpath expression. It can also return | an xml object if desired. @param source_xml: Plain text...
def xpath(source_xml, xpath_expr, req_format='string'): """ Filter xml based on an xpath expression. Purpose: This function applies an Xpath expression to the XML | supplied by source_xml. Returns a string subtree or | subtrees that match the Xpath expression. It can also return ...
Делает из obj строку `true` или `false`
def lowcase_str_boolean(obj): "Делает из obj строку `true` или `false`" if isinstance(obj, str): if obj not in ["true", "false"]: raise RuntimeError( 'Expecting "true" or "false", got {}'.format(obj)) return obj return str(bool(obj)).lower()
Проверяет и формирует аргументы для запроса
def validate_args(api_key, *, rate="informers", **kwargs): "Проверяет и формирует аргументы для запроса" rate = Rate.validate(rate) headers = {"X-Yandex-API-Key": api_key} url = "https://api.weather.yandex.ru/v1/{}".format(rate) if rate == "informers": params = ARGS_SCHEMA(kwargs) else: ...
Выполняет доступ к API. session - модуль requests или сессия из него api_key - строка ключа доступа к API rate - тариф, может быть `informers` или `forecast` lat, lon - широта и долгота ``` import yandex_weather_api import requests as req yandex_weather_api.get(req, "ЗАМЕНИ_МЕНЯ_КЛЮЧО...
def get(session, api_key, **kwargs): """ Выполняет доступ к API. session - модуль requests или сессия из него api_key - строка ключа доступа к API rate - тариф, может быть `informers` или `forecast` lat, lon - широта и долгота ``` import yandex_weather_api import requests as req ...
Get etcd status. :param timeout: Request timeout in seconds. :type timeout: int :returns: The current etcd cluster status. :rtype: instance of :class:`txaioetcd.Status`
def status(self, timeout=None): """ Get etcd status. :param timeout: Request timeout in seconds. :type timeout: int :returns: The current etcd cluster status. :rtype: instance of :class:`txaioetcd.Status` """ assembler = commons.StatusRequestAssembler(se...
Set the value for the key in the key-value store. Setting a value on a key increments the revision of the key-value store and generates one event in the event history. :param key: key is the key, in bytes, to put into the key-value store. :type key: bytes :...
def set(self, key, value, lease=None, return_previous=None, timeout=None): """ Set the value for the key in the key-value store. Setting a value on a key increments the revision of the key-value store and generates one event in the event history. :param key: key is the ...
Range gets the keys in the range from the key-value store. :param key: key is the first key for the range. If range_end is not given, the request only looks up key. :type key: bytes :param range_end: range_end is the upper bound on the requested range [key, range_end). ...
def get(self, key, range_end=None, count_only=None, keys_only=None, limit=None, max_create_revision=None, min_create_revision=None, min_mod_revision=None, revision=None, serializable=None, ...
Delete value(s) from etcd. :param key: key is the first key to delete in the range. :type key: bytes or instance of :class:`txaioetcd.KeySet` :param return_previous: If enabled, return the deleted key-value pairs :type return_previous: bool or None :param timeout: Request time...
def delete(self, key, return_previous=None, timeout=None): """ Delete value(s) from etcd. :param key: key is the first key to delete in the range. :type key: bytes or instance of :class:`txaioetcd.KeySet` :param return_previous: If enabled, return the deleted key-value pairs ...
Watch one or more keys or key sets and invoke a callback. Watch watches for events happening or that have happened. The entire event history can be watched starting from the last compaction revision. :param keys: Watch these keys / key sets. :type keys: list of bytes or list of instanc...
def watch(self, keys, on_watch, filters=None, start_revision=None, return_previous=None): """ Watch one or more keys or key sets and invoke a callback. Watch watches for events happening or that have happened. The entire event history can be watched starting from the last compaction rev...
Submit a transaction. Processes multiple requests in a single transaction. A transaction increments the revision of the key-value store and generates events with the same revision for every completed request. It is not allowed to modify the same key several times within...
def submit(self, txn, timeout=None): """ Submit a transaction. Processes multiple requests in a single transaction. A transaction increments the revision of the key-value store and generates events with the same revision for every completed request. It is not al...
Creates a lease which expires if the server does not receive a keep alive within a given time to live period. All keys attached to the lease will be expired and deleted if the lease expires. Each expired key generates a delete event in the event history. :param time_to_live: T...
def lease(self, time_to_live, lease_id=None, timeout=None): """ Creates a lease which expires if the server does not receive a keep alive within a given time to live period. All keys attached to the lease will be expired and deleted if the lease expires. Each expired ke...
Get a list of staged (in-progress) imports. :return: :class:`imports.Import <imports.Import>` list
def list(self): """Get a list of staged (in-progress) imports. :return: :class:`imports.Import <imports.Import>` list """ schema = ImportSchema() resp = self.service.list(self.base) return self.service.decode(schema, resp, many=True)
Stage an import from a file upload. :param fd: File-like object to upload. :param filename: (optional) Filename to use for import as string. :return: :class:`imports.Import <imports.Import>` object
def stage_import_from_file(self, fd, filename='upload.gz'): """Stage an import from a file upload. :param fd: File-like object to upload. :param filename: (optional) Filename to use for import as string. :return: :class:`imports.Import <imports.Import>` object """ schema...
Stage an import from a filesystem path. :param filepath: Local filesystem path as string. :return: :class:`imports.Import <imports.Import>` object
def stage_import_from_filesystem(self, filepath): """Stage an import from a filesystem path. :param filepath: Local filesystem path as string. :return: :class:`imports.Import <imports.Import>` object """ schema = ImportSchema() resp = self.service.post(self.base, ...
Stage an import from a URL to another CDRouter system. :param url: URL to import as string. :param token: (optional) API token to use as string (may be required if importing from a CDRouter 10+ system). :param username: (optional) API username to use as string (may be required if importing from...
def stage_import_from_url(self, url, token=None, username=None, password=None, insecure=False): """Stage an import from a URL to another CDRouter system. :param url: URL to import as string. :param token: (optional) API token to use as string (may be required if importing from a CDRouter 10+ sy...
Get a commit request for a staged import. :param id: Staged import ID as an int. :return: :class:`imports.Request <imports.Request>` object :rtype: imports.Request
def get_commit_request(self, id): # pylint: disable=invalid-name,redefined-builtin """Get a commit request for a staged import. :param id: Staged import ID as an int. :return: :class:`imports.Request <imports.Request>` object :rtype: imports.Request """ schema = RequestS...
Commit a staged import. :param id: Staged import ID as an int. :param impreq: :class:`imports.Request <imports.Request>` object :return: :class:`imports.Request <imports.Request>` object :rtype: imports.Request
def commit(self, id, impreq): # pylint: disable=invalid-name,redefined-builtin """Commit a staged import. :param id: Staged import ID as an int. :param impreq: :class:`imports.Request <imports.Request>` object :return: :class:`imports.Request <imports.Request>` object :rtype: im...
Takes a model instance and converts it into a dict.
def model_to_dict(instance, **options): "Takes a model instance and converts it into a dict." options = _defaults(options) attrs = {} if options['prehook']: if isinstance(options['prehook'], collections.Callable): instance = options['prehook'](instance) if instance is N...
Recursively attempts to find ``Model`` and ``QuerySet`` instances to convert them into their representative datastructure per their ``Resource`` (if one exists).
def serialize(self, obj, fields=None, exclude=None, **options): """Recursively attempts to find ``Model`` and ``QuerySet`` instances to convert them into their representative datastructure per their ``Resource`` (if one exists). """ options = _merge({}, self.options, options) ...
Sets the root save directory for saving screenshots. Screenshots will be saved in subdirectories under this directory by browser window size.
def set_save_directory(base, source): """Sets the root save directory for saving screenshots. Screenshots will be saved in subdirectories under this directory by browser window size. """ root = os.path.join(base, source) if not os.path.isdir(root): os.makedirs(root) world.screensho...
Change a user's password. :param id: User ID as an int. :param new: New password as string. :param old: (optional) Old password as string (required if performing action as non-admin). :param change_token: (optional) If bool `True`, also generate a new API token for user. :return...
def change_password(self, id, new, old=None, change_token=True): # pylint: disable=invalid-name,redefined-builtin """Change a user's password. :param id: User ID as an int. :param new: New password as string. :param old: (optional) Old password as string (required if performing action a...
Change a user's token. :param id: User ID as an int. :return: :class:`users.User <users.User>` object :rtype: users.User
def change_token(self, id): # pylint: disable=invalid-name,redefined-builtin """Change a user's token. :param id: User ID as an int. :return: :class:`users.User <users.User>` object :rtype: users.User """ schema = UserSchema(exclude=('password', 'password_confirm')) ...
Bulk copy a set of users. :param ids: Int list of user IDs. :return: :class:`users.User <users.User>` list
def bulk_copy(self, ids): """Bulk copy a set of users. :param ids: Int list of user IDs. :return: :class:`users.User <users.User>` list """ schema = UserSchema() return self.service.bulk_copy(self.base, self.RESOURCE, ids, schema)
Use FIFO(First In First Out) strategy for evicting, it will find an item by earliest birthday date then remove it. Test: >>> from common_cache import CacheItem >>> dict = {} >>> dict['a'] = CacheItem(key='a', value=0, expire=5) >>> dict['b'] = CacheItem(key='b', value=1, expire=5) >>> dict['c']...
def fifo_for_evict(cache_dict, evict_number=1): """ Use FIFO(First In First Out) strategy for evicting, it will find an item by earliest birthday date then remove it. Test: >>> from common_cache import CacheItem >>> dict = {} >>> dict['a'] = CacheItem(key='a', value=0, expire=5) >>> dict['b...
Use LRU(Least Recently Used) strategy for evicting, the item that last used of time is the earliest will be removed. The parameter cache_dict must is an OrderedDict because its implementation based on the OrderedDict and reinsert key and value when every time to get the cache, this operation will make the cache...
def lru_for_evict(cache_dict, evict_number=1): """ Use LRU(Least Recently Used) strategy for evicting, the item that last used of time is the earliest will be removed. The parameter cache_dict must is an OrderedDict because its implementation based on the OrderedDict and reinsert key and value when ever...
Get a list of a device's attachments. :param id: Device ID as an int. :param filter: (optional) Filters to apply as a string list. :param type: (optional) `union` or `inter` as string. :param sort: (optional) Sort fields to apply as string list. :param limit: (optional) Limit re...
def list(self, id, filter=None, type=None, sort=None, limit=None, page=None): # pylint: disable=invalid-name,redefined-builtin """Get a list of a device's attachments. :param id: Device ID as an int. :param filter: (optional) Filters to apply as a string list. :param type: (optional) `u...
Get a list of attachments. Whereas ``list`` fetches a single page of attachments according to its ``limit`` and ``page`` arguments, ``iter_list`` returns all attachments by internally making successive calls to ``list``. :param id: Device ID as an int. :param args: Arguments th...
def iter_list(self, id, *args, **kwargs): """Get a list of attachments. Whereas ``list`` fetches a single page of attachments according to its ``limit`` and ``page`` arguments, ``iter_list`` returns all attachments by internally making successive calls to ``list``. :param id: D...
Get a device's attachment. :param id: Device ID as an int. :param attid: Attachment ID as an int. :return: :class:`attachments.Attachment <attachments.Attachment>` object :rtype: attachments.Attachment
def get(self, id, attid): # pylint: disable=invalid-name,redefined-builtin """Get a device's attachment. :param id: Device ID as an int. :param attid: Attachment ID as an int. :return: :class:`attachments.Attachment <attachments.Attachment>` object :rtype: attachments.Attachment...
Add an attachment to a device. :param id: Device ID as an int. :param fd: File-like object to upload. :param filename: (optional) Name to use for new attachment as a string. :return: :class:`attachments.Attachment <attachments.Attachment>` object :rtype: attachments.Attachment
def create(self, id, fd, filename='attachment-name'): # pylint: disable=invalid-name,redefined-builtin """Add an attachment to a device. :param id: Device ID as an int. :param fd: File-like object to upload. :param filename: (optional) Name to use for new attachment as a string. ...
Download a device's attachment. :param id: Device ID as an int. :param attid: Attachment ID as an int. :rtype: tuple `(io.BytesIO, 'filename')`
def download(self, id, attid): # pylint: disable=invalid-name,redefined-builtin """Download a device's attachment. :param id: Device ID as an int. :param attid: Attachment ID as an int. :rtype: tuple `(io.BytesIO, 'filename')` """ resp = self.service.get_id(self._base(id...
Edit a device's attachment. :param resource: :class:`attachments.Attachment <attachments.Attachment>` object :return: :class:`attachments.Attachment <attachments.Attachment>` object :rtype: attachments.Attachment
def edit(self, resource): # pylint: disable=invalid-name,redefined-builtin """Edit a device's attachment. :param resource: :class:`attachments.Attachment <attachments.Attachment>` object :return: :class:`attachments.Attachment <attachments.Attachment>` object :rtype: attachments.Attachm...
Delete a device's attachment. :param id: Device ID as an int. :param attid: Attachment ID as an int.
def delete(self, id, attid): # pylint: disable=invalid-name,redefined-builtin """Delete a device's attachment. :param id: Device ID as an int. :param attid: Attachment ID as an int. """ return self.service.edit(self._base(id), attid)
Get a device by name. :param name: Device name as string. :return: :class:`devices.Device <devices.Device>` object :rtype: devices.Device
def get_by_name(self, name): # pylint: disable=invalid-name,redefined-builtin """Get a device by name. :param name: Device name as string. :return: :class:`devices.Device <devices.Device>` object :rtype: devices.Device """ rs, _ = self.list(filter=field('name').eq(name),...
Edit a device. :param resource: :class:`devices.Device <devices.Device>` object :return: :class:`devices.Device <devices.Device>` object :rtype: devices.Device
def edit(self, resource): """Edit a device. :param resource: :class:`devices.Device <devices.Device>` object :return: :class:`devices.Device <devices.Device>` object :rtype: devices.Device """ schema = DeviceSchema(exclude=('id', 'created', 'updated', 'result_id', 'attac...
Get information on proxy connection to a device's management interface. :param id: Device ID as an int. :return: :class:`devices.Connection <devices.Connection>` object :rtype: devices.Connection
def get_connection(self, id): # pylint: disable=invalid-name,redefined-builtin """Get information on proxy connection to a device's management interface. :param id: Device ID as an int. :return: :class:`devices.Connection <devices.Connection>` object :rtype: devices.Connection "...