Search is not available for this dataset
text
stringlengths
75
104k
def normalize_whitespace(text): """ Returns the given text with outer whitespace removed and inner whitespace collapsed. Args: text (str): The text to normalize. Returns: str: The normalized text. """ return re.sub(r"\s+", " ", text, flags=re.UNICODE).strip()
def toregex(text, exact=False): """ Returns a compiled regular expression for the given text. Args: text (str | RegexObject): The text to match. exact (bool, optional): Whether the generated regular expression should match exact strings. Defaults to False. Returns: ...
def resolves_for(self, session): """ Returns whether this query resolves for the given session. Args: session (Session): The session for which this query should be executed. Returns: bool: Whether this query resolves. """ if self.url: ...
def current(self): """ bool: Whether this window is the window in which commands are being executed. """ try: return self.driver.current_window_handle == self.handle except self.driver.no_such_window_error: return False
def resize_to(self, width, height): """ Resizes the window to the given dimensions. If this method was called for a window that is not current, then after calling this method the current window should remain the same as it was before calling this method. Args: width...
def boot(self): """ Boots a server for the app, if it isn't already booted. Returns: Server: This server. """ if not self.responsive: # Remember the port so we can reuse it if we try to serve this same app again. type(self)._ports[self.port_k...
def responsive(self): """ bool: Whether the server for this app is up and responsive. """ if self.server_thread and self.server_thread.join(0): return False try: # Try to fetch the endpoint added by the middleware. identify_url = "http://{0}:{1}/__identify__...
def cgetter(self, fcget: typing.Optional[typing.Callable[[typing.Any], typing.Any]]) -> "AdvancedProperty": """Descriptor to change the class wide getter on a property. :param fcget: new class-wide getter. :type fcget: typing.Optional[typing.Callable[[typing.Any, ], typing.Any]] :return...
def instance_method(self, imeth: typing.Optional[typing.Callable[..., typing.Any]]) -> "SeparateClassMethod": """Descriptor to change instance method. :param imeth: New instance method. :type imeth: typing.Optional[typing.Callable] :return: SeparateClassMethod :rtype: SeparateCl...
def class_method(self, cmeth: typing.Optional[typing.Callable[..., typing.Any]]) -> "SeparateClassMethod": """Descriptor to change class method. :param cmeth: New class method. :type cmeth: typing.Optional[typing.Callable] :return: SeparateClassMethod :rtype: SeparateClassMethod...
def __traceback(self) -> str: """Get outer traceback text for logging.""" if not self.log_traceback: return "" exc_info = sys.exc_info() stack = traceback.extract_stack() exc_tb = traceback.extract_tb(exc_info[2]) full_tb = stack[:1] + exc_tb # cut decorator ...
def __get_obj_source(self, instance: typing.Any, owner: typing.Optional[type] = None) -> str: """Get object repr block.""" if self.log_object_repr: return f"{instance!r}" return f"<{owner.__name__ if owner is not None else instance.__class__.__name__}() at 0x{id(instance):X}>"
def _get_logger_for_instance(self, instance: typing.Any) -> logging.Logger: """Get logger for log calls. :param instance: Owner class instance. Filled only if instance created, else None. :type instance: typing.Optional[owner] :return: logger instance :rtype: logging.Logger ...
def logger(self, logger: typing.Union[logging.Logger, str, None]) -> None: """Logger instance to use as override.""" if logger is None or isinstance(logger, logging.Logger): self.__logger = logger else: self.__logger = logging.getLogger(logger)
def get_simple_vars_from_src(src): """Get simple (string/number/boolean and None) assigned values from source. :param src: Source code :type src: str :returns: OrderedDict with keys, values = variable names, values :rtype: typing.Dict[ str, typing.Union[ ...
def run(self): """Run. :raises BuildFailed: extension build failed and need to skip cython part. """ try: build_ext.build_ext.run(self) # Copy __init__.py back to repair package. build_dir = os.path.abspath(self.build_lib) root_dir = os.p...
def _call_api(self, method, params=None): """ Low-level method to call the Slack API. Args: method: {str} method name to call params: {dict} GET parameters The token will always be added """ url = self.url.format(method=method) if ...
def channels(self): """ List of channels of this slack team """ if not self._channels: self._channels = self._call_api('channels.list')['channels'] return self._channels
def users(self): """ List of users of this slack team """ if not self._users: self._users = self._call_api('users.list')['members'] return self._users
def channel_from_name(self, name): """ Return the channel dict given by human-readable {name} """ try: channel = [channel for channel in self.channels if channel['name'] == name][0] except IndexError: raise ValueError('Unknown channe...
def make_message(self, text, channel): """ High-level function for creating messages. Return packed bytes. Args: text: {str} channel: {str} Either name or ID """ try: channel_id = self.slack.channel_from_name(channel)['id'] except Valu...
def translate(self, message): """ Translate machine identifiers into human-readable """ # translate user try: user_id = message.pop('user') user = self.slack.user_from_id(user_id) message[u'user'] = user['name'] except (KeyError, IndexE...
def onMessage(self, payload, isBinary): """ Send the payload onto the {slack.[payload['type]'} channel. The message is transalated from IDs to human-readable identifiers. Note: The slack API only sends JSON, isBinary will always be false. """ msg = self.translate(unpack(...
def sendSlack(self, message): """ Send message to Slack """ channel = message.get('channel', 'general') self.sendMessage(self.make_message(message['text'], channel))
def read_channel(self): """ Get available messages and send through to the protocol """ channel, message = self.protocol.channel_layer.receive_many([u'slack.send'], block=False) delay = 0.1 if channel: self.protocols[0].sendSlack(message) reactor.callL...
def run(self): """ Main interface. Instantiate the SlackAPI, connect to RTM and start the client. """ slack = SlackAPI(token=self.token) rtm = slack.rtm_start() factory = SlackClientFactory(rtm['url']) # Attach attributes factory.protocol = SlackC...
def run(self, args): """ Pass in raw arguments, instantiate Slack API and begin client. """ args = self.parser.parse_args(args) if not args.token: raise ValueError('Supply the slack token through --token or setting DJANGOBOT_TOKEN') # Import the channel layer...
def _set_affiliation(self, v, load=False): """ Setter method for affiliation, mapped from YANG variable /universe/individual/affiliation (identityref) If this variable is read-only (config: false) in the source YANG file, then _set_affiliation is considered as a private method. Backends looking ...
def dict_diff(prv, nxt): """Return a dict of keys that differ with another config object.""" keys = set(prv.keys() + nxt.keys()) result = {} for k in keys: if prv.get(k) != nxt.get(k): result[k] = (prv.get(k), nxt.get(k)) return result
def colorize(msg, color): """Given a string add necessary codes to format the string.""" if DONT_COLORIZE: return msg else: return "{}{}{}".format(COLORS[color], msg, COLORS["endc"])
def v2_playbook_on_task_start(self, task, **kwargs): """Run when a task starts.""" self.last_task_name = task.get_name() self.printed_last_task = False
def v2_runner_on_ok(self, result, **kwargs): """Run when a task finishes correctly.""" failed = "failed" in result._result unreachable = "unreachable" in result._result if ( "print_action" in result._task.tags or failed or unreachable or s...
def v2_playbook_on_stats(self, stats): """Display info about playbook statistics.""" print() self.printed_last_task = False self._print_task("STATS") hosts = sorted(stats.processed.keys()) for host in hosts: s = stats.summarize(host) if s["failur...
def v2_runner_on_skipped(self, result, **kwargs): """Run when a task is skipped.""" if self._display.verbosity > 1: self._print_task() self.last_skipped = False line_length = 120 spaces = " " * (31 - len(result._host.name) - 4) line = " * {}...
def parse_indented_config(config, current_indent=0, previous_indent=0, nested=False): """ This methid basically reads a configuration that conforms to a very poor industry standard and returns a nested structure that behaves like a dict. For example: {'enable password whatever': {}, 'interf...
def prefix_to_addrmask(value, sep=" "): """ Converts a CIDR formatted prefix into an address netmask representation. Argument sep specifies the separator between the address and netmask parts. By default it's a single space. Examples: >>> "{{ '192.168.0.1/24|prefix_to_addrmask }}" -> "192.1...
def _set_keepalive_interval(self, v, load=False): """ Setter method for keepalive_interval, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/peer_groups/peer_group/timers/state/keepalive_interval (decimal64) If this variable is read-only (config: false) in the sou...
def check_empty(default=""): """ Decorator that checks if a value passed to a Jinja filter evaluates to false and returns an empty string. Otherwise calls the original Jinja filter. Example usage: @check_empty def my_jinja_filter(value, arg1): """ def real_decorator(func): @wr...
def add_model(self, model, force=False): """ Add a model. The model will be asssigned to a class attribute with the YANG name of the model. Args: model (PybindBase): Model to add. force (bool): If not set, verify the model is in SUPPORTED_MODELS Example...
def get(self, filter=False): """ Returns a dictionary with the values of the model. Note that the values of the leafs are YANG classes. Args: filter (bool): If set to ``True``, show only values that have been set. Returns: dict: A dictionary with the val...
def load_dict(self, data, overwrite=False, auto_load_model=True): """ Load a dictionary into the model. Args: data(dict): Dictionary to load overwrite(bool): Whether the data present in the model should be overwritten by the data in the dict or not. ...
def to_dict(self, filter=True): """ Returns a dictionary with the values of the model. Note that the values of the leafs are evaluated to python types. Args: filter (bool): If set to ``True``, show only values that have been set. Returns: dict: A diction...
def parse_config(self, device=None, profile=None, native=None, attrs=None): """ Parse native configuration and load it into the corresponding models. Only models that have been added to the root object will be parsed. If ``native`` is passed to the method that's what we will parse, othe...
def parse_state(self, device=None, profile=None, native=None, attrs=None): """ Parse native state and load it into the corresponding models. Only models that have been added to the root object will be parsed. If ``native`` is passed to the method that's what we will parse, otherwise, we...
def translate_config(self, profile, merge=None, replace=None): """ Translate the object to native configuration. In this context, merge and replace means the following: * **Merge** - Elements that exist in both ``self`` and ``merge`` will use by default the values in ``merge`...
def load_filters(): """ Loads and returns all filters. """ all_filters = {} for m in JINJA_FILTERS: if hasattr(m, "filters"): all_filters.update(m.filters()) return all_filters
def _parse_list_nested_recursive( cls, data, path, iterators, list_vars, cur_vars=None ): """ This helps parsing shit like: <protocols> <bgp> <group> <name>my_peers</name> <neighbor> ...
def _flatten_dictionary(obj, path, key_name): """ This method tries to use the path `?my_field` to convert: a: aa: 1 ab: 2 b: ba: 3 ba: 4 into: - my_field: a aa: 1 ab: 2 - my_field: b ba: 3 ba: 4 """ result = [] if ">" in...
def _set_trunk_vlans(self, v, load=False): """ Setter method for trunk_vlans, mapped from YANG variable /interfaces/interface/aggregation/switched_vlan/state/trunk_vlans (union) If this variable is read-only (config: false) in the source YANG file, then _set_trunk_vlans is considered as a private ...
def find_yang_file(profile, filename, path): """ Find the necessary file for the given test case. Args: device(napalm device connection): for which device filename(str): file to find path(str): where to find it relative to where the module is installed """ # Find base_dir of...
def model_to_dict(model, mode="", show_defaults=False): """ Given a model, return a representation of the model in a dict. This is mostly useful to have a quick visual represenation of the model. Args: model (PybindBase): Model to transform. mode (string): Whether to print config, sta...
def diff(f, s): """ Given two models, return the difference between them. Args: f (Pybindbase): First element. s (Pybindbase): Second element. Returns: dict: A dictionary highlighting the differences. Examples: >>> diff = napalm_yang.utils.diff(candidate, runnin...
def http_post(self, url, data=None): """POST to URL and get result as a response object. :param url: URL to POST. :type url: str :param data: Data to send in the form body. :type data: str :rtype: requests.Response """ if not url.startswith('https://'): ...
def get_authorization_code_uri(self, **params): """Construct a full URL that can be used to obtain an authorization code from the provider authorization_uri. Use this URI in a client frame to cause the provider to generate an authorization code. :rtype: str """ if 'respo...
def get_token(self, code, **params): """Get an access token from the provider token URI. :param code: Authorization code. :type code: str :return: Dict containing access token, refresh token, etc. :rtype: dict """ params['code'] = code if 'grant_type' not...
def url_query_params(url): """Return query parameters as a dict from the specified URL. :param url: URL. :type url: str :rtype: dict """ return dict(urlparse.parse_qsl(urlparse.urlparse(url).query, True))
def url_dequery(url): """Return a URL with the query component removed. :param url: URL to dequery. :type url: str :rtype: str """ url = urlparse.urlparse(url) return urlparse.urlunparse((url.scheme, url.netloc, url.path, ...
def build_url(base, additional_params=None): """Construct a URL based off of base containing all parameters in the query portion of base plus any additional parameters. :param base: Base URL :type base: str ::param additional_params: Additional query parameters to include. :type additional_para...
def _handle_exception(self, exc): """Handle an internal exception that was caught and suppressed. :param exc: Exception to process. :type exc: Exception """ logger = logging.getLogger(__name__) logger.exception(exc)
def _make_response(self, body='', headers=None, status_code=200): """Return a response object from the given parameters. :param body: Buffer/string containing the response body. :type body: str :param headers: Dict of headers to include in the requests. :type headers: dict ...
def _make_redirect_error_response(self, redirect_uri, err): """Return a HTTP 302 redirect response object containing the error. :param redirect_uri: Client redirect URI. :type redirect_uri: str :param err: OAuth error message. :type err: str :rtype: requests.Response ...
def _make_json_response(self, data, headers=None, status_code=200): """Return a response object from the given JSON data. :param data: Data to JSON-encode. :type data: mixed :param headers: Dict of headers to include in the requests. :type headers: dict :param status_cod...
def get_authorization_code(self, response_type, client_id, redirect_uri, **params): """Generate authorization code HTTP response. :param response_type: Desired response type. Must...
def refresh_token(self, grant_type, client_id, client_secret, refresh_token, **params): """Generate access token HTTP response from a refresh token. :param grant_type: Desired grant type. Must ...
def get_token(self, grant_type, client_id, client_secret, redirect_uri, code, **params): """Generate access token HTTP response. :param grant_type: Desired grant type. Must be "authorization_code...
def get_authorization_code_from_uri(self, uri): """Get authorization code response from a URI. This method will ignore the domain and path of the request, instead automatically parsing the query string parameters. :param uri: URI to parse for authorization information. :type uri...
def get_token_from_post_data(self, data): """Get a token response from POST data. :param data: POST data containing authorization information. :type data: dict :rtype: requests.Response """ try: # Verify OAuth 2.0 Parameters for x in ['grant_type'...
def get_authorization(self): """Get authorization object representing status of authentication.""" auth = self.authorization_class() header = self.get_authorization_header() if not header or not header.split: return auth header = header.split() if len(header) ...
def make_i2c_rdwr_data(messages): """Utility function to create and return an i2c_rdwr_ioctl_data structure populated with a list of specified I2C messages. The messages parameter should be a list of tuples which represent the individual I2C messages to send in this transaction. Tuples should contain ...
def open(self, bus): """Open the smbus interface on the specified bus.""" # Close the device if it's already open. if self._device is not None: self.close() # Try to open the file for the specified bus. Must turn off buffering # or else Python 3 fails (see: https://b...
def read_byte(self, addr): """Read a single byte from the specified device.""" assert self._device is not None, 'Bus must be opened before operations are made against it!' self._select_device(addr) return ord(self._device.read(1))
def read_bytes(self, addr, number): """Read many bytes from the specified device.""" assert self._device is not None, 'Bus must be opened before operations are made against it!' self._select_device(addr) return self._device.read(number)
def read_byte_data(self, addr, cmd): """Read a single byte from the specified cmd register of the device.""" assert self._device is not None, 'Bus must be opened before operations are made against it!' # Build ctypes values to marshall between ioctl and Python. reg = c_uint8(cmd) ...
def read_word_data(self, addr, cmd): """Read a word (2 bytes) from the specified cmd register of the device. Note that this will interpret data using the endianness of the processor running Python (typically little endian)! """ assert self._device is not None, 'Bus must be opened...
def read_i2c_block_data(self, addr, cmd, length=32): """Perform a read from the specified cmd register of device. Length number of bytes (default of 32) will be read and returned as a bytearray. """ assert self._device is not None, 'Bus must be opened before operations are made against ...
def write_quick(self, addr): """Write a single byte to the specified device.""" # What a strange function, from the python-smbus source this appears to # just write a single byte that initiates a write to the specified device # address (but writes no data!). The functionality is duplica...
def write_byte(self, addr, val): """Write a single byte to the specified device.""" assert self._device is not None, 'Bus must be opened before operations are made against it!' self._select_device(addr) data = bytearray(1) data[0] = val & 0xFF self._device.write(data)
def write_bytes(self, addr, buf): """Write many bytes to the specified device. buf is a bytearray""" assert self._device is not None, 'Bus must be opened before operations are made against it!' self._select_device(addr) self._device.write(buf)
def write_byte_data(self, addr, cmd, val): """Write a byte of data to the specified cmd register of the device. """ assert self._device is not None, 'Bus must be opened before operations are made against it!' # Construct a string of data to send with the command register and byte value. ...
def write_word_data(self, addr, cmd, val): """Write a word (2 bytes) of data to the specified cmd register of the device. Note that this will write the data in the endianness of the processor running Python (typically little endian)! """ assert self._device is not None, 'Bus mus...
def write_block_data(self, addr, cmd, vals): """Write a block of data to the specified cmd register of the device. The amount of data to write should be the first byte inside the vals string/bytearray and that count of bytes of data to write should follow it. """ # Just u...
def write_i2c_block_data(self, addr, cmd, vals): """Write a buffer of data to the specified cmd register of the device. """ assert self._device is not None, 'Bus must be opened before operations are made against it!' # Construct a string of data to send, including room for the command re...
def process_call(self, addr, cmd, val): """Perform a smbus process call by writing a word (2 byte) value to the specified register of the device, and then reading a word of response data (which is returned). """ assert self._device is not None, 'Bus must be opened before operatio...
def cdn_url(self): """Returns file's CDN url. Usage example:: >>> file_ = File('a771f854-c2cb-408a-8c36-71af77811f3b') >>> file_.cdn_url https://ucarecdn.com/a771f854-c2cb-408a-8c36-71af77811f3b/ You can set default effects:: >>> file_.default_...
def datetime_stored(self): """Returns file's store aware *datetime* in UTC format. It might do API request once because it depends on ``info()``. """ if self.info().get('datetime_stored'): return dateutil.parser.parse(self.info()['datetime_stored'])
def datetime_removed(self): """Returns file's remove aware *datetime* in UTC format. It might do API request once because it depends on ``info()``. """ if self.info().get('datetime_removed'): return dateutil.parser.parse(self.info()['datetime_removed'])
def datetime_uploaded(self): """Returns file's upload aware *datetime* in UTC format. It might do API request once because it depends on ``info()``. """ if self.info().get('datetime_uploaded'): return dateutil.parser.parse(self.info()['datetime_uploaded'])
def copy(self, effects=None, target=None): """Creates a File Copy on Uploadcare or Custom Storage. File.copy method is deprecated and will be removed in 4.0.0. Please use `create_local_copy` and `create_remote_copy` instead. Args: - effects: Adds CDN...
def create_local_copy(self, effects=None, store=None): """Creates a Local File Copy on Uploadcare Storage. Args: - effects: Adds CDN image effects. If ``self.default_effects`` property is set effects will be combined with default effects. - store:...
def create_remote_copy(self, target, effects=None, make_public=None, pattern=None): """Creates file copy in remote storage. Args: - target: Name of a custom storage connected to the project. - effects: Adds CDN image eff...
def construct_from(cls, file_info): """Constructs ``File`` instance from file information. For example you have result of ``/files/1921953c-5d94-4e47-ba36-c2e1dd165e1a/`` API request:: >>> file_info = { # ... 'uuid': '1921953c-5d94-4e47-ba36-...
def upload(cls, file_obj, store=None): """Uploads a file and returns ``File`` instance. Args: - file_obj: file object to upload to - store (Optional[bool]): Should the file be automatically stored upon upload. Defaults to None. - False - do not st...
def upload_from_url(cls, url, store=None, filename=None): """Uploads file from given url and returns ``FileFromUrl`` instance. Args: - url (str): URL of file to upload to - store (Optional[bool]): Should the file be automatically stored upon upload. Defaults to N...
def upload_from_url_sync(cls, url, timeout=30, interval=0.3, until_ready=False, store=None, filename=None): """Uploads file from given url and returns ``File`` instance. Args: - url (str): URL of file to upload to - store (Optional[bool]): Should the...
def file_cdn_urls(self): """Returns CDN urls of all files from group without API requesting. Usage example:: >>> file_group = FileGroup('0513dda0-582f-447d-846f-096e5df9e2bb~2') >>> file_group.file_cdn_urls[0] 'https://ucarecdn.com/0513dda0-582f-447d-846f-096e5df9e2...
def datetime_created(self): """Returns file group's create aware *datetime* in UTC format.""" if self.info().get('datetime_created'): return dateutil.parser.parse(self.info()['datetime_created'])
def construct_from(cls, group_info): """Constructs ``FileGroup`` instance from group information.""" group = cls(group_info['id']) group._info_cache = group_info return group
def create(cls, files): """Creates file group and returns ``FileGroup`` instance. It expects iterable object that contains ``File`` instances, e.g.:: >>> file_1 = File('6c5e9526-b0fe-4739-8975-72e8d5ee6342') >>> file_2 = File('a771f854-c2cb-408a-8c36-71af77811f3b') ...
def _base_opration(self, method): """ Base method for storage operations. """ uuids = self.uuids() while True: chunk = list(islice(uuids, 0, self.chunk_size)) if not chunk: return rest_request(method, self.storage_url, chunk)
def uuids(self): """ Extract uuid from each item of specified ``seq``. """ for f in self._seq: if isinstance(f, File): yield f.uuid elif isinstance(f, six.string_types): yield f else: raise ValueError( ...