idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
3,000
def enable ( self , enable_password ) : if self . device . prompt [ - 1 ] == '#' : self . log ( "Device is already in privileged mode" ) return events = [ self . password_re , self . device . prompt_re , pexpect . TIMEOUT , pexpect . EOF ] transitions = [ ( self . password_re , [ 0 ] , 1 , partial ( a_send_password , e...
Change to the privilege mode .
3,001
def description ( tag ) : tag_object = Tag ( tag ) results = [ ] results . extend ( tag_object . descriptions ) subtags = tag_object . subtags for subtag in subtags : results += subtag . description return results
Gets a list of descriptions given the tag .
3,002
def prior_draw ( self , N = 1 ) : p = np . random . ranf ( size = ( N , self . ndim ) ) p = ( self . _upper_right - self . _lower_left ) * p + self . _lower_left return p
Draw N samples from the prior .
3,003
def lnprior ( self , X ) : if np . any ( X < self . _lower_left ) or np . any ( X > self . _upper_right ) : return - np . inf else : return 0.0
Use a uniform bounded prior .
3,004
def lnlike ( self , X ) : return - 3.5 * np . log ( self . _interpolant ( X [ 0 ] , X [ 1 ] , grid = False ) )
Use a softened version of the interpolant as a likelihood .
3,005
def echo_info ( conn ) : click . echo ( "General information:" ) click . echo ( " Hostname: {}" . format ( conn . hostname ) ) click . echo ( " HW Family: {}" . format ( conn . family ) ) click . echo ( " HW Platform: {}" . format ( conn . platform ) ) click . echo ( " SW Type: {}" . format ( conn . os_type ) ) click ....
Print detected information .
3,006
def run ( url , cmd , log_path , log_level , log_session , force_discovery , print_info ) : log_level = log_levels [ log_level ] conn = condoor . Connection ( "host" , list ( url ) , log_session = log_session , log_level = log_level , log_dir = log_path ) try : conn . connect ( force_discovery = force_discovery ) if pr...
Run the main function .
3,007
def convert ( self , value , param , ctx ) : if not isinstance ( value , tuple ) : parsed = urlparse . urlparse ( value ) if parsed . scheme not in ( 'telnet' , 'ssh' ) : self . fail ( 'invalid URL scheme (%s). Only telnet and ssh URLs are ' 'allowed' % parsed , param , ctx ) return value
Convert to URL scheme .
3,008
def a_send_line ( text , ctx ) : if hasattr ( text , '__iter__' ) : try : ctx . ctrl . sendline ( text . next ( ) ) except StopIteration : ctx . finished = True else : ctx . ctrl . sendline ( text ) return True
Send text line to the controller followed by os . linesep .
3,009
def a_send_username ( username , ctx ) : if username : ctx . ctrl . sendline ( username ) return True else : ctx . ctrl . disconnect ( ) raise ConnectionAuthenticationError ( "Username not provided" , ctx . ctrl . hostname )
Sent the username text .
3,010
def a_send_password ( password , ctx ) : if password : ctx . ctrl . send_command ( password , password = True ) return True else : ctx . ctrl . disconnect ( ) raise ConnectionAuthenticationError ( "Password not provided" , ctx . ctrl . hostname )
Send the password text .
3,011
def a_standby_console ( ctx ) : ctx . device . is_console = True ctx . ctrl . disconnect ( ) raise ConnectionError ( "Standby console" , ctx . ctrl . hostname )
Raise ConnectionError exception when connected to standby console .
3,012
def a_not_committed ( ctx ) : ctx . ctrl . sendline ( 'n' ) ctx . msg = "Some active software packages are not yet committed. Reload may cause software rollback." ctx . device . chain . connection . emit_message ( ctx . msg , log_level = logging . ERROR ) ctx . failed = True return False
Provide the message that current software is not committed and reload is not possible .
3,013
def a_stays_connected ( ctx ) : ctx . ctrl . connected = True ctx . device . connected = False return True
Stay connected .
3,014
def a_unexpected_prompt ( ctx ) : prompt = ctx . ctrl . match . group ( 0 ) ctx . msg = "Received the jump host prompt: '{}'" . format ( prompt ) ctx . device . connected = False ctx . finished = True raise ConnectionError ( "Unable to connect to the device." , ctx . ctrl . hostname )
Provide message when received humphost prompt .
3,015
def a_connection_timeout ( ctx ) : prompt = ctx . ctrl . after ctx . msg = "Received the jump host prompt: '{}'" . format ( prompt ) ctx . device . connected = False ctx . finished = True raise ConnectionTimeoutError ( "Unable to connect to the device." , ctx . ctrl . hostname )
Check the prompt and update the drivers .
3,016
def a_expected_prompt ( ctx ) : prompt = ctx . ctrl . match . group ( 0 ) ctx . device . update_driver ( prompt ) ctx . device . update_config_mode ( ) ctx . device . update_hostname ( ) ctx . finished = True return True
Update driver config mode and hostname when received an expected prompt .
3,017
def a_return_and_reconnect ( ctx ) : ctx . ctrl . send ( "\r" ) ctx . device . connect ( ctx . ctrl ) return True
Send new line and reconnect .
3,018
def a_store_cmd_result ( ctx ) : result = ctx . ctrl . before index = result . find ( '\n' ) if index > 0 : result = result [ index + 1 : ] ctx . device . last_command_result = result . replace ( '\r' , '' ) return True
Store the command result for complex state machines .
3,019
def a_message_callback ( ctx ) : message = ctx . ctrl . after . strip ( ) . splitlines ( ) [ - 1 ] ctx . device . chain . connection . emit_message ( message , log_level = logging . INFO ) return True
Message the captured pattern .
3,020
def a_capture_show_configuration_failed ( ctx ) : result = ctx . device . send ( "show configuration failed" ) ctx . device . last_command_result = result index = result . find ( "SEMANTIC ERRORS" ) ctx . device . chain . connection . emit_message ( result , log_level = logging . ERROR ) if index > 0 : raise Configurat...
Capture the show configuration failed result .
3,021
def a_configuration_inconsistency ( ctx ) : ctx . msg = "This SDR's running configuration is inconsistent with persistent configuration. " "No configuration commits for this SDR will be allowed until a 'clear configuration inconsistency' " "command is performed." ctx . device . chain . connection . emit_message ( "Conf...
Raise the configuration inconsistency error .
3,022
def fqdn ( self ) : if self . _fqdn is None : self . _fqdn = socket . getfqdn ( ) if "." not in self . _fqdn : try : info = socket . getaddrinfo ( host = "localhost" , port = None , proto = socket . IPPROTO_TCP ) except socket . gaierror : addr = "127.0.0.1" else : addr = info [ 0 ] [ 4 ] [ 0 ] self . _fqdn = "[{}]" . ...
Returns the string used to identify the client when initiating a SMTP session .
3,023
def reset_state ( self ) : self . last_helo_response = ( None , None ) self . last_ehlo_response = ( None , None ) self . supports_esmtp = False self . esmtp_extensions = { } self . auth_mechanisms = [ ] self . ssl_context = False self . reader = None self . writer = None self . transport = None
Resets some attributes to their default values .
3,024
async def helo ( self , from_host = None ) : if from_host is None : from_host = self . fqdn code , message = await self . do_cmd ( "HELO" , from_host ) self . last_helo_response = ( code , message ) return code , message
Sends a SMTP HELO command . - Identifies the client and starts the session .
3,025
async def ehlo ( self , from_host = None ) : if from_host is None : from_host = self . fqdn code , message = await self . do_cmd ( "EHLO" , from_host ) self . last_ehlo_response = ( code , message ) extns , auths = SMTP . parse_esmtp_extensions ( message ) self . esmtp_extensions = extns self . auth_mechanisms = auths ...
Sends a SMTP EHLO command . - Identifies the client and starts the session .
3,026
async def help ( self , command_name = None ) : if command_name is None : command_name = "" code , message = await self . do_cmd ( "HELP" , command_name ) return message
Sends a SMTP HELP command .
3,027
async def mail ( self , sender , options = None ) : if options is None : options = [ ] from_addr = "FROM:{}" . format ( quoteaddr ( sender ) ) code , message = await self . do_cmd ( "MAIL" , from_addr , * options ) return code , message
Sends a SMTP MAIL command . - Starts the mail transfer session .
3,028
async def rcpt ( self , recipient , options = None ) : if options is None : options = [ ] to_addr = "TO:{}" . format ( quoteaddr ( recipient ) ) code , message = await self . do_cmd ( "RCPT" , to_addr , * options ) return code , message
Sends a SMTP RCPT command . - Indicates a recipient for the e - mail .
3,029
async def quit ( self ) : code = - 1 message = None try : code , message = await self . do_cmd ( "QUIT" ) except ConnectionError : pass except SMTPCommandFailedError : pass await self . close ( ) return code , message
Sends a SMTP QUIT command . - Ends the session .
3,030
async def data ( self , email_message ) : code , message = await self . do_cmd ( "DATA" , success = ( 354 , ) ) email_message = SMTP . prepare_message ( email_message ) self . writer . write ( email_message ) await self . writer . drain ( ) code , message = await self . reader . read_reply ( ) return code , message
Sends a SMTP DATA command . - Transmits the message to the server .
3,031
async def auth ( self , username , password ) : await self . ehlo_or_helo_if_needed ( ) errors = [ ] code = message = None for auth , meth in self . __class__ . _supported_auth_mechanisms . items ( ) : if auth in self . auth_mechanisms : auth_func = getattr ( self , meth ) try : code , message = await auth_func ( usern...
Tries to authenticate user against the SMTP server .
3,032
async def starttls ( self , context = None ) : if not self . use_aioopenssl : raise BadImplementationError ( "This connection does not use aioopenssl" ) import aioopenssl import OpenSSL await self . ehlo_or_helo_if_needed ( ) if "starttls" not in self . esmtp_extensions : raise SMTPCommandNotSupportedError ( "STARTTLS"...
Upgrades the connection to the SMTP server into TLS mode .
3,033
async def sendmail ( self , sender , recipients , message , mail_options = None , rcpt_options = None ) : if isinstance ( recipients , str ) : recipients = [ recipients ] if mail_options is None : mail_options = [ ] if rcpt_options is None : rcpt_options = [ ] await self . ehlo_or_helo_if_needed ( ) if self . supports_...
Performs an entire e - mail transaction .
3,034
async def _auth_cram_md5 ( self , username , password ) : mechanism = "CRAM-MD5" code , message = await self . do_cmd ( "AUTH" , mechanism , success = ( 334 , ) ) decoded_challenge = base64 . b64decode ( message ) challenge_hash = hmac . new ( key = password . encode ( "utf-8" ) , msg = decoded_challenge , digestmod = ...
Performs an authentication attemps using the CRAM - MD5 mechanism .
3,035
async def _auth_login ( self , username , password ) : mechanism = "LOGIN" code , message = await self . do_cmd ( "AUTH" , mechanism , SMTP . b64enc ( username ) , success = ( 334 , ) ) try : code , message = await self . do_cmd ( SMTP . b64enc ( password ) , success = ( 235 , 503 ) ) except SMTPCommandFailedError as e...
Performs an authentication attempt using the LOGIN mechanism .
3,036
async def _auth_plain ( self , username , password ) : mechanism = "PLAIN" credentials = "\0{}\0{}" . format ( username , password ) encoded_credentials = SMTP . b64enc ( credentials ) try : code , message = await self . do_cmd ( "AUTH" , mechanism , encoded_credentials , success = ( 235 , 503 ) ) except SMTPCommandFai...
Performs an authentication attempt using the PLAIN mechanism .
3,037
def format ( self ) : tag = self . data [ 'tag' ] subtags = tag . split ( '-' ) if len ( subtags ) == 1 : return subtags [ 0 ] formatted_tag = subtags [ 0 ] private_tag = False for i , subtag in enumerate ( subtags [ 1 : ] ) : if len ( subtags [ i ] ) == 1 or private_tag : formatted_tag += '-' + subtag private_tag = Tr...
Get format according to algorithm defined in RFC 5646 section 2 . 1 . 1 .
3,038
def ObjectEnum ( ctx ) : return Enum ( ctx , villager_male = 83 , villager_female = 293 , scout_cavalry = 448 , eagle_warrior = 751 , king = 434 , flare = 332 , relic = 285 , turkey = 833 , sheep = 594 , deer = 65 , boar = 48 , iron_boar = 810 , ostrich = 1026 , javelina = 822 , crocodile = 1031 , rhinoceros = 1139 , w...
Object Enumeration .
3,039
def GameTypeEnum ( ctx ) : return Enum ( ctx , RM = 0 , Regicide = 1 , DM = 2 , Scenario = 3 , Campaign = 4 , KingOfTheHill = 5 , WonderRace = 6 , DefendTheWonder = 7 , TurboRandom = 8 )
Game Type Enumeration .
3,040
def ObjectTypeEnum ( ctx ) : return Enum ( ctx , static = 10 , animated = 20 , doppelganger = 25 , moving = 30 , action = 40 , base = 50 , missile = 60 , combat = 70 , building = 80 , tree = 90 , default = Pass )
Object Type Enumeration .
3,041
def PlayerTypeEnum ( ctx ) : return Enum ( ctx , absent = 0 , closed = 1 , human = 2 , eliminated = 3 , computer = 4 , cyborg = 5 , spectator = 6 )
Player Type Enumeration .
3,042
def ResourceEnum ( ctx ) : return Enum ( ctx , food = 0 , wood = 1 , stone = 2 , gold = 3 , decay = 12 , fish = 17 , default = Pass )
Resource Type Enumeration .
3,043
def VictoryEnum ( ctx ) : return Enum ( ctx , standard = 0 , conquest = 1 , exploration = 2 , ruins = 3 , artifacts = 4 , discoveries = 5 , gold = 6 , time_limit = 7 , score = 8 , standard2 = 9 , regicide = 10 , last_man = 11 )
Victory Type Enumeration .
3,044
def StartingAgeEnum ( ctx ) : return Enum ( ctx , what = - 2 , unset = - 1 , dark = 0 , feudal = 1 , castle = 2 , imperial = 3 , postimperial = 4 , dmpostimperial = 6 )
Starting Age Enumeration .
3,045
def GameActionModeEnum ( ctx ) : return Enum ( ctx , diplomacy = 0 , speed = 1 , instant_build = 2 , quick_build = 4 , allied_victory = 5 , cheat = 6 , unk0 = 9 , spy = 10 , unk1 = 11 , farm_queue = 13 , farm_unqueue = 14 , default = Pass )
Game Action Modes .
3,046
def ReleaseTypeEnum ( ctx ) : return Enum ( ctx , all = 0 , selected = 3 , sametype = 4 , notselected = 5 , inversetype = 6 , default = Pass )
Types of Releases .
3,047
def MyDiplomacyEnum ( ctx ) : return Enum ( ctx , gaia = 0 , self = 1 , ally = 2 , neutral = 3 , enemy = 4 , invalid_player = - 1 )
Player s Diplomacy Enumeration .
3,048
def ActionEnum ( ctx ) : return Enum ( ctx , interact = 0 , stop = 1 , ai_interact = 2 , move = 3 , add_attribute = 5 , give_attribute = 6 , ai_move = 10 , resign = 11 , spec = 15 , waypoint = 16 , stance = 18 , guard = 19 , follow = 20 , patrol = 21 , formation = 23 , save = 27 , ai_waypoint = 31 , chapter = 32 , ai_c...
Action Enumeration .
3,049
def newKernel ( self , nb ) : manager , kernel = utils . start_new_kernel ( kernel_name = nb . metadata . kernelspec . name ) return kernel
generate a new kernel
3,050
def configure ( self , options , conf ) : super ( Nosebook , self ) . configure ( options , conf ) self . testMatch = re . compile ( options . nosebookTestMatch ) . match self . testMatchCell = re . compile ( options . nosebookTestMatchCell ) . match scrubs = [ ] if options . nosebookScrub : try : scrubs = json . loads...
apply configured options
3,051
def wantFile ( self , filename ) : log . info ( "considering %s" , filename ) if self . testMatch ( filename ) is None : return False nb = self . readnb ( filename ) for cell in self . codeCells ( nb ) : return True log . info ( "no `code` cells in %s" , filename ) return False
filter files to those that match nosebook - match
3,052
def create_connection ( cls , address , timeout = None , source_address = None ) : sock = socket . create_connection ( address , timeout , source_address ) return cls ( sock )
Create a SlipSocket connection .
3,053
def send_msg ( self , message ) : packet = self . driver . send ( message ) self . send_bytes ( packet )
Send a SLIP - encoded message over the stream .
3,054
def recv_msg ( self ) : if self . _messages : return self . _messages . popleft ( ) if self . _protocol_error : self . _handle_pending_protocol_error ( ) while not self . _messages and not self . _stream_closed : try : if self . _flush_needed : self . _flush_needed = False self . _messages . extend ( self . driver . fl...
Receive a single message from the stream .
3,055
def finalize ( self ) : self . pause_session_logging ( ) self . _disable_logging ( ) self . _msg_callback = None self . _error_msg_callback = None self . _warning_msg_callback = None self . _info_msg_callback = None
Clean up the object .
3,056
def _chain_indices ( self ) : chain_indices = deque ( range ( len ( self . connection_chains ) ) ) chain_indices . rotate ( self . _last_chain_index ) return chain_indices
Get the deque of chain indices starting with last successful index .
3,057
def resume_session_logging ( self ) : self . _chain . ctrl . set_session_log ( self . session_fd ) self . log ( "Session logging resumed" )
Resume session logging .
3,058
def rollback ( self , label = None , plane = 'sdr' ) : begin = time . time ( ) rb_label = self . _chain . target_device . rollback ( label = label , plane = plane ) elapsed = time . time ( ) - begin if label : self . emit_message ( "Configuration rollback last {:.0f}s. Label: {}" . format ( elapsed , rb_label ) , log_l...
Rollback the configuration .
3,059
def discovery ( self , logfile = None , tracefile = None ) : self . _enable_logging ( logfile = logfile , tracefile = tracefile ) self . log ( "'discovery' method is deprecated. Please 'connect' with force_discovery=True." ) self . log ( "Device discovery process started" ) self . connect ( logfile = logfile , force_di...
Discover the device details .
3,060
def reload ( self , reload_timeout = 300 , save_config = True , no_reload_cmd = False ) : begin = time . time ( ) self . _chain . target_device . clear_info ( ) result = False try : result = self . _chain . target_device . reload ( reload_timeout , save_config , no_reload_cmd ) except ConnectionStandbyConsole as exc : ...
Reload the device and wait for device to boot up .
3,061
def run_fsm ( self , name , command , events , transitions , timeout , max_transitions = 20 ) : return self . _chain . target_device . run_fsm ( name , command , events , transitions , timeout , max_transitions )
Instantiate and run the Finite State Machine for the current device connection .
3,062
def emit_message ( self , message , log_level ) : self . log ( message ) if log_level == logging . ERROR : if self . _error_msg_callback : self . _error_msg_callback ( message ) return if log_level == logging . WARNING : if self . _warning_msg_callback : self . _warning_msg_callback ( message ) return if log_level == l...
Call the msg callback function with the message .
3,063
def msg_callback ( self , callback ) : if callable ( callback ) : self . _msg_callback = callback else : self . _msg_callback = None
Set the message callback .
3,064
def error_msg_callback ( self , callback ) : if callable ( callback ) : self . _error_msg_callback = callback else : self . _error_msg_callback = None
Set the error message callback .
3,065
def warning_msg_callback ( self , callback ) : if callable ( callback ) : self . _warning_msg_callback = callback else : self . _warning_msg_callback = None
Set the warning message callback .
3,066
def info_msg_callback ( self , callback ) : if callable ( callback ) : self . _info_msg_callback = callback else : self . _info_msg_callback = None
Set the info message callback .
3,067
def _get_view_details ( self , urlpatterns , parent = '' ) : for pattern in urlpatterns : if isinstance ( pattern , ( URLPattern , RegexURLPattern ) ) : try : d = describe_pattern ( pattern ) docstr = pattern . callback . __doc__ method = None expected_json_response = '' expected_url = '' if docstr : u = re . findall (...
Recursive function to extract all url details
3,068
def for_each_child ( node , callback ) : for name in node . _fields : value = getattr ( node , name ) if isinstance ( value , list ) : for item in value : if isinstance ( item , ast . AST ) : callback ( item ) elif isinstance ( value , ast . AST ) : callback ( value )
Calls the callback for each AST node that s a child of the given node .
3,069
def resolve_frompath ( pkgpath , relpath , level = 0 ) : if level == 0 : return relpath parts = pkgpath . split ( '.' ) + [ '_' ] parts = parts [ : - level ] + ( relpath . split ( '.' ) if relpath else [ ] ) return '.' . join ( parts )
Resolves the path of the module referred to by from .. x import y .
3,070
def find_module ( modpath ) : module_path = modpath . replace ( '.' , '/' ) + '.py' init_path = modpath . replace ( '.' , '/' ) + '/__init__.py' for root_path in sys . path : path = os . path . join ( root_path , module_path ) if os . path . isfile ( path ) : return path path = os . path . join ( root_path , init_path ...
Determines whether a module exists with the given modpath .
3,071
def add ( self , modpath , name , origin ) : self . map . setdefault ( modpath , { } ) . setdefault ( name , set ( ) ) . add ( origin )
Adds a possible origin for the given name in the given module .
3,072
def add_package_origins ( self , modpath ) : parts = modpath . split ( '.' ) parent = parts [ 0 ] for part in parts [ 1 : ] : child = parent + '.' + part if self . find_module ( child ) : self . add ( parent , part , child ) parent = child
Whenever you import a . b . c Python automatically binds b in a to the a . b module and binds c in a . b to the a . b . c module .
3,073
def scan_module ( self , pkgpath , modpath , node ) : def scan_imports ( node ) : if node_type ( node ) == 'Import' : for binding in node . names : name , asname = binding . name , binding . asname if asname : self . add ( modpath , asname , name ) else : top_name = name . split ( '.' ) [ 0 ] self . add ( modpath , top...
Scans a module collecting possible origins for all names assuming names can only become bound to values in other modules by import .
3,074
def get_origins ( self , modpath , name ) : return self . map . get ( modpath , { } ) . get ( name , set ( ) )
Returns the set of possible origins for a name in a module .
3,075
def dump ( self ) : for modpath in sorted ( self . map ) : title = 'Imports in %s' % modpath print ( '\n' + title + '\n' + '-' * len ( title ) ) for name , value in sorted ( self . map . get ( modpath , { } ) . items ( ) ) : print ( ' %s -> %s' % ( name , ', ' . join ( sorted ( value ) ) ) )
Prints out the contents of the import map .
3,076
def scan_module ( self , modpath , node ) : used_origins = self . map . setdefault ( modpath , set ( ) ) def get_origins ( modpath , name ) : origins = set ( ) def walk_origins ( modpath , name ) : for origin in self . import_map . get_origins ( modpath , name ) : if origin not in origins : origins . add ( origin ) if ...
Scans a module collecting all used origins assuming that modules are obtained only by dotted paths and no other kinds of expressions .
3,077
def dump ( self ) : for modpath in sorted ( self . map ) : title = 'Used by %s' % modpath print ( '\n' + title + '\n' + '-' * len ( title ) ) for origin in sorted ( self . get_used_origins ( modpath ) ) : print ( ' %s' % origin )
Prints out the contents of the usage map .
3,078
def convert_to_timestamp ( time ) : if time == - 1 : return None time = int ( time * 1000 ) hour = time // 1000 // 3600 minute = ( time // 1000 // 60 ) % 60 second = ( time // 1000 ) % 60 return str ( hour ) . zfill ( 2 ) + ":" + str ( minute ) . zfill ( 2 ) + ":" + str ( second ) . zfill ( 2 )
Convert int to timestamp string .
3,079
def _parse ( self , stream , context , path ) : length = self . length ( context ) new_stream = BytesIO ( construct . core . _read_stream ( stream , length ) ) return self . subcon . _parse ( new_stream , context , path )
Parse tunnel .
3,080
def _parse ( self , stream , context , path ) : start = stream . tell ( ) read_bytes = "" if self . max_length : read_bytes = stream . read ( self . max_length ) else : read_bytes = stream . read ( ) skip = read_bytes . find ( self . find ) + len ( self . find ) stream . seek ( start + skip ) return skip
Parse stream to find a given byte string .
3,081
def _parse ( self , stream , context , path ) : objs = [ ] while True : start = stream . tell ( ) test = stream . read ( len ( self . find ) ) stream . seek ( start ) if test == self . find : break else : subobj = self . subcon . _parse ( stream , context , path ) objs . append ( subobj ) return objs
Parse until a given byte string is found .
3,082
def _parse ( self , stream , context , path ) : num_players = context . _ . _ . _ . replay . num_players start = stream . tell ( ) read_bytes = stream . read ( ) marker_up14 = read_bytes . find ( b"\x16\xc6\x00\x00\x00\x21" ) marker_up15 = read_bytes . find ( b"\x16\xf0\x00\x00\x00\x21" ) marker = - 1 if marker_up14 > ...
Parse until the end of objects data .
3,083
def rollback ( self , label , plane ) : cm_label = 'condoor-{}' . format ( int ( time . time ( ) ) ) self . device . send ( self . rollback_cmd . format ( label ) , timeout = 120 ) return cm_label
Rollback config .
3,084
def start ( builtins = False , profile_threads = True ) : _vendorized_yappi . yappi . set_context_id_callback ( lambda : greenlet and id ( greenlet . getcurrent ( ) ) or 0 ) _vendorized_yappi . yappi . set_context_name_callback ( lambda : greenlet and greenlet . getcurrent ( ) . __class__ . __name__ or '' ) _vendorized...
Starts profiling all threads and all greenlets .
3,085
def connect ( self , driver ) : events = [ ESCAPE_CHAR , driver . press_return_re , driver . standby_re , driver . username_re , driver . password_re , driver . more_re , self . device . prompt_re , driver . rommon_re , driver . unable_to_connect_re , driver . timeout_re , pexpect . TIMEOUT , PASSWORD_OK , driver . syn...
Connect using the Telnet protocol specific FSM .
3,086
def disconnect ( self , driver ) : self . log ( "TELNETCONSOLE disconnect" ) try : while self . device . mode != 'global' : self . device . send ( 'exit' , timeout = 10 ) except OSError : self . log ( "TELNETCONSOLE already disconnected" ) except pexpect . TIMEOUT : self . log ( "TELNETCONSOLE unable to get the root pr...
Disconnect from the console .
3,087
def _calculate_apm ( index , player_actions , other_actions , duration ) : apm_per_player = { } for player_index , histogram in player_actions . items ( ) : apm_per_player [ player_index ] = sum ( histogram . values ( ) ) total_unattributed = sum ( other_actions . values ( ) ) total_attributed = sum ( apm_per_player . ...
Calculate player s rAPM .
3,088
def guess_finished ( summary , postgame ) : if postgame and postgame . complete : return True for player in summary [ 'players' ] : if 'resign' in player [ 'action_histogram' ] : return True return False
Sometimes a game is finished but not recorded as such .
3,089
def _num_players ( self ) : self . _player_num = 0 self . _computer_num = 0 for player in self . _header . scenario . game_settings . player_info : if player . type == 'human' : self . _player_num += 1 elif player . type == 'computer' : self . _computer_num += 1
Compute number of players both human and computer .
3,090
def _parse_lobby_chat ( self , messages , source , timestamp ) : for message in messages : if message . message_length == 0 : continue chat = ChatMessage ( message . message , timestamp , self . _players ( ) , source = source ) self . _parse_chat ( chat )
Parse a lobby chat message .
3,091
def _parse_action ( self , action , current_time ) : if action . action_type == 'research' : name = mgz . const . TECHNOLOGIES [ action . data . technology_type ] self . _research [ action . data . player_id ] . append ( { 'technology' : name , 'timestamp' : _timestamp_to_time ( action . timestamp ) } ) elif action . a...
Parse a player action .
3,092
def operations ( self , op_types = None ) : if not op_types : op_types = [ 'message' , 'action' , 'sync' , 'viewlock' , 'savedchapter' ] while self . _handle . tell ( ) < self . _eof : current_time = mgz . util . convert_to_timestamp ( self . _time / 1000 ) try : operation = mgz . body . operation . parse_stream ( self...
Process operation stream .
3,093
def summarize ( self ) : if not self . _achievements_summarized : for _ in self . operations ( ) : pass self . _summarize ( ) return self . _summary
Summarize game .
3,094
def is_nomad ( self ) : nomad = self . _header . initial . restore_time == 0 or None for i in range ( 1 , self . _header . replay . num_players ) : for obj in self . _header . initial . players [ i ] . objects : if obj . type == 'building' and obj . object_type == 'tc_1' : return False return nomad
Is this game nomad .
3,095
def is_regicide ( self ) : for i in range ( 1 , self . _header . replay . num_players ) : for obj in self . _header . initial . players [ i ] . objects : if obj . type == 'unit' and obj . object_type == 'king' : return True return False
Is this game regicide .
3,096
def _parse_chat ( self , chat ) : if chat . data [ 'type' ] == 'chat' : if chat . data [ 'player' ] in [ p . player_name for i , p in self . _players ( ) ] : self . _chat . append ( chat . data ) elif chat . data [ 'type' ] == 'ladder' : self . _ladder = chat . data [ 'ladder' ] elif chat . data [ 'type' ] == 'rating' ...
Parse a chat message .
3,097
def _compass_position ( self , player_x , player_y ) : map_dim = self . _map . size_x third = map_dim * ( 1 / 3.0 ) for direction in mgz . const . COMPASS : point = mgz . const . COMPASS [ direction ] xlower = point [ 0 ] * map_dim xupper = ( point [ 0 ] * map_dim ) + third ylower = point [ 1 ] * map_dim yupper = ( poi...
Get compass position of player .
3,098
def _players ( self ) : for i in range ( 1 , self . _header . replay . num_players ) : yield i , self . _header . initial . players [ i ] . attributes
Get player attributes with index . No Gaia .
3,099
def players ( self , postgame , game_type ) : for i , attributes in self . _players ( ) : yield self . _parse_player ( i , attributes , postgame , game_type )
Return parsed players .