INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Reload the device.
def reload(self, reload_timeout, save_config): """Reload the device.""" PROCEED = re.compile(re.escape("Proceed with reload? [confirm]")) CONTINUE = re.compile(re.escape("Do you wish to continue?[confirm(y/n)]")) DONE = re.compile(re.escape("[Done]")) CONFIGURATION_COMPLETED = re...
Apply config.
def config(self, config_text, plane): """Apply config.""" NO_CONFIGURATION_CHANGE = re.compile("No configuration changes to commit") CONFIGURATION_FAILED = re.compile("show configuration failed") CONFIGURATION_INCONSITENCY = re.compile("No configuration commits for this SDR will be allow...
Rollback config.
def rollback(self, label, plane): """Rollback config.""" cm_label = 'condoor-{}'.format(int(time.time())) self.device.send(self.rollback_cmd.format(label), timeout=120) return cm_label
Compute the Gelman-Rubin R-statistic from an ensemble of chains. `chains` is expected to have shape `(nsteps, nchains)` if samples are one dimensional, or `(nsteps, nchains, ndim)` if multidimensional. For multidimensional samples R-statistics will be computed for each dimension. :param chains: ...
def gelman_rubin(chains, return_cdf=False): """ Compute the Gelman-Rubin R-statistic from an ensemble of chains. `chains` is expected to have shape `(nsteps, nchains)` if samples are one dimensional, or `(nsteps, nchains, ndim)` if multidimensional. For multidimensional samples R-statistics will b...
Starts profiling all threads and all greenlets. This function can be called from any thread at any time. Resumes profiling if stop() was called previously. * `builtins`: Profile builtin functions used by standart Python modules. * `profile_threads`: Profile all threads if ``True``, else profile only t...
def start(builtins=False, profile_threads=True): """Starts profiling all threads and all greenlets. This function can be called from any thread at any time. Resumes profiling if stop() was called previously. * `builtins`: Profile builtin functions used by standart Python modules. * `profile_thread...
Connect using the Telnet protocol specific FSM.
def connect(self, driver): """Connect using the Telnet protocol specific FSM.""" # 0 1 2 3 events = [ESCAPE_CHAR, driver.press_return_re, driver.standby_re, driver.username_re, # 4 ...
Disconnect using protocol specific method.
def disconnect(self, device): """Disconnect using protocol specific method.""" # self.device.ctrl.sendcontrol(']') # self.device.ctrl.sendline('quit') self.log("TELNET disconnect") try: self.device.ctrl.send(chr(4)) except OSError: self.log("Protoc...
Disconnect from the console.
def disconnect(self, driver): """Disconnect from the console.""" self.log("TELNETCONSOLE disconnect") try: while self.device.mode != 'global': self.device.send('exit', timeout=10) except OSError: self.log("TELNETCONSOLE already disconnected") ...
Find date in recorded game default(ish) filename.
def _find_date(filename): """Find date in recorded game default(ish) filename.""" has_date = re.search(MATCH_DATE, filename) if has_date: year = has_date.group('year') month = has_date.group('month') day = has_date.group('day') if int(year) > 2000 and int(month) in range(1, 1...
Calculate player's rAPM.
def _calculate_apm(index, player_actions, other_actions, duration): """Calculate player's rAPM.""" apm_per_player = {} for player_index, histogram in player_actions.items(): apm_per_player[player_index] = sum(histogram.values()) total_unattributed = sum(other_actions.values()) total_attribut...
Sometimes a game is finished, but not recorded as such.
def guess_finished(summary, postgame): """Sometimes a game is finished, but not recorded as such.""" if postgame and postgame.complete: return True for player in summary['players']: if 'resign' in player['action_histogram']: return True return False
Compute number of players, both human and computer.
def _num_players(self): """Compute number of players, both human and computer.""" self._player_num = 0 self._computer_num = 0 for player in self._header.scenario.game_settings.player_info: if player.type == 'human': self._player_num += 1 elif playe...
Parse a lobby chat message.
def _parse_lobby_chat(self, messages, source, timestamp): """Parse a lobby chat message.""" for message in messages: if message.message_length == 0: continue chat = ChatMessage(message.message, timestamp, self._players(), source=source) self._parse_cha...
Parse a player action. TODO: handle cancels
def _parse_action(self, action, current_time): """Parse a player action. TODO: handle cancels """ if action.action_type == 'research': name = mgz.const.TECHNOLOGIES[action.data.technology_type] self._research[action.data.player_id].append({ 'techn...
Process operation stream.
def operations(self, op_types=None): """Process operation stream.""" if not op_types: op_types = ['message', 'action', 'sync', 'viewlock', 'savedchapter'] while self._handle.tell() < self._eof: current_time = mgz.util.convert_to_timestamp(self._time / 1000) tr...
Summarize game.
def summarize(self): """Summarize game.""" if not self._achievements_summarized: for _ in self.operations(): pass self._summarize() return self._summary
Is this game nomad. TODO: Can we get from UP 1.4 achievements?
def is_nomad(self): """Is this game nomad. TODO: Can we get from UP 1.4 achievements? """ nomad = self._header.initial.restore_time == 0 or None for i in range(1, self._header.replay.num_players): for obj in self._header.initial.players[i].objects: if...
Is this game regicide.
def is_regicide(self): """Is this game regicide.""" for i in range(1, self._header.replay.num_players): for obj in self._header.initial.players[i].objects: if obj.type == 'unit' and obj.object_type == 'king': return True return False
Parse a chat message.
def _parse_chat(self, chat): """Parse a chat message.""" if chat.data['type'] == 'chat': if chat.data['player'] in [p.player_name for i, p in self._players()]: self._chat.append(chat.data) elif chat.data['type'] == 'ladder': self._ladder = chat.data['ladde...
Parse a player.
def _parse_player(self, index, attributes, postgame, game_type): """Parse a player.""" try: voobly_user = voobly.user(self._voobly_session, attributes.player_name, ladder_ids=VOOBLY_LADDERS.values()) voobly_ladder = '{} {}'.format(game_type, ...
Get compass position of player.
def _compass_position(self, player_x, player_y): """Get compass position of player.""" map_dim = self._map.size_x third = map_dim * (1/3.0) for direction in mgz.const.COMPASS: point = mgz.const.COMPASS[direction] xlower = point[0] * map_dim xupper = (p...
Get player attributes with index. No Gaia.
def _players(self): """Get player attributes with index. No Gaia.""" for i in range(1, self._header.replay.num_players): yield i, self._header.initial.players[i].attributes
Return parsed players.
def players(self, postgame, game_type): """Return parsed players.""" for i, attributes in self._players(): yield self._parse_player(i, attributes, postgame, game_type)
Get list of teams.
def teams(self): """Get list of teams.""" teams = {} default_team = 1 for i in range(1, self._header.replay.num_players): attributes = self._header.initial.players[i].attributes team = self._header.lobby.teams[i - 1] if team == 1: team ...
Compute diplomacy.
def _compute_diplomacy(self): """Compute diplomacy.""" self._diplomacy = { 'teams': self.teams(), 'ffa': len(self.teams()) == (self._player_num + self._computer_num and self._player_num + self._computer_num > 2), 'TG': len(sel...
Get age the game was won in.
def _won_in(self): """Get age the game was won in.""" if not self._summary['finished']: return starting_age = self._summary['settings']['starting_age'].lower() if starting_age == 'post imperial': starting_age = 'imperial' ages_reached = set([starting_age])...
Get rec owner number.
def _rec_owner_number(self): """Get rec owner number.""" player = self._header.initial.players[self._header.replay.rec_player] return player.attributes.player_color + 1
Get modification timestamp from rec file.
def _get_timestamp(self): """Get modification timestamp from rec file.""" filename_date = _find_date(os.path.basename(self._path)) if filename_date: return filename_date
Mark the winning team.
def _set_winning_team(self): """Mark the winning team.""" if not self._summary['finished']: return for team in self._summary['diplomacy']['teams']: team['winner'] = False for player_number in team['player_numbers']: for player in self._summary[...
Compute a map hash based on a combination of map attributes. - Elevation - Map name - Player names, colors, and civilizations
def _map_hash(self): """Compute a map hash based on a combination of map attributes. - Elevation - Map name - Player names, colors, and civilizations """ elevation_bytes = bytes([tile.elevation for tile in self._header.map_info.tile]) map_name_bytes = self._map.n...
Game summary implementation.
def _summarize(self): """Game summary implementation.""" self._achievements_summarized = True data = None if self._postgame: data = self._postgame.action game_type = 'DM' if self._header.lobby.game_type == 'DM' else 'RM' self._summary = { 'players'...
Return device info dict.
def device_info(self): """Return device info dict.""" return { 'family': self.family, 'platform': self.platform, 'os_type': self.os_type, 'os_version': self.os_version, 'udi': self.udi, # TODO(klstanie): add property to make driver ...
Clear the device info.
def clear_info(self): """Clear the device info.""" self._version_text = None self._inventory_text = None self._users_text = None self.os_version = None self.os_type = None self.family = None self.platform = None self.udi = None # self.is_co...
Connect to the device.
def connect(self, ctrl): """Connect to the device.""" if self.prompt: self.prompt_re = self.driver.make_dynamic_prompt(self.prompt) else: self.prompt_re = self.driver.prompt_re self.ctrl = ctrl if self.protocol.connect(self.driver): if self.pr...
Disconnect the device.
def disconnect(self): """Disconnect the device.""" self.chain.connection.log("Disconnecting: {}".format(self)) if self.connected: if self.protocol: if self.is_console: while self.mode != 'global': try: ...
Send the command to the device and return the output. Args: cmd (str): Command string for execution. Defaults to empty string. timeout (int): Timeout in seconds. Defaults to 60s wait_for_string (str): This is optional string that driver waits for after comman...
def send(self, cmd="", timeout=60, wait_for_string=None, password=False): """Send the command to the device and return the output. Args: cmd (str): Command string for execution. Defaults to empty string. timeout (int): Timeout in seconds. Defaults to 60s wait_for_str...
Execute command.
def execute_command(self, cmd, timeout, wait_for_string, password): """Execute command.""" try: self.last_command_result = None self.ctrl.send_command(cmd, password=password) if wait_for_string is None: wait_for_string = self.prompt_re # h...
Make driver factory function.
def make_driver(self, driver_name='generic'): """Make driver factory function.""" module_str = 'condoor.drivers.%s' % driver_name try: __import__(module_str) module = sys.modules[module_str] driver_class = getattr(module, 'Driver') except ImportError a...
Return version text and collect if not collected.
def version_text(self): """Return version text and collect if not collected.""" if self._version_text is None: self.chain.connection.log("Collecting version information") self._version_text = self.driver.get_version_text() if self._version_text: self.c...
Return hostname text and collect if not collected.
def hostname_text(self): """Return hostname text and collect if not collected.""" if self._hostname_text is None: self.chain.connection.log("Collecting hostname information") self._hostname_text = self.driver.get_hostname_text() if self._hostname_text: ...
Return inventory information and collect if not available.
def inventory_text(self): """Return inventory information and collect if not available.""" if self._inventory_text is None: self.chain.connection.log("Collecting inventory information") self._inventory_text = self.driver.get_inventory_text() if self._inventory_text: ...
Return connected users information and collect if not available.
def users_text(self): """Return connected users information and collect if not available.""" if self._users_text is None: self.chain.connection.log("Getting connected users text") self._users_text = self.driver.get_users_text() if self._users_text: sel...
Provide protocol name based on node_info.
def get_protocol_name(self): """Provide protocol name based on node_info.""" protocol_name = self.node_info.protocol if self.is_console: protocol_name += '_console' return protocol_name
Extend prompt with flexible mode handling regexp.
def make_dynamic_prompt(self, prompt): """Extend prompt with flexible mode handling regexp.""" if prompt: self.prompt_re = self.driver.make_dynamic_prompt(prompt)
Update udi.
def update_udi(self): """Update udi.""" self.chain.connection.log("Parsing inventory") # TODO: Maybe validate if udi is complete self.udi = parse_inventory(self.inventory_text)
Update config mode.
def update_config_mode(self, prompt=None): """Update config mode.""" # TODO: Fix the conflict with config mode attribute at connection if prompt: self.mode = self.driver.update_config_mode(prompt) else: self.mode = self.driver.update_config_mode(self.prompt)
Update driver based on new prompt.
def update_driver(self, prompt): """Update driver based on new prompt.""" prompt = prompt.lstrip() self.chain.connection.log("({}): Prompt: '{}'".format(self.driver.platform, prompt)) self.prompt = prompt driver_name = self.driver.update_driver(prompt) if driver_name is N...
Send commands to prepare terminal session configuration.
def prepare_terminal_session(self): """Send commands to prepare terminal session configuration.""" for cmd in self.driver.prepare_terminal_session: try: self.send(cmd) except CommandSyntaxError: self.chain.connection.log("Command not supported or n...
Update os_type attribute.
def update_os_type(self): """Update os_type attribute.""" self.chain.connection.log("Detecting os type") os_type = self.driver.get_os_type(self.version_text) if os_type: self.chain.connection.log("SW Type: {}".format(os_type)) self.os_type = os_type
Update os_version attribute.
def update_os_version(self): """Update os_version attribute.""" self.chain.connection.log("Detecting os version") os_version = self.driver.get_os_version(self.version_text) if os_version: self.chain.connection.log("SW Version: {}".format(os_version)) self.os_versi...
Update family attribute.
def update_family(self): """Update family attribute.""" self.chain.connection.log("Detecting hw family") family = self.driver.get_hw_family(self.version_text) if family: self.chain.connection.log("HW Family: {}".format(family)) self.family = family
Update platform attribute.
def update_platform(self): """Update platform attribute.""" self.chain.connection.log("Detecting hw platform") platform = self.driver.get_hw_platform(self.udi) if platform: self.chain.connection.log("HW Platform: {}".format(platform)) self.platform = platform
Update is_console whether connected via console.
def update_console(self): """Update is_console whether connected via console.""" self.chain.connection.log("Detecting console connection") is_console = self.driver.is_console(self.users_text) if is_console is not None: self.is_console = is_console
Reload device.
def reload(self, reload_timeout, save_config, no_reload_cmd): """Reload device.""" if not no_reload_cmd: self.ctrl.send_command(self.driver.reload_cmd) return self.driver.reload(reload_timeout, save_config)
Wrap the FSM code.
def run_fsm(self, name, command, events, transitions, timeout, max_transitions=20): """Wrap the FSM code.""" self.ctrl.send_command(command) return FSM(name, self, events, transitions, timeout=timeout, max_transitions=max_transitions).run()
Apply config to the device.
def config(self, configlet, plane, **attributes): """Apply config to the device.""" try: config_text = configlet.format(**attributes) except KeyError as exp: raise CommandSyntaxError("Configuration template error: {}".format(str(exp))) return self.driver.config(c...
Return the version information from Unix host.
def get_version_text(self): """Return the version information from Unix host.""" version_text = None try: version_text = self.device.send('uname -sr', timeout=10) except CommandError as exc: exc.command = 'show version' raise exc return versi...
Device object generator.
def device_gen(chain, urls): """Device object generator.""" itr = iter(urls) last = next(itr) for url in itr: yield Device(chain, make_hop_info_from_url(last), driver_name='jumphost', is_target=False) last = url yield Device(chain, make_hop_info_from_url(last), driver_name='generic',...
Connect to the target device using the intermediate jumphosts.
def connect(self): """Connect to the target device using the intermediate jumphosts.""" device = None # logger.debug("Connecting to: {}".format(str(self))) for device in self.devices: if not device.connected: self.connection.emit_message("Connecting {}".format...
Disconnect from the device.
def disconnect(self): """Disconnect from the device.""" self.target_device.disconnect() self.ctrl.disconnect() self.tail_disconnect(-1)
Return if target device is discovered.
def is_discovered(self): """Return if target device is discovered.""" if self.target_device is None: return False if None in (self.target_device.version_text, self.target_device.os_type, self.target_device.os_version, self.target_device.inventory_text, self.targe...
Return the list of intermediate prompts. All except target.
def get_previous_prompts(self, device): """Return the list of intermediate prompts. All except target.""" device_index = self.devices.index(device) prompts = [re.compile("(?!x)x")] + \ [dev.prompt_re for dev in self.devices[:device_index] if dev.prompt_re is not None] r...
Return the device index in the chain based on prompt.
def get_device_index_based_on_prompt(self, prompt): """Return the device index in the chain based on prompt.""" conn_info = "" for device in self.devices: conn_info += str(device) + "->" if device.prompt == prompt: self.connection.log("Connected: {}".forma...
Mark all devices disconnected except target in the chain.
def tail_disconnect(self, index): """Mark all devices disconnected except target in the chain.""" try: for device in self.devices[index + 1:]: device.connected = False except IndexError: pass
Send command to the target device.
def send(self, cmd, timeout, wait_for_string, password): """Send command to the target device.""" return self.target_device.send(cmd, timeout=timeout, wait_for_string=wait_for_string, password=password)
Update the chain object with the predefined data.
def update(self, data): """Update the chain object with the predefined data.""" if data is None: for device in self.devices: device.clear_info() else: for device, device_info in zip(self.devices, data): device.device_info = device_info ...
Wrap the FSM action function providing extended logging information based on doc string.
def action(func): """Wrap the FSM action function providing extended logging information based on doc string.""" @wraps(func) def call_action(*args, **kwargs): """Wrap the function with logger debug.""" try: ctx = kwargs['ctx'] except KeyError: ctx = None ...
Start the FSM. Returns: boolean: True if FSM reaches the last state or false if the exception or error message was raised
def run(self): """Start the FSM. Returns: boolean: True if FSM reaches the last state or false if the exception or error message was raised """ ctx = FSM.Context(self.name, self.device) transition_counter = 0 timeout = self.timeout self.log("{} Start...
The state of the mock server will be stored in the resulting object created here
def get_store(url_details): """ The state of the mock server will be stored in the resulting object created here """ store = {} for detail in url_details: base_url = detail['url'].strip() # If a url detail has instances, it means that # we want to also create an endpoint...
Builds a server file. 1. Extract mock response details from all valid docstrings in existing views 2. Parse and generate mock values 3. Create a store of all endpoints and data 4. Construct server file
def build(port=8000, fixtures=None): """ Builds a server file. 1. Extract mock response details from all valid docstrings in existing views 2. Parse and generate mock values 3. Create a store of all endpoints and data 4. Construct server file """ extractor = Extractor() parser = Par...
Get the preferred subtag. :return: preferred :class:`language_tags.Subtag.Subtag` if exists, otherwise None.
def preferred(self): """ Get the preferred subtag. :return: preferred :class:`language_tags.Subtag.Subtag` if exists, otherwise None. """ if 'Preferred-Value' in self.data['record']: preferred = self.data['record']['Preferred-Value'] type = self.data['typ...
Get the subtag code conventional format according to RFC 5646 section 2.1.1. :return: string -- subtag code conventional format.
def format(self): """ Get the subtag code conventional format according to RFC 5646 section 2.1.1. :return: string -- subtag code conventional format. """ subtag = self.data['subtag'] if self.data['type'] == 'region': return subtag.upper() if self.dat...
Creates a Freshbooks client for a freshbooks domain, using an auth object.
def AuthorizingClient( domain, auth, request_encoder, response_decoder, user_agent=None ): """Creates a Freshbooks client for a freshbooks domain, using an auth object. """ http_transport = transport.HttpTransport( api_url(domain), build_headers(auth, user_agent)...
Creates a Freshbooks client for a freshbooks domain, using token-based auth. The optional request_encoder and response_decoder parameters can be passed the logging_request_encoder and logging_response_decoder objects from this module, or custom encoders, to aid debugging or change the behaviour...
def TokenClient( domain, token, user_agent=None, request_encoder=default_request_encoder, response_decoder=default_response_decoder, ): """Creates a Freshbooks client for a freshbooks domain, using token-based auth. The optional request_encoder and response_decoder parameters can be...
Creates a Freshbooks client for a freshbooks domain, using OAuth. Token management is assumed to have been handled out of band. The optional request_encoder and response_decoder parameters can be passed the logging_request_encoder and logging_response_decoder objects from this module, or custom enc...
def OAuthClient( domain, consumer_key, consumer_secret, token, token_secret, user_agent=None, request_encoder=default_request_encoder, response_decoder=default_response_decoder ): """Creates a Freshbooks client for a freshbooks domain, using OAuth. Token management is assumed to ...
r"""Generates a covariance matrix according to an squared-exponential autocovariance .. math:: \left\langle x_i x_j \right\rangle = \sigma_0^2 \delta_{ij} + \sigma^2 \exp\left[ - \frac{\left| t_i - t_j\right|^2}{2 \tau^2} \right]
def generate_covariance(ts, sigma, tau): r"""Generates a covariance matrix according to an squared-exponential autocovariance .. math:: \left\langle x_i x_j \right\rangle = \sigma_0^2 \delta_{ij} + \sigma^2 \exp\left[ - \frac{\left| t_i - t_j\right|^2}{2 \tau^2} \right] """ ndim = ...
The medias needed to enhance the admin page.
def _media(self): """ The medias needed to enhance the admin page. """ media = super(EntryAdminTinyMCEMixin, self).media media += TinyMCE().media + Media( js=[reverse('tinymce-js', args=['admin/zinnia/entry']), reverse('tinymce-filebrowser-callback')]...
Creates an etree element following the simple field convention. Values are assumed to be strs, unicodes, ints, floats, or Decimals: >>> element = encode_as_simple('foo', '5') >>> element.tag == 'foo' True >>> element.text == '5' True >>> element = encode_as_simpl...
def encode_as_simple(name, value): """Creates an etree element following the simple field convention. Values are assumed to be strs, unicodes, ints, floats, or Decimals: >>> element = encode_as_simple('foo', '5') >>> element.tag == 'foo' True >>> element.text == '5' ...
Wait for string FSM for XR 64 bit.
def wait_for_string(self, expected_string, timeout=60): """Wait for string FSM for XR 64 bit.""" ADMIN_USERNAME_PROMPT = re.compile("Admin Username:") ADMIN_PASSWORD_PROMPT = re.compile("Password:") # Big thanks to calvados developers for make this FSM such complex ;-) # ...
Reload the device.
def reload(self, reload_timeout, save_config): """Reload the device.""" MAX_BOOT_TIME = 1800 # 30 minutes - TODO(klstanie): move to config RELOAD_PROMPT = re.compile(re.escape("Reload hardware module ? [no,yes]")) START_TO_BACKUP = re.compile("Status report.*START TO BACKUP") B...
Returns the radial velocity measurements associated with the planets in parameters ps at times ts. The returned array has shape (Nts,).
def rv_model(ts, K, e, omega, chi, P): """Returns the radial velocity measurements associated with the planets in parameters ps at times ts. The returned array has shape (Nts,).""" assert ts.ndim == 1, 'ts must be one-dimensional' return kp.rv_model(ts, K, e, omega, chi, P)
Decrypt GPG objects in configuration. Args: cfg (dict): configuration dictionary gpg_config (dict): gpg configuration dict of arguments for gpg including: homedir, binary, and keyring (require all if any) example: gpg_config = {'homedir': '~/....
def gpg_decrypt(cfg, gpg_config=None): """Decrypt GPG objects in configuration. Args: cfg (dict): configuration dictionary gpg_config (dict): gpg configuration dict of arguments for gpg including: homedir, binary, and keyring (require all if any) example:...
Decrypt KMS objects in configuration. Args: cfg (dict): configuration dictionary aws_config (dict): aws credentials dict of arguments passed into boto3 session example: aws_creds = {'aws_access_key_id': aws_access_key_id, 'aws_sec...
def kms_decrypt(cfg, aws_config=None): """Decrypt KMS objects in configuration. Args: cfg (dict): configuration dictionary aws_config (dict): aws credentials dict of arguments passed into boto3 session example: aws_creds = {'aws_access_key_id': aws_access...
Return the version information from the device.
def get_version_text(self): """Return the version information from the device.""" show_version_brief_not_supported = False version_text = None try: version_text = self.device.send("show version brief", timeout=120) except CommandError: show_version_brief_n...
Return the inventory information from the device.
def get_inventory_text(self): """Return the inventory information from the device.""" inventory_text = None if self.inventory_cmd: try: inventory_text = self.device.send(self.inventory_cmd, timeout=120) self.log('Inventory collected') excep...
Return the users logged in information from the device.
def get_users_text(self): """Return the users logged in information from the device.""" users_text = None if self.users_cmd: try: users_text = self.device.send(self.users_cmd, timeout=60) except CommandError: self.log('Unable to collect con...
Return the OS type information from the device.
def get_os_type(self, version_text): # pylint: disable=no-self-use """Return the OS type information from the device.""" os_type = None if version_text is None: return os_type match = re.search("(XR|XE|NX-OS)", version_text) if match: os_type = match.gro...
Return the OS version information from the device.
def get_os_version(self, version_text): """Return the OS version information from the device.""" os_version = None if version_text is None: return os_version match = re.search(self.version_re, version_text, re.MULTILINE) if match: os_version = match.group(...
Return the HW family information from the device.
def get_hw_family(self, version_text): """Return the HW family information from the device.""" family = None if version_text is None: return family match = re.search(self.platform_re, version_text, re.MULTILINE) if match: self.platform_string = match.grou...
Return th HW platform information from the device.
def get_hw_platform(self, udi): """Return th HW platform information from the device.""" platform = None try: pid = udi['pid'] if pid == '': self.log("Empty PID. Use the hw family from the platform string.") return self.raw_family ...
Return if device is connected over console.
def is_console(self, users_text): """Return if device is connected over console.""" if users_text is None: self.log("Console information not collected") return None for line in users_text.split('\n'): if '*' in line: match = re.search(self.vty...
Wait for string FSM.
def wait_for_string(self, expected_string, timeout=60): """Wait for string FSM.""" # 0 1 2 3 events = [self.syntax_error_re, self.connection_closed_re, expected_string, self.press_return_re, ...
Reload the device and waits for device to boot up. It posts the informational message to the log if not implemented by device driver.
def reload(self, reload_timeout=300, save_config=True): """Reload the device and waits for device to boot up. It posts the informational message to the log if not implemented by device driver. """ self.log("Reload not implemented on {} platform".format(self.platform))
Extract the base prompt pattern.
def base_prompt(self, prompt): """Extract the base prompt pattern.""" if prompt is None: return None if not self.device.is_target: return prompt pattern = pattern_manager.pattern(self.platform, "prompt_dynamic", compiled=False) pattern = pattern.format(pro...
Update config mode based on the prompt analysis.
def update_config_mode(self, prompt): # pylint: disable=no-self-use """Update config mode based on the prompt analysis.""" mode = 'global' if prompt: if 'config' in prompt: mode = 'config' elif 'admin' in prompt: mode = 'admin' se...
Update the hostname based on the prompt analysis.
def update_hostname(self, prompt): """Update the hostname based on the prompt analysis.""" result = re.search(self.prompt_re, prompt) if result: hostname = result.group('hostname') self.log("Hostname detected: {}".format(hostname)) else: hostname = sel...
Enter the device plane. Enter the device plane a.k.a. mode, i.e. admin, qnx, calvados
def enter_plane(self, plane): """Enter the device plane. Enter the device plane a.k.a. mode, i.e. admin, qnx, calvados """ try: cmd = CONF['driver'][self.platform]['planes'][plane] self.plane = plane except KeyError: cmd = None if cmd...
This is a temporary static method, when there are more factory methods, we can move this to another class or find a way to maintain it in a scalable manner
def handle_other_factory_method(attr, minimum, maximum): """ This is a temporary static method, when there are more factory methods, we can move this to another class or find a way to maintain it in a scalable manner """ if attr == 'percentage': if minimum: ...
Callable used in re.sub to match, generate and replace the valid syntax found in the mock response specifications.
def _replace_faker_attr(self, matchobj): """ Callable used in re.sub to match, generate and replace the valid syntax found in the mock response specifications. """ attr = matchobj.group(0).replace('<', '').replace('>', '') # Prepare template to handle quotes # Fo...
Retrieves the syntax from the response and goes through each one to generate and replace it with mock values
def _parse_syntax(self, raw): """ Retrieves the syntax from the response and goes through each one to generate and replace it with mock values """ raw = str(raw) # treat the value as a string regardless of its actual data type has_syntax = re.findall(r'<(\^)?(fk__)?(\w+)...