Search is not available for this dataset
text
stringlengths
75
104k
def reference(self): """Return the Reference object for this Key. This is a entity_pb.Reference instance -- a protocol buffer class used by the lower-level API to the datastore. NOTE: The caller should not mutate the return value. """ if self.__reference is None: self.__reference = _Cons...
def urlsafe(self): """Return a url-safe string encoding this Key's Reference. This string is compatible with other APIs and languages and with the strings used to represent Keys in GQL and in the App Engine Admin Console. """ # This is 3-4x faster than urlsafe_b64decode() urlsafe = base64.b...
def get_async(self, **ctx_options): """Return a Future whose result is the entity for this Key. If no such entity exists, a Future is still returned, and the Future's eventual return result be None. """ from . import model, tasklets ctx = tasklets.get_context() cls = model.Model._kind_map.g...
def delete_async(self, **ctx_options): """Schedule deletion of the entity for this Key. This returns a Future, whose result becomes available once the deletion is complete. If no such entity exists, a Future is still returned. In all cases the Future's result is None (i.e. there is no way to tell...
def add_flow_exception(exc): """Add an exception that should not be logged. The argument must be a subclass of Exception. """ global _flow_exceptions if not isinstance(exc, type) or not issubclass(exc, Exception): raise TypeError('Expected an Exception subclass, got %r' % (exc,)) as_set = set(_flow_exc...
def _init_flow_exceptions(): """Internal helper to initialize _flow_exceptions. This automatically adds webob.exc.HTTPException, if it can be imported. """ global _flow_exceptions _flow_exceptions = () add_flow_exception(datastore_errors.Rollback) try: from webob import exc except ImportError: ...
def sleep(dt): """Public function to sleep some time. Example: yield tasklets.sleep(0.5) # Sleep for half a sec. """ fut = Future('sleep(%.3f)' % dt) eventloop.queue_call(dt, fut.set_result, None) return fut
def _transfer_result(fut1, fut2): """Helper to transfer result or errors from one Future to another.""" exc = fut1.get_exception() if exc is not None: tb = fut1.get_traceback() fut2.set_exception(exc, tb) else: val = fut1.get_result() fut2.set_result(val)
def synctasklet(func): """Decorator to run a function as a tasklet when called. Use this to wrap a request handler function that will be called by some web application framework (e.g. a Django view function or a webapp.RequestHandler.get method). """ taskletfunc = tasklet(func) # wrap at declaration time....
def toplevel(func): """A sync tasklet that sets a fresh default Context. Use this for toplevel view functions such as webapp.RequestHandler.get() or Django view functions. """ synctaskletfunc = synctasklet(func) # wrap at declaration time. @utils.wrapping(func) def add_context_wrapper(*args, **kwds): ...
def _make_cloud_datastore_context(app_id, external_app_ids=()): """Creates a new context to connect to a remote Cloud Datastore instance. This should only be used outside of Google App Engine. Args: app_id: The application id to connect to. This differs from the project id as it may have an additional...
def _analyze_indexed_fields(indexed_fields): """Internal helper to check a list of indexed fields. Args: indexed_fields: A list of names, possibly dotted names. (A dotted name is a string containing names separated by dots, e.g. 'foo.bar.baz'. An undotted name is a string containing no dots, e.g. 'foo'...
def _make_model_class(message_type, indexed_fields, **props): """Construct a Model subclass corresponding to a Message subclass. Args: message_type: A Message subclass. indexed_fields: A list of dotted and undotted field names. **props: Additional properties with which to seed the class. Returns: ...
def _message_to_entity(msg, modelclass): """Recursive helper for _to_base_type() to convert a message to an entity. Args: msg: A Message instance. modelclass: A Model subclass. Returns: An instance of modelclass. """ ent = modelclass() for prop_name, prop in modelclass._properties.iteritems():...
def _projected_entity_to_message(ent, message_type): """Recursive helper for _from_base_type() to convert an entity to a message. Args: ent: A Model instance. message_type: A Message subclass. Returns: An instance of message_type. """ msg = message_type() analyzed = _analyze_indexed_fields(ent...
def _validate(self, value): """Validate an Enum value. Raises: TypeError if the value is not an instance of self._enum_type. """ if not isinstance(value, self._enum_type): raise TypeError('Expected a %s instance, got %r instead' % (self._enum_type.__name__, value))
def _validate(self, msg): """Validate an Enum value. Raises: TypeError if the value is not an instance of self._message_type. """ if not isinstance(msg, self._message_type): raise TypeError('Expected a %s instance for %s property', self._message_type.__name__, ...
def _to_base_type(self, msg): """Convert a Message value to a Model instance (entity).""" ent = _message_to_entity(msg, self._modelclass) ent.blob_ = self._protocol_impl.encode_message(msg) return ent
def _from_base_type(self, ent): """Convert a Model instance (entity) to a Message value.""" if ent._projection: # Projection query result. Reconstitute the message from the fields. return _projected_entity_to_message(ent, self._message_type) blob = ent.blob_ if blob is not None: prot...
def _get_value(self, entity): """Compute and store a default value if necessary.""" value = super(_ClassKeyProperty, self)._get_value(entity) if not value: value = entity._class_key() self._store_value(entity, value) return value
def _update_kind_map(cls): """Override; called by Model._fix_up_properties(). Update the kind map as well as the class map, except for PolyModel itself (its class key is empty). Note that the kind map will contain entries for all classes in a PolyModel hierarchy; they all have the same kind, but d...
def _from_pb(cls, pb, set_key=True, ent=None, key=None): """Override. Use the class map to give the entity the correct subclass. """ prop_name = cls.class_._name class_name = [] for plist in [pb.property_list(), pb.raw_property_list()]: for p in plist: if p.name() == prop_name: ...
def _get_kind(cls): """Override. Make sure that the kind returned is the root class of the polymorphic hierarchy. """ bases = cls._get_hierarchy() if not bases: # We have to jump through some hoops to call the superclass' # _get_kind() method. First, this is called by the metaclass...
def _get_hierarchy(cls): """Internal helper to return the list of polymorphic base classes. This returns a list of class objects, e.g. [Animal, Feline, Cat]. """ bases = [] for base in cls.mro(): # pragma: no branch if hasattr(base, '_get_hierarchy'): bases.append(base) del bases...
def find_env_paths_in_basedirs(base_dirs): """Returns all potential envs in a basedir""" # get potential env path in the base_dirs env_path = [] for base_dir in base_dirs: env_path.extend(glob.glob(os.path.join( os.path.expanduser(base_dir), '*', ''))) # self.log.info("Found the ...
def convert_to_env_data(mgr, env_paths, validator_func, activate_func, name_template, display_name_template, name_prefix): """Converts a list of paths to environments to env_data. env_data is a structure {name -> (ressourcedir, kernel spec)} """ env_data = {} for venv_dir in...
def validate_IPykernel(venv_dir): """Validates that this env contains an IPython kernel and returns info to start it Returns: tuple (ARGV, language, resource_dir) """ python_exe_name = find_exe(venv_dir, "python") if python_exe_name is None: python_exe_name = find_exe(venv_dir, "py...
def validate_IRkernel(venv_dir): """Validates that this env contains an IRkernel kernel and returns info to start it Returns: tuple (ARGV, language, resource_dir) """ r_exe_name = find_exe(venv_dir, "R") if r_exe_name is None: return [], None, None # check if this is really an...
def find_exe(env_dir, name): """Finds a exe with that name in the environment path""" if platform.system() == "Windows": name = name + ".exe" # find the binary exe_name = os.path.join(env_dir, name) if not os.path.exists(exe_name): exe_name = os.path.join(env_dir, "bin", name) ...
def get_virtualenv_env_data(mgr): """Finds kernel specs from virtualenv environments env_data is a structure {name -> (resourcedir, kernel spec)} """ if not mgr.find_virtualenv_envs: return {} mgr.log.debug("Looking for virtualenv environments in %s...", mgr.virtualenv_env_dirs) # fi...
def source_bash(args, stdin=None): """Simply bash-specific wrapper around source-foreign Returns a dict to be used as a new environment""" args = list(args) new_args = ['bash', '--sourcer=source'] new_args.extend(args) return source_foreign(new_args, stdin=stdin)
def source_zsh(args, stdin=None): """Simply zsh-specific wrapper around source-foreign Returns a dict to be used as a new environment""" args = list(args) new_args = ['zsh', '--sourcer=source'] new_args.extend(args) return source_foreign(new_args, stdin=stdin)
def source_cmd(args, stdin=None): """Simple cmd.exe-specific wrapper around source-foreign. returns a dict to be used as a new environment """ args = list(args) fpath = locate_binary(args[0]) args[0] = fpath if fpath else args[0] if not os.path.isfile(args[0]): raise RuntimeError("C...
def argvquote(arg, force=False): """ Returns an argument quoted in such a way that that CommandLineToArgvW on Windows will return the argument string unchanged. This is the same thing Popen does when supplied with an list of arguments. Arguments in a command line should be separated by spaces; this ...
def escape_windows_cmd_string(s): """Returns a string that is usable by the Windows cmd.exe. The escaping is based on details here and emperical testing: http://www.robvanderwoude.com/escapechars.php """ for c in '()%!^<>&|"': s = s.replace(c, '^' + c) s = s.replace('/?', '/.') retur...
def source_foreign(args, stdin=None): """Sources a file written in a foreign shell language.""" parser = _ensure_source_foreign_parser() ns = parser.parse_args(args) if ns.prevcmd is not None: pass # don't change prevcmd if given explicitly elif os.path.isfile(ns.files_or_code[0]): ...
def _is_executable_file(path): """Checks that path is an executable regular file, or a symlink towards one. This is roughly ``os.path isfile(path) and os.access(path, os.X_OK)``. This function was forked from pexpect originally: Copyright (c) 2013-2014, Pexpect development team Copyright (c) 2012,...
def foreign_shell_data(shell, interactive=True, login=False, envcmd=None, aliascmd=None, extra_args=(), currenv=None, safe=False, prevcmd='', postcmd='', funcscmd=None, sourcer=None, use_tmpfile=False, tmpfile_ext=None, runcmd=N...
def to_bool(x): """"Converts to a boolean in a semantically meaningful way.""" if isinstance(x, bool): return x elif isinstance(x, str): return False if x.lower() in _FALSES else True else: return bool(x)
def parse_env(s): """Parses the environment portion of string into a dict.""" m = ENV_RE.search(s) if m is None: return {} g1 = m.group(1) env = dict(ENV_SPLIT_RE.findall(g1)) return env
def get_conda_env_data(mgr): """Finds kernel specs from conda environments env_data is a structure {name -> (resourcedir, kernel spec)} """ if not mgr.find_conda_envs: return {} mgr.log.debug("Looking for conda environments in %s...", mgr.conda_env_dirs) # find all potential env paths...
def _find_conda_env_paths_from_conda(mgr): """Returns a list of path as given by `conda env list --json`. Returns empty list, if conda couldn't be called. """ # this is expensive, so make it configureable... if not mgr.use_conda_directly: return [] mgr.log.debug("Looking for conda envir...
def validate_env(self, envname): """ Check the name of the environment against the black list and the whitelist. If a whitelist is specified only it is checked. """ if self.whitelist_envs and envname in self.whitelist_envs: return True elif self.whitelist_envs...
def _get_env_data(self, reload=False): """Get the data about the available environments. env_data is a structure {name -> (resourcedir, kernel spec)} """ # This is called much too often and finding-process is really expensive :-( if not reload and getattr(self, "_env_data_cache...
def find_kernel_specs_for_envs(self): """Returns a dict mapping kernel names to resource directories.""" data = self._get_env_data() return {name: data[name][0] for name in data}
def get_all_kernel_specs_for_envs(self): """Returns the dict of name -> kernel_spec for all environments""" data = self._get_env_data() return {name: data[name][1] for name in data}
def find_kernel_specs(self): """Returns a dict mapping kernel names to resource directories.""" # let real installed kernels overwrite envs with the same name: # this is the same order as the get_kernel_spec way, which also prefers # kernels from the jupyter dir over env kernels. ...
def get_all_specs(self): """Returns a dict mapping kernel names and resource directories. """ # This is new in 4.1 -> https://github.com/jupyter/jupyter_client/pull/93 specs = self.get_all_kernel_specs_for_envs() specs.update(super(EnvironmentKernelSpecManager, self).get_all_spec...
def get_kernel_spec(self, kernel_name): """Returns a :class:`KernelSpec` instance for the given kernel_name. Raises :exc:`NoSuchKernel` if the given kernel name is not found. """ try: return super(EnvironmentKernelSpecManager, self).get_kernel_spec(k...
def to_latin(string_to_transliterate, lang_code='sr'): ''' Transliterate serbian cyrillic string of characters to latin string of characters. :param string_to_transliterate: The cyrillic string to transliterate into latin characters. :param lang_code: Indicates the cyrillic language code we are translating ...
def to_cyrillic(string_to_transliterate, lang_code='sr'): ''' Transliterate serbian latin string of characters to cyrillic string of characters. :param string_to_transliterate: The latin string to transliterate into cyrillic characters. :param lang_code: Indicates the cyrillic language code we are translati...
def parse(self, stream, media_type=None, parser_context=None): """ Parses the incoming bytestream as XML and returns the resulting data. """ assert etree, 'XMLParser requires defusedxml to be installed' parser_context = parser_context or {} encoding = parser_context.get(...
def _xml_convert(self, element): """ convert the xml `element` into the corresponding python object """ children = list(element) if len(children) == 0: return self._type_convert(element.text) else: # if the fist child tag is list-item means all c...
def _type_convert(self, value): """ Converts the value returned by the XMl parse into the equivalent Python type """ if value is None: return value try: return datetime.datetime.strptime(value, '%Y-%m-%d %H:%M:%S') except ValueError: ...
def render(self, data, accepted_media_type=None, renderer_context=None): """ Renders `data` into serialized XML. """ if data is None: return '' stream = StringIO() xml = SimplerXMLGenerator(stream, self.charset) xml.startDocument() xml.startE...
def open(self): """Open a connection to the device.""" device_type = 'cisco_ios' if self.transport == 'telnet': device_type = 'cisco_ios_telnet' self.device = ConnectHandler(device_type=device_type, host=self.hostname, ...
def _create_tmp_file(config): """Write temp file and for use with inline config and SCP.""" tmp_dir = tempfile.gettempdir() rand_fname = py23_compat.text_type(uuid.uuid4()) filename = os.path.join(tmp_dir, rand_fname) with open(filename, 'wt') as fobj: fobj.write(conf...
def _load_candidate_wrapper(self, source_file=None, source_config=None, dest_file=None, file_system=None): """ Transfer file to remote device for either merge or replace operations Returns (return_status, msg) """ return_status = False msg...
def load_replace_candidate(self, filename=None, config=None): """ SCP file to device filesystem, defaults to candidate_config. Return None or raise exception """ self.config_replace = True return_status, msg = self._load_candidate_wrapper(source_file=filename, ...
def load_merge_candidate(self, filename=None, config=None): """ SCP file to remote device. Merge configuration in: copy <file> running-config """ self.config_replace = False return_status, msg = self._load_candidate_wrapper(source_file=filename, ...
def _commit_hostname_handler(self, cmd): """Special handler for hostname change on commit operation.""" current_prompt = self.device.find_prompt().strip() terminating_char = current_prompt[-1] pattern = r"[>#{}]\s*$".format(terminating_char) # Look exclusively for trailing patter...
def commit_config(self): """ If replacement operation, perform 'configure replace' for the entire config. If merge operation, perform copy <file> running-config. """ # Always generate a rollback config on commit self._gen_rollback_cfg() if self.config_replace: ...
def discard_config(self): """Set candidate_cfg to current running-config. Erase the merge_cfg file.""" discard_candidate = 'copy running-config {}'.format(self._gen_full_path(self.candidate_cfg)) discard_merge = 'copy null: {}'.format(self._gen_full_path(self.merge_cfg)) self._disable_co...
def _xfer_file(self, source_file=None, source_config=None, dest_file=None, file_system=None, TransferClass=FileTransfer): """Transfer file to remote device. By default, this will use Secure Copy if self.inline_transfer is set, then will use Netmiko InlineTransfer method to tr...
def _gen_full_path(self, filename, file_system=None): """Generate full file path on remote device.""" if file_system is None: return '{}/{}'.format(self.dest_file_system, filename) else: if ":" not in file_system: raise ValueError("Invalid file_system spec...
def _gen_rollback_cfg(self): """Save a configuration that can be used for rollback.""" cfg_file = self._gen_full_path(self.rollback_cfg) cmd = 'copy running-config {}'.format(cfg_file) self._disable_confirm() self.device.send_command_expect(cmd) self._enable_confirm()
def _check_file_exists(self, cfg_file): """ Check that the file exists on remote device using full path. cfg_file is full path i.e. flash:/file_name For example # dir flash:/candidate_config.txt Directory of flash:/candidate_config.txt 33 -rw- 5592 Dec...
def _expand_interface_name(self, interface_brief): """ Obtain the full interface name from the abbreviated name. Cache mappings in self.interface_map. """ if self.interface_map.get(interface_brief): return self.interface_map.get(interface_brief) command = 'sh...
def get_lldp_neighbors(self): """IOS implementation of get_lldp_neighbors.""" lldp = {} command = 'show lldp neighbors' output = self._send_command(command) # Check if router supports the command if '% Invalid input' in output: return {} # Process th...
def get_lldp_neighbors_detail(self, interface=''): """ IOS implementation of get_lldp_neighbors_detail. Calls get_lldp_neighbors. """ lldp = {} lldp_neighbors = self.get_lldp_neighbors() # Filter to specific interface if interface: lldp_data ...
def get_facts(self): """Return a set of facts from the devices.""" # default values. vendor = u'Cisco' uptime = -1 serial_number, fqdn, os_version, hostname, domain_name = ('Unknown',) * 5 # obtain output from device show_ver = self._send_command('show version') ...
def get_interfaces(self): """ Get interface details. last_flapped is not implemented Example Output: { u'Vlan1': { 'description': u'N/A', 'is_enabled': True, 'is_up': True, 'last_flapped': -1.0, ...
def get_interfaces_ip(self): """ Get interface ip details. Returns a dict of dicts Example Output: { u'FastEthernet8': { 'ipv4': { u'10.66.43.169': { 'prefix_length': 22}}}, u'Loopback555': { 'ipv4': { u'192.168.1.1': { 'prefix_length': 24}}, ...
def bgp_time_conversion(bgp_uptime): """ Convert string time to seconds. Examples 00:14:23 00:13:40 00:00:21 00:00:13 00:00:49 1d11h 1d17h 1w0d 8w5d 1y28w never """ bgp_uptime = bgp_uptime.st...
def get_bgp_neighbors(self): """BGP neighbor information. Currently no VRF support. Supports both IPv4 and IPv6. """ supported_afi = ['ipv4', 'ipv6'] bgp_neighbor_data = dict() bgp_neighbor_data['global'] = {} # get summary output from device cmd_bgp_al...
def get_environment(self): """ Get environment facts. power and fan are currently not implemented cpu is using 1-minute average cpu hard-coded to cpu0 (i.e. only a single CPU) """ environment = {} cpu_cmd = 'show proc cpu' mem_cmd = 'show memory s...
def get_arp_table(self): """ Get arp table information. Return a list of dictionaries having the following set of keys: * interface (string) * mac (string) * ip (string) * age (float) For example:: [ { ...
def cli(self, commands): """ Execute a list of commands and return the output in a dictionary format using the command as the key. Example input: ['show clock', 'show calendar'] Output example: { 'show calendar': u'22:02:01 UTC Thu Feb 18 2016', 's...
def get_mac_address_table(self): """ Returns a lists of dictionaries. Each dictionary represents an entry in the MAC Address Table, having the following keys * mac (string) * interface (string) * vlan (int) * active (boolean) * static (...
def traceroute(self, destination, source=C.TRACEROUTE_SOURCE, ttl=C.TRACEROUTE_TTL, timeout=C.TRACEROUTE_TIMEOUT, vrf=C.TRACEROUTE_VRF): """ Executes traceroute on the device and returns a dictionary with the result. :param destination: Host or IP Address of the destination ...
def get_config(self, retrieve='all'): """Implementation of get_config for IOS. Returns the startup or/and running configuration as dictionary. The keys of the dictionary represent the type of configuration (startup or running). The candidate is always empty string, since IOS doe...
def set_range(self, value): """Set the range of the accelerometer to the provided value. Range value should be one of these constants: - ADXL345_RANGE_2_G = +/-2G - ADXL345_RANGE_4_G = +/-4G - ADXL345_RANGE_8_G = +/-8G - ADXL345_RANGE_16_G = +/-16G ...
def read(self): """Read the current value of the accelerometer and return it as a tuple of signed 16-bit X, Y, Z axis values. """ raw = self._device.readList(ADXL345_REG_DATAX0, 6) return struct.unpack('<hhh', raw)
def deinit(bus=DEFAULT_SPI_BUS, chip_select=DEFAULT_SPI_CHIP_SELECT): """Stops interrupts on all boards. Only required when using :func:`digital_read` and :func:`digital_write`. :param bus: SPI bus /dev/spidev<bus>.<chipselect> (default: {bus}) :type bus: int :param chip_select: SPI chip...
def digital_write(pin_num, value, hardware_addr=0): """Writes the value to the input pin specified. .. note:: This function is for familiarality with users of other types of IO board. Consider accessing the ``output_pins`` attribute of a PiFaceDigital object: >>> pfd = PiFaceDigital(hardw...
def digital_write_pullup(pin_num, value, hardware_addr=0): """Writes the value to the input pullup specified. .. note:: This function is for familiarality with users of other types of IO board. Consider accessing the ``gppub`` attribute of a PiFaceDigital object: >>> pfd = PiFaceDigital(h...
def get_my_ip(): """Returns this computers IP address as a string.""" ip = subprocess.check_output(GET_IP_CMD, shell=True).decode('utf-8')[:-1] return ip.strip()
def set_output_port(self, new_value, old_value=0): """Sets the output port value to new_value, defaults to old_value.""" print("Setting output port to {}.".format(new_value)) port_value = old_value try: port_value = int(new_value) # dec except ValueError: ...
def _request_api(self, **kwargs): """Wrap the calls the url, with the given arguments. :param str url: Url to call with the given arguments :param str method: [POST | GET] Method to use on the request :param int status: Expected status code """ _url = kwargs.get('url') ...
def get_infos_with_id(self, uid): """Get info about a user based on his id. :return: JSON """ _logid = uid _user_info_url = USER_INFO_URL.format(logid=_logid) return self._request_api(url=_user_info_url).json()
def get_current_activities(self, login=None, **kwargs): """Get the current activities of user. Either use the `login` param, or the client's login if unset. :return: JSON """ _login = kwargs.get( 'login', login or self._login ) _activity_...
def get_notifications(self, login=None, **kwargs): """Get the current notifications of a user. :return: JSON """ _login = kwargs.get( 'login', login or self._login ) _notif_url = NOTIF_URL.format(login=_login) return self._request_api(url...
def get_grades(self, login=None, promotion=None, **kwargs): """Get a user's grades on a single promotion based on his login. Either use the `login` param, or the client's login if unset. :return: JSON """ _login = kwargs.get( 'login', login or self._logi...
def get_picture(self, login=None, **kwargs): """Get a user's picture. :param str login: Login of the user to check :return: JSON """ _login = kwargs.get( 'login', login or self._login ) _activities_url = PICTURE_URL.format(login=_login) ...
def get_projects(self, **kwargs): """Get a user's project. :param str login: User's login (Default: self._login) :return: JSON """ _login = kwargs.get('login', self._login) search_url = SEARCH_URL.format(login=_login) return self._request_api(url=search_url).jso...
def get_activities_for_project(self, module=None, **kwargs): """Get the related activities of a project. :param str module: Stages of a given module :return: JSON """ _module_id = kwargs.get('module', module) _activities_url = ACTIVITIES_URL.format(module_id=_module_id)...
def get_group_for_activity(self, module=None, project=None, **kwargs): """Get groups for activity. :param str module: Base module :param str module: Project which contains the group requested :return: JSON """ _module_id = kwargs.get('module', module) _project_i...
def get_students(self, **kwargs): """Get users by promotion id. :param int promotion: Promotion ID :return: JSON """ _promotion_id = kwargs.get('promotion') _url = PROMOTION_URL.format(promo_id=_promotion_id) return self._request_api(url=_url).json()
def get_log_events(self, login=None, **kwargs): """Get a user's log events. :param str login: User's login (Default: self._login) :return: JSON """ _login = kwargs.get( 'login', login ) log_events_url = GSA_EVENTS_URL.format(login=_login)...
def get_events(self, login=None, start_date=None, end_date=None, **kwargs): """Get a user's events. :param str login: User's login (Default: self._login) :param str start_date: Start date :param str end_date: To date :return: JSON """ _login = kwargs.get( ...