repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
sequence
docstring
stringlengths
3
17.3k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
happyleavesaoc/aoc-mgz
mgz/recorded_game/__init__.py
RecordedGame._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]) for player in self._summary['players']: for age, reached in player['ages'].items(): if reached: ages_reached.add(age) ages = ['imperial', 'castle', 'feudal', 'dark'] for age in ages: if age in ages_reached: return age
python
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]) for player in self._summary['players']: for age, reached in player['ages'].items(): if reached: ages_reached.add(age) ages = ['imperial', 'castle', 'feudal', 'dark'] for age in ages: if age in ages_reached: return age
[ "def", "_won_in", "(", "self", ")", ":", "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", "]", ")", "for", "player", "in", "self", ".", "_summary", "[", "'players'", "]", ":", "for", "age", ",", "reached", "in", "player", "[", "'ages'", "]", ".", "items", "(", ")", ":", "if", "reached", ":", "ages_reached", ".", "add", "(", "age", ")", "ages", "=", "[", "'imperial'", ",", "'castle'", ",", "'feudal'", ",", "'dark'", "]", "for", "age", "in", "ages", ":", "if", "age", "in", "ages_reached", ":", "return", "age" ]
Get age the game was won in.
[ "Get", "age", "the", "game", "was", "won", "in", "." ]
13fc379cc062d7640bfa028eed9c0d45d37a7b2b
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/recorded_game/__init__.py#L398-L413
train
happyleavesaoc/aoc-mgz
mgz/recorded_game/__init__.py
RecordedGame._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
python
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
[ "def", "_rec_owner_number", "(", "self", ")", ":", "player", "=", "self", ".", "_header", ".", "initial", ".", "players", "[", "self", ".", "_header", ".", "replay", ".", "rec_player", "]", "return", "player", ".", "attributes", ".", "player_color", "+", "1" ]
Get rec owner number.
[ "Get", "rec", "owner", "number", "." ]
13fc379cc062d7640bfa028eed9c0d45d37a7b2b
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/recorded_game/__init__.py#L415-L418
train
happyleavesaoc/aoc-mgz
mgz/recorded_game/__init__.py
RecordedGame._get_timestamp
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
python
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
[ "def", "_get_timestamp", "(", "self", ")", ":", "filename_date", "=", "_find_date", "(", "os", ".", "path", ".", "basename", "(", "self", ".", "_path", ")", ")", "if", "filename_date", ":", "return", "filename_date" ]
Get modification timestamp from rec file.
[ "Get", "modification", "timestamp", "from", "rec", "file", "." ]
13fc379cc062d7640bfa028eed9c0d45d37a7b2b
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/recorded_game/__init__.py#L427-L431
train
happyleavesaoc/aoc-mgz
mgz/recorded_game/__init__.py
RecordedGame._set_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['players']: if player_number == player['number']: if player['winner']: team['winner'] = True
python
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['players']: if player_number == player['number']: if player['winner']: team['winner'] = True
[ "def", "_set_winning_team", "(", "self", ")", ":", "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", "[", "'players'", "]", ":", "if", "player_number", "==", "player", "[", "'number'", "]", ":", "if", "player", "[", "'winner'", "]", ":", "team", "[", "'winner'", "]", "=", "True" ]
Mark the winning team.
[ "Mark", "the", "winning", "team", "." ]
13fc379cc062d7640bfa028eed9c0d45d37a7b2b
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/recorded_game/__init__.py#L444-L454
train
happyleavesaoc/aoc-mgz
mgz/recorded_game/__init__.py
RecordedGame._map_hash
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.name().encode() player_bytes = b'' for _, attributes in self._players(): player_bytes += (mgz.const.PLAYER_COLORS[attributes.player_color].encode() + attributes.player_name.encode() + mgz.const.CIVILIZATION_NAMES[attributes.civilization].encode()) return hashlib.sha1(elevation_bytes + map_name_bytes + player_bytes).hexdigest()
python
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.name().encode() player_bytes = b'' for _, attributes in self._players(): player_bytes += (mgz.const.PLAYER_COLORS[attributes.player_color].encode() + attributes.player_name.encode() + mgz.const.CIVILIZATION_NAMES[attributes.civilization].encode()) return hashlib.sha1(elevation_bytes + map_name_bytes + player_bytes).hexdigest()
[ "def", "_map_hash", "(", "self", ")", ":", "elevation_bytes", "=", "bytes", "(", "[", "tile", ".", "elevation", "for", "tile", "in", "self", ".", "_header", ".", "map_info", ".", "tile", "]", ")", "map_name_bytes", "=", "self", ".", "_map", ".", "name", "(", ")", ".", "encode", "(", ")", "player_bytes", "=", "b''", "for", "_", ",", "attributes", "in", "self", ".", "_players", "(", ")", ":", "player_bytes", "+=", "(", "mgz", ".", "const", ".", "PLAYER_COLORS", "[", "attributes", ".", "player_color", "]", ".", "encode", "(", ")", "+", "attributes", ".", "player_name", ".", "encode", "(", ")", "+", "mgz", ".", "const", ".", "CIVILIZATION_NAMES", "[", "attributes", ".", "civilization", "]", ".", "encode", "(", ")", ")", "return", "hashlib", ".", "sha1", "(", "elevation_bytes", "+", "map_name_bytes", "+", "player_bytes", ")", ".", "hexdigest", "(", ")" ]
Compute a map hash based on a combination of map attributes. - Elevation - Map name - Player names, colors, and civilizations
[ "Compute", "a", "map", "hash", "based", "on", "a", "combination", "of", "map", "attributes", "." ]
13fc379cc062d7640bfa028eed9c0d45d37a7b2b
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/recorded_game/__init__.py#L456-L470
train
kstaniek/condoor
condoor/device.py
Device.device_info
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 automatically 'driver_name': self.driver.platform, 'mode': self.mode, 'is_console': self.is_console, 'is_target': self.is_target, # 'prompt': self.driver.base_prompt(self.prompt), 'hostname': self.hostname, }
python
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 automatically 'driver_name': self.driver.platform, 'mode': self.mode, 'is_console': self.is_console, 'is_target': self.is_target, # 'prompt': self.driver.base_prompt(self.prompt), 'hostname': self.hostname, }
[ "def", "device_info", "(", "self", ")", ":", "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 automatically", "'driver_name'", ":", "self", ".", "driver", ".", "platform", ",", "'mode'", ":", "self", ".", "mode", ",", "'is_console'", ":", "self", ".", "is_console", ",", "'is_target'", ":", "self", ".", "is_target", ",", "# 'prompt': self.driver.base_prompt(self.prompt),", "'hostname'", ":", "self", ".", "hostname", ",", "}" ]
Return device info dict.
[ "Return", "device", "info", "dict", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/device.py#L65-L80
train
kstaniek/condoor
condoor/device.py
Device.clear_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_console = None self.prompt = None self.prompt_re = None
python
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_console = None self.prompt = None self.prompt_re = None
[ "def", "clear_info", "(", "self", ")", ":", "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_console = None", "self", ".", "prompt", "=", "None", "self", ".", "prompt_re", "=", "None" ]
Clear the device info.
[ "Clear", "the", "device", "info", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/device.py#L92-L104
train
kstaniek/condoor
condoor/device.py
Device.disconnect
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: self.send('exit', timeout=10) except CommandTimeoutError: break self.protocol.disconnect(self.driver) self.protocol = None self.connected = False self.ctrl = None
python
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: self.send('exit', timeout=10) except CommandTimeoutError: break self.protocol.disconnect(self.driver) self.protocol = None self.connected = False self.ctrl = None
[ "def", "disconnect", "(", "self", ")", ":", "self", ".", "chain", ".", "connection", ".", "log", "(", "\"Disconnecting: {}\"", ".", "format", "(", "self", ")", ")", "if", "self", ".", "connected", ":", "if", "self", ".", "protocol", ":", "if", "self", ".", "is_console", ":", "while", "self", ".", "mode", "!=", "'global'", ":", "try", ":", "self", ".", "send", "(", "'exit'", ",", "timeout", "=", "10", ")", "except", "CommandTimeoutError", ":", "break", "self", ".", "protocol", ".", "disconnect", "(", "self", ".", "driver", ")", "self", ".", "protocol", "=", "None", "self", ".", "connected", "=", "False", "self", ".", "ctrl", "=", "None" ]
Disconnect the device.
[ "Disconnect", "the", "device", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/device.py#L182-L198
train
kstaniek/condoor
condoor/device.py
Device.make_driver
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 as e: # pylint: disable=invalid-name print("driver name: {}".format(driver_name)) self.chain.connection.log("Import error: {}: '{}'".format(driver_name, str(e))) # no driver - call again with default 'generic' return self.make_driver() self.chain.connection.log("Make Device: {} with Driver: {}".format(self, driver_class.platform)) return driver_class(self)
python
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 as e: # pylint: disable=invalid-name print("driver name: {}".format(driver_name)) self.chain.connection.log("Import error: {}: '{}'".format(driver_name, str(e))) # no driver - call again with default 'generic' return self.make_driver() self.chain.connection.log("Make Device: {} with Driver: {}".format(self, driver_class.platform)) return driver_class(self)
[ "def", "make_driver", "(", "self", ",", "driver_name", "=", "'generic'", ")", ":", "module_str", "=", "'condoor.drivers.%s'", "%", "driver_name", "try", ":", "__import__", "(", "module_str", ")", "module", "=", "sys", ".", "modules", "[", "module_str", "]", "driver_class", "=", "getattr", "(", "module", ",", "'Driver'", ")", "except", "ImportError", "as", "e", ":", "# pylint: disable=invalid-name", "print", "(", "\"driver name: {}\"", ".", "format", "(", "driver_name", ")", ")", "self", ".", "chain", ".", "connection", ".", "log", "(", "\"Import error: {}: '{}'\"", ".", "format", "(", "driver_name", ",", "str", "(", "e", ")", ")", ")", "# no driver - call again with default 'generic'", "return", "self", ".", "make_driver", "(", ")", "self", ".", "chain", ".", "connection", ".", "log", "(", "\"Make Device: {} with Driver: {}\"", ".", "format", "(", "self", ",", "driver_class", ".", "platform", ")", ")", "return", "driver_class", "(", "self", ")" ]
Make driver factory function.
[ "Make", "driver", "factory", "function", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/device.py#L310-L324
train
kstaniek/condoor
condoor/device.py
Device.version_text
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.chain.connection.log("Version info collected") else: self.chain.connection.log("Version info not collected") return self._version_text
python
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.chain.connection.log("Version info collected") else: self.chain.connection.log("Version info not collected") return self._version_text
[ "def", "version_text", "(", "self", ")", ":", "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", ".", "chain", ".", "connection", ".", "log", "(", "\"Version info collected\"", ")", "else", ":", "self", ".", "chain", ".", "connection", ".", "log", "(", "\"Version info not collected\"", ")", "return", "self", ".", "_version_text" ]
Return version text and collect if not collected.
[ "Return", "version", "text", "and", "collect", "if", "not", "collected", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/device.py#L331-L341
train
kstaniek/condoor
condoor/device.py
Device.hostname_text
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: self.chain.connection.log("Hostname info collected") else: self.chain.connection.log("Hostname info not collected") return self._hostname_text
python
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: self.chain.connection.log("Hostname info collected") else: self.chain.connection.log("Hostname info not collected") return self._hostname_text
[ "def", "hostname_text", "(", "self", ")", ":", "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", ":", "self", ".", "chain", ".", "connection", ".", "log", "(", "\"Hostname info collected\"", ")", "else", ":", "self", ".", "chain", ".", "connection", ".", "log", "(", "\"Hostname info not collected\"", ")", "return", "self", ".", "_hostname_text" ]
Return hostname text and collect if not collected.
[ "Return", "hostname", "text", "and", "collect", "if", "not", "collected", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/device.py#L344-L353
train
kstaniek/condoor
condoor/device.py
Device.inventory_text
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: self.chain.connection.log("Inventory info collected") else: self.chain.connection.log("Inventory info not collected") return self._inventory_text
python
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: self.chain.connection.log("Inventory info collected") else: self.chain.connection.log("Inventory info not collected") return self._inventory_text
[ "def", "inventory_text", "(", "self", ")", ":", "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", ":", "self", ".", "chain", ".", "connection", ".", "log", "(", "\"Inventory info collected\"", ")", "else", ":", "self", ".", "chain", ".", "connection", ".", "log", "(", "\"Inventory info not collected\"", ")", "return", "self", ".", "_inventory_text" ]
Return inventory information and collect if not available.
[ "Return", "inventory", "information", "and", "collect", "if", "not", "available", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/device.py#L356-L365
train
kstaniek/condoor
condoor/device.py
Device.users_text
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: self.chain.connection.log("Users text collected") else: self.chain.connection.log("Users text not collected") return self._users_text
python
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: self.chain.connection.log("Users text collected") else: self.chain.connection.log("Users text not collected") return self._users_text
[ "def", "users_text", "(", "self", ")", ":", "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", ":", "self", ".", "chain", ".", "connection", ".", "log", "(", "\"Users text collected\"", ")", "else", ":", "self", ".", "chain", ".", "connection", ".", "log", "(", "\"Users text not collected\"", ")", "return", "self", ".", "_users_text" ]
Return connected users information and collect if not available.
[ "Return", "connected", "users", "information", "and", "collect", "if", "not", "available", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/device.py#L368-L377
train
kstaniek/condoor
condoor/device.py
Device.get_protocol_name
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
python
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
[ "def", "get_protocol_name", "(", "self", ")", ":", "protocol_name", "=", "self", ".", "node_info", ".", "protocol", "if", "self", ".", "is_console", ":", "protocol_name", "+=", "'_console'", "return", "protocol_name" ]
Provide protocol name based on node_info.
[ "Provide", "protocol", "name", "based", "on", "node_info", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/device.py#L379-L384
train
kstaniek/condoor
condoor/device.py
Device.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)
python
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)
[ "def", "update_udi", "(", "self", ")", ":", "self", ".", "chain", ".", "connection", ".", "log", "(", "\"Parsing inventory\"", ")", "# TODO: Maybe validate if udi is complete", "self", ".", "udi", "=", "parse_inventory", "(", "self", ".", "inventory_text", ")" ]
Update udi.
[ "Update", "udi", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/device.py#L391-L395
train
kstaniek/condoor
condoor/device.py
Device.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)
python
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)
[ "def", "update_config_mode", "(", "self", ",", "prompt", "=", "None", ")", ":", "# 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 config mode.
[ "Update", "config", "mode", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/device.py#L397-L403
train
kstaniek/condoor
condoor/device.py
Device.update_driver
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 None: self.chain.connection.log("New driver not detected. Using existing {} driver.".format(self.driver.platform)) return self.driver_name = driver_name
python
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 None: self.chain.connection.log("New driver not detected. Using existing {} driver.".format(self.driver.platform)) return self.driver_name = driver_name
[ "def", "update_driver", "(", "self", ",", "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", "None", ":", "self", ".", "chain", ".", "connection", ".", "log", "(", "\"New driver not detected. Using existing {} driver.\"", ".", "format", "(", "self", ".", "driver", ".", "platform", ")", ")", "return", "self", ".", "driver_name", "=", "driver_name" ]
Update driver based on new prompt.
[ "Update", "driver", "based", "on", "new", "prompt", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/device.py#L409-L418
train
kstaniek/condoor
condoor/device.py
Device.prepare_terminal_session
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 not authorized: '{}'. Skipping".format(cmd)) pass
python
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 not authorized: '{}'. Skipping".format(cmd)) pass
[ "def", "prepare_terminal_session", "(", "self", ")", ":", "for", "cmd", "in", "self", ".", "driver", ".", "prepare_terminal_session", ":", "try", ":", "self", ".", "send", "(", "cmd", ")", "except", "CommandSyntaxError", ":", "self", ".", "chain", ".", "connection", ".", "log", "(", "\"Command not supported or not authorized: '{}'. Skipping\"", ".", "format", "(", "cmd", ")", ")", "pass" ]
Send commands to prepare terminal session configuration.
[ "Send", "commands", "to", "prepare", "terminal", "session", "configuration", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/device.py#L420-L427
train
kstaniek/condoor
condoor/device.py
Device.update_os_type
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
python
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
[ "def", "update_os_type", "(", "self", ")", ":", "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_type attribute.
[ "Update", "os_type", "attribute", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/device.py#L429-L435
train
kstaniek/condoor
condoor/device.py
Device.update_os_version
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_version = os_version
python
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_version = os_version
[ "def", "update_os_version", "(", "self", ")", ":", "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_version", "=", "os_version" ]
Update os_version attribute.
[ "Update", "os_version", "attribute", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/device.py#L437-L443
train
kstaniek/condoor
condoor/device.py
Device.update_family
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
python
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
[ "def", "update_family", "(", "self", ")", ":", "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 family attribute.
[ "Update", "family", "attribute", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/device.py#L445-L451
train
kstaniek/condoor
condoor/device.py
Device.update_platform
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
python
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
[ "def", "update_platform", "(", "self", ")", ":", "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 platform attribute.
[ "Update", "platform", "attribute", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/device.py#L453-L459
train
kstaniek/condoor
condoor/device.py
Device.update_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
python
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
[ "def", "update_console", "(", "self", ")", ":", "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" ]
Update is_console whether connected via console.
[ "Update", "is_console", "whether", "connected", "via", "console", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/device.py#L461-L466
train
kstaniek/condoor
condoor/device.py
Device.reload
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)
python
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)
[ "def", "reload", "(", "self", ",", "reload_timeout", ",", "save_config", ",", "no_reload_cmd", ")", ":", "if", "not", "no_reload_cmd", ":", "self", ".", "ctrl", ".", "send_command", "(", "self", ".", "driver", ".", "reload_cmd", ")", "return", "self", ".", "driver", ".", "reload", "(", "reload_timeout", ",", "save_config", ")" ]
Reload device.
[ "Reload", "device", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/device.py#L476-L480
train
kstaniek/condoor
condoor/device.py
Device.run_fsm
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()
python
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()
[ "def", "run_fsm", "(", "self", ",", "name", ",", "command", ",", "events", ",", "transitions", ",", "timeout", ",", "max_transitions", "=", "20", ")", ":", "self", ".", "ctrl", ".", "send_command", "(", "command", ")", "return", "FSM", "(", "name", ",", "self", ",", "events", ",", "transitions", ",", "timeout", "=", "timeout", ",", "max_transitions", "=", "max_transitions", ")", ".", "run", "(", ")" ]
Wrap the FSM code.
[ "Wrap", "the", "FSM", "code", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/device.py#L482-L485
train
kstaniek/condoor
condoor/device.py
Device.config
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(config_text, plane)
python
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(config_text, plane)
[ "def", "config", "(", "self", ",", "configlet", ",", "plane", ",", "*", "*", "attributes", ")", ":", "try", ":", "config_text", "=", "configlet", ".", "format", "(", "*", "*", "attributes", ")", "except", "KeyError", "as", "exp", ":", "raise", "CommandSyntaxError", "(", "\"Configuration template error: {}\"", ".", "format", "(", "str", "(", "exp", ")", ")", ")", "return", "self", ".", "driver", ".", "config", "(", "config_text", ",", "plane", ")" ]
Apply config to the device.
[ "Apply", "config", "to", "the", "device", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/device.py#L487-L494
train
kstaniek/condoor
condoor/chain.py
device_gen
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', is_target=True)
python
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', is_target=True)
[ "def", "device_gen", "(", "chain", ",", "urls", ")", ":", "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'", ",", "is_target", "=", "True", ")" ]
Device object generator.
[ "Device", "object", "generator", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/chain.py#L12-L19
train
kstaniek/condoor
condoor/chain.py
Chain.connect
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(str(device)), log_level=logging.INFO) protocol_name = device.get_protocol_name() device.protocol = make_protocol(protocol_name, device) command = device.protocol.get_command() self.ctrl.spawn_session(command=command) try: result = device.connect(self.ctrl) except CommandSyntaxError as exc: # all commands during discovery provides itself in exception except # spawn session which is handled differently. If command syntax error is detected during spawning # a new session then the problem is either on jumphost or csm server. # The problem with spawning session is detected in connect FSM for telnet and ssh. if exc.command: cmd = exc.command host = device.hostname else: cmd = command host = "Jumphost/CSM" self.connection.log( "Command not supported or not authorized on {}: '{}'".format(host, cmd)) raise CommandError(message="Command not supported or not authorized", command=cmd, host=host) if result: # logger.info("Connected to {}".format(device)) self.connection.emit_message("Connected {}".format(device), log_level=logging.INFO) else: if device.last_error_msg: message = device.last_error_msg device.last_error_msg = None else: message = "Connection error" self.connection.log(message) raise ConnectionError(message) # , host=str(device)) if device is None: raise ConnectionError("No devices") return True
python
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(str(device)), log_level=logging.INFO) protocol_name = device.get_protocol_name() device.protocol = make_protocol(protocol_name, device) command = device.protocol.get_command() self.ctrl.spawn_session(command=command) try: result = device.connect(self.ctrl) except CommandSyntaxError as exc: # all commands during discovery provides itself in exception except # spawn session which is handled differently. If command syntax error is detected during spawning # a new session then the problem is either on jumphost or csm server. # The problem with spawning session is detected in connect FSM for telnet and ssh. if exc.command: cmd = exc.command host = device.hostname else: cmd = command host = "Jumphost/CSM" self.connection.log( "Command not supported or not authorized on {}: '{}'".format(host, cmd)) raise CommandError(message="Command not supported or not authorized", command=cmd, host=host) if result: # logger.info("Connected to {}".format(device)) self.connection.emit_message("Connected {}".format(device), log_level=logging.INFO) else: if device.last_error_msg: message = device.last_error_msg device.last_error_msg = None else: message = "Connection error" self.connection.log(message) raise ConnectionError(message) # , host=str(device)) if device is None: raise ConnectionError("No devices") return True
[ "def", "connect", "(", "self", ")", ":", "device", "=", "None", "# logger.debug(\"Connecting to: {}\".format(str(self)))", "for", "device", "in", "self", ".", "devices", ":", "if", "not", "device", ".", "connected", ":", "self", ".", "connection", ".", "emit_message", "(", "\"Connecting {}\"", ".", "format", "(", "str", "(", "device", ")", ")", ",", "log_level", "=", "logging", ".", "INFO", ")", "protocol_name", "=", "device", ".", "get_protocol_name", "(", ")", "device", ".", "protocol", "=", "make_protocol", "(", "protocol_name", ",", "device", ")", "command", "=", "device", ".", "protocol", ".", "get_command", "(", ")", "self", ".", "ctrl", ".", "spawn_session", "(", "command", "=", "command", ")", "try", ":", "result", "=", "device", ".", "connect", "(", "self", ".", "ctrl", ")", "except", "CommandSyntaxError", "as", "exc", ":", "# all commands during discovery provides itself in exception except", "# spawn session which is handled differently. If command syntax error is detected during spawning", "# a new session then the problem is either on jumphost or csm server.", "# The problem with spawning session is detected in connect FSM for telnet and ssh.", "if", "exc", ".", "command", ":", "cmd", "=", "exc", ".", "command", "host", "=", "device", ".", "hostname", "else", ":", "cmd", "=", "command", "host", "=", "\"Jumphost/CSM\"", "self", ".", "connection", ".", "log", "(", "\"Command not supported or not authorized on {}: '{}'\"", ".", "format", "(", "host", ",", "cmd", ")", ")", "raise", "CommandError", "(", "message", "=", "\"Command not supported or not authorized\"", ",", "command", "=", "cmd", ",", "host", "=", "host", ")", "if", "result", ":", "# logger.info(\"Connected to {}\".format(device))", "self", ".", "connection", ".", "emit_message", "(", "\"Connected {}\"", ".", "format", "(", "device", ")", ",", "log_level", "=", "logging", ".", "INFO", ")", "else", ":", "if", "device", ".", "last_error_msg", ":", "message", "=", "device", ".", "last_error_msg", "device", ".", "last_error_msg", "=", "None", "else", ":", "message", "=", "\"Connection error\"", "self", ".", "connection", ".", "log", "(", "message", ")", "raise", "ConnectionError", "(", "message", ")", "# , host=str(device))", "if", "device", "is", "None", ":", "raise", "ConnectionError", "(", "\"No devices\"", ")", "return", "True" ]
Connect to the target device using the intermediate jumphosts.
[ "Connect", "to", "the", "target", "device", "using", "the", "intermediate", "jumphosts", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/chain.py#L40-L87
train
kstaniek/condoor
condoor/chain.py
Chain.disconnect
def disconnect(self): """Disconnect from the device.""" self.target_device.disconnect() self.ctrl.disconnect() self.tail_disconnect(-1)
python
def disconnect(self): """Disconnect from the device.""" self.target_device.disconnect() self.ctrl.disconnect() self.tail_disconnect(-1)
[ "def", "disconnect", "(", "self", ")", ":", "self", ".", "target_device", ".", "disconnect", "(", ")", "self", ".", "ctrl", ".", "disconnect", "(", ")", "self", ".", "tail_disconnect", "(", "-", "1", ")" ]
Disconnect from the device.
[ "Disconnect", "from", "the", "device", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/chain.py#L89-L93
train
kstaniek/condoor
condoor/chain.py
Chain.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.target_device.family, self.target_device.platform): return False return True
python
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.target_device.family, self.target_device.platform): return False return True
[ "def", "is_discovered", "(", "self", ")", ":", "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", ".", "target_device", ".", "family", ",", "self", ".", "target_device", ".", "platform", ")", ":", "return", "False", "return", "True" ]
Return if target device is discovered.
[ "Return", "if", "target", "device", "is", "discovered", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/chain.py#L113-L121
train
kstaniek/condoor
condoor/chain.py
Chain.get_previous_prompts
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] return prompts
python
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] return prompts
[ "def", "get_previous_prompts", "(", "self", ",", "device", ")", ":", "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", "]", "return", "prompts" ]
Return the list of intermediate prompts. All except target.
[ "Return", "the", "list", "of", "intermediate", "prompts", ".", "All", "except", "target", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/chain.py#L131-L136
train
kstaniek/condoor
condoor/chain.py
Chain.get_device_index_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: {}".format(conn_info)) return self.devices.index(device) else: return None
python
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: {}".format(conn_info)) return self.devices.index(device) else: return None
[ "def", "get_device_index_based_on_prompt", "(", "self", ",", "prompt", ")", ":", "conn_info", "=", "\"\"", "for", "device", "in", "self", ".", "devices", ":", "conn_info", "+=", "str", "(", "device", ")", "+", "\"->\"", "if", "device", ".", "prompt", "==", "prompt", ":", "self", ".", "connection", ".", "log", "(", "\"Connected: {}\"", ".", "format", "(", "conn_info", ")", ")", "return", "self", ".", "devices", ".", "index", "(", "device", ")", "else", ":", "return", "None" ]
Return the device index in the chain based on prompt.
[ "Return", "the", "device", "index", "in", "the", "chain", "based", "on", "prompt", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/chain.py#L138-L147
train
kstaniek/condoor
condoor/chain.py
Chain.tail_disconnect
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
python
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
[ "def", "tail_disconnect", "(", "self", ",", "index", ")", ":", "try", ":", "for", "device", "in", "self", ".", "devices", "[", "index", "+", "1", ":", "]", ":", "device", ".", "connected", "=", "False", "except", "IndexError", ":", "pass" ]
Mark all devices disconnected except target in the chain.
[ "Mark", "all", "devices", "disconnected", "except", "target", "in", "the", "chain", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/chain.py#L149-L155
train
kstaniek/condoor
condoor/chain.py
Chain.send
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)
python
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)
[ "def", "send", "(", "self", ",", "cmd", ",", "timeout", ",", "wait_for_string", ",", "password", ")", ":", "return", "self", ".", "target_device", ".", "send", "(", "cmd", ",", "timeout", "=", "timeout", ",", "wait_for_string", "=", "wait_for_string", ",", "password", "=", "password", ")" ]
Send command to the target device.
[ "Send", "command", "to", "the", "target", "device", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/chain.py#L157-L159
train
kstaniek/condoor
condoor/chain.py
Chain.update
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 self.connection.log("Device information updated -> [{}]".format(device))
python
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 self.connection.log("Device information updated -> [{}]".format(device))
[ "def", "update", "(", "self", ",", "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", "self", ".", "connection", ".", "log", "(", "\"Device information updated -> [{}]\"", ".", "format", "(", "device", ")", ")" ]
Update the chain object with the predefined data.
[ "Update", "the", "chain", "object", "with", "the", "predefined", "data", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/chain.py#L161-L169
train
kstaniek/condoor
condoor/fsm.py
action
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 if ctx is None: try: ctx = args[-1] except IndexError: ctx = None if ctx: if func.__doc__ is None: ctx.device.chain.connection.log("A={}".format(func.__name__)) else: ctx.device.chain.connection.log("A={}".format(func.__doc__.split('\n', 1)[0])) return func(*args, **kwargs) return call_action
python
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 if ctx is None: try: ctx = args[-1] except IndexError: ctx = None if ctx: if func.__doc__ is None: ctx.device.chain.connection.log("A={}".format(func.__name__)) else: ctx.device.chain.connection.log("A={}".format(func.__doc__.split('\n', 1)[0])) return func(*args, **kwargs) return call_action
[ "def", "action", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "call_action", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"Wrap the function with logger debug.\"\"\"", "try", ":", "ctx", "=", "kwargs", "[", "'ctx'", "]", "except", "KeyError", ":", "ctx", "=", "None", "if", "ctx", "is", "None", ":", "try", ":", "ctx", "=", "args", "[", "-", "1", "]", "except", "IndexError", ":", "ctx", "=", "None", "if", "ctx", ":", "if", "func", ".", "__doc__", "is", "None", ":", "ctx", ".", "device", ".", "chain", ".", "connection", ".", "log", "(", "\"A={}\"", ".", "format", "(", "func", ".", "__name__", ")", ")", "else", ":", "ctx", ".", "device", ".", "chain", ".", "connection", ".", "log", "(", "\"A={}\"", ".", "format", "(", "func", ".", "__doc__", ".", "split", "(", "'\\n'", ",", "1", ")", "[", "0", "]", ")", ")", "return", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "call_action" ]
Wrap the FSM action function providing extended logging information based on doc string.
[ "Wrap", "the", "FSM", "action", "function", "providing", "extended", "logging", "information", "based", "on", "doc", "string", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/fsm.py#L12-L33
train
kstaniek/condoor
condoor/fsm.py
FSM.run
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".format(self.name)) while transition_counter < self.max_transitions: transition_counter += 1 try: start_time = time() if self.init_pattern is None: ctx.event = self.ctrl.expect(self.events, searchwindowsize=self.searchwindowsize, timeout=timeout) else: self.log("INIT_PATTERN={}".format(pattern_to_str(self.init_pattern))) try: ctx.event = self.events.index(self.init_pattern) except ValueError: self.log("INIT_PATTERN unknown.") continue finally: self.init_pattern = None finish_time = time() - start_time key = (ctx.event, ctx.state) ctx.pattern = self.events[ctx.event] if key in self.transition_table: transition = self.transition_table[key] next_state, action_instance, next_timeout = transition self.log("E={},S={},T={},RT={:.2f}".format(ctx.event, ctx.state, timeout, finish_time)) if callable(action_instance) and not isclass(action_instance): if not action_instance(ctx): self.log("Error: {}".format(ctx.msg)) return False elif isinstance(action_instance, Exception): self.log("A=Exception {}".format(action_instance)) raise action_instance elif action_instance is None: self.log("A=None") else: self.log("FSM Action is not callable: {}".format(str(action_instance))) raise RuntimeWarning("FSM Action is not callable") if next_timeout != 0: # no change if set to 0 timeout = next_timeout ctx.state = next_state self.log("NS={},NT={}".format(next_state, timeout)) else: self.log("Unknown transition: EVENT={},STATE={}".format(ctx.event, ctx.state)) continue except EOF: raise ConnectionError("Session closed unexpectedly", self.ctrl.hostname) if ctx.finished or next_state == -1: self.log("{} Stop at E={},S={}".format(self.name, ctx.event, ctx.state)) return True # check while else if even exists self.log("FSM looped. Exiting") return False
python
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".format(self.name)) while transition_counter < self.max_transitions: transition_counter += 1 try: start_time = time() if self.init_pattern is None: ctx.event = self.ctrl.expect(self.events, searchwindowsize=self.searchwindowsize, timeout=timeout) else: self.log("INIT_PATTERN={}".format(pattern_to_str(self.init_pattern))) try: ctx.event = self.events.index(self.init_pattern) except ValueError: self.log("INIT_PATTERN unknown.") continue finally: self.init_pattern = None finish_time = time() - start_time key = (ctx.event, ctx.state) ctx.pattern = self.events[ctx.event] if key in self.transition_table: transition = self.transition_table[key] next_state, action_instance, next_timeout = transition self.log("E={},S={},T={},RT={:.2f}".format(ctx.event, ctx.state, timeout, finish_time)) if callable(action_instance) and not isclass(action_instance): if not action_instance(ctx): self.log("Error: {}".format(ctx.msg)) return False elif isinstance(action_instance, Exception): self.log("A=Exception {}".format(action_instance)) raise action_instance elif action_instance is None: self.log("A=None") else: self.log("FSM Action is not callable: {}".format(str(action_instance))) raise RuntimeWarning("FSM Action is not callable") if next_timeout != 0: # no change if set to 0 timeout = next_timeout ctx.state = next_state self.log("NS={},NT={}".format(next_state, timeout)) else: self.log("Unknown transition: EVENT={},STATE={}".format(ctx.event, ctx.state)) continue except EOF: raise ConnectionError("Session closed unexpectedly", self.ctrl.hostname) if ctx.finished or next_state == -1: self.log("{} Stop at E={},S={}".format(self.name, ctx.event, ctx.state)) return True # check while else if even exists self.log("FSM looped. Exiting") return False
[ "def", "run", "(", "self", ")", ":", "ctx", "=", "FSM", ".", "Context", "(", "self", ".", "name", ",", "self", ".", "device", ")", "transition_counter", "=", "0", "timeout", "=", "self", ".", "timeout", "self", ".", "log", "(", "\"{} Start\"", ".", "format", "(", "self", ".", "name", ")", ")", "while", "transition_counter", "<", "self", ".", "max_transitions", ":", "transition_counter", "+=", "1", "try", ":", "start_time", "=", "time", "(", ")", "if", "self", ".", "init_pattern", "is", "None", ":", "ctx", ".", "event", "=", "self", ".", "ctrl", ".", "expect", "(", "self", ".", "events", ",", "searchwindowsize", "=", "self", ".", "searchwindowsize", ",", "timeout", "=", "timeout", ")", "else", ":", "self", ".", "log", "(", "\"INIT_PATTERN={}\"", ".", "format", "(", "pattern_to_str", "(", "self", ".", "init_pattern", ")", ")", ")", "try", ":", "ctx", ".", "event", "=", "self", ".", "events", ".", "index", "(", "self", ".", "init_pattern", ")", "except", "ValueError", ":", "self", ".", "log", "(", "\"INIT_PATTERN unknown.\"", ")", "continue", "finally", ":", "self", ".", "init_pattern", "=", "None", "finish_time", "=", "time", "(", ")", "-", "start_time", "key", "=", "(", "ctx", ".", "event", ",", "ctx", ".", "state", ")", "ctx", ".", "pattern", "=", "self", ".", "events", "[", "ctx", ".", "event", "]", "if", "key", "in", "self", ".", "transition_table", ":", "transition", "=", "self", ".", "transition_table", "[", "key", "]", "next_state", ",", "action_instance", ",", "next_timeout", "=", "transition", "self", ".", "log", "(", "\"E={},S={},T={},RT={:.2f}\"", ".", "format", "(", "ctx", ".", "event", ",", "ctx", ".", "state", ",", "timeout", ",", "finish_time", ")", ")", "if", "callable", "(", "action_instance", ")", "and", "not", "isclass", "(", "action_instance", ")", ":", "if", "not", "action_instance", "(", "ctx", ")", ":", "self", ".", "log", "(", "\"Error: {}\"", ".", "format", "(", "ctx", ".", "msg", ")", ")", "return", "False", "elif", "isinstance", "(", "action_instance", ",", "Exception", ")", ":", "self", ".", "log", "(", "\"A=Exception {}\"", ".", "format", "(", "action_instance", ")", ")", "raise", "action_instance", "elif", "action_instance", "is", "None", ":", "self", ".", "log", "(", "\"A=None\"", ")", "else", ":", "self", ".", "log", "(", "\"FSM Action is not callable: {}\"", ".", "format", "(", "str", "(", "action_instance", ")", ")", ")", "raise", "RuntimeWarning", "(", "\"FSM Action is not callable\"", ")", "if", "next_timeout", "!=", "0", ":", "# no change if set to 0", "timeout", "=", "next_timeout", "ctx", ".", "state", "=", "next_state", "self", ".", "log", "(", "\"NS={},NT={}\"", ".", "format", "(", "next_state", ",", "timeout", ")", ")", "else", ":", "self", ".", "log", "(", "\"Unknown transition: EVENT={},STATE={}\"", ".", "format", "(", "ctx", ".", "event", ",", "ctx", ".", "state", ")", ")", "continue", "except", "EOF", ":", "raise", "ConnectionError", "(", "\"Session closed unexpectedly\"", ",", "self", ".", "ctrl", ".", "hostname", ")", "if", "ctx", ".", "finished", "or", "next_state", "==", "-", "1", ":", "self", ".", "log", "(", "\"{} Stop at E={},S={}\"", ".", "format", "(", "self", ".", "name", ",", "ctx", ".", "event", ",", "ctx", ".", "state", ")", ")", "return", "True", "# check while else if even exists", "self", ".", "log", "(", "\"FSM looped. Exiting\"", ")", "return", "False" ]
Start the FSM. Returns: boolean: True if FSM reaches the last state or false if the exception or error message was raised
[ "Start", "the", "FSM", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/fsm.py#L152-L218
train
thomasjiangcy/django-rest-mock
rest_mock_server/builder.py
build
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 = Parser(extractor.url_details, fixtures) parser.parse() url_details = parser.results _store = get_store(url_details) store = json.dumps(_store) variables = str(Variable('let', 'store', store)) functions = DATA_FINDER + GET_HANDLER + MODIFY_HANDLER + POST_HANDLER endpoints = [] endpoint_uris = [] for u in parser.results: endpoint = Endpoint() if u['method'].lower() in ['get', 'post']: method = u['method'].lower() else: method = 'modify' response = str(ResponseBody(method)) # Check in store if the base url has individual instances u['url'], list_url = clean_url(u['full_url'], _store, u['method'].lower()) if list_url is not None and u['method'].lower() == 'get': list_endpoint = Endpoint() list_endpoint.construct('get', list_url, response) if str(list_endpoint) not in endpoints: endpoints.append(str(list_endpoint)) if list_endpoint.uri not in endpoint_uris: endpoint_uris.append(list_endpoint.uri) if method == 'modify': without_prefix = re.sub(r'\/(\w+)\_\_', '', u['url']) for k, v in _store.items(): if without_prefix in k: options = v.get('options', '{}') options = ast.literal_eval(options) modifiers = [] if options is not None: modifiers = options.get('modifiers', []) if modifiers: for mod in modifiers: if u['method'].lower() == mod: mod_endpoint = Endpoint() uri = without_prefix if v.get('position') is not None and v['position'] == 'url': uri = re.sub(r'\/?\_\_key', '/:id', u['full_url']) mod_endpoint.construct(u['method'].lower(), uri, response) if str(mod_endpoint) not in endpoints: endpoints.append(str(mod_endpoint)) if mod_endpoint.uri not in endpoint_uris: endpoint_uris.append(mod_endpoint.uri) else: endpoint.construct(u['method'], u['url'], response) if str(endpoint) not in endpoints: endpoints.append(str(endpoint)) if endpoint.uri not in endpoint_uris: endpoint_uris.append(endpoint.uri) endpoints = ''.join(endpoints) express = ExpressServer() express.construct(variables, functions, endpoints, port) return express
python
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 = Parser(extractor.url_details, fixtures) parser.parse() url_details = parser.results _store = get_store(url_details) store = json.dumps(_store) variables = str(Variable('let', 'store', store)) functions = DATA_FINDER + GET_HANDLER + MODIFY_HANDLER + POST_HANDLER endpoints = [] endpoint_uris = [] for u in parser.results: endpoint = Endpoint() if u['method'].lower() in ['get', 'post']: method = u['method'].lower() else: method = 'modify' response = str(ResponseBody(method)) # Check in store if the base url has individual instances u['url'], list_url = clean_url(u['full_url'], _store, u['method'].lower()) if list_url is not None and u['method'].lower() == 'get': list_endpoint = Endpoint() list_endpoint.construct('get', list_url, response) if str(list_endpoint) not in endpoints: endpoints.append(str(list_endpoint)) if list_endpoint.uri not in endpoint_uris: endpoint_uris.append(list_endpoint.uri) if method == 'modify': without_prefix = re.sub(r'\/(\w+)\_\_', '', u['url']) for k, v in _store.items(): if without_prefix in k: options = v.get('options', '{}') options = ast.literal_eval(options) modifiers = [] if options is not None: modifiers = options.get('modifiers', []) if modifiers: for mod in modifiers: if u['method'].lower() == mod: mod_endpoint = Endpoint() uri = without_prefix if v.get('position') is not None and v['position'] == 'url': uri = re.sub(r'\/?\_\_key', '/:id', u['full_url']) mod_endpoint.construct(u['method'].lower(), uri, response) if str(mod_endpoint) not in endpoints: endpoints.append(str(mod_endpoint)) if mod_endpoint.uri not in endpoint_uris: endpoint_uris.append(mod_endpoint.uri) else: endpoint.construct(u['method'], u['url'], response) if str(endpoint) not in endpoints: endpoints.append(str(endpoint)) if endpoint.uri not in endpoint_uris: endpoint_uris.append(endpoint.uri) endpoints = ''.join(endpoints) express = ExpressServer() express.construct(variables, functions, endpoints, port) return express
[ "def", "build", "(", "port", "=", "8000", ",", "fixtures", "=", "None", ")", ":", "extractor", "=", "Extractor", "(", ")", "parser", "=", "Parser", "(", "extractor", ".", "url_details", ",", "fixtures", ")", "parser", ".", "parse", "(", ")", "url_details", "=", "parser", ".", "results", "_store", "=", "get_store", "(", "url_details", ")", "store", "=", "json", ".", "dumps", "(", "_store", ")", "variables", "=", "str", "(", "Variable", "(", "'let'", ",", "'store'", ",", "store", ")", ")", "functions", "=", "DATA_FINDER", "+", "GET_HANDLER", "+", "MODIFY_HANDLER", "+", "POST_HANDLER", "endpoints", "=", "[", "]", "endpoint_uris", "=", "[", "]", "for", "u", "in", "parser", ".", "results", ":", "endpoint", "=", "Endpoint", "(", ")", "if", "u", "[", "'method'", "]", ".", "lower", "(", ")", "in", "[", "'get'", ",", "'post'", "]", ":", "method", "=", "u", "[", "'method'", "]", ".", "lower", "(", ")", "else", ":", "method", "=", "'modify'", "response", "=", "str", "(", "ResponseBody", "(", "method", ")", ")", "# Check in store if the base url has individual instances", "u", "[", "'url'", "]", ",", "list_url", "=", "clean_url", "(", "u", "[", "'full_url'", "]", ",", "_store", ",", "u", "[", "'method'", "]", ".", "lower", "(", ")", ")", "if", "list_url", "is", "not", "None", "and", "u", "[", "'method'", "]", ".", "lower", "(", ")", "==", "'get'", ":", "list_endpoint", "=", "Endpoint", "(", ")", "list_endpoint", ".", "construct", "(", "'get'", ",", "list_url", ",", "response", ")", "if", "str", "(", "list_endpoint", ")", "not", "in", "endpoints", ":", "endpoints", ".", "append", "(", "str", "(", "list_endpoint", ")", ")", "if", "list_endpoint", ".", "uri", "not", "in", "endpoint_uris", ":", "endpoint_uris", ".", "append", "(", "list_endpoint", ".", "uri", ")", "if", "method", "==", "'modify'", ":", "without_prefix", "=", "re", ".", "sub", "(", "r'\\/(\\w+)\\_\\_'", ",", "''", ",", "u", "[", "'url'", "]", ")", "for", "k", ",", "v", "in", "_store", ".", "items", "(", ")", ":", "if", "without_prefix", "in", "k", ":", "options", "=", "v", ".", "get", "(", "'options'", ",", "'{}'", ")", "options", "=", "ast", ".", "literal_eval", "(", "options", ")", "modifiers", "=", "[", "]", "if", "options", "is", "not", "None", ":", "modifiers", "=", "options", ".", "get", "(", "'modifiers'", ",", "[", "]", ")", "if", "modifiers", ":", "for", "mod", "in", "modifiers", ":", "if", "u", "[", "'method'", "]", ".", "lower", "(", ")", "==", "mod", ":", "mod_endpoint", "=", "Endpoint", "(", ")", "uri", "=", "without_prefix", "if", "v", ".", "get", "(", "'position'", ")", "is", "not", "None", "and", "v", "[", "'position'", "]", "==", "'url'", ":", "uri", "=", "re", ".", "sub", "(", "r'\\/?\\_\\_key'", ",", "'/:id'", ",", "u", "[", "'full_url'", "]", ")", "mod_endpoint", ".", "construct", "(", "u", "[", "'method'", "]", ".", "lower", "(", ")", ",", "uri", ",", "response", ")", "if", "str", "(", "mod_endpoint", ")", "not", "in", "endpoints", ":", "endpoints", ".", "append", "(", "str", "(", "mod_endpoint", ")", ")", "if", "mod_endpoint", ".", "uri", "not", "in", "endpoint_uris", ":", "endpoint_uris", ".", "append", "(", "mod_endpoint", ".", "uri", ")", "else", ":", "endpoint", ".", "construct", "(", "u", "[", "'method'", "]", ",", "u", "[", "'url'", "]", ",", "response", ")", "if", "str", "(", "endpoint", ")", "not", "in", "endpoints", ":", "endpoints", ".", "append", "(", "str", "(", "endpoint", ")", ")", "if", "endpoint", ".", "uri", "not", "in", "endpoint_uris", ":", "endpoint_uris", ".", "append", "(", "endpoint", ".", "uri", ")", "endpoints", "=", "''", ".", "join", "(", "endpoints", ")", "express", "=", "ExpressServer", "(", ")", "express", ".", "construct", "(", "variables", ",", "functions", ",", "endpoints", ",", "port", ")", "return", "express" ]
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
[ "Builds", "a", "server", "file", "." ]
09e91de20d1a5efd5c47c6e3d7fe979443012e2c
https://github.com/thomasjiangcy/django-rest-mock/blob/09e91de20d1a5efd5c47c6e3d7fe979443012e2c/rest_mock_server/builder.py#L177-L245
train
OnroerendErfgoed/language-tags
language_tags/Subtag.py
Subtag.preferred
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['type'] if type == 'extlang': type = 'language' return Subtag(preferred, type) return None
python
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['type'] if type == 'extlang': type = 'language' return Subtag(preferred, type) return None
[ "def", "preferred", "(", "self", ")", ":", "if", "'Preferred-Value'", "in", "self", ".", "data", "[", "'record'", "]", ":", "preferred", "=", "self", ".", "data", "[", "'record'", "]", "[", "'Preferred-Value'", "]", "type", "=", "self", ".", "data", "[", "'type'", "]", "if", "type", "==", "'extlang'", ":", "type", "=", "'language'", "return", "Subtag", "(", "preferred", ",", "type", ")", "return", "None" ]
Get the preferred subtag. :return: preferred :class:`language_tags.Subtag.Subtag` if exists, otherwise None.
[ "Get", "the", "preferred", "subtag", "." ]
acb91e5458d22617f344e2eefaba9a9865373fdd
https://github.com/OnroerendErfgoed/language-tags/blob/acb91e5458d22617f344e2eefaba9a9865373fdd/language_tags/Subtag.py#L86-L98
train
OnroerendErfgoed/language-tags
language_tags/Subtag.py
Subtag.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.data['type'] == 'script': return subtag.capitalize() return subtag
python
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.data['type'] == 'script': return subtag.capitalize() return subtag
[ "def", "format", "(", "self", ")", ":", "subtag", "=", "self", ".", "data", "[", "'subtag'", "]", "if", "self", ".", "data", "[", "'type'", "]", "==", "'region'", ":", "return", "subtag", ".", "upper", "(", ")", "if", "self", ".", "data", "[", "'type'", "]", "==", "'script'", ":", "return", "subtag", ".", "capitalize", "(", ")", "return", "subtag" ]
Get the subtag code conventional format according to RFC 5646 section 2.1.1. :return: string -- subtag code conventional format.
[ "Get", "the", "subtag", "code", "conventional", "format", "according", "to", "RFC", "5646", "section", "2", ".", "1", ".", "1", "." ]
acb91e5458d22617f344e2eefaba9a9865373fdd
https://github.com/OnroerendErfgoed/language-tags/blob/acb91e5458d22617f344e2eefaba9a9865373fdd/language_tags/Subtag.py#L101-L112
train
freshbooks/refreshbooks
refreshbooks/api.py
AuthorizingClient
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) ) return client.Client( request_encoder, http_transport, response_decoder )
python
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) ) return client.Client( request_encoder, http_transport, response_decoder )
[ "def", "AuthorizingClient", "(", "domain", ",", "auth", ",", "request_encoder", ",", "response_decoder", ",", "user_agent", "=", "None", ")", ":", "http_transport", "=", "transport", ".", "HttpTransport", "(", "api_url", "(", "domain", ")", ",", "build_headers", "(", "auth", ",", "user_agent", ")", ")", "return", "client", ".", "Client", "(", "request_encoder", ",", "http_transport", ",", "response_decoder", ")" ]
Creates a Freshbooks client for a freshbooks domain, using an auth object.
[ "Creates", "a", "Freshbooks", "client", "for", "a", "freshbooks", "domain", "using", "an", "auth", "object", "." ]
cfd65ecd38cb6be3b61dbf6a01f93800603f34b1
https://github.com/freshbooks/refreshbooks/blob/cfd65ecd38cb6be3b61dbf6a01f93800603f34b1/refreshbooks/api.py#L72-L92
train
freshbooks/refreshbooks
refreshbooks/api.py
TokenClient
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 passed the logging_request_encoder and logging_response_decoder objects from this module, or custom encoders, to aid debugging or change the behaviour of refreshbooks' request-to-XML-to-response mapping. The optional user_agent keyword parameter can be used to specify the user agent string passed to FreshBooks. If unset, a default user agent string is used. """ return AuthorizingClient( domain, transport.TokenAuthorization(token), request_encoder, response_decoder, user_agent=user_agent )
python
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 passed the logging_request_encoder and logging_response_decoder objects from this module, or custom encoders, to aid debugging or change the behaviour of refreshbooks' request-to-XML-to-response mapping. The optional user_agent keyword parameter can be used to specify the user agent string passed to FreshBooks. If unset, a default user agent string is used. """ return AuthorizingClient( domain, transport.TokenAuthorization(token), request_encoder, response_decoder, user_agent=user_agent )
[ "def", "TokenClient", "(", "domain", ",", "token", ",", "user_agent", "=", "None", ",", "request_encoder", "=", "default_request_encoder", ",", "response_decoder", "=", "default_response_decoder", ",", ")", ":", "return", "AuthorizingClient", "(", "domain", ",", "transport", ".", "TokenAuthorization", "(", "token", ")", ",", "request_encoder", ",", "response_decoder", ",", "user_agent", "=", "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 of refreshbooks' request-to-XML-to-response mapping. The optional user_agent keyword parameter can be used to specify the user agent string passed to FreshBooks. If unset, a default user agent string is used.
[ "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", "of", "refreshbooks", "request", "-", "to", "-", "XML", "-", "to", "-", "response", "mapping", ".", "The", "optional", "user_agent", "keyword", "parameter", "can", "be", "used", "to", "specify", "the", "user", "agent", "string", "passed", "to", "FreshBooks", ".", "If", "unset", "a", "default", "user", "agent", "string", "is", "used", "." ]
cfd65ecd38cb6be3b61dbf6a01f93800603f34b1
https://github.com/freshbooks/refreshbooks/blob/cfd65ecd38cb6be3b61dbf6a01f93800603f34b1/refreshbooks/api.py#L94-L120
train
freshbooks/refreshbooks
refreshbooks/api.py
OAuthClient
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 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 encoders, to aid debugging or change the behaviour of refreshbooks' request-to-XML-to-response mapping. The optional user_agent keyword parameter can be used to specify the user agent string passed to FreshBooks. If unset, a default user agent string is used. """ return _create_oauth_client( AuthorizingClient, domain, consumer_key, consumer_secret, token, token_secret, user_agent=user_agent, request_encoder=request_encoder, response_decoder=response_decoder )
python
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 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 encoders, to aid debugging or change the behaviour of refreshbooks' request-to-XML-to-response mapping. The optional user_agent keyword parameter can be used to specify the user agent string passed to FreshBooks. If unset, a default user agent string is used. """ return _create_oauth_client( AuthorizingClient, domain, consumer_key, consumer_secret, token, token_secret, user_agent=user_agent, request_encoder=request_encoder, response_decoder=response_decoder )
[ "def", "OAuthClient", "(", "domain", ",", "consumer_key", ",", "consumer_secret", ",", "token", ",", "token_secret", ",", "user_agent", "=", "None", ",", "request_encoder", "=", "default_request_encoder", ",", "response_decoder", "=", "default_response_decoder", ")", ":", "return", "_create_oauth_client", "(", "AuthorizingClient", ",", "domain", ",", "consumer_key", ",", "consumer_secret", ",", "token", ",", "token_secret", ",", "user_agent", "=", "user_agent", ",", "request_encoder", "=", "request_encoder", ",", "response_decoder", "=", "response_decoder", ")" ]
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 encoders, to aid debugging or change the behaviour of refreshbooks' request-to-XML-to-response mapping. The optional user_agent keyword parameter can be used to specify the user agent string passed to FreshBooks. If unset, a default user agent string is used.
[ "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", "encoders", "to", "aid", "debugging", "or", "change", "the", "behaviour", "of", "refreshbooks", "request", "-", "to", "-", "XML", "-", "to", "-", "response", "mapping", ".", "The", "optional", "user_agent", "keyword", "parameter", "can", "be", "used", "to", "specify", "the", "user", "agent", "string", "passed", "to", "FreshBooks", ".", "If", "unset", "a", "default", "user", "agent", "string", "is", "used", "." ]
cfd65ecd38cb6be3b61dbf6a01f93800603f34b1
https://github.com/freshbooks/refreshbooks/blob/cfd65ecd38cb6be3b61dbf6a01f93800603f34b1/refreshbooks/api.py#L122-L154
train
theherk/figgypy
figgypy/decrypt.py
gpg_decrypt
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: gpg_config = {'homedir': '~/.gnupg/', 'binary': 'gpg', 'keyring': 'pubring.kbx'} Returns: dict: decrypted configuration dictionary The aim is to find in the dictionary items which have been encrypted with gpg, then decrypt them if possible. We will either detect the encryption based on the PGP block text or a user can create a key "_gpg" in which to store the data. Either case will work. In the case of the "_gpg" key all data at this level will be replaced with the decrypted contents. For example: {'component': {'key': 'PGP Block ...'}} will transform to: {'component': {'key': 'decrypted value'}} However: {'component': {'key': {'_gpg': 'PGP Block ...', 'nothing': 'should go here'}}} will transform to: {'component': {'key': 'decrypted value'}} """ def decrypt(obj): """Decrypt the object. It is an inner function because we must first verify that gpg is ready. If we did them in the same function we would end up calling the gpg checks several times, potentially, since we are calling this recursively. """ if isinstance(obj, list): res_v = [] for item in obj: res_v.append(decrypt(item)) return res_v elif isinstance(obj, dict): if '_gpg' in obj: try: decrypted = gpg.decrypt(obj['_gpg']) if decrypted.ok: obj = n(decrypted.data.decode('utf-8').encode()) else: log.error("gpg error unpacking secrets %s", decrypted.stderr) except Exception as err: log.error("error unpacking secrets %s", err) else: for k, v in obj.items(): obj[k] = decrypt(v) else: try: if 'BEGIN PGP' in obj: try: decrypted = gpg.decrypt(obj) if decrypted.ok: obj = n(decrypted.data.decode('utf-8').encode()) else: log.error("gpg error unpacking secrets %s", decrypted.stderr) except Exception as err: log.error("error unpacking secrets %s", err) except TypeError: log.debug('Pass on decryption. Only decrypt strings') return obj if GPG_IMPORTED: if not gpg_config: gpg_config = {} defaults = {'homedir': '~/.gnupg/'} env_fields = {'homedir': 'FIGGYPY_GPG_HOMEDIR', 'binary': 'FIGGYPY_GPG_BINARY', 'keyring': 'FIGGYPY_GPG_KEYRING'} for k, v in env_fields.items(): gpg_config[k] = env_or_default(v, defaults[k] if k in defaults else None) try: gpg = gnupg.GPG(**gpg_config) except (OSError, RuntimeError): log.exception('Failed to configure gpg. Will be unable to decrypt secrets.') return decrypt(cfg) return cfg
python
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: gpg_config = {'homedir': '~/.gnupg/', 'binary': 'gpg', 'keyring': 'pubring.kbx'} Returns: dict: decrypted configuration dictionary The aim is to find in the dictionary items which have been encrypted with gpg, then decrypt them if possible. We will either detect the encryption based on the PGP block text or a user can create a key "_gpg" in which to store the data. Either case will work. In the case of the "_gpg" key all data at this level will be replaced with the decrypted contents. For example: {'component': {'key': 'PGP Block ...'}} will transform to: {'component': {'key': 'decrypted value'}} However: {'component': {'key': {'_gpg': 'PGP Block ...', 'nothing': 'should go here'}}} will transform to: {'component': {'key': 'decrypted value'}} """ def decrypt(obj): """Decrypt the object. It is an inner function because we must first verify that gpg is ready. If we did them in the same function we would end up calling the gpg checks several times, potentially, since we are calling this recursively. """ if isinstance(obj, list): res_v = [] for item in obj: res_v.append(decrypt(item)) return res_v elif isinstance(obj, dict): if '_gpg' in obj: try: decrypted = gpg.decrypt(obj['_gpg']) if decrypted.ok: obj = n(decrypted.data.decode('utf-8').encode()) else: log.error("gpg error unpacking secrets %s", decrypted.stderr) except Exception as err: log.error("error unpacking secrets %s", err) else: for k, v in obj.items(): obj[k] = decrypt(v) else: try: if 'BEGIN PGP' in obj: try: decrypted = gpg.decrypt(obj) if decrypted.ok: obj = n(decrypted.data.decode('utf-8').encode()) else: log.error("gpg error unpacking secrets %s", decrypted.stderr) except Exception as err: log.error("error unpacking secrets %s", err) except TypeError: log.debug('Pass on decryption. Only decrypt strings') return obj if GPG_IMPORTED: if not gpg_config: gpg_config = {} defaults = {'homedir': '~/.gnupg/'} env_fields = {'homedir': 'FIGGYPY_GPG_HOMEDIR', 'binary': 'FIGGYPY_GPG_BINARY', 'keyring': 'FIGGYPY_GPG_KEYRING'} for k, v in env_fields.items(): gpg_config[k] = env_or_default(v, defaults[k] if k in defaults else None) try: gpg = gnupg.GPG(**gpg_config) except (OSError, RuntimeError): log.exception('Failed to configure gpg. Will be unable to decrypt secrets.') return decrypt(cfg) return cfg
[ "def", "gpg_decrypt", "(", "cfg", ",", "gpg_config", "=", "None", ")", ":", "def", "decrypt", "(", "obj", ")", ":", "\"\"\"Decrypt the object.\n\n It is an inner function because we must first verify that gpg\n is ready. If we did them in the same function we would end up\n calling the gpg checks several times, potentially, since we are\n calling this recursively.\n \"\"\"", "if", "isinstance", "(", "obj", ",", "list", ")", ":", "res_v", "=", "[", "]", "for", "item", "in", "obj", ":", "res_v", ".", "append", "(", "decrypt", "(", "item", ")", ")", "return", "res_v", "elif", "isinstance", "(", "obj", ",", "dict", ")", ":", "if", "'_gpg'", "in", "obj", ":", "try", ":", "decrypted", "=", "gpg", ".", "decrypt", "(", "obj", "[", "'_gpg'", "]", ")", "if", "decrypted", ".", "ok", ":", "obj", "=", "n", "(", "decrypted", ".", "data", ".", "decode", "(", "'utf-8'", ")", ".", "encode", "(", ")", ")", "else", ":", "log", ".", "error", "(", "\"gpg error unpacking secrets %s\"", ",", "decrypted", ".", "stderr", ")", "except", "Exception", "as", "err", ":", "log", ".", "error", "(", "\"error unpacking secrets %s\"", ",", "err", ")", "else", ":", "for", "k", ",", "v", "in", "obj", ".", "items", "(", ")", ":", "obj", "[", "k", "]", "=", "decrypt", "(", "v", ")", "else", ":", "try", ":", "if", "'BEGIN PGP'", "in", "obj", ":", "try", ":", "decrypted", "=", "gpg", ".", "decrypt", "(", "obj", ")", "if", "decrypted", ".", "ok", ":", "obj", "=", "n", "(", "decrypted", ".", "data", ".", "decode", "(", "'utf-8'", ")", ".", "encode", "(", ")", ")", "else", ":", "log", ".", "error", "(", "\"gpg error unpacking secrets %s\"", ",", "decrypted", ".", "stderr", ")", "except", "Exception", "as", "err", ":", "log", ".", "error", "(", "\"error unpacking secrets %s\"", ",", "err", ")", "except", "TypeError", ":", "log", ".", "debug", "(", "'Pass on decryption. Only decrypt strings'", ")", "return", "obj", "if", "GPG_IMPORTED", ":", "if", "not", "gpg_config", ":", "gpg_config", "=", "{", "}", "defaults", "=", "{", "'homedir'", ":", "'~/.gnupg/'", "}", "env_fields", "=", "{", "'homedir'", ":", "'FIGGYPY_GPG_HOMEDIR'", ",", "'binary'", ":", "'FIGGYPY_GPG_BINARY'", ",", "'keyring'", ":", "'FIGGYPY_GPG_KEYRING'", "}", "for", "k", ",", "v", "in", "env_fields", ".", "items", "(", ")", ":", "gpg_config", "[", "k", "]", "=", "env_or_default", "(", "v", ",", "defaults", "[", "k", "]", "if", "k", "in", "defaults", "else", "None", ")", "try", ":", "gpg", "=", "gnupg", ".", "GPG", "(", "*", "*", "gpg_config", ")", "except", "(", "OSError", ",", "RuntimeError", ")", ":", "log", ".", "exception", "(", "'Failed to configure gpg. Will be unable to decrypt secrets.'", ")", "return", "decrypt", "(", "cfg", ")", "return", "cfg" ]
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': '~/.gnupg/', 'binary': 'gpg', 'keyring': 'pubring.kbx'} Returns: dict: decrypted configuration dictionary The aim is to find in the dictionary items which have been encrypted with gpg, then decrypt them if possible. We will either detect the encryption based on the PGP block text or a user can create a key "_gpg" in which to store the data. Either case will work. In the case of the "_gpg" key all data at this level will be replaced with the decrypted contents. For example: {'component': {'key': 'PGP Block ...'}} will transform to: {'component': {'key': 'decrypted value'}} However: {'component': {'key': {'_gpg': 'PGP Block ...', 'nothing': 'should go here'}}} will transform to: {'component': {'key': 'decrypted value'}}
[ "Decrypt", "GPG", "objects", "in", "configuration", "." ]
324d1b281a8df20a26b92f42bf7fda0cca892116
https://github.com/theherk/figgypy/blob/324d1b281a8df20a26b92f42bf7fda0cca892116/figgypy/decrypt.py#L26-L119
train
theherk/figgypy
figgypy/decrypt.py
kms_decrypt
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_key_id, 'aws_secret_access_key': aws_secret_access_key, 'region_name': 'us-east-1'} Returns: dict: decrypted configuration dictionary AWS credentials follow the standard boto flow. Provided values first, followed by environment, and then configuration files on the machine. Ideally, one would set up an IAM role for this machine to authenticate. The aim is to find in the dictionary items which have been encrypted with KMS, then decrypt them if possible. A user can create a key "_kms" in which to store the data. All data at this level will be replaced with the decrypted contents. For example: {'component': {'key': {'_kms': 'encrypted cipher text', 'nothing': 'should go here'}}} will transform to: {'component': {'key': 'decrypted value'}} To get the value to be stored as a KMS encrypted string: from figgypy.utils import kms_encrypt encrypted = kms_encrypt('your secret', 'your key or alias', optional_aws_config) """ def decrypt(obj): """Decrypt the object. It is an inner function because we must first configure our KMS client. Then we call this recursively on the object. """ if isinstance(obj, list): res_v = [] for item in obj: res_v.append(decrypt(item)) return res_v elif isinstance(obj, dict): if '_kms' in obj: try: res = client.decrypt(CiphertextBlob=b64decode(obj['_kms'])) obj = n(res['Plaintext']) except ClientError as err: if 'AccessDeniedException' in err.args[0]: log.warning('Unable to decrypt %s. Key does not exist or no access', obj['_kms']) else: raise else: for k, v in obj.items(): obj[k] = decrypt(v) else: pass return obj try: aws = boto3.session.Session(**aws_config) client = aws.client('kms') except NoRegionError: log.info('Missing or invalid aws configuration. Will not be able to unpack KMS secrets.') return cfg return decrypt(cfg)
python
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_key_id, 'aws_secret_access_key': aws_secret_access_key, 'region_name': 'us-east-1'} Returns: dict: decrypted configuration dictionary AWS credentials follow the standard boto flow. Provided values first, followed by environment, and then configuration files on the machine. Ideally, one would set up an IAM role for this machine to authenticate. The aim is to find in the dictionary items which have been encrypted with KMS, then decrypt them if possible. A user can create a key "_kms" in which to store the data. All data at this level will be replaced with the decrypted contents. For example: {'component': {'key': {'_kms': 'encrypted cipher text', 'nothing': 'should go here'}}} will transform to: {'component': {'key': 'decrypted value'}} To get the value to be stored as a KMS encrypted string: from figgypy.utils import kms_encrypt encrypted = kms_encrypt('your secret', 'your key or alias', optional_aws_config) """ def decrypt(obj): """Decrypt the object. It is an inner function because we must first configure our KMS client. Then we call this recursively on the object. """ if isinstance(obj, list): res_v = [] for item in obj: res_v.append(decrypt(item)) return res_v elif isinstance(obj, dict): if '_kms' in obj: try: res = client.decrypt(CiphertextBlob=b64decode(obj['_kms'])) obj = n(res['Plaintext']) except ClientError as err: if 'AccessDeniedException' in err.args[0]: log.warning('Unable to decrypt %s. Key does not exist or no access', obj['_kms']) else: raise else: for k, v in obj.items(): obj[k] = decrypt(v) else: pass return obj try: aws = boto3.session.Session(**aws_config) client = aws.client('kms') except NoRegionError: log.info('Missing or invalid aws configuration. Will not be able to unpack KMS secrets.') return cfg return decrypt(cfg)
[ "def", "kms_decrypt", "(", "cfg", ",", "aws_config", "=", "None", ")", ":", "def", "decrypt", "(", "obj", ")", ":", "\"\"\"Decrypt the object.\n\n It is an inner function because we must first configure our KMS\n client. Then we call this recursively on the object.\n \"\"\"", "if", "isinstance", "(", "obj", ",", "list", ")", ":", "res_v", "=", "[", "]", "for", "item", "in", "obj", ":", "res_v", ".", "append", "(", "decrypt", "(", "item", ")", ")", "return", "res_v", "elif", "isinstance", "(", "obj", ",", "dict", ")", ":", "if", "'_kms'", "in", "obj", ":", "try", ":", "res", "=", "client", ".", "decrypt", "(", "CiphertextBlob", "=", "b64decode", "(", "obj", "[", "'_kms'", "]", ")", ")", "obj", "=", "n", "(", "res", "[", "'Plaintext'", "]", ")", "except", "ClientError", "as", "err", ":", "if", "'AccessDeniedException'", "in", "err", ".", "args", "[", "0", "]", ":", "log", ".", "warning", "(", "'Unable to decrypt %s. Key does not exist or no access'", ",", "obj", "[", "'_kms'", "]", ")", "else", ":", "raise", "else", ":", "for", "k", ",", "v", "in", "obj", ".", "items", "(", ")", ":", "obj", "[", "k", "]", "=", "decrypt", "(", "v", ")", "else", ":", "pass", "return", "obj", "try", ":", "aws", "=", "boto3", ".", "session", ".", "Session", "(", "*", "*", "aws_config", ")", "client", "=", "aws", ".", "client", "(", "'kms'", ")", "except", "NoRegionError", ":", "log", ".", "info", "(", "'Missing or invalid aws configuration. Will not be able to unpack KMS secrets.'", ")", "return", "cfg", "return", "decrypt", "(", "cfg", ")" ]
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_secret_access_key': aws_secret_access_key, 'region_name': 'us-east-1'} Returns: dict: decrypted configuration dictionary AWS credentials follow the standard boto flow. Provided values first, followed by environment, and then configuration files on the machine. Ideally, one would set up an IAM role for this machine to authenticate. The aim is to find in the dictionary items which have been encrypted with KMS, then decrypt them if possible. A user can create a key "_kms" in which to store the data. All data at this level will be replaced with the decrypted contents. For example: {'component': {'key': {'_kms': 'encrypted cipher text', 'nothing': 'should go here'}}} will transform to: {'component': {'key': 'decrypted value'}} To get the value to be stored as a KMS encrypted string: from figgypy.utils import kms_encrypt encrypted = kms_encrypt('your secret', 'your key or alias', optional_aws_config)
[ "Decrypt", "KMS", "objects", "in", "configuration", "." ]
324d1b281a8df20a26b92f42bf7fda0cca892116
https://github.com/theherk/figgypy/blob/324d1b281a8df20a26b92f42bf7fda0cca892116/figgypy/decrypt.py#L122-L191
train
kstaniek/condoor
condoor/drivers/generic.py
Driver.get_version_text
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_not_supported = True if show_version_brief_not_supported: try: # IOS Hack - need to check if show version brief is supported on IOS/IOS XE version_text = self.device.send("show version", timeout=120) except CommandError as exc: exc.command = 'show version' raise exc return version_text
python
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_not_supported = True if show_version_brief_not_supported: try: # IOS Hack - need to check if show version brief is supported on IOS/IOS XE version_text = self.device.send("show version", timeout=120) except CommandError as exc: exc.command = 'show version' raise exc return version_text
[ "def", "get_version_text", "(", "self", ")", ":", "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_not_supported", "=", "True", "if", "show_version_brief_not_supported", ":", "try", ":", "# IOS Hack - need to check if show version brief is supported on IOS/IOS XE", "version_text", "=", "self", ".", "device", ".", "send", "(", "\"show version\"", ",", "timeout", "=", "120", ")", "except", "CommandError", "as", "exc", ":", "exc", ".", "command", "=", "'show version'", "raise", "exc", "return", "version_text" ]
Return the version information from the device.
[ "Return", "the", "version", "information", "from", "the", "device", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/drivers/generic.py#L63-L80
train
kstaniek/condoor
condoor/drivers/generic.py
Driver.get_inventory_text
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') except CommandError: self.log('Unable to collect inventory') else: self.log('No inventory command for {}'.format(self.platform)) return inventory_text
python
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') except CommandError: self.log('Unable to collect inventory') else: self.log('No inventory command for {}'.format(self.platform)) return inventory_text
[ "def", "get_inventory_text", "(", "self", ")", ":", "inventory_text", "=", "None", "if", "self", ".", "inventory_cmd", ":", "try", ":", "inventory_text", "=", "self", ".", "device", ".", "send", "(", "self", ".", "inventory_cmd", ",", "timeout", "=", "120", ")", "self", ".", "log", "(", "'Inventory collected'", ")", "except", "CommandError", ":", "self", ".", "log", "(", "'Unable to collect inventory'", ")", "else", ":", "self", ".", "log", "(", "'No inventory command for {}'", ".", "format", "(", "self", ".", "platform", ")", ")", "return", "inventory_text" ]
Return the inventory information from the device.
[ "Return", "the", "inventory", "information", "from", "the", "device", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/drivers/generic.py#L82-L93
train
kstaniek/condoor
condoor/drivers/generic.py
Driver.get_users_text
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 connected users information') else: self.log('No users command for {}'.format(self.platform)) return users_text
python
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 connected users information') else: self.log('No users command for {}'.format(self.platform)) return users_text
[ "def", "get_users_text", "(", "self", ")", ":", "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 connected users information'", ")", "else", ":", "self", ".", "log", "(", "'No users command for {}'", ".", "format", "(", "self", ".", "platform", ")", ")", "return", "users_text" ]
Return the users logged in information from the device.
[ "Return", "the", "users", "logged", "in", "information", "from", "the", "device", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/drivers/generic.py#L99-L109
train
kstaniek/condoor
condoor/drivers/generic.py
Driver.get_os_type
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.group(1) else: os_type = 'IOS' if os_type == "XR": match = re.search("Build Information", version_text) if match: os_type = "eXR" match = re.search("XR Admin Software", version_text) if match: os_type = "Calvados" return os_type
python
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.group(1) else: os_type = 'IOS' if os_type == "XR": match = re.search("Build Information", version_text) if match: os_type = "eXR" match = re.search("XR Admin Software", version_text) if match: os_type = "Calvados" return os_type
[ "def", "get_os_type", "(", "self", ",", "version_text", ")", ":", "# pylint: disable=no-self-use", "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", ".", "group", "(", "1", ")", "else", ":", "os_type", "=", "'IOS'", "if", "os_type", "==", "\"XR\"", ":", "match", "=", "re", ".", "search", "(", "\"Build Information\"", ",", "version_text", ")", "if", "match", ":", "os_type", "=", "\"eXR\"", "match", "=", "re", ".", "search", "(", "\"XR Admin Software\"", ",", "version_text", ")", "if", "match", ":", "os_type", "=", "\"Calvados\"", "return", "os_type" ]
Return the OS type information from the device.
[ "Return", "the", "OS", "type", "information", "from", "the", "device", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/drivers/generic.py#L111-L130
train
kstaniek/condoor
condoor/drivers/generic.py
Driver.get_os_version
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(1) return os_version
python
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(1) return os_version
[ "def", "get_os_version", "(", "self", ",", "version_text", ")", ":", "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", "(", "1", ")", "return", "os_version" ]
Return the OS version information from the device.
[ "Return", "the", "OS", "version", "information", "from", "the", "device", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/drivers/generic.py#L132-L141
train
kstaniek/condoor
condoor/drivers/generic.py
Driver.get_hw_family
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.group() self.log("Platform string: {}".format(match.group())) self.raw_family = match.group(1) # sort keys on len reversed (longest first) for key in sorted(self.families, key=len, reverse=True): if self.raw_family.startswith(key): family = self.families[key] break else: self.log("Platform {} not supported".format(family)) else: self.log("Platform string not present. Refer to CSCux08958") return family
python
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.group() self.log("Platform string: {}".format(match.group())) self.raw_family = match.group(1) # sort keys on len reversed (longest first) for key in sorted(self.families, key=len, reverse=True): if self.raw_family.startswith(key): family = self.families[key] break else: self.log("Platform {} not supported".format(family)) else: self.log("Platform string not present. Refer to CSCux08958") return family
[ "def", "get_hw_family", "(", "self", ",", "version_text", ")", ":", "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", ".", "group", "(", ")", "self", ".", "log", "(", "\"Platform string: {}\"", ".", "format", "(", "match", ".", "group", "(", ")", ")", ")", "self", ".", "raw_family", "=", "match", ".", "group", "(", "1", ")", "# sort keys on len reversed (longest first)", "for", "key", "in", "sorted", "(", "self", ".", "families", ",", "key", "=", "len", ",", "reverse", "=", "True", ")", ":", "if", "self", ".", "raw_family", ".", "startswith", "(", "key", ")", ":", "family", "=", "self", ".", "families", "[", "key", "]", "break", "else", ":", "self", ".", "log", "(", "\"Platform {} not supported\"", ".", "format", "(", "family", ")", ")", "else", ":", "self", ".", "log", "(", "\"Platform string not present. Refer to CSCux08958\"", ")", "return", "family" ]
Return the HW family information from the device.
[ "Return", "the", "HW", "family", "information", "from", "the", "device", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/drivers/generic.py#L143-L163
train
kstaniek/condoor
condoor/drivers/generic.py
Driver.get_hw_platform
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 match = re.search(self.pid2platform_re, pid) if match: platform = match.group(1) except KeyError: pass return platform
python
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 match = re.search(self.pid2platform_re, pid) if match: platform = match.group(1) except KeyError: pass return platform
[ "def", "get_hw_platform", "(", "self", ",", "udi", ")", ":", "platform", "=", "None", "try", ":", "pid", "=", "udi", "[", "'pid'", "]", "if", "pid", "==", "''", ":", "self", ".", "log", "(", "\"Empty PID. Use the hw family from the platform string.\"", ")", "return", "self", ".", "raw_family", "match", "=", "re", ".", "search", "(", "self", ".", "pid2platform_re", ",", "pid", ")", "if", "match", ":", "platform", "=", "match", ".", "group", "(", "1", ")", "except", "KeyError", ":", "pass", "return", "platform" ]
Return th HW platform information from the device.
[ "Return", "th", "HW", "platform", "information", "from", "the", "device", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/drivers/generic.py#L165-L178
train
kstaniek/condoor
condoor/drivers/generic.py
Driver.is_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_re, line) if match: self.log("Detected connection to vty") return False else: match = re.search(self.console_re, line) if match: self.log("Detected connection to console") return True self.log("Connection port unknown") return None
python
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_re, line) if match: self.log("Detected connection to vty") return False else: match = re.search(self.console_re, line) if match: self.log("Detected connection to console") return True self.log("Connection port unknown") return None
[ "def", "is_console", "(", "self", ",", "users_text", ")", ":", "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_re", ",", "line", ")", "if", "match", ":", "self", ".", "log", "(", "\"Detected connection to vty\"", ")", "return", "False", "else", ":", "match", "=", "re", ".", "search", "(", "self", ".", "console_re", ",", "line", ")", "if", "match", ":", "self", ".", "log", "(", "\"Detected connection to console\"", ")", "return", "True", "self", ".", "log", "(", "\"Connection port unknown\"", ")", "return", "None" ]
Return if device is connected over console.
[ "Return", "if", "device", "is", "connected", "over", "console", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/drivers/generic.py#L180-L199
train
kstaniek/condoor
condoor/drivers/generic.py
Driver.wait_for_string
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, # 4 5 6 7 self.more_re, pexpect.TIMEOUT, pexpect.EOF, self.buffer_overflow_re] # add detected prompts chain events += self.device.get_previous_prompts() # without target prompt self.log("Expecting: {}".format(pattern_to_str(expected_string))) transitions = [ (self.syntax_error_re, [0], -1, CommandSyntaxError("Command unknown", self.device.hostname), 0), (self.connection_closed_re, [0], 1, a_connection_closed, 10), (pexpect.TIMEOUT, [0], -1, CommandTimeoutError("Timeout waiting for prompt", self.device.hostname), 0), (pexpect.EOF, [0, 1], -1, ConnectionError("Unexpected device disconnect", self.device.hostname), 0), (self.more_re, [0], 0, partial(a_send, " "), 10), (expected_string, [0, 1], -1, a_expected_prompt, 0), (self.press_return_re, [0], -1, a_stays_connected, 0), # TODO: Customize in XR driver (self.buffer_overflow_re, [0], -1, CommandSyntaxError("Command too long", self.device.hostname), 0) ] for prompt in self.device.get_previous_prompts(): transitions.append((prompt, [0, 1], 0, a_unexpected_prompt, 0)) fsm = FSM("WAIT-4-STRING", self.device, events, transitions, timeout=timeout) return fsm.run()
python
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, # 4 5 6 7 self.more_re, pexpect.TIMEOUT, pexpect.EOF, self.buffer_overflow_re] # add detected prompts chain events += self.device.get_previous_prompts() # without target prompt self.log("Expecting: {}".format(pattern_to_str(expected_string))) transitions = [ (self.syntax_error_re, [0], -1, CommandSyntaxError("Command unknown", self.device.hostname), 0), (self.connection_closed_re, [0], 1, a_connection_closed, 10), (pexpect.TIMEOUT, [0], -1, CommandTimeoutError("Timeout waiting for prompt", self.device.hostname), 0), (pexpect.EOF, [0, 1], -1, ConnectionError("Unexpected device disconnect", self.device.hostname), 0), (self.more_re, [0], 0, partial(a_send, " "), 10), (expected_string, [0, 1], -1, a_expected_prompt, 0), (self.press_return_re, [0], -1, a_stays_connected, 0), # TODO: Customize in XR driver (self.buffer_overflow_re, [0], -1, CommandSyntaxError("Command too long", self.device.hostname), 0) ] for prompt in self.device.get_previous_prompts(): transitions.append((prompt, [0, 1], 0, a_unexpected_prompt, 0)) fsm = FSM("WAIT-4-STRING", self.device, events, transitions, timeout=timeout) return fsm.run()
[ "def", "wait_for_string", "(", "self", ",", "expected_string", ",", "timeout", "=", "60", ")", ":", "# 0 1 2 3", "events", "=", "[", "self", ".", "syntax_error_re", ",", "self", ".", "connection_closed_re", ",", "expected_string", ",", "self", ".", "press_return_re", ",", "# 4 5 6 7", "self", ".", "more_re", ",", "pexpect", ".", "TIMEOUT", ",", "pexpect", ".", "EOF", ",", "self", ".", "buffer_overflow_re", "]", "# add detected prompts chain", "events", "+=", "self", ".", "device", ".", "get_previous_prompts", "(", ")", "# without target prompt", "self", ".", "log", "(", "\"Expecting: {}\"", ".", "format", "(", "pattern_to_str", "(", "expected_string", ")", ")", ")", "transitions", "=", "[", "(", "self", ".", "syntax_error_re", ",", "[", "0", "]", ",", "-", "1", ",", "CommandSyntaxError", "(", "\"Command unknown\"", ",", "self", ".", "device", ".", "hostname", ")", ",", "0", ")", ",", "(", "self", ".", "connection_closed_re", ",", "[", "0", "]", ",", "1", ",", "a_connection_closed", ",", "10", ")", ",", "(", "pexpect", ".", "TIMEOUT", ",", "[", "0", "]", ",", "-", "1", ",", "CommandTimeoutError", "(", "\"Timeout waiting for prompt\"", ",", "self", ".", "device", ".", "hostname", ")", ",", "0", ")", ",", "(", "pexpect", ".", "EOF", ",", "[", "0", ",", "1", "]", ",", "-", "1", ",", "ConnectionError", "(", "\"Unexpected device disconnect\"", ",", "self", ".", "device", ".", "hostname", ")", ",", "0", ")", ",", "(", "self", ".", "more_re", ",", "[", "0", "]", ",", "0", ",", "partial", "(", "a_send", ",", "\" \"", ")", ",", "10", ")", ",", "(", "expected_string", ",", "[", "0", ",", "1", "]", ",", "-", "1", ",", "a_expected_prompt", ",", "0", ")", ",", "(", "self", ".", "press_return_re", ",", "[", "0", "]", ",", "-", "1", ",", "a_stays_connected", ",", "0", ")", ",", "# TODO: Customize in XR driver", "(", "self", ".", "buffer_overflow_re", ",", "[", "0", "]", ",", "-", "1", ",", "CommandSyntaxError", "(", "\"Command too long\"", ",", "self", ".", "device", ".", "hostname", ")", ",", "0", ")", "]", "for", "prompt", "in", "self", ".", "device", ".", "get_previous_prompts", "(", ")", ":", "transitions", ".", "append", "(", "(", "prompt", ",", "[", "0", ",", "1", "]", ",", "0", ",", "a_unexpected_prompt", ",", "0", ")", ")", "fsm", "=", "FSM", "(", "\"WAIT-4-STRING\"", ",", "self", ".", "device", ",", "events", ",", "transitions", ",", "timeout", "=", "timeout", ")", "return", "fsm", ".", "run", "(", ")" ]
Wait for string FSM.
[ "Wait", "for", "string", "FSM", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/drivers/generic.py#L206-L234
train
kstaniek/condoor
condoor/drivers/generic.py
Driver.reload
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))
python
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))
[ "def", "reload", "(", "self", ",", "reload_timeout", "=", "300", ",", "save_config", "=", "True", ")", ":", "self", ".", "log", "(", "\"Reload not implemented on {} platform\"", ".", "format", "(", "self", ".", "platform", ")", ")" ]
Reload the device and waits for device to boot up. It posts the informational message to the log if not implemented by device driver.
[ "Reload", "the", "device", "and", "waits", "for", "device", "to", "boot", "up", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/drivers/generic.py#L282-L287
train
kstaniek/condoor
condoor/drivers/generic.py
Driver.base_prompt
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(prompt="(?P<prompt>.*?)") result = re.search(pattern, prompt) if result: base = result.group("prompt") + "#" self.log("base prompt: {}".format(base)) return base else: self.log("Unable to extract the base prompt") return prompt
python
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(prompt="(?P<prompt>.*?)") result = re.search(pattern, prompt) if result: base = result.group("prompt") + "#" self.log("base prompt: {}".format(base)) return base else: self.log("Unable to extract the base prompt") return prompt
[ "def", "base_prompt", "(", "self", ",", "prompt", ")", ":", "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", "(", "prompt", "=", "\"(?P<prompt>.*?)\"", ")", "result", "=", "re", ".", "search", "(", "pattern", ",", "prompt", ")", "if", "result", ":", "base", "=", "result", ".", "group", "(", "\"prompt\"", ")", "+", "\"#\"", "self", ".", "log", "(", "\"base prompt: {}\"", ".", "format", "(", "base", ")", ")", "return", "base", "else", ":", "self", ".", "log", "(", "\"Unable to extract the base prompt\"", ")", "return", "prompt" ]
Extract the base prompt pattern.
[ "Extract", "the", "base", "prompt", "pattern", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/drivers/generic.py#L293-L308
train
kstaniek/condoor
condoor/drivers/generic.py
Driver.update_config_mode
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' self.log("Mode: {}".format(mode)) return mode
python
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' self.log("Mode: {}".format(mode)) return mode
[ "def", "update_config_mode", "(", "self", ",", "prompt", ")", ":", "# pylint: disable=no-self-use", "mode", "=", "'global'", "if", "prompt", ":", "if", "'config'", "in", "prompt", ":", "mode", "=", "'config'", "elif", "'admin'", "in", "prompt", ":", "mode", "=", "'admin'", "self", ".", "log", "(", "\"Mode: {}\"", ".", "format", "(", "mode", ")", ")", "return", "mode" ]
Update config mode based on the prompt analysis.
[ "Update", "config", "mode", "based", "on", "the", "prompt", "analysis", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/drivers/generic.py#L327-L337
train
kstaniek/condoor
condoor/drivers/generic.py
Driver.update_hostname
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 = self.device.hostname self.log("Hostname not set: {}".format(prompt)) return hostname
python
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 = self.device.hostname self.log("Hostname not set: {}".format(prompt)) return hostname
[ "def", "update_hostname", "(", "self", ",", "prompt", ")", ":", "result", "=", "re", ".", "search", "(", "self", ".", "prompt_re", ",", "prompt", ")", "if", "result", ":", "hostname", "=", "result", ".", "group", "(", "'hostname'", ")", "self", ".", "log", "(", "\"Hostname detected: {}\"", ".", "format", "(", "hostname", ")", ")", "else", ":", "hostname", "=", "self", ".", "device", ".", "hostname", "self", ".", "log", "(", "\"Hostname not set: {}\"", ".", "format", "(", "prompt", ")", ")", "return", "hostname" ]
Update the hostname based on the prompt analysis.
[ "Update", "the", "hostname", "based", "on", "the", "prompt", "analysis", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/drivers/generic.py#L339-L348
train
kstaniek/condoor
condoor/drivers/generic.py
Driver.enter_plane
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: self.log("Entering the {} plane".format(plane)) self.device.send(cmd)
python
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: self.log("Entering the {} plane".format(plane)) self.device.send(cmd)
[ "def", "enter_plane", "(", "self", ",", "plane", ")", ":", "try", ":", "cmd", "=", "CONF", "[", "'driver'", "]", "[", "self", ".", "platform", "]", "[", "'planes'", "]", "[", "plane", "]", "self", ".", "plane", "=", "plane", "except", "KeyError", ":", "cmd", "=", "None", "if", "cmd", ":", "self", ".", "log", "(", "\"Entering the {} plane\"", ".", "format", "(", "plane", ")", ")", "self", ".", "device", ".", "send", "(", "cmd", ")" ]
Enter the device plane. Enter the device plane a.k.a. mode, i.e. admin, qnx, calvados
[ "Enter", "the", "device", "plane", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/drivers/generic.py#L360-L373
train
thomasjiangcy/django-rest-mock
rest_mock_server/core/factory.py
FixtureFactory.handle_other_factory_method
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: minimum = ast.literal_eval(minimum) else: minimum = 0 if maximum: maximum = ast.literal_eval(maximum) else: maximum = 100 val = random.uniform(minimum, maximum) return val # If `attr` isn't specified above, we need to raise an error raise ValueError('`%s` isn\'t a valid factory method.' % attr)
python
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: minimum = ast.literal_eval(minimum) else: minimum = 0 if maximum: maximum = ast.literal_eval(maximum) else: maximum = 100 val = random.uniform(minimum, maximum) return val # If `attr` isn't specified above, we need to raise an error raise ValueError('`%s` isn\'t a valid factory method.' % attr)
[ "def", "handle_other_factory_method", "(", "attr", ",", "minimum", ",", "maximum", ")", ":", "if", "attr", "==", "'percentage'", ":", "if", "minimum", ":", "minimum", "=", "ast", ".", "literal_eval", "(", "minimum", ")", "else", ":", "minimum", "=", "0", "if", "maximum", ":", "maximum", "=", "ast", ".", "literal_eval", "(", "maximum", ")", "else", ":", "maximum", "=", "100", "val", "=", "random", ".", "uniform", "(", "minimum", ",", "maximum", ")", "return", "val", "# If `attr` isn't specified above, we need to raise an error", "raise", "ValueError", "(", "'`%s` isn\\'t a valid factory method.'", "%", "attr", ")" ]
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
[ "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" ]
09e91de20d1a5efd5c47c6e3d7fe979443012e2c
https://github.com/thomasjiangcy/django-rest-mock/blob/09e91de20d1a5efd5c47c6e3d7fe979443012e2c/rest_mock_server/core/factory.py#L82-L101
train
thomasjiangcy/django-rest-mock
rest_mock_server/core/factory.py
FixtureFactory._parse_syntax
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+)?([0-9]*[.]?[0-9]+?)?(\:)?([0-9]*[.]?[0-9]+?)?(\:)?([0-9]*[.]?[0-9]+?)?>', raw, flags=re.DOTALL) if has_syntax: fake_val = re.sub( r'\'?\"?<(\^)?(fk__)?(\w+)?([0-9]*[.]?[0-9]+?)?(\:)?([0-9]*[.]?[0-9]+?)?(\:)?([0-9]*[.]?[0-9]+?)?>\'?\"?', self._replace_faker_attr, raw, flags=re.DOTALL ) fake_val = fake_val.replace("'", '"') try: fake_val = json.loads(fake_val) except: pass return fake_val else: return raw
python
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+)?([0-9]*[.]?[0-9]+?)?(\:)?([0-9]*[.]?[0-9]+?)?(\:)?([0-9]*[.]?[0-9]+?)?>', raw, flags=re.DOTALL) if has_syntax: fake_val = re.sub( r'\'?\"?<(\^)?(fk__)?(\w+)?([0-9]*[.]?[0-9]+?)?(\:)?([0-9]*[.]?[0-9]+?)?(\:)?([0-9]*[.]?[0-9]+?)?>\'?\"?', self._replace_faker_attr, raw, flags=re.DOTALL ) fake_val = fake_val.replace("'", '"') try: fake_val = json.loads(fake_val) except: pass return fake_val else: return raw
[ "def", "_parse_syntax", "(", "self", ",", "raw", ")", ":", "raw", "=", "str", "(", "raw", ")", "# treat the value as a string regardless of its actual data type", "has_syntax", "=", "re", ".", "findall", "(", "r'<(\\^)?(fk__)?(\\w+)?([0-9]*[.]?[0-9]+?)?(\\:)?([0-9]*[.]?[0-9]+?)?(\\:)?([0-9]*[.]?[0-9]+?)?>'", ",", "raw", ",", "flags", "=", "re", ".", "DOTALL", ")", "if", "has_syntax", ":", "fake_val", "=", "re", ".", "sub", "(", "r'\\'?\\\"?<(\\^)?(fk__)?(\\w+)?([0-9]*[.]?[0-9]+?)?(\\:)?([0-9]*[.]?[0-9]+?)?(\\:)?([0-9]*[.]?[0-9]+?)?>\\'?\\\"?'", ",", "self", ".", "_replace_faker_attr", ",", "raw", ",", "flags", "=", "re", ".", "DOTALL", ")", "fake_val", "=", "fake_val", ".", "replace", "(", "\"'\"", ",", "'\"'", ")", "try", ":", "fake_val", "=", "json", ".", "loads", "(", "fake_val", ")", "except", ":", "pass", "return", "fake_val", "else", ":", "return", "raw" ]
Retrieves the syntax from the response and goes through each one to generate and replace it with mock values
[ "Retrieves", "the", "syntax", "from", "the", "response", "and", "goes", "through", "each", "one", "to", "generate", "and", "replace", "it", "with", "mock", "values" ]
09e91de20d1a5efd5c47c6e3d7fe979443012e2c
https://github.com/thomasjiangcy/django-rest-mock/blob/09e91de20d1a5efd5c47c6e3d7fe979443012e2c/rest_mock_server/core/factory.py#L234-L256
train
thomasjiangcy/django-rest-mock
rest_mock_server/core/factory.py
FixtureFactory.count
def count(self, source, target): """ The 'count' relationship is used for listing endpoints where a specific attribute might hold the value to the number of instances of another attribute. """ try: source_value = self._response_holder[source] except KeyError: # Source value hasn't been determined yet, we need # to generate the source value first raw = self.fake_response[source] source_value = self._parse_syntax(raw) if isinstance(source_value, str): source_value = int(source_value) target = self.fake_response[target] values = [] for _ in range(source_value): self._is_empty = False # Remote state for re.sub to switch in case it hits a None value mock_value = self._parse_syntax(target) mock_value = str(mock_value) # Treat the value as a string regardless of its actual data type _target = mock_value[1:-1] # Remove extra quotation _target = _target.replace("'", '"') try: mock_value = json.loads(_target) except: mock_value = _target # If uniqueness is specified and this mock value isn't # in the store yet, then we can append it to the results if not self._is_empty: values.append(mock_value) return values
python
def count(self, source, target): """ The 'count' relationship is used for listing endpoints where a specific attribute might hold the value to the number of instances of another attribute. """ try: source_value = self._response_holder[source] except KeyError: # Source value hasn't been determined yet, we need # to generate the source value first raw = self.fake_response[source] source_value = self._parse_syntax(raw) if isinstance(source_value, str): source_value = int(source_value) target = self.fake_response[target] values = [] for _ in range(source_value): self._is_empty = False # Remote state for re.sub to switch in case it hits a None value mock_value = self._parse_syntax(target) mock_value = str(mock_value) # Treat the value as a string regardless of its actual data type _target = mock_value[1:-1] # Remove extra quotation _target = _target.replace("'", '"') try: mock_value = json.loads(_target) except: mock_value = _target # If uniqueness is specified and this mock value isn't # in the store yet, then we can append it to the results if not self._is_empty: values.append(mock_value) return values
[ "def", "count", "(", "self", ",", "source", ",", "target", ")", ":", "try", ":", "source_value", "=", "self", ".", "_response_holder", "[", "source", "]", "except", "KeyError", ":", "# Source value hasn't been determined yet, we need", "# to generate the source value first", "raw", "=", "self", ".", "fake_response", "[", "source", "]", "source_value", "=", "self", ".", "_parse_syntax", "(", "raw", ")", "if", "isinstance", "(", "source_value", ",", "str", ")", ":", "source_value", "=", "int", "(", "source_value", ")", "target", "=", "self", ".", "fake_response", "[", "target", "]", "values", "=", "[", "]", "for", "_", "in", "range", "(", "source_value", ")", ":", "self", ".", "_is_empty", "=", "False", "# Remote state for re.sub to switch in case it hits a None value", "mock_value", "=", "self", ".", "_parse_syntax", "(", "target", ")", "mock_value", "=", "str", "(", "mock_value", ")", "# Treat the value as a string regardless of its actual data type", "_target", "=", "mock_value", "[", "1", ":", "-", "1", "]", "# Remove extra quotation", "_target", "=", "_target", ".", "replace", "(", "\"'\"", ",", "'\"'", ")", "try", ":", "mock_value", "=", "json", ".", "loads", "(", "_target", ")", "except", ":", "mock_value", "=", "_target", "# If uniqueness is specified and this mock value isn't", "# in the store yet, then we can append it to the results", "if", "not", "self", ".", "_is_empty", ":", "values", ".", "append", "(", "mock_value", ")", "return", "values" ]
The 'count' relationship is used for listing endpoints where a specific attribute might hold the value to the number of instances of another attribute.
[ "The", "count", "relationship", "is", "used", "for", "listing", "endpoints", "where", "a", "specific", "attribute", "might", "hold", "the", "value", "to", "the", "number", "of", "instances", "of", "another", "attribute", "." ]
09e91de20d1a5efd5c47c6e3d7fe979443012e2c
https://github.com/thomasjiangcy/django-rest-mock/blob/09e91de20d1a5efd5c47c6e3d7fe979443012e2c/rest_mock_server/core/factory.py#L262-L294
train
kstaniek/condoor
condoor/protocols/ssh.py
SSH.get_command
def get_command(self, version=2): """Return the SSH protocol specific command to connect.""" try: options = _C['options'] options_str = " -o ".join(options) if options_str: options_str = "-o " + options_str + " " except KeyError: options_str = "" if self.username: # Not supported on SunOS # "-o ConnectTimeout={} command = "ssh {}" \ "-{} " \ "-p {} {}@{}".format(options_str, version, self.port, self.username, self.hostname) else: command = "ssh {} " \ "-{} " \ "-p {} {}".format(options_str, version, self.port, self.hostname) return command
python
def get_command(self, version=2): """Return the SSH protocol specific command to connect.""" try: options = _C['options'] options_str = " -o ".join(options) if options_str: options_str = "-o " + options_str + " " except KeyError: options_str = "" if self.username: # Not supported on SunOS # "-o ConnectTimeout={} command = "ssh {}" \ "-{} " \ "-p {} {}@{}".format(options_str, version, self.port, self.username, self.hostname) else: command = "ssh {} " \ "-{} " \ "-p {} {}".format(options_str, version, self.port, self.hostname) return command
[ "def", "get_command", "(", "self", ",", "version", "=", "2", ")", ":", "try", ":", "options", "=", "_C", "[", "'options'", "]", "options_str", "=", "\" -o \"", ".", "join", "(", "options", ")", "if", "options_str", ":", "options_str", "=", "\"-o \"", "+", "options_str", "+", "\" \"", "except", "KeyError", ":", "options_str", "=", "\"\"", "if", "self", ".", "username", ":", "# Not supported on SunOS", "# \"-o ConnectTimeout={}", "command", "=", "\"ssh {}\"", "\"-{} \"", "\"-p {} {}@{}\"", ".", "format", "(", "options_str", ",", "version", ",", "self", ".", "port", ",", "self", ".", "username", ",", "self", ".", "hostname", ")", "else", ":", "command", "=", "\"ssh {} \"", "\"-{} \"", "\"-p {} {}\"", ".", "format", "(", "options_str", ",", "version", ",", "self", ".", "port", ",", "self", ".", "hostname", ")", "return", "command" ]
Return the SSH protocol specific command to connect.
[ "Return", "the", "SSH", "protocol", "specific", "command", "to", "connect", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/protocols/ssh.py#L32-L52
train
kstaniek/condoor
condoor/protocols/ssh.py
SSH.connect
def connect(self, driver): """Connect using the SSH protocol specific FSM.""" # 0 1 2 events = [driver.password_re, self.device.prompt_re, driver.unable_to_connect_re, # 3 4 5 6 7 NEWSSHKEY, KNOWN_HOSTS, HOST_KEY_FAILED, MODULUS_TOO_SMALL, PROTOCOL_DIFFER, # 8 9 10 driver.timeout_re, pexpect.TIMEOUT, driver.syntax_error_re] transitions = [ (driver.password_re, [0, 1, 4, 5], -1, partial(a_save_last_pattern, self), 0), (driver.syntax_error_re, [0], -1, CommandSyntaxError("Command syntax error"), 0), (self.device.prompt_re, [0], -1, partial(a_save_last_pattern, self), 0), # cover all messages indicating that connection was not set up (driver.unable_to_connect_re, [0], -1, a_unable_to_connect, 0), (NEWSSHKEY, [0], 1, partial(a_send_line, "yes"), 10), (KNOWN_HOSTS, [0, 1], 0, None, 0), (HOST_KEY_FAILED, [0], -1, ConnectionError("Host key failed", self.hostname), 0), (MODULUS_TOO_SMALL, [0], 0, self.fallback_to_sshv1, 0), (PROTOCOL_DIFFER, [0], 4, self.fallback_to_sshv1, 0), (PROTOCOL_DIFFER, [4], -1, ConnectionError("Protocol version differs", self.hostname), 0), (pexpect.TIMEOUT, [0], 5, partial(a_send, "\r\n"), 10), (pexpect.TIMEOUT, [5], -1, ConnectionTimeoutError("Connection timeout", self.hostname), 0), (driver.timeout_re, [0], -1, ConnectionTimeoutError("Connection timeout", self.hostname), 0), ] self.log("EXPECTED_PROMPT={}".format(pattern_to_str(self.device.prompt_re))) fsm = FSM("SSH-CONNECT", self.device, events, transitions, timeout=_C['connect_timeout'], searchwindowsize=160) return fsm.run()
python
def connect(self, driver): """Connect using the SSH protocol specific FSM.""" # 0 1 2 events = [driver.password_re, self.device.prompt_re, driver.unable_to_connect_re, # 3 4 5 6 7 NEWSSHKEY, KNOWN_HOSTS, HOST_KEY_FAILED, MODULUS_TOO_SMALL, PROTOCOL_DIFFER, # 8 9 10 driver.timeout_re, pexpect.TIMEOUT, driver.syntax_error_re] transitions = [ (driver.password_re, [0, 1, 4, 5], -1, partial(a_save_last_pattern, self), 0), (driver.syntax_error_re, [0], -1, CommandSyntaxError("Command syntax error"), 0), (self.device.prompt_re, [0], -1, partial(a_save_last_pattern, self), 0), # cover all messages indicating that connection was not set up (driver.unable_to_connect_re, [0], -1, a_unable_to_connect, 0), (NEWSSHKEY, [0], 1, partial(a_send_line, "yes"), 10), (KNOWN_HOSTS, [0, 1], 0, None, 0), (HOST_KEY_FAILED, [0], -1, ConnectionError("Host key failed", self.hostname), 0), (MODULUS_TOO_SMALL, [0], 0, self.fallback_to_sshv1, 0), (PROTOCOL_DIFFER, [0], 4, self.fallback_to_sshv1, 0), (PROTOCOL_DIFFER, [4], -1, ConnectionError("Protocol version differs", self.hostname), 0), (pexpect.TIMEOUT, [0], 5, partial(a_send, "\r\n"), 10), (pexpect.TIMEOUT, [5], -1, ConnectionTimeoutError("Connection timeout", self.hostname), 0), (driver.timeout_re, [0], -1, ConnectionTimeoutError("Connection timeout", self.hostname), 0), ] self.log("EXPECTED_PROMPT={}".format(pattern_to_str(self.device.prompt_re))) fsm = FSM("SSH-CONNECT", self.device, events, transitions, timeout=_C['connect_timeout'], searchwindowsize=160) return fsm.run()
[ "def", "connect", "(", "self", ",", "driver", ")", ":", "# 0 1 2", "events", "=", "[", "driver", ".", "password_re", ",", "self", ".", "device", ".", "prompt_re", ",", "driver", ".", "unable_to_connect_re", ",", "# 3 4 5 6 7", "NEWSSHKEY", ",", "KNOWN_HOSTS", ",", "HOST_KEY_FAILED", ",", "MODULUS_TOO_SMALL", ",", "PROTOCOL_DIFFER", ",", "# 8 9 10", "driver", ".", "timeout_re", ",", "pexpect", ".", "TIMEOUT", ",", "driver", ".", "syntax_error_re", "]", "transitions", "=", "[", "(", "driver", ".", "password_re", ",", "[", "0", ",", "1", ",", "4", ",", "5", "]", ",", "-", "1", ",", "partial", "(", "a_save_last_pattern", ",", "self", ")", ",", "0", ")", ",", "(", "driver", ".", "syntax_error_re", ",", "[", "0", "]", ",", "-", "1", ",", "CommandSyntaxError", "(", "\"Command syntax error\"", ")", ",", "0", ")", ",", "(", "self", ".", "device", ".", "prompt_re", ",", "[", "0", "]", ",", "-", "1", ",", "partial", "(", "a_save_last_pattern", ",", "self", ")", ",", "0", ")", ",", "# cover all messages indicating that connection was not set up", "(", "driver", ".", "unable_to_connect_re", ",", "[", "0", "]", ",", "-", "1", ",", "a_unable_to_connect", ",", "0", ")", ",", "(", "NEWSSHKEY", ",", "[", "0", "]", ",", "1", ",", "partial", "(", "a_send_line", ",", "\"yes\"", ")", ",", "10", ")", ",", "(", "KNOWN_HOSTS", ",", "[", "0", ",", "1", "]", ",", "0", ",", "None", ",", "0", ")", ",", "(", "HOST_KEY_FAILED", ",", "[", "0", "]", ",", "-", "1", ",", "ConnectionError", "(", "\"Host key failed\"", ",", "self", ".", "hostname", ")", ",", "0", ")", ",", "(", "MODULUS_TOO_SMALL", ",", "[", "0", "]", ",", "0", ",", "self", ".", "fallback_to_sshv1", ",", "0", ")", ",", "(", "PROTOCOL_DIFFER", ",", "[", "0", "]", ",", "4", ",", "self", ".", "fallback_to_sshv1", ",", "0", ")", ",", "(", "PROTOCOL_DIFFER", ",", "[", "4", "]", ",", "-", "1", ",", "ConnectionError", "(", "\"Protocol version differs\"", ",", "self", ".", "hostname", ")", ",", "0", ")", ",", "(", "pexpect", ".", "TIMEOUT", ",", "[", "0", "]", ",", "5", ",", "partial", "(", "a_send", ",", "\"\\r\\n\"", ")", ",", "10", ")", ",", "(", "pexpect", ".", "TIMEOUT", ",", "[", "5", "]", ",", "-", "1", ",", "ConnectionTimeoutError", "(", "\"Connection timeout\"", ",", "self", ".", "hostname", ")", ",", "0", ")", ",", "(", "driver", ".", "timeout_re", ",", "[", "0", "]", ",", "-", "1", ",", "ConnectionTimeoutError", "(", "\"Connection timeout\"", ",", "self", ".", "hostname", ")", ",", "0", ")", ",", "]", "self", ".", "log", "(", "\"EXPECTED_PROMPT={}\"", ".", "format", "(", "pattern_to_str", "(", "self", ".", "device", ".", "prompt_re", ")", ")", ")", "fsm", "=", "FSM", "(", "\"SSH-CONNECT\"", ",", "self", ".", "device", ",", "events", ",", "transitions", ",", "timeout", "=", "_C", "[", "'connect_timeout'", "]", ",", "searchwindowsize", "=", "160", ")", "return", "fsm", ".", "run", "(", ")" ]
Connect using the SSH protocol specific FSM.
[ "Connect", "using", "the", "SSH", "protocol", "specific", "FSM", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/protocols/ssh.py#L54-L83
train
kstaniek/condoor
condoor/protocols/ssh.py
SSH.authenticate
def authenticate(self, driver): """Authenticate using the SSH protocol specific FSM.""" # 0 1 2 3 events = [driver.press_return_re, driver.password_re, self.device.prompt_re, pexpect.TIMEOUT] transitions = [ (driver.press_return_re, [0, 1], 1, partial(a_send, "\r\n"), 10), (driver.password_re, [0], 1, partial(a_send_password, self._acquire_password()), _C['first_prompt_timeout']), (driver.password_re, [1], -1, a_authentication_error, 0), (self.device.prompt_re, [0, 1], -1, None, 0), (pexpect.TIMEOUT, [1], -1, ConnectionError("Error getting device prompt") if self.device.is_target else partial(a_send, "\r\n"), 0) ] self.log("EXPECTED_PROMPT={}".format(pattern_to_str(self.device.prompt_re))) fsm = FSM("SSH-AUTH", self.device, events, transitions, init_pattern=self.last_pattern, timeout=30) return fsm.run()
python
def authenticate(self, driver): """Authenticate using the SSH protocol specific FSM.""" # 0 1 2 3 events = [driver.press_return_re, driver.password_re, self.device.prompt_re, pexpect.TIMEOUT] transitions = [ (driver.press_return_re, [0, 1], 1, partial(a_send, "\r\n"), 10), (driver.password_re, [0], 1, partial(a_send_password, self._acquire_password()), _C['first_prompt_timeout']), (driver.password_re, [1], -1, a_authentication_error, 0), (self.device.prompt_re, [0, 1], -1, None, 0), (pexpect.TIMEOUT, [1], -1, ConnectionError("Error getting device prompt") if self.device.is_target else partial(a_send, "\r\n"), 0) ] self.log("EXPECTED_PROMPT={}".format(pattern_to_str(self.device.prompt_re))) fsm = FSM("SSH-AUTH", self.device, events, transitions, init_pattern=self.last_pattern, timeout=30) return fsm.run()
[ "def", "authenticate", "(", "self", ",", "driver", ")", ":", "# 0 1 2 3", "events", "=", "[", "driver", ".", "press_return_re", ",", "driver", ".", "password_re", ",", "self", ".", "device", ".", "prompt_re", ",", "pexpect", ".", "TIMEOUT", "]", "transitions", "=", "[", "(", "driver", ".", "press_return_re", ",", "[", "0", ",", "1", "]", ",", "1", ",", "partial", "(", "a_send", ",", "\"\\r\\n\"", ")", ",", "10", ")", ",", "(", "driver", ".", "password_re", ",", "[", "0", "]", ",", "1", ",", "partial", "(", "a_send_password", ",", "self", ".", "_acquire_password", "(", ")", ")", ",", "_C", "[", "'first_prompt_timeout'", "]", ")", ",", "(", "driver", ".", "password_re", ",", "[", "1", "]", ",", "-", "1", ",", "a_authentication_error", ",", "0", ")", ",", "(", "self", ".", "device", ".", "prompt_re", ",", "[", "0", ",", "1", "]", ",", "-", "1", ",", "None", ",", "0", ")", ",", "(", "pexpect", ".", "TIMEOUT", ",", "[", "1", "]", ",", "-", "1", ",", "ConnectionError", "(", "\"Error getting device prompt\"", ")", "if", "self", ".", "device", ".", "is_target", "else", "partial", "(", "a_send", ",", "\"\\r\\n\"", ")", ",", "0", ")", "]", "self", ".", "log", "(", "\"EXPECTED_PROMPT={}\"", ".", "format", "(", "pattern_to_str", "(", "self", ".", "device", ".", "prompt_re", ")", ")", ")", "fsm", "=", "FSM", "(", "\"SSH-AUTH\"", ",", "self", ".", "device", ",", "events", ",", "transitions", ",", "init_pattern", "=", "self", ".", "last_pattern", ",", "timeout", "=", "30", ")", "return", "fsm", ".", "run", "(", ")" ]
Authenticate using the SSH protocol specific FSM.
[ "Authenticate", "using", "the", "SSH", "protocol", "specific", "FSM", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/protocols/ssh.py#L85-L102
train
kstaniek/condoor
condoor/protocols/ssh.py
SSH.disconnect
def disconnect(self, driver): """Disconnect using the protocol specific method.""" self.log("SSH disconnect") try: self.device.ctrl.sendline('\x03') self.device.ctrl.sendline('\x04') except OSError: self.log("Protocol already disconnected")
python
def disconnect(self, driver): """Disconnect using the protocol specific method.""" self.log("SSH disconnect") try: self.device.ctrl.sendline('\x03') self.device.ctrl.sendline('\x04') except OSError: self.log("Protocol already disconnected")
[ "def", "disconnect", "(", "self", ",", "driver", ")", ":", "self", ".", "log", "(", "\"SSH disconnect\"", ")", "try", ":", "self", ".", "device", ".", "ctrl", ".", "sendline", "(", "'\\x03'", ")", "self", ".", "device", ".", "ctrl", ".", "sendline", "(", "'\\x04'", ")", "except", "OSError", ":", "self", ".", "log", "(", "\"Protocol already disconnected\"", ")" ]
Disconnect using the protocol specific method.
[ "Disconnect", "using", "the", "protocol", "specific", "method", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/protocols/ssh.py#L104-L111
train
kstaniek/condoor
condoor/protocols/ssh.py
SSH.fallback_to_sshv1
def fallback_to_sshv1(self, ctx): """Fallback to SSHv1.""" command = self.get_command(version=1) ctx.spawn_session(command) return True
python
def fallback_to_sshv1(self, ctx): """Fallback to SSHv1.""" command = self.get_command(version=1) ctx.spawn_session(command) return True
[ "def", "fallback_to_sshv1", "(", "self", ",", "ctx", ")", ":", "command", "=", "self", ".", "get_command", "(", "version", "=", "1", ")", "ctx", ".", "spawn_session", "(", "command", ")", "return", "True" ]
Fallback to SSHv1.
[ "Fallback", "to", "SSHv1", "." ]
77c054b29d4e286c1d7aca2c74dff86b805e1fae
https://github.com/kstaniek/condoor/blob/77c054b29d4e286c1d7aca2c74dff86b805e1fae/condoor/protocols/ssh.py#L115-L119
train
rs/domcheck
domcheck/strategies.py
search_meta_tag
def search_meta_tag(html_doc, prefix, code): """ Checks whether the html_doc contains a meta matching the prefix & code """ regex = '<meta\s+(?:name=([\'\"]){0}\\1\s+content=([\'\"]){1}\\2|content=([\'\"]){1}\\3\s+name=([\'\"]){0}\\4)\s*/?>'.format(prefix, code) meta = re.compile(regex, flags=re.MULTILINE | re.IGNORECASE) m = meta.search(html_doc) if m: head = re.search(r'</head>', html_doc, flags=re.IGNORECASE) if head and m.start() < head.start(): return True return False
python
def search_meta_tag(html_doc, prefix, code): """ Checks whether the html_doc contains a meta matching the prefix & code """ regex = '<meta\s+(?:name=([\'\"]){0}\\1\s+content=([\'\"]){1}\\2|content=([\'\"]){1}\\3\s+name=([\'\"]){0}\\4)\s*/?>'.format(prefix, code) meta = re.compile(regex, flags=re.MULTILINE | re.IGNORECASE) m = meta.search(html_doc) if m: head = re.search(r'</head>', html_doc, flags=re.IGNORECASE) if head and m.start() < head.start(): return True return False
[ "def", "search_meta_tag", "(", "html_doc", ",", "prefix", ",", "code", ")", ":", "regex", "=", "'<meta\\s+(?:name=([\\'\\\"]){0}\\\\1\\s+content=([\\'\\\"]){1}\\\\2|content=([\\'\\\"]){1}\\\\3\\s+name=([\\'\\\"]){0}\\\\4)\\s*/?>'", ".", "format", "(", "prefix", ",", "code", ")", "meta", "=", "re", ".", "compile", "(", "regex", ",", "flags", "=", "re", ".", "MULTILINE", "|", "re", ".", "IGNORECASE", ")", "m", "=", "meta", ".", "search", "(", "html_doc", ")", "if", "m", ":", "head", "=", "re", ".", "search", "(", "r'</head>'", ",", "html_doc", ",", "flags", "=", "re", ".", "IGNORECASE", ")", "if", "head", "and", "m", ".", "start", "(", ")", "<", "head", ".", "start", "(", ")", ":", "return", "True", "return", "False" ]
Checks whether the html_doc contains a meta matching the prefix & code
[ "Checks", "whether", "the", "html_doc", "contains", "a", "meta", "matching", "the", "prefix", "&", "code" ]
43e10c345320564a1236778e8577e2b8ef825925
https://github.com/rs/domcheck/blob/43e10c345320564a1236778e8577e2b8ef825925/domcheck/strategies.py#L51-L62
train
happyleavesaoc/aoc-mgz
mgz/summary.py
find_postgame
def find_postgame(data, size): """Find postgame struct. We can find postgame location by scanning the last few thousand bytes of the rec and looking for a pattern as follows: [action op] [action length] [action type] 01 00 00 00 30 08 00 00 ff The last occurance of this pattern signals the start of the postgame structure. Note that the postgame action length is always constant, unlike other actions. """ pos = None for i in range(size - SEARCH_MAX_BYTES, size - LOOKAHEAD): op_type, length, action_type = struct.unpack('<IIB', data[i:i + LOOKAHEAD]) if op_type == 0x01 and length == POSTGAME_LENGTH and action_type == 0xFF: LOGGER.debug("found postgame candidate @ %d with length %d", i + LOOKAHEAD, length) return i + LOOKAHEAD, length
python
def find_postgame(data, size): """Find postgame struct. We can find postgame location by scanning the last few thousand bytes of the rec and looking for a pattern as follows: [action op] [action length] [action type] 01 00 00 00 30 08 00 00 ff The last occurance of this pattern signals the start of the postgame structure. Note that the postgame action length is always constant, unlike other actions. """ pos = None for i in range(size - SEARCH_MAX_BYTES, size - LOOKAHEAD): op_type, length, action_type = struct.unpack('<IIB', data[i:i + LOOKAHEAD]) if op_type == 0x01 and length == POSTGAME_LENGTH and action_type == 0xFF: LOGGER.debug("found postgame candidate @ %d with length %d", i + LOOKAHEAD, length) return i + LOOKAHEAD, length
[ "def", "find_postgame", "(", "data", ",", "size", ")", ":", "pos", "=", "None", "for", "i", "in", "range", "(", "size", "-", "SEARCH_MAX_BYTES", ",", "size", "-", "LOOKAHEAD", ")", ":", "op_type", ",", "length", ",", "action_type", "=", "struct", ".", "unpack", "(", "'<IIB'", ",", "data", "[", "i", ":", "i", "+", "LOOKAHEAD", "]", ")", "if", "op_type", "==", "0x01", "and", "length", "==", "POSTGAME_LENGTH", "and", "action_type", "==", "0xFF", ":", "LOGGER", ".", "debug", "(", "\"found postgame candidate @ %d with length %d\"", ",", "i", "+", "LOOKAHEAD", ",", "length", ")", "return", "i", "+", "LOOKAHEAD", ",", "length" ]
Find postgame struct. We can find postgame location by scanning the last few thousand bytes of the rec and looking for a pattern as follows: [action op] [action length] [action type] 01 00 00 00 30 08 00 00 ff The last occurance of this pattern signals the start of the postgame structure. Note that the postgame action length is always constant, unlike other actions.
[ "Find", "postgame", "struct", "." ]
13fc379cc062d7640bfa028eed9c0d45d37a7b2b
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/summary.py#L54-L73
train
happyleavesaoc/aoc-mgz
mgz/summary.py
parse_postgame
def parse_postgame(handle, size): """Parse postgame structure.""" data = handle.read() postgame = find_postgame(data, size) if postgame: pos, length = postgame try: return mgz.body.actions.postgame.parse(data[pos:pos + length]) except construct.core.ConstructError: raise IOError("failed to parse postgame") raise IOError("could not find postgame")
python
def parse_postgame(handle, size): """Parse postgame structure.""" data = handle.read() postgame = find_postgame(data, size) if postgame: pos, length = postgame try: return mgz.body.actions.postgame.parse(data[pos:pos + length]) except construct.core.ConstructError: raise IOError("failed to parse postgame") raise IOError("could not find postgame")
[ "def", "parse_postgame", "(", "handle", ",", "size", ")", ":", "data", "=", "handle", ".", "read", "(", ")", "postgame", "=", "find_postgame", "(", "data", ",", "size", ")", "if", "postgame", ":", "pos", ",", "length", "=", "postgame", "try", ":", "return", "mgz", ".", "body", ".", "actions", ".", "postgame", ".", "parse", "(", "data", "[", "pos", ":", "pos", "+", "length", "]", ")", "except", "construct", ".", "core", ".", "ConstructError", ":", "raise", "IOError", "(", "\"failed to parse postgame\"", ")", "raise", "IOError", "(", "\"could not find postgame\"", ")" ]
Parse postgame structure.
[ "Parse", "postgame", "structure", "." ]
13fc379cc062d7640bfa028eed9c0d45d37a7b2b
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/summary.py#L76-L86
train
happyleavesaoc/aoc-mgz
mgz/summary.py
ach
def ach(structure, fields): """Get field from achievements structure.""" field = fields.pop(0) if structure: if hasattr(structure, field): structure = getattr(structure, field) if not fields: return structure return ach(structure, fields) return None
python
def ach(structure, fields): """Get field from achievements structure.""" field = fields.pop(0) if structure: if hasattr(structure, field): structure = getattr(structure, field) if not fields: return structure return ach(structure, fields) return None
[ "def", "ach", "(", "structure", ",", "fields", ")", ":", "field", "=", "fields", ".", "pop", "(", "0", ")", "if", "structure", ":", "if", "hasattr", "(", "structure", ",", "field", ")", ":", "structure", "=", "getattr", "(", "structure", ",", "field", ")", "if", "not", "fields", ":", "return", "structure", "return", "ach", "(", "structure", ",", "fields", ")", "return", "None" ]
Get field from achievements structure.
[ "Get", "field", "from", "achievements", "structure", "." ]
13fc379cc062d7640bfa028eed9c0d45d37a7b2b
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/summary.py#L89-L98
train
happyleavesaoc/aoc-mgz
mgz/summary.py
Summary.get_postgame
def get_postgame(self): """Get postgame structure.""" if self._cache['postgame'] is not None: return self._cache['postgame'] self._handle.seek(0) try: self._cache['postgame'] = parse_postgame(self._handle, self.size) return self._cache['postgame'] except IOError: self._cache['postgame'] = False return None finally: self._handle.seek(self.body_position)
python
def get_postgame(self): """Get postgame structure.""" if self._cache['postgame'] is not None: return self._cache['postgame'] self._handle.seek(0) try: self._cache['postgame'] = parse_postgame(self._handle, self.size) return self._cache['postgame'] except IOError: self._cache['postgame'] = False return None finally: self._handle.seek(self.body_position)
[ "def", "get_postgame", "(", "self", ")", ":", "if", "self", ".", "_cache", "[", "'postgame'", "]", "is", "not", "None", ":", "return", "self", ".", "_cache", "[", "'postgame'", "]", "self", ".", "_handle", ".", "seek", "(", "0", ")", "try", ":", "self", ".", "_cache", "[", "'postgame'", "]", "=", "parse_postgame", "(", "self", ".", "_handle", ",", "self", ".", "size", ")", "return", "self", ".", "_cache", "[", "'postgame'", "]", "except", "IOError", ":", "self", ".", "_cache", "[", "'postgame'", "]", "=", "False", "return", "None", "finally", ":", "self", ".", "_handle", ".", "seek", "(", "self", ".", "body_position", ")" ]
Get postgame structure.
[ "Get", "postgame", "structure", "." ]
13fc379cc062d7640bfa028eed9c0d45d37a7b2b
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/summary.py#L138-L150
train
happyleavesaoc/aoc-mgz
mgz/summary.py
Summary.get_duration
def get_duration(self): """Get game duration.""" postgame = self.get_postgame() if postgame: return postgame.duration_int * 1000 duration = self._header.initial.restore_time try: while self._handle.tell() < self.size: operation = mgz.body.operation.parse_stream(self._handle) if operation.type == 'sync': duration += operation.time_increment elif operation.type == 'action': if operation.action.type == 'resign': self._cache['resigned'].add(operation.action.player_id) self._handle.seek(self.body_position) except (construct.core.ConstructError, zlib.error, ValueError): raise RuntimeError("invalid mgz file") return duration
python
def get_duration(self): """Get game duration.""" postgame = self.get_postgame() if postgame: return postgame.duration_int * 1000 duration = self._header.initial.restore_time try: while self._handle.tell() < self.size: operation = mgz.body.operation.parse_stream(self._handle) if operation.type == 'sync': duration += operation.time_increment elif operation.type == 'action': if operation.action.type == 'resign': self._cache['resigned'].add(operation.action.player_id) self._handle.seek(self.body_position) except (construct.core.ConstructError, zlib.error, ValueError): raise RuntimeError("invalid mgz file") return duration
[ "def", "get_duration", "(", "self", ")", ":", "postgame", "=", "self", ".", "get_postgame", "(", ")", "if", "postgame", ":", "return", "postgame", ".", "duration_int", "*", "1000", "duration", "=", "self", ".", "_header", ".", "initial", ".", "restore_time", "try", ":", "while", "self", ".", "_handle", ".", "tell", "(", ")", "<", "self", ".", "size", ":", "operation", "=", "mgz", ".", "body", ".", "operation", ".", "parse_stream", "(", "self", ".", "_handle", ")", "if", "operation", ".", "type", "==", "'sync'", ":", "duration", "+=", "operation", ".", "time_increment", "elif", "operation", ".", "type", "==", "'action'", ":", "if", "operation", ".", "action", ".", "type", "==", "'resign'", ":", "self", ".", "_cache", "[", "'resigned'", "]", ".", "add", "(", "operation", ".", "action", ".", "player_id", ")", "self", ".", "_handle", ".", "seek", "(", "self", ".", "body_position", ")", "except", "(", "construct", ".", "core", ".", "ConstructError", ",", "zlib", ".", "error", ",", "ValueError", ")", ":", "raise", "RuntimeError", "(", "\"invalid mgz file\"", ")", "return", "duration" ]
Get game duration.
[ "Get", "game", "duration", "." ]
13fc379cc062d7640bfa028eed9c0d45d37a7b2b
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/summary.py#L152-L169
train
happyleavesaoc/aoc-mgz
mgz/summary.py
Summary.get_restored
def get_restored(self): """Check for restored game.""" return self._header.initial.restore_time > 0, self._header.initial.restore_time
python
def get_restored(self): """Check for restored game.""" return self._header.initial.restore_time > 0, self._header.initial.restore_time
[ "def", "get_restored", "(", "self", ")", ":", "return", "self", ".", "_header", ".", "initial", ".", "restore_time", ">", "0", ",", "self", ".", "_header", ".", "initial", ".", "restore_time" ]
Check for restored game.
[ "Check", "for", "restored", "game", "." ]
13fc379cc062d7640bfa028eed9c0d45d37a7b2b
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/summary.py#L171-L173
train
happyleavesaoc/aoc-mgz
mgz/summary.py
Summary.get_version
def get_version(self): """Get game version.""" return mgz.const.VERSIONS[self._header.version], str(self._header.sub_version)[:5]
python
def get_version(self): """Get game version.""" return mgz.const.VERSIONS[self._header.version], str(self._header.sub_version)[:5]
[ "def", "get_version", "(", "self", ")", ":", "return", "mgz", ".", "const", ".", "VERSIONS", "[", "self", ".", "_header", ".", "version", "]", ",", "str", "(", "self", ".", "_header", ".", "sub_version", ")", "[", ":", "5", "]" ]
Get game version.
[ "Get", "game", "version", "." ]
13fc379cc062d7640bfa028eed9c0d45d37a7b2b
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/summary.py#L175-L177
train
happyleavesaoc/aoc-mgz
mgz/summary.py
Summary.get_dataset
def get_dataset(self): """Get dataset.""" sample = self._header.initial.players[0].attributes.player_stats if 'mod' in sample and sample.mod['id'] > 0: return sample.mod elif 'trickle_food' in sample and sample.trickle_food: return { 'id': 1, 'name': mgz.const.MODS.get(1), 'version': '<5.7.2' } return { 'id': 0, 'name': 'Age of Kings: The Conquerors', 'version': '1.0c' }
python
def get_dataset(self): """Get dataset.""" sample = self._header.initial.players[0].attributes.player_stats if 'mod' in sample and sample.mod['id'] > 0: return sample.mod elif 'trickle_food' in sample and sample.trickle_food: return { 'id': 1, 'name': mgz.const.MODS.get(1), 'version': '<5.7.2' } return { 'id': 0, 'name': 'Age of Kings: The Conquerors', 'version': '1.0c' }
[ "def", "get_dataset", "(", "self", ")", ":", "sample", "=", "self", ".", "_header", ".", "initial", ".", "players", "[", "0", "]", ".", "attributes", ".", "player_stats", "if", "'mod'", "in", "sample", "and", "sample", ".", "mod", "[", "'id'", "]", ">", "0", ":", "return", "sample", ".", "mod", "elif", "'trickle_food'", "in", "sample", "and", "sample", ".", "trickle_food", ":", "return", "{", "'id'", ":", "1", ",", "'name'", ":", "mgz", ".", "const", ".", "MODS", ".", "get", "(", "1", ")", ",", "'version'", ":", "'<5.7.2'", "}", "return", "{", "'id'", ":", "0", ",", "'name'", ":", "'Age of Kings: The Conquerors'", ",", "'version'", ":", "'1.0c'", "}" ]
Get dataset.
[ "Get", "dataset", "." ]
13fc379cc062d7640bfa028eed9c0d45d37a7b2b
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/summary.py#L179-L194
train
happyleavesaoc/aoc-mgz
mgz/summary.py
Summary.get_teams
def get_teams(self): """Get teams.""" if self._cache['teams']: return self._cache['teams'] teams = [] for j, player in enumerate(self._header.initial.players): added = False for i in range(0, len(self._header.initial.players)): if player.attributes.my_diplomacy[i] == 'ally': inner_team = False outer_team = False new_team = True for t, tl in enumerate(teams): if j in tl or i in tl: new_team = False if j in tl and i not in tl: inner_team = t break if j not in tl and i in tl: outer_team = t break if new_team: teams.append([i, j]) if inner_team is not False: teams[inner_team].append(i) if outer_team is not False: teams[outer_team].append(j) added = True if not added and j != 0: teams.append([j]) self._cache['teams'] = teams return teams
python
def get_teams(self): """Get teams.""" if self._cache['teams']: return self._cache['teams'] teams = [] for j, player in enumerate(self._header.initial.players): added = False for i in range(0, len(self._header.initial.players)): if player.attributes.my_diplomacy[i] == 'ally': inner_team = False outer_team = False new_team = True for t, tl in enumerate(teams): if j in tl or i in tl: new_team = False if j in tl and i not in tl: inner_team = t break if j not in tl and i in tl: outer_team = t break if new_team: teams.append([i, j]) if inner_team is not False: teams[inner_team].append(i) if outer_team is not False: teams[outer_team].append(j) added = True if not added and j != 0: teams.append([j]) self._cache['teams'] = teams return teams
[ "def", "get_teams", "(", "self", ")", ":", "if", "self", ".", "_cache", "[", "'teams'", "]", ":", "return", "self", ".", "_cache", "[", "'teams'", "]", "teams", "=", "[", "]", "for", "j", ",", "player", "in", "enumerate", "(", "self", ".", "_header", ".", "initial", ".", "players", ")", ":", "added", "=", "False", "for", "i", "in", "range", "(", "0", ",", "len", "(", "self", ".", "_header", ".", "initial", ".", "players", ")", ")", ":", "if", "player", ".", "attributes", ".", "my_diplomacy", "[", "i", "]", "==", "'ally'", ":", "inner_team", "=", "False", "outer_team", "=", "False", "new_team", "=", "True", "for", "t", ",", "tl", "in", "enumerate", "(", "teams", ")", ":", "if", "j", "in", "tl", "or", "i", "in", "tl", ":", "new_team", "=", "False", "if", "j", "in", "tl", "and", "i", "not", "in", "tl", ":", "inner_team", "=", "t", "break", "if", "j", "not", "in", "tl", "and", "i", "in", "tl", ":", "outer_team", "=", "t", "break", "if", "new_team", ":", "teams", ".", "append", "(", "[", "i", ",", "j", "]", ")", "if", "inner_team", "is", "not", "False", ":", "teams", "[", "inner_team", "]", ".", "append", "(", "i", ")", "if", "outer_team", "is", "not", "False", ":", "teams", "[", "outer_team", "]", ".", "append", "(", "j", ")", "added", "=", "True", "if", "not", "added", "and", "j", "!=", "0", ":", "teams", ".", "append", "(", "[", "j", "]", ")", "self", ".", "_cache", "[", "'teams'", "]", "=", "teams", "return", "teams" ]
Get teams.
[ "Get", "teams", "." ]
13fc379cc062d7640bfa028eed9c0d45d37a7b2b
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/summary.py#L200-L231
train
happyleavesaoc/aoc-mgz
mgz/summary.py
Summary.get_achievements
def get_achievements(self, name): """Get achievements for a player. Must match on name, not index, since order is not always the same. """ postgame = self.get_postgame() if not postgame: return None for achievements in postgame.achievements: # achievements player name can be shorter if name.startswith(achievements.player_name.replace(b'\x00', b'')): return achievements return None
python
def get_achievements(self, name): """Get achievements for a player. Must match on name, not index, since order is not always the same. """ postgame = self.get_postgame() if not postgame: return None for achievements in postgame.achievements: # achievements player name can be shorter if name.startswith(achievements.player_name.replace(b'\x00', b'')): return achievements return None
[ "def", "get_achievements", "(", "self", ",", "name", ")", ":", "postgame", "=", "self", ".", "get_postgame", "(", ")", "if", "not", "postgame", ":", "return", "None", "for", "achievements", "in", "postgame", ".", "achievements", ":", "# achievements player name can be shorter", "if", "name", ".", "startswith", "(", "achievements", ".", "player_name", ".", "replace", "(", "b'\\x00'", ",", "b''", ")", ")", ":", "return", "achievements", "return", "None" ]
Get achievements for a player. Must match on name, not index, since order is not always the same.
[ "Get", "achievements", "for", "a", "player", "." ]
13fc379cc062d7640bfa028eed9c0d45d37a7b2b
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/summary.py#L265-L277
train
happyleavesaoc/aoc-mgz
mgz/summary.py
Summary._process_body
def _process_body(self): """Get Voobly ladder. This is expensive if the rec is not from Voobly, since it will search the whole file. Returns tuple, (from_voobly, ladder_name, rated, ratings). """ start_time = time.time() ratings = {} encoding = self.get_encoding() checksums = [] ladder= None voobly = False rated = False i = 0 while self._handle.tell() < self.size: try: op = mgz.body.operation.parse_stream(self._handle) if op.type == 'sync': i += 1 if op.type == 'sync' and op.checksum is not None and len(checksums) < CHECKSUMS: checksums.append(op.checksum.sync.to_bytes(8, 'big', signed=True)) elif op.type == 'message' and op.subtype == 'chat': text = op.data.text.decode(encoding) if text.find('Voobly: Ratings provided') > 0: start = text.find("'") + 1 end = text.find("'", start) ladder = text[start:end] voobly = True elif text.find('<Rating>') > 0: player_start = text.find('>') + 2 player_end = text.find(':', player_start) player = text[player_start:player_end] ratings[player] = int(text[player_end + 2:len(text)]) elif text.find('No ratings are available') > 0: voobly = True elif text.find('This match was played at Voobly.com') > 0: voobly = True if i > MAX_SYNCS: break except (construct.core.ConstructError, ValueError): break self._handle.seek(self.body_position) rated = len(ratings) > 0 and set(ratings.values()) != {1600} self._cache['hash'] = hashlib.sha1(b''.join(checksums)) if len(checksums) == CHECKSUMS else None self._cache['from_voobly'] = voobly self._cache['ladder'] = ladder self._cache['rated'] = rated self._cache['ratings'] = ratings if rated else {} LOGGER.info("parsed limited rec body in %.2f seconds", time.time() - start_time) return voobly, ladder, rated, ratings
python
def _process_body(self): """Get Voobly ladder. This is expensive if the rec is not from Voobly, since it will search the whole file. Returns tuple, (from_voobly, ladder_name, rated, ratings). """ start_time = time.time() ratings = {} encoding = self.get_encoding() checksums = [] ladder= None voobly = False rated = False i = 0 while self._handle.tell() < self.size: try: op = mgz.body.operation.parse_stream(self._handle) if op.type == 'sync': i += 1 if op.type == 'sync' and op.checksum is not None and len(checksums) < CHECKSUMS: checksums.append(op.checksum.sync.to_bytes(8, 'big', signed=True)) elif op.type == 'message' and op.subtype == 'chat': text = op.data.text.decode(encoding) if text.find('Voobly: Ratings provided') > 0: start = text.find("'") + 1 end = text.find("'", start) ladder = text[start:end] voobly = True elif text.find('<Rating>') > 0: player_start = text.find('>') + 2 player_end = text.find(':', player_start) player = text[player_start:player_end] ratings[player] = int(text[player_end + 2:len(text)]) elif text.find('No ratings are available') > 0: voobly = True elif text.find('This match was played at Voobly.com') > 0: voobly = True if i > MAX_SYNCS: break except (construct.core.ConstructError, ValueError): break self._handle.seek(self.body_position) rated = len(ratings) > 0 and set(ratings.values()) != {1600} self._cache['hash'] = hashlib.sha1(b''.join(checksums)) if len(checksums) == CHECKSUMS else None self._cache['from_voobly'] = voobly self._cache['ladder'] = ladder self._cache['rated'] = rated self._cache['ratings'] = ratings if rated else {} LOGGER.info("parsed limited rec body in %.2f seconds", time.time() - start_time) return voobly, ladder, rated, ratings
[ "def", "_process_body", "(", "self", ")", ":", "start_time", "=", "time", ".", "time", "(", ")", "ratings", "=", "{", "}", "encoding", "=", "self", ".", "get_encoding", "(", ")", "checksums", "=", "[", "]", "ladder", "=", "None", "voobly", "=", "False", "rated", "=", "False", "i", "=", "0", "while", "self", ".", "_handle", ".", "tell", "(", ")", "<", "self", ".", "size", ":", "try", ":", "op", "=", "mgz", ".", "body", ".", "operation", ".", "parse_stream", "(", "self", ".", "_handle", ")", "if", "op", ".", "type", "==", "'sync'", ":", "i", "+=", "1", "if", "op", ".", "type", "==", "'sync'", "and", "op", ".", "checksum", "is", "not", "None", "and", "len", "(", "checksums", ")", "<", "CHECKSUMS", ":", "checksums", ".", "append", "(", "op", ".", "checksum", ".", "sync", ".", "to_bytes", "(", "8", ",", "'big'", ",", "signed", "=", "True", ")", ")", "elif", "op", ".", "type", "==", "'message'", "and", "op", ".", "subtype", "==", "'chat'", ":", "text", "=", "op", ".", "data", ".", "text", ".", "decode", "(", "encoding", ")", "if", "text", ".", "find", "(", "'Voobly: Ratings provided'", ")", ">", "0", ":", "start", "=", "text", ".", "find", "(", "\"'\"", ")", "+", "1", "end", "=", "text", ".", "find", "(", "\"'\"", ",", "start", ")", "ladder", "=", "text", "[", "start", ":", "end", "]", "voobly", "=", "True", "elif", "text", ".", "find", "(", "'<Rating>'", ")", ">", "0", ":", "player_start", "=", "text", ".", "find", "(", "'>'", ")", "+", "2", "player_end", "=", "text", ".", "find", "(", "':'", ",", "player_start", ")", "player", "=", "text", "[", "player_start", ":", "player_end", "]", "ratings", "[", "player", "]", "=", "int", "(", "text", "[", "player_end", "+", "2", ":", "len", "(", "text", ")", "]", ")", "elif", "text", ".", "find", "(", "'No ratings are available'", ")", ">", "0", ":", "voobly", "=", "True", "elif", "text", ".", "find", "(", "'This match was played at Voobly.com'", ")", ">", "0", ":", "voobly", "=", "True", "if", "i", ">", "MAX_SYNCS", ":", "break", "except", "(", "construct", ".", "core", ".", "ConstructError", ",", "ValueError", ")", ":", "break", "self", ".", "_handle", ".", "seek", "(", "self", ".", "body_position", ")", "rated", "=", "len", "(", "ratings", ")", ">", "0", "and", "set", "(", "ratings", ".", "values", "(", ")", ")", "!=", "{", "1600", "}", "self", ".", "_cache", "[", "'hash'", "]", "=", "hashlib", ".", "sha1", "(", "b''", ".", "join", "(", "checksums", ")", ")", "if", "len", "(", "checksums", ")", "==", "CHECKSUMS", "else", "None", "self", ".", "_cache", "[", "'from_voobly'", "]", "=", "voobly", "self", ".", "_cache", "[", "'ladder'", "]", "=", "ladder", "self", ".", "_cache", "[", "'rated'", "]", "=", "rated", "self", ".", "_cache", "[", "'ratings'", "]", "=", "ratings", "if", "rated", "else", "{", "}", "LOGGER", ".", "info", "(", "\"parsed limited rec body in %.2f seconds\"", ",", "time", ".", "time", "(", ")", "-", "start_time", ")", "return", "voobly", ",", "ladder", ",", "rated", ",", "ratings" ]
Get Voobly ladder. This is expensive if the rec is not from Voobly, since it will search the whole file. Returns tuple, (from_voobly, ladder_name, rated, ratings).
[ "Get", "Voobly", "ladder", "." ]
13fc379cc062d7640bfa028eed9c0d45d37a7b2b
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/summary.py#L353-L403
train
happyleavesaoc/aoc-mgz
mgz/summary.py
Summary.get_settings
def get_settings(self): """Get settings.""" postgame = self.get_postgame() return { 'type': ( self._header.lobby.game_type_id, self._header.lobby.game_type ), 'difficulty': ( self._header.scenario.game_settings.difficulty_id, self._header.scenario.game_settings.difficulty ), 'population_limit': self._header.lobby.population_limit * 25, 'map_reveal_choice': ( self._header.lobby.reveal_map_id, self._header.lobby.reveal_map ), 'speed': ( self._header.replay.game_speed_id, mgz.const.SPEEDS.get(self._header.replay.game_speed_id) ), 'cheats': self._header.replay.cheats_enabled, 'lock_teams': self._header.lobby.lock_teams, 'starting_resources': ( postgame.resource_level_id if postgame else None, postgame.resource_level if postgame else None, ), 'starting_age': ( postgame.starting_age_id if postgame else None, postgame.starting_age if postgame else None ), 'victory_condition': ( postgame.victory_type_id if postgame else None, postgame.victory_type if postgame else None ), 'team_together': not postgame.team_together if postgame else None, 'all_technologies': postgame.all_techs if postgame else None, 'lock_speed': postgame.lock_speed if postgame else None, 'multiqueue': None }
python
def get_settings(self): """Get settings.""" postgame = self.get_postgame() return { 'type': ( self._header.lobby.game_type_id, self._header.lobby.game_type ), 'difficulty': ( self._header.scenario.game_settings.difficulty_id, self._header.scenario.game_settings.difficulty ), 'population_limit': self._header.lobby.population_limit * 25, 'map_reveal_choice': ( self._header.lobby.reveal_map_id, self._header.lobby.reveal_map ), 'speed': ( self._header.replay.game_speed_id, mgz.const.SPEEDS.get(self._header.replay.game_speed_id) ), 'cheats': self._header.replay.cheats_enabled, 'lock_teams': self._header.lobby.lock_teams, 'starting_resources': ( postgame.resource_level_id if postgame else None, postgame.resource_level if postgame else None, ), 'starting_age': ( postgame.starting_age_id if postgame else None, postgame.starting_age if postgame else None ), 'victory_condition': ( postgame.victory_type_id if postgame else None, postgame.victory_type if postgame else None ), 'team_together': not postgame.team_together if postgame else None, 'all_technologies': postgame.all_techs if postgame else None, 'lock_speed': postgame.lock_speed if postgame else None, 'multiqueue': None }
[ "def", "get_settings", "(", "self", ")", ":", "postgame", "=", "self", ".", "get_postgame", "(", ")", "return", "{", "'type'", ":", "(", "self", ".", "_header", ".", "lobby", ".", "game_type_id", ",", "self", ".", "_header", ".", "lobby", ".", "game_type", ")", ",", "'difficulty'", ":", "(", "self", ".", "_header", ".", "scenario", ".", "game_settings", ".", "difficulty_id", ",", "self", ".", "_header", ".", "scenario", ".", "game_settings", ".", "difficulty", ")", ",", "'population_limit'", ":", "self", ".", "_header", ".", "lobby", ".", "population_limit", "*", "25", ",", "'map_reveal_choice'", ":", "(", "self", ".", "_header", ".", "lobby", ".", "reveal_map_id", ",", "self", ".", "_header", ".", "lobby", ".", "reveal_map", ")", ",", "'speed'", ":", "(", "self", ".", "_header", ".", "replay", ".", "game_speed_id", ",", "mgz", ".", "const", ".", "SPEEDS", ".", "get", "(", "self", ".", "_header", ".", "replay", ".", "game_speed_id", ")", ")", ",", "'cheats'", ":", "self", ".", "_header", ".", "replay", ".", "cheats_enabled", ",", "'lock_teams'", ":", "self", ".", "_header", ".", "lobby", ".", "lock_teams", ",", "'starting_resources'", ":", "(", "postgame", ".", "resource_level_id", "if", "postgame", "else", "None", ",", "postgame", ".", "resource_level", "if", "postgame", "else", "None", ",", ")", ",", "'starting_age'", ":", "(", "postgame", ".", "starting_age_id", "if", "postgame", "else", "None", ",", "postgame", ".", "starting_age", "if", "postgame", "else", "None", ")", ",", "'victory_condition'", ":", "(", "postgame", ".", "victory_type_id", "if", "postgame", "else", "None", ",", "postgame", ".", "victory_type", "if", "postgame", "else", "None", ")", ",", "'team_together'", ":", "not", "postgame", ".", "team_together", "if", "postgame", "else", "None", ",", "'all_technologies'", ":", "postgame", ".", "all_techs", "if", "postgame", "else", "None", ",", "'lock_speed'", ":", "postgame", ".", "lock_speed", "if", "postgame", "else", "None", ",", "'multiqueue'", ":", "None", "}" ]
Get settings.
[ "Get", "settings", "." ]
13fc379cc062d7640bfa028eed9c0d45d37a7b2b
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/summary.py#L405-L444
train
happyleavesaoc/aoc-mgz
mgz/summary.py
Summary.get_map
def get_map(self): """Get the map metadata.""" if self._cache['map']: return self._cache['map'] map_id = self._header.scenario.game_settings.map_id instructions = self._header.scenario.messages.instructions size = mgz.const.MAP_SIZES.get(self._header.map_info.size_x) dimension = self._header.map_info.size_x custom = True name = 'Unknown' language = None encoding = 'unknown' # detect encoding and language for pair in ENCODING_MARKERS: marker = pair[0] test_encoding = pair[1] e_m = marker.encode(test_encoding) for line in instructions.split(b'\n'): pos = line.find(e_m) if pos > -1: encoding = test_encoding name = line[pos+len(e_m):].decode(encoding) language = pair[2] break # disambiguate certain languages if not language: language = 'unknown' for pair in LANGUAGE_MARKERS: if instructions.find(pair[0].encode(pair[1])) > -1: language = pair[2] break self._cache['encoding'] = encoding self._cache['language'] = language # lookup base game map if applicable if map_id != 44: if map_id not in mgz.const.MAP_NAMES: raise ValueError('unspecified builtin map') name = mgz.const.MAP_NAMES[map_id] custom = False # extract map seed match = re.search(b'\x00.*? (\-?[0-9]+)\x00.*?\.rms', instructions) seed = None if match: seed = int(match.group(1)) # extract userpatch modes has_modes = name.find(': !') mode_string = '' if has_modes > -1: mode_string = name[has_modes + 3:] name = name[:has_modes] modes = { 'direct_placement': 'P' in mode_string, 'effect_quantity': 'C' in mode_string, 'guard_state': 'G' in mode_string, 'fixed_positions': 'F' in mode_string } self._cache['map'] = { 'id': map_id if not custom else None, 'name': name.strip(), 'size': size, 'dimension': dimension, 'seed': seed, 'modes': modes, 'custom': custom, 'zr': name.startswith('ZR@') } return self._cache['map']
python
def get_map(self): """Get the map metadata.""" if self._cache['map']: return self._cache['map'] map_id = self._header.scenario.game_settings.map_id instructions = self._header.scenario.messages.instructions size = mgz.const.MAP_SIZES.get(self._header.map_info.size_x) dimension = self._header.map_info.size_x custom = True name = 'Unknown' language = None encoding = 'unknown' # detect encoding and language for pair in ENCODING_MARKERS: marker = pair[0] test_encoding = pair[1] e_m = marker.encode(test_encoding) for line in instructions.split(b'\n'): pos = line.find(e_m) if pos > -1: encoding = test_encoding name = line[pos+len(e_m):].decode(encoding) language = pair[2] break # disambiguate certain languages if not language: language = 'unknown' for pair in LANGUAGE_MARKERS: if instructions.find(pair[0].encode(pair[1])) > -1: language = pair[2] break self._cache['encoding'] = encoding self._cache['language'] = language # lookup base game map if applicable if map_id != 44: if map_id not in mgz.const.MAP_NAMES: raise ValueError('unspecified builtin map') name = mgz.const.MAP_NAMES[map_id] custom = False # extract map seed match = re.search(b'\x00.*? (\-?[0-9]+)\x00.*?\.rms', instructions) seed = None if match: seed = int(match.group(1)) # extract userpatch modes has_modes = name.find(': !') mode_string = '' if has_modes > -1: mode_string = name[has_modes + 3:] name = name[:has_modes] modes = { 'direct_placement': 'P' in mode_string, 'effect_quantity': 'C' in mode_string, 'guard_state': 'G' in mode_string, 'fixed_positions': 'F' in mode_string } self._cache['map'] = { 'id': map_id if not custom else None, 'name': name.strip(), 'size': size, 'dimension': dimension, 'seed': seed, 'modes': modes, 'custom': custom, 'zr': name.startswith('ZR@') } return self._cache['map']
[ "def", "get_map", "(", "self", ")", ":", "if", "self", ".", "_cache", "[", "'map'", "]", ":", "return", "self", ".", "_cache", "[", "'map'", "]", "map_id", "=", "self", ".", "_header", ".", "scenario", ".", "game_settings", ".", "map_id", "instructions", "=", "self", ".", "_header", ".", "scenario", ".", "messages", ".", "instructions", "size", "=", "mgz", ".", "const", ".", "MAP_SIZES", ".", "get", "(", "self", ".", "_header", ".", "map_info", ".", "size_x", ")", "dimension", "=", "self", ".", "_header", ".", "map_info", ".", "size_x", "custom", "=", "True", "name", "=", "'Unknown'", "language", "=", "None", "encoding", "=", "'unknown'", "# detect encoding and language", "for", "pair", "in", "ENCODING_MARKERS", ":", "marker", "=", "pair", "[", "0", "]", "test_encoding", "=", "pair", "[", "1", "]", "e_m", "=", "marker", ".", "encode", "(", "test_encoding", ")", "for", "line", "in", "instructions", ".", "split", "(", "b'\\n'", ")", ":", "pos", "=", "line", ".", "find", "(", "e_m", ")", "if", "pos", ">", "-", "1", ":", "encoding", "=", "test_encoding", "name", "=", "line", "[", "pos", "+", "len", "(", "e_m", ")", ":", "]", ".", "decode", "(", "encoding", ")", "language", "=", "pair", "[", "2", "]", "break", "# disambiguate certain languages", "if", "not", "language", ":", "language", "=", "'unknown'", "for", "pair", "in", "LANGUAGE_MARKERS", ":", "if", "instructions", ".", "find", "(", "pair", "[", "0", "]", ".", "encode", "(", "pair", "[", "1", "]", ")", ")", ">", "-", "1", ":", "language", "=", "pair", "[", "2", "]", "break", "self", ".", "_cache", "[", "'encoding'", "]", "=", "encoding", "self", ".", "_cache", "[", "'language'", "]", "=", "language", "# lookup base game map if applicable", "if", "map_id", "!=", "44", ":", "if", "map_id", "not", "in", "mgz", ".", "const", ".", "MAP_NAMES", ":", "raise", "ValueError", "(", "'unspecified builtin map'", ")", "name", "=", "mgz", ".", "const", ".", "MAP_NAMES", "[", "map_id", "]", "custom", "=", "False", "# extract map seed", "match", "=", "re", ".", "search", "(", "b'\\x00.*? (\\-?[0-9]+)\\x00.*?\\.rms'", ",", "instructions", ")", "seed", "=", "None", "if", "match", ":", "seed", "=", "int", "(", "match", ".", "group", "(", "1", ")", ")", "# extract userpatch modes", "has_modes", "=", "name", ".", "find", "(", "': !'", ")", "mode_string", "=", "''", "if", "has_modes", ">", "-", "1", ":", "mode_string", "=", "name", "[", "has_modes", "+", "3", ":", "]", "name", "=", "name", "[", ":", "has_modes", "]", "modes", "=", "{", "'direct_placement'", ":", "'P'", "in", "mode_string", ",", "'effect_quantity'", ":", "'C'", "in", "mode_string", ",", "'guard_state'", ":", "'G'", "in", "mode_string", ",", "'fixed_positions'", ":", "'F'", "in", "mode_string", "}", "self", ".", "_cache", "[", "'map'", "]", "=", "{", "'id'", ":", "map_id", "if", "not", "custom", "else", "None", ",", "'name'", ":", "name", ".", "strip", "(", ")", ",", "'size'", ":", "size", ",", "'dimension'", ":", "dimension", ",", "'seed'", ":", "seed", ",", "'modes'", ":", "modes", ",", "'custom'", ":", "custom", ",", "'zr'", ":", "name", ".", "startswith", "(", "'ZR@'", ")", "}", "return", "self", ".", "_cache", "[", "'map'", "]" ]
Get the map metadata.
[ "Get", "the", "map", "metadata", "." ]
13fc379cc062d7640bfa028eed9c0d45d37a7b2b
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/summary.py#L461-L533
train
happyleavesaoc/aoc-mgz
mgz/summary.py
Summary.get_completed
def get_completed(self): """Determine if the game was completed. If there's a postgame, it will indicate completion. If there is no postgame, guess based on resignation. """ postgame = self.get_postgame() if postgame: return postgame.complete else: return True if self._cache['resigned'] else False
python
def get_completed(self): """Determine if the game was completed. If there's a postgame, it will indicate completion. If there is no postgame, guess based on resignation. """ postgame = self.get_postgame() if postgame: return postgame.complete else: return True if self._cache['resigned'] else False
[ "def", "get_completed", "(", "self", ")", ":", "postgame", "=", "self", ".", "get_postgame", "(", ")", "if", "postgame", ":", "return", "postgame", ".", "complete", "else", ":", "return", "True", "if", "self", ".", "_cache", "[", "'resigned'", "]", "else", "False" ]
Determine if the game was completed. If there's a postgame, it will indicate completion. If there is no postgame, guess based on resignation.
[ "Determine", "if", "the", "game", "was", "completed", "." ]
13fc379cc062d7640bfa028eed9c0d45d37a7b2b
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/summary.py#L535-L545
train
happyleavesaoc/aoc-mgz
mgz/summary.py
Summary.get_mirror
def get_mirror(self): """Determine mirror match.""" mirror = False if self.get_diplomacy()['1v1']: civs = set() for data in self.get_players(): civs.add(data['civilization']) mirror = (len(civs) == 1) return mirror
python
def get_mirror(self): """Determine mirror match.""" mirror = False if self.get_diplomacy()['1v1']: civs = set() for data in self.get_players(): civs.add(data['civilization']) mirror = (len(civs) == 1) return mirror
[ "def", "get_mirror", "(", "self", ")", ":", "mirror", "=", "False", "if", "self", ".", "get_diplomacy", "(", ")", "[", "'1v1'", "]", ":", "civs", "=", "set", "(", ")", "for", "data", "in", "self", ".", "get_players", "(", ")", ":", "civs", ".", "add", "(", "data", "[", "'civilization'", "]", ")", "mirror", "=", "(", "len", "(", "civs", ")", "==", "1", ")", "return", "mirror" ]
Determine mirror match.
[ "Determine", "mirror", "match", "." ]
13fc379cc062d7640bfa028eed9c0d45d37a7b2b
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/summary.py#L547-L555
train
happyleavesaoc/aoc-mgz
mgz/summary.py
Summary.guess_winner
def guess_winner(self, i): """Guess if a player won. Find what team the player was on. If anyone on their team resigned, assume the player lost. """ for team in self.get_teams(): if i not in team: continue for p in team: if p in self._cache['resigned']: return False return True
python
def guess_winner(self, i): """Guess if a player won. Find what team the player was on. If anyone on their team resigned, assume the player lost. """ for team in self.get_teams(): if i not in team: continue for p in team: if p in self._cache['resigned']: return False return True
[ "def", "guess_winner", "(", "self", ",", "i", ")", ":", "for", "team", "in", "self", ".", "get_teams", "(", ")", ":", "if", "i", "not", "in", "team", ":", "continue", "for", "p", "in", "team", ":", "if", "p", "in", "self", ".", "_cache", "[", "'resigned'", "]", ":", "return", "False", "return", "True" ]
Guess if a player won. Find what team the player was on. If anyone on their team resigned, assume the player lost.
[ "Guess", "if", "a", "player", "won", "." ]
13fc379cc062d7640bfa028eed9c0d45d37a7b2b
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/summary.py#L557-L569
train
fernandojunior/python-pattern-observer
observer.py
Event.trigger
def trigger(self, *args, **kwargs): """Execute the handlers with a message, if any.""" for h in self.handlers: h(*args, **kwargs)
python
def trigger(self, *args, **kwargs): """Execute the handlers with a message, if any.""" for h in self.handlers: h(*args, **kwargs)
[ "def", "trigger", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "for", "h", "in", "self", ".", "handlers", ":", "h", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
Execute the handlers with a message, if any.
[ "Execute", "the", "handlers", "with", "a", "message", "if", "any", "." ]
9acb029dd6c9276830ea2d7655bbb80eed8e95fa
https://github.com/fernandojunior/python-pattern-observer/blob/9acb029dd6c9276830ea2d7655bbb80eed8e95fa/observer.py#L43-L46
train
fernandojunior/python-pattern-observer
observer.py
Observable.on
def on(self, event, handler=None): """Create, add or update an event with a handler or more attached.""" if isinstance(event, str) and ' ' in event: # event is list str-based self.on(event.split(' '), handler) elif isinstance(event, list): # many events contains same handler for each in event: self.on(each, handler) elif isinstance(event, dict): # event is a dict of <event, handler> for key, value in event.items(): self.on(key, value) elif isinstance(handler, list): # handler is a list of handlers for each in handler: self.on(event, each) elif isinstance(handler, Event): # handler is Event object self.events[event] = handler # add or update an event setattr(self, event, self.events[event]) # self.event.trigger() elif event in self.events: # add a handler to an existing event self.events[event].on(handler) else: # create new event with a handler attached self.on(event, Event(handler))
python
def on(self, event, handler=None): """Create, add or update an event with a handler or more attached.""" if isinstance(event, str) and ' ' in event: # event is list str-based self.on(event.split(' '), handler) elif isinstance(event, list): # many events contains same handler for each in event: self.on(each, handler) elif isinstance(event, dict): # event is a dict of <event, handler> for key, value in event.items(): self.on(key, value) elif isinstance(handler, list): # handler is a list of handlers for each in handler: self.on(event, each) elif isinstance(handler, Event): # handler is Event object self.events[event] = handler # add or update an event setattr(self, event, self.events[event]) # self.event.trigger() elif event in self.events: # add a handler to an existing event self.events[event].on(handler) else: # create new event with a handler attached self.on(event, Event(handler))
[ "def", "on", "(", "self", ",", "event", ",", "handler", "=", "None", ")", ":", "if", "isinstance", "(", "event", ",", "str", ")", "and", "' '", "in", "event", ":", "# event is list str-based", "self", ".", "on", "(", "event", ".", "split", "(", "' '", ")", ",", "handler", ")", "elif", "isinstance", "(", "event", ",", "list", ")", ":", "# many events contains same handler", "for", "each", "in", "event", ":", "self", ".", "on", "(", "each", ",", "handler", ")", "elif", "isinstance", "(", "event", ",", "dict", ")", ":", "# event is a dict of <event, handler>", "for", "key", ",", "value", "in", "event", ".", "items", "(", ")", ":", "self", ".", "on", "(", "key", ",", "value", ")", "elif", "isinstance", "(", "handler", ",", "list", ")", ":", "# handler is a list of handlers", "for", "each", "in", "handler", ":", "self", ".", "on", "(", "event", ",", "each", ")", "elif", "isinstance", "(", "handler", ",", "Event", ")", ":", "# handler is Event object", "self", ".", "events", "[", "event", "]", "=", "handler", "# add or update an event", "setattr", "(", "self", ",", "event", ",", "self", ".", "events", "[", "event", "]", ")", "# self.event.trigger()", "elif", "event", "in", "self", ".", "events", ":", "# add a handler to an existing event", "self", ".", "events", "[", "event", "]", ".", "on", "(", "handler", ")", "else", ":", "# create new event with a handler attached", "self", ".", "on", "(", "event", ",", "Event", "(", "handler", ")", ")" ]
Create, add or update an event with a handler or more attached.
[ "Create", "add", "or", "update", "an", "event", "with", "a", "handler", "or", "more", "attached", "." ]
9acb029dd6c9276830ea2d7655bbb80eed8e95fa
https://github.com/fernandojunior/python-pattern-observer/blob/9acb029dd6c9276830ea2d7655bbb80eed8e95fa/observer.py#L59-L78
train
fernandojunior/python-pattern-observer
observer.py
Observable.off
def off(self, event, handler=None): """Remove an event or a handler from it.""" if handler: self.events[event].off(handler) else: del self.events[event] delattr(self, event)
python
def off(self, event, handler=None): """Remove an event or a handler from it.""" if handler: self.events[event].off(handler) else: del self.events[event] delattr(self, event)
[ "def", "off", "(", "self", ",", "event", ",", "handler", "=", "None", ")", ":", "if", "handler", ":", "self", ".", "events", "[", "event", "]", ".", "off", "(", "handler", ")", "else", ":", "del", "self", ".", "events", "[", "event", "]", "delattr", "(", "self", ",", "event", ")" ]
Remove an event or a handler from it.
[ "Remove", "an", "event", "or", "a", "handler", "from", "it", "." ]
9acb029dd6c9276830ea2d7655bbb80eed8e95fa
https://github.com/fernandojunior/python-pattern-observer/blob/9acb029dd6c9276830ea2d7655bbb80eed8e95fa/observer.py#L80-L86
train
fernandojunior/python-pattern-observer
observer.py
Observable.trigger
def trigger(self, *args, **kargs): """ Execute all event handlers with optional arguments for the observable. """ event = args[0] if isinstance(event, str) and ' ' in event: event = event.split(' ') # split event names ... if isinstance(event, list): # event is a list of events for each in event: self.events[each].trigger(*args[1:], **kargs) else: self.events[event].trigger(*args[1:], **kargs)
python
def trigger(self, *args, **kargs): """ Execute all event handlers with optional arguments for the observable. """ event = args[0] if isinstance(event, str) and ' ' in event: event = event.split(' ') # split event names ... if isinstance(event, list): # event is a list of events for each in event: self.events[each].trigger(*args[1:], **kargs) else: self.events[event].trigger(*args[1:], **kargs)
[ "def", "trigger", "(", "self", ",", "*", "args", ",", "*", "*", "kargs", ")", ":", "event", "=", "args", "[", "0", "]", "if", "isinstance", "(", "event", ",", "str", ")", "and", "' '", "in", "event", ":", "event", "=", "event", ".", "split", "(", "' '", ")", "# split event names ...", "if", "isinstance", "(", "event", ",", "list", ")", ":", "# event is a list of events", "for", "each", "in", "event", ":", "self", ".", "events", "[", "each", "]", ".", "trigger", "(", "*", "args", "[", "1", ":", "]", ",", "*", "*", "kargs", ")", "else", ":", "self", ".", "events", "[", "event", "]", ".", "trigger", "(", "*", "args", "[", "1", ":", "]", ",", "*", "*", "kargs", ")" ]
Execute all event handlers with optional arguments for the observable.
[ "Execute", "all", "event", "handlers", "with", "optional", "arguments", "for", "the", "observable", "." ]
9acb029dd6c9276830ea2d7655bbb80eed8e95fa
https://github.com/fernandojunior/python-pattern-observer/blob/9acb029dd6c9276830ea2d7655bbb80eed8e95fa/observer.py#L88-L101
train
bfarr/kombine
kombine/interruptible_pool.py
_initializer_wrapper
def _initializer_wrapper(initializer, *args): """ Ignore SIGINT. During typical keyboard interrupts, the parent does the killing. """ signal.signal(signal.SIGINT, signal.SIG_IGN) if initializer is not None: initializer(*args)
python
def _initializer_wrapper(initializer, *args): """ Ignore SIGINT. During typical keyboard interrupts, the parent does the killing. """ signal.signal(signal.SIGINT, signal.SIG_IGN) if initializer is not None: initializer(*args)
[ "def", "_initializer_wrapper", "(", "initializer", ",", "*", "args", ")", ":", "signal", ".", "signal", "(", "signal", ".", "SIGINT", ",", "signal", ".", "SIG_IGN", ")", "if", "initializer", "is", "not", "None", ":", "initializer", "(", "*", "args", ")" ]
Ignore SIGINT. During typical keyboard interrupts, the parent does the killing.
[ "Ignore", "SIGINT", ".", "During", "typical", "keyboard", "interrupts", "the", "parent", "does", "the", "killing", "." ]
50c946dee5da33e7baab71d9bd6c265ff02ffb13
https://github.com/bfarr/kombine/blob/50c946dee5da33e7baab71d9bd6c265ff02ffb13/kombine/interruptible_pool.py#L20-L27
train
networks-lab/tidyextractors
tidyextractors/base_extractor.py
BaseExtractor._col_type_set
def _col_type_set(self, col, df): """ Determines the set of types present in a DataFrame column. :param str col: A column name. :param pandas.DataFrame df: The dataset. Usually ``self._data``. :return: A set of Types. """ type_set = set() if df[col].dtype == np.dtype(object): unindexed_col = list(df[col]) for i in range(0, len(df[col])): if unindexed_col[i] == np.nan: continue else: type_set.add(type(unindexed_col[i])) return type_set else: type_set.add(df[col].dtype) return type_set
python
def _col_type_set(self, col, df): """ Determines the set of types present in a DataFrame column. :param str col: A column name. :param pandas.DataFrame df: The dataset. Usually ``self._data``. :return: A set of Types. """ type_set = set() if df[col].dtype == np.dtype(object): unindexed_col = list(df[col]) for i in range(0, len(df[col])): if unindexed_col[i] == np.nan: continue else: type_set.add(type(unindexed_col[i])) return type_set else: type_set.add(df[col].dtype) return type_set
[ "def", "_col_type_set", "(", "self", ",", "col", ",", "df", ")", ":", "type_set", "=", "set", "(", ")", "if", "df", "[", "col", "]", ".", "dtype", "==", "np", ".", "dtype", "(", "object", ")", ":", "unindexed_col", "=", "list", "(", "df", "[", "col", "]", ")", "for", "i", "in", "range", "(", "0", ",", "len", "(", "df", "[", "col", "]", ")", ")", ":", "if", "unindexed_col", "[", "i", "]", "==", "np", ".", "nan", ":", "continue", "else", ":", "type_set", ".", "add", "(", "type", "(", "unindexed_col", "[", "i", "]", ")", ")", "return", "type_set", "else", ":", "type_set", ".", "add", "(", "df", "[", "col", "]", ".", "dtype", ")", "return", "type_set" ]
Determines the set of types present in a DataFrame column. :param str col: A column name. :param pandas.DataFrame df: The dataset. Usually ``self._data``. :return: A set of Types.
[ "Determines", "the", "set", "of", "types", "present", "in", "a", "DataFrame", "column", "." ]
658448ed533beecf32adcc188fc64d1068d15ca6
https://github.com/networks-lab/tidyextractors/blob/658448ed533beecf32adcc188fc64d1068d15ca6/tidyextractors/base_extractor.py#L84-L103
train
networks-lab/tidyextractors
tidyextractors/base_extractor.py
BaseExtractor.raw
def raw(self, drop_collections = False): """ Produces the extractor object's data as it is stored internally. :param bool drop_collections: Defaults to False. Indicates whether columns with lists/dicts/sets will be dropped. :return: pandas.DataFrame """ base_df = self._data if drop_collections is True: out_df = self._drop_collections(base_df) else: out_df = base_df return out_df
python
def raw(self, drop_collections = False): """ Produces the extractor object's data as it is stored internally. :param bool drop_collections: Defaults to False. Indicates whether columns with lists/dicts/sets will be dropped. :return: pandas.DataFrame """ base_df = self._data if drop_collections is True: out_df = self._drop_collections(base_df) else: out_df = base_df return out_df
[ "def", "raw", "(", "self", ",", "drop_collections", "=", "False", ")", ":", "base_df", "=", "self", ".", "_data", "if", "drop_collections", "is", "True", ":", "out_df", "=", "self", ".", "_drop_collections", "(", "base_df", ")", "else", ":", "out_df", "=", "base_df", "return", "out_df" ]
Produces the extractor object's data as it is stored internally. :param bool drop_collections: Defaults to False. Indicates whether columns with lists/dicts/sets will be dropped. :return: pandas.DataFrame
[ "Produces", "the", "extractor", "object", "s", "data", "as", "it", "is", "stored", "internally", "." ]
658448ed533beecf32adcc188fc64d1068d15ca6
https://github.com/networks-lab/tidyextractors/blob/658448ed533beecf32adcc188fc64d1068d15ca6/tidyextractors/base_extractor.py#L121-L134
train
TkTech/Jawa
jawa/classloader.py
_walk
def _walk(path, follow_links=False, maximum_depth=None): """A modified os.walk with support for maximum traversal depth.""" root_level = path.rstrip(os.path.sep).count(os.path.sep) for root, dirs, files in os.walk(path, followlinks=follow_links): yield root, dirs, files if maximum_depth is None: continue if root_level + maximum_depth <= root.count(os.path.sep): del dirs[:]
python
def _walk(path, follow_links=False, maximum_depth=None): """A modified os.walk with support for maximum traversal depth.""" root_level = path.rstrip(os.path.sep).count(os.path.sep) for root, dirs, files in os.walk(path, followlinks=follow_links): yield root, dirs, files if maximum_depth is None: continue if root_level + maximum_depth <= root.count(os.path.sep): del dirs[:]
[ "def", "_walk", "(", "path", ",", "follow_links", "=", "False", ",", "maximum_depth", "=", "None", ")", ":", "root_level", "=", "path", ".", "rstrip", "(", "os", ".", "path", ".", "sep", ")", ".", "count", "(", "os", ".", "path", ".", "sep", ")", "for", "root", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "path", ",", "followlinks", "=", "follow_links", ")", ":", "yield", "root", ",", "dirs", ",", "files", "if", "maximum_depth", "is", "None", ":", "continue", "if", "root_level", "+", "maximum_depth", "<=", "root", ".", "count", "(", "os", ".", "path", ".", "sep", ")", ":", "del", "dirs", "[", ":", "]" ]
A modified os.walk with support for maximum traversal depth.
[ "A", "modified", "os", ".", "walk", "with", "support", "for", "maximum", "traversal", "depth", "." ]
94c8424e699029ac33fbc0e866fff0ecb2742289
https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/classloader.py#L14-L23
train
TkTech/Jawa
jawa/classloader.py
ClassLoader.update
def update(self, *sources, follow_symlinks: bool=False, maximum_depth: int=20): """Add one or more ClassFile sources to the class loader. If a given source is a directory path, it is traversed up to the maximum set depth and all files under it are added to the class loader lookup table. If a given source is a .jar or .zip file it will be opened and the file index added to the class loader lookup table. If a given source is a ClassFile or a subclass, it's immediately added to the class loader lookup table and the class cache. :param sources: One or more ClassFile sources to be added. :param follow_symlinks: True if symlinks should be followed when traversing filesystem directories. [default: False] :param maximum_depth: The maximum sub-directory depth when traversing filesystem directories. If set to `None` no limit will be enforced. [default: 20] """ for source in sources: if isinstance(source, self.klass): self.path_map[source.this.name.value] = source self.class_cache[source.this.name.value] = source continue # Explicit cast to str to support Path objects. source = str(source) if source.lower().endswith(('.zip', '.jar')): zf = ZipFile(source, 'r') self.path_map.update(zip(zf.namelist(), repeat(zf))) elif os.path.isdir(source): walker = _walk( source, follow_links=follow_symlinks, maximum_depth=maximum_depth ) for root, dirs, files in walker: for file_ in files: path_full = os.path.join(root, file_) path_suffix = os.path.relpath(path_full, source) self.path_map[path_suffix] = path_full
python
def update(self, *sources, follow_symlinks: bool=False, maximum_depth: int=20): """Add one or more ClassFile sources to the class loader. If a given source is a directory path, it is traversed up to the maximum set depth and all files under it are added to the class loader lookup table. If a given source is a .jar or .zip file it will be opened and the file index added to the class loader lookup table. If a given source is a ClassFile or a subclass, it's immediately added to the class loader lookup table and the class cache. :param sources: One or more ClassFile sources to be added. :param follow_symlinks: True if symlinks should be followed when traversing filesystem directories. [default: False] :param maximum_depth: The maximum sub-directory depth when traversing filesystem directories. If set to `None` no limit will be enforced. [default: 20] """ for source in sources: if isinstance(source, self.klass): self.path_map[source.this.name.value] = source self.class_cache[source.this.name.value] = source continue # Explicit cast to str to support Path objects. source = str(source) if source.lower().endswith(('.zip', '.jar')): zf = ZipFile(source, 'r') self.path_map.update(zip(zf.namelist(), repeat(zf))) elif os.path.isdir(source): walker = _walk( source, follow_links=follow_symlinks, maximum_depth=maximum_depth ) for root, dirs, files in walker: for file_ in files: path_full = os.path.join(root, file_) path_suffix = os.path.relpath(path_full, source) self.path_map[path_suffix] = path_full
[ "def", "update", "(", "self", ",", "*", "sources", ",", "follow_symlinks", ":", "bool", "=", "False", ",", "maximum_depth", ":", "int", "=", "20", ")", ":", "for", "source", "in", "sources", ":", "if", "isinstance", "(", "source", ",", "self", ".", "klass", ")", ":", "self", ".", "path_map", "[", "source", ".", "this", ".", "name", ".", "value", "]", "=", "source", "self", ".", "class_cache", "[", "source", ".", "this", ".", "name", ".", "value", "]", "=", "source", "continue", "# Explicit cast to str to support Path objects.", "source", "=", "str", "(", "source", ")", "if", "source", ".", "lower", "(", ")", ".", "endswith", "(", "(", "'.zip'", ",", "'.jar'", ")", ")", ":", "zf", "=", "ZipFile", "(", "source", ",", "'r'", ")", "self", ".", "path_map", ".", "update", "(", "zip", "(", "zf", ".", "namelist", "(", ")", ",", "repeat", "(", "zf", ")", ")", ")", "elif", "os", ".", "path", ".", "isdir", "(", "source", ")", ":", "walker", "=", "_walk", "(", "source", ",", "follow_links", "=", "follow_symlinks", ",", "maximum_depth", "=", "maximum_depth", ")", "for", "root", ",", "dirs", ",", "files", "in", "walker", ":", "for", "file_", "in", "files", ":", "path_full", "=", "os", ".", "path", ".", "join", "(", "root", ",", "file_", ")", "path_suffix", "=", "os", ".", "path", ".", "relpath", "(", "path_full", ",", "source", ")", "self", ".", "path_map", "[", "path_suffix", "]", "=", "path_full" ]
Add one or more ClassFile sources to the class loader. If a given source is a directory path, it is traversed up to the maximum set depth and all files under it are added to the class loader lookup table. If a given source is a .jar or .zip file it will be opened and the file index added to the class loader lookup table. If a given source is a ClassFile or a subclass, it's immediately added to the class loader lookup table and the class cache. :param sources: One or more ClassFile sources to be added. :param follow_symlinks: True if symlinks should be followed when traversing filesystem directories. [default: False] :param maximum_depth: The maximum sub-directory depth when traversing filesystem directories. If set to `None` no limit will be enforced. [default: 20]
[ "Add", "one", "or", "more", "ClassFile", "sources", "to", "the", "class", "loader", "." ]
94c8424e699029ac33fbc0e866fff0ecb2742289
https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/classloader.py#L62-L105
train
TkTech/Jawa
jawa/classloader.py
ClassLoader.open
def open(self, path: str, mode: str='r') -> IO: """Open an IO-like object for `path`. .. note:: Mode *must* be either 'r' or 'w', as the underlying objects do not understand the full range of modes. :param path: The path to open. :param mode: The mode of the file being opened, either 'r' or 'w'. """ entry = self.path_map.get(path) if entry is None: raise FileNotFoundError() if isinstance(entry, str): with open(entry, 'rb' if mode == 'r' else mode) as source: yield source elif isinstance(entry, ZipFile): yield io.BytesIO(entry.read(path)) else: raise NotImplementedError()
python
def open(self, path: str, mode: str='r') -> IO: """Open an IO-like object for `path`. .. note:: Mode *must* be either 'r' or 'w', as the underlying objects do not understand the full range of modes. :param path: The path to open. :param mode: The mode of the file being opened, either 'r' or 'w'. """ entry = self.path_map.get(path) if entry is None: raise FileNotFoundError() if isinstance(entry, str): with open(entry, 'rb' if mode == 'r' else mode) as source: yield source elif isinstance(entry, ZipFile): yield io.BytesIO(entry.read(path)) else: raise NotImplementedError()
[ "def", "open", "(", "self", ",", "path", ":", "str", ",", "mode", ":", "str", "=", "'r'", ")", "->", "IO", ":", "entry", "=", "self", ".", "path_map", ".", "get", "(", "path", ")", "if", "entry", "is", "None", ":", "raise", "FileNotFoundError", "(", ")", "if", "isinstance", "(", "entry", ",", "str", ")", ":", "with", "open", "(", "entry", ",", "'rb'", "if", "mode", "==", "'r'", "else", "mode", ")", "as", "source", ":", "yield", "source", "elif", "isinstance", "(", "entry", ",", "ZipFile", ")", ":", "yield", "io", ".", "BytesIO", "(", "entry", ".", "read", "(", "path", ")", ")", "else", ":", "raise", "NotImplementedError", "(", ")" ]
Open an IO-like object for `path`. .. note:: Mode *must* be either 'r' or 'w', as the underlying objects do not understand the full range of modes. :param path: The path to open. :param mode: The mode of the file being opened, either 'r' or 'w'.
[ "Open", "an", "IO", "-", "like", "object", "for", "path", "." ]
94c8424e699029ac33fbc0e866fff0ecb2742289
https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/classloader.py#L108-L129
train
TkTech/Jawa
jawa/classloader.py
ClassLoader.load
def load(self, path: str) -> ClassFile: """Load the class at `path` and return it. Load will attempt to load the file at `path` and `path` + .class before failing. :param path: Fully-qualified path to a ClassFile. """ # Try to refresh the class from the cache, loading it from disk # if not found. try: r = self.class_cache.pop(path) except KeyError: with self.open(f'{path}.class') as source: r = self.klass(source) r.classloader = self # Even if it was found re-set the key to update the OrderedDict # ordering. self.class_cache[path] = r # If the cache is enabled remove every item over N started from # the least-used. if self.max_cache > 0: to_pop = max(len(self.class_cache) - self.max_cache, 0) for _ in repeat(None, to_pop): self.class_cache.popitem(last=False) return r
python
def load(self, path: str) -> ClassFile: """Load the class at `path` and return it. Load will attempt to load the file at `path` and `path` + .class before failing. :param path: Fully-qualified path to a ClassFile. """ # Try to refresh the class from the cache, loading it from disk # if not found. try: r = self.class_cache.pop(path) except KeyError: with self.open(f'{path}.class') as source: r = self.klass(source) r.classloader = self # Even if it was found re-set the key to update the OrderedDict # ordering. self.class_cache[path] = r # If the cache is enabled remove every item over N started from # the least-used. if self.max_cache > 0: to_pop = max(len(self.class_cache) - self.max_cache, 0) for _ in repeat(None, to_pop): self.class_cache.popitem(last=False) return r
[ "def", "load", "(", "self", ",", "path", ":", "str", ")", "->", "ClassFile", ":", "# Try to refresh the class from the cache, loading it from disk", "# if not found.", "try", ":", "r", "=", "self", ".", "class_cache", ".", "pop", "(", "path", ")", "except", "KeyError", ":", "with", "self", ".", "open", "(", "f'{path}.class'", ")", "as", "source", ":", "r", "=", "self", ".", "klass", "(", "source", ")", "r", ".", "classloader", "=", "self", "# Even if it was found re-set the key to update the OrderedDict", "# ordering.", "self", ".", "class_cache", "[", "path", "]", "=", "r", "# If the cache is enabled remove every item over N started from", "# the least-used.", "if", "self", ".", "max_cache", ">", "0", ":", "to_pop", "=", "max", "(", "len", "(", "self", ".", "class_cache", ")", "-", "self", ".", "max_cache", ",", "0", ")", "for", "_", "in", "repeat", "(", "None", ",", "to_pop", ")", ":", "self", ".", "class_cache", ".", "popitem", "(", "last", "=", "False", ")", "return", "r" ]
Load the class at `path` and return it. Load will attempt to load the file at `path` and `path` + .class before failing. :param path: Fully-qualified path to a ClassFile.
[ "Load", "the", "class", "at", "path", "and", "return", "it", "." ]
94c8424e699029ac33fbc0e866fff0ecb2742289
https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/classloader.py#L131-L159
train
TkTech/Jawa
jawa/classloader.py
ClassLoader.dependencies
def dependencies(self, path: str) -> Set[str]: """Returns a set of all classes referenced by the ClassFile at `path` without reading the entire ClassFile. This is an optimization method that does not load a complete ClassFile, nor does it add the results to the ClassLoader cache. :param path: Fully-qualified path to a ClassFile. """ return set(c.name.value for c in self.search_constant_pool( path=path, type_=ConstantClass ))
python
def dependencies(self, path: str) -> Set[str]: """Returns a set of all classes referenced by the ClassFile at `path` without reading the entire ClassFile. This is an optimization method that does not load a complete ClassFile, nor does it add the results to the ClassLoader cache. :param path: Fully-qualified path to a ClassFile. """ return set(c.name.value for c in self.search_constant_pool( path=path, type_=ConstantClass ))
[ "def", "dependencies", "(", "self", ",", "path", ":", "str", ")", "->", "Set", "[", "str", "]", ":", "return", "set", "(", "c", ".", "name", ".", "value", "for", "c", "in", "self", ".", "search_constant_pool", "(", "path", "=", "path", ",", "type_", "=", "ConstantClass", ")", ")" ]
Returns a set of all classes referenced by the ClassFile at `path` without reading the entire ClassFile. This is an optimization method that does not load a complete ClassFile, nor does it add the results to the ClassLoader cache. :param path: Fully-qualified path to a ClassFile.
[ "Returns", "a", "set", "of", "all", "classes", "referenced", "by", "the", "ClassFile", "at", "path", "without", "reading", "the", "entire", "ClassFile", "." ]
94c8424e699029ac33fbc0e866fff0ecb2742289
https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/classloader.py#L166-L178
train
TkTech/Jawa
jawa/classloader.py
ClassLoader.search_constant_pool
def search_constant_pool(self, *, path: str, **options): """Partially load the class at `path`, yield all matching constants from the ConstantPool. This is an optimization method that does not load a complete ClassFile, nor does it add the results to the ClassLoader cache. :param path: Fully-qualified path to a ClassFile. :param options: A list of options to pass into `ConstantPool.find()` """ with self.open(f'{path}.class') as source: # Skip over the magic, minor, and major version. source.read(8) pool = ConstantPool() pool.unpack(source) yield from pool.find(**options)
python
def search_constant_pool(self, *, path: str, **options): """Partially load the class at `path`, yield all matching constants from the ConstantPool. This is an optimization method that does not load a complete ClassFile, nor does it add the results to the ClassLoader cache. :param path: Fully-qualified path to a ClassFile. :param options: A list of options to pass into `ConstantPool.find()` """ with self.open(f'{path}.class') as source: # Skip over the magic, minor, and major version. source.read(8) pool = ConstantPool() pool.unpack(source) yield from pool.find(**options)
[ "def", "search_constant_pool", "(", "self", ",", "*", ",", "path", ":", "str", ",", "*", "*", "options", ")", ":", "with", "self", ".", "open", "(", "f'{path}.class'", ")", "as", "source", ":", "# Skip over the magic, minor, and major version.", "source", ".", "read", "(", "8", ")", "pool", "=", "ConstantPool", "(", ")", "pool", ".", "unpack", "(", "source", ")", "yield", "from", "pool", ".", "find", "(", "*", "*", "options", ")" ]
Partially load the class at `path`, yield all matching constants from the ConstantPool. This is an optimization method that does not load a complete ClassFile, nor does it add the results to the ClassLoader cache. :param path: Fully-qualified path to a ClassFile. :param options: A list of options to pass into `ConstantPool.find()`
[ "Partially", "load", "the", "class", "at", "path", "yield", "all", "matching", "constants", "from", "the", "ConstantPool", "." ]
94c8424e699029ac33fbc0e866fff0ecb2742289
https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/classloader.py#L180-L195
train
TkTech/Jawa
jawa/classloader.py
ClassLoader.classes
def classes(self) -> Iterator[str]: """Yield the name of all classes discovered in the path map.""" yield from ( c[:-6] for c in self.path_map.keys() if c.endswith('.class') )
python
def classes(self) -> Iterator[str]: """Yield the name of all classes discovered in the path map.""" yield from ( c[:-6] for c in self.path_map.keys() if c.endswith('.class') )
[ "def", "classes", "(", "self", ")", "->", "Iterator", "[", "str", "]", ":", "yield", "from", "(", "c", "[", ":", "-", "6", "]", "for", "c", "in", "self", ".", "path_map", ".", "keys", "(", ")", "if", "c", ".", "endswith", "(", "'.class'", ")", ")" ]
Yield the name of all classes discovered in the path map.
[ "Yield", "the", "name", "of", "all", "classes", "discovered", "in", "the", "path", "map", "." ]
94c8424e699029ac33fbc0e866fff0ecb2742289
https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/classloader.py#L198-L203
train
networks-lab/tidyextractors
tidyextractors/tidytwitter/twitter_extractor.py
TwitterExtractor._make_object_dict
def _make_object_dict(self, obj): """ Processes an object, exporting its data as a nested dictionary. :param obj: An object :return: A nested dictionary of object data """ data = {} for attr in dir(obj): if attr[0] is not '_' and attr is not 'status': datum = getattr(obj, attr) if not isinstance(datum, types.MethodType): data.update(self._handle_object(attr,datum)) return data
python
def _make_object_dict(self, obj): """ Processes an object, exporting its data as a nested dictionary. :param obj: An object :return: A nested dictionary of object data """ data = {} for attr in dir(obj): if attr[0] is not '_' and attr is not 'status': datum = getattr(obj, attr) if not isinstance(datum, types.MethodType): data.update(self._handle_object(attr,datum)) return data
[ "def", "_make_object_dict", "(", "self", ",", "obj", ")", ":", "data", "=", "{", "}", "for", "attr", "in", "dir", "(", "obj", ")", ":", "if", "attr", "[", "0", "]", "is", "not", "'_'", "and", "attr", "is", "not", "'status'", ":", "datum", "=", "getattr", "(", "obj", ",", "attr", ")", "if", "not", "isinstance", "(", "datum", ",", "types", ".", "MethodType", ")", ":", "data", ".", "update", "(", "self", ".", "_handle_object", "(", "attr", ",", "datum", ")", ")", "return", "data" ]
Processes an object, exporting its data as a nested dictionary. :param obj: An object :return: A nested dictionary of object data
[ "Processes", "an", "object", "exporting", "its", "data", "as", "a", "nested", "dictionary", "." ]
658448ed533beecf32adcc188fc64d1068d15ca6
https://github.com/networks-lab/tidyextractors/blob/658448ed533beecf32adcc188fc64d1068d15ca6/tidyextractors/tidytwitter/twitter_extractor.py#L165-L178
train
TkTech/Jawa
jawa/fields.py
Field.unpack
def unpack(self, source: IO): """ Read the Field from the file-like object `fio`. .. note:: Advanced usage only. You will typically never need to call this method as it will be called for you when loading a ClassFile. :param source: Any file-like object providing `read()` """ self.access_flags.unpack(source.read(2)) self._name_index, self._descriptor_index = unpack('>HH', source.read(4)) self.attributes.unpack(source)
python
def unpack(self, source: IO): """ Read the Field from the file-like object `fio`. .. note:: Advanced usage only. You will typically never need to call this method as it will be called for you when loading a ClassFile. :param source: Any file-like object providing `read()` """ self.access_flags.unpack(source.read(2)) self._name_index, self._descriptor_index = unpack('>HH', source.read(4)) self.attributes.unpack(source)
[ "def", "unpack", "(", "self", ",", "source", ":", "IO", ")", ":", "self", ".", "access_flags", ".", "unpack", "(", "source", ".", "read", "(", "2", ")", ")", "self", ".", "_name_index", ",", "self", ".", "_descriptor_index", "=", "unpack", "(", "'>HH'", ",", "source", ".", "read", "(", "4", ")", ")", "self", ".", "attributes", ".", "unpack", "(", "source", ")" ]
Read the Field from the file-like object `fio`. .. note:: Advanced usage only. You will typically never need to call this method as it will be called for you when loading a ClassFile. :param source: Any file-like object providing `read()`
[ "Read", "the", "Field", "from", "the", "file", "-", "like", "object", "fio", "." ]
94c8424e699029ac33fbc0e866fff0ecb2742289
https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/fields.py#L59-L72
train