idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
24,300 | def set_max_threads ( self , max_threads ) : if max_threads is None : raise TypeError ( 'max_threads must not be None.' ) self . _check_if_ready ( ) self . collection . set_max_working ( max_threads ) | Set the maximum number of concurrent threads . |
24,301 | def authorize ( scope , password = [ None ] ) : conn = scope . get ( '__connection__' ) password = password [ 0 ] if password is None : conn . app_authorize ( ) else : account = Account ( '' , password ) conn . app_authorize ( account ) return True | Looks for a password prompt on the current connection and enters the given password . If a password is not given the function uses the same password that was used at the last login attempt ; it is an error if no such attempt was made before . |
24,302 | def close ( scope ) : conn = scope . get ( '__connection__' ) conn . close ( 1 ) scope . define ( __response__ = conn . response ) return True | Closes the existing connection with the remote host . This function is rarely used as normally Exscript closes the connection automatically when the script has completed . |
24,303 | def exec_ ( scope , data ) : conn = scope . get ( '__connection__' ) response = [ ] for line in data : conn . send ( line ) conn . expect_prompt ( ) response += conn . response . split ( '\n' ) [ 1 : ] scope . define ( __response__ = response ) return True | Sends the given data to the remote host and waits until the host has responded with a prompt . If the given data is a list of strings each item is sent and after each item a prompt is expected . |
24,304 | def wait_for ( scope , prompt ) : conn = scope . get ( '__connection__' ) conn . expect ( prompt ) scope . define ( __response__ = conn . response ) return True | Waits until the response of the remote host contains the given pattern . |
24,305 | def set_prompt ( scope , prompt = None ) : conn = scope . get ( '__connection__' ) conn . set_prompt ( prompt ) return True | Defines the pattern that is recognized at any future time when Exscript needs to wait for a prompt . In other words whenever Exscript waits for a prompt it searches the response of the host for the given pattern and continues as soon as the pattern is found . |
24,306 | def set_error ( scope , error_re = None ) : conn = scope . get ( '__connection__' ) conn . set_error_prompt ( error_re ) return True | Defines a pattern that whenever detected in the response of the remote host causes an error to be raised . |
24,307 | def set_timeout ( scope , timeout ) : conn = scope . get ( '__connection__' ) conn . set_timeout ( int ( timeout [ 0 ] ) ) return True | Defines the time after which Exscript fails if it does not receive a prompt from the remote host . |
24,308 | def add_command ( self , command , handler , prompt = True ) : if prompt : thehandler = self . _create_autoprompt_handler ( handler ) else : thehandler = handler self . commands . add ( command , thehandler ) | Registers a command . |
24,309 | def add_commands_from_file ( self , filename , autoprompt = True ) : if autoprompt : deco = self . _create_autoprompt_handler else : deco = None self . commands . add_from_file ( filename , deco ) | Wrapper around add_command_handler that reads the handlers from the file with the given name . The file is a Python script containing a list named commands of tuples that map command names to handlers . |
24,310 | def init ( self ) : self . logged_in = False if self . login_type == self . LOGIN_TYPE_PASSWORDONLY : self . prompt_stage = self . PROMPT_STAGE_PASSWORD elif self . login_type == self . LOGIN_TYPE_NONE : self . prompt_stage = self . PROMPT_STAGE_CUSTOM else : self . prompt_stage = self . PROMPT_STAGE_USERNAME return self . banner + self . _get_prompt ( ) | Init or reset the virtual device . |
24,311 | def do ( self , command ) : echo = self . echo and command or '' if not self . logged_in : return echo + '\n' + self . _get_prompt ( ) response = self . commands . eval ( command ) if response is None : return echo + '\n' + self . _get_prompt ( ) return echo + response | Executes the given command on the virtual device and returns the response . |
24,312 | def get_user ( prompt = None ) : try : env_user = getpass . getuser ( ) except KeyError : env_user = '' if prompt is None : prompt = "Please enter your user name" if env_user is None or env_user == '' : user = input ( '%s: ' % prompt ) else : user = input ( '%s [%s]: ' % ( prompt , env_user ) ) if user == '' : user = env_user return user | Prompts the user for his login name defaulting to the USER environment variable . Returns a string containing the username . May throw an exception if EOF is given by the user . |
24,313 | def get ( self , key , default = None ) : if not self . parser : return default try : return self . parser . get ( self . section , key ) except ( configparser . NoSectionError , configparser . NoOptionError ) : return default | Returns the input with the given key from the section that was passed to the constructor . If either the section or the key are not found the default value is returned . |
24,314 | def set ( self , key , value ) : if value is None : return None self . parser . set ( self . section , key , value ) with NamedTemporaryFile ( delete = False ) as tmpfile : pass with codecs . open ( tmpfile . name , 'w' , encoding = 'utf8' ) as fp : self . parser . write ( fp ) self . file . close ( ) shutil . move ( tmpfile . name , self . file . name ) self . file = open ( self . file . name ) return value | Saves the input with the given key in the section that was passed to the constructor . If either the section or the key are not found they are created . |
24,315 | def acquire ( self , signal = True ) : if not self . needs_lock : return with self . synclock : while not self . lock . acquire ( False ) : self . synclock . wait ( ) if signal : self . acquired_event ( self ) self . synclock . notify_all ( ) | Locks the account . Method has no effect if the constructor argument needs_lock wsa set to False . |
24,316 | def release ( self , signal = True ) : if not self . needs_lock : return with self . synclock : self . lock . release ( ) if signal : self . released_event ( self ) self . synclock . notify_all ( ) | Unlocks the account . Method has no effect if the constructor argument needs_lock wsa set to False . |
24,317 | def set_name ( self , name ) : self . name = name self . changed_event . emit ( self ) | Changes the name of the account . |
24,318 | def set_password ( self , password ) : self . password = password self . changed_event . emit ( self ) | Changes the password of the account . |
24,319 | def set_authorization_password ( self , password ) : self . authorization_password = password self . changed_event . emit ( self ) | Changes the authorization password of the account . |
24,320 | def for_host ( parent , host ) : account = AccountProxy ( parent ) account . host = host if account . acquire ( ) : return account return None | Returns a new AccountProxy that has an account acquired . The account is chosen based on what the connected AccountManager selects for the given host . |
24,321 | def for_account_hash ( parent , account_hash ) : account = AccountProxy ( parent ) account . account_hash = account_hash if account . acquire ( ) : return account return None | Returns a new AccountProxy that acquires the account with the given hash if such an account is known to the account manager . It is an error if the account manager does not have such an account . |
24,322 | def acquire ( self ) : if self . host : self . parent . send ( ( 'acquire-account-for-host' , self . host ) ) elif self . account_hash : self . parent . send ( ( 'acquire-account-from-hash' , self . account_hash ) ) else : self . parent . send ( ( 'acquire-account' ) ) response = self . parent . recv ( ) if isinstance ( response , Exception ) : raise response if response is None : return False self . account_hash , self . user , self . password , self . authorization_password , self . key = response return True | Locks the account . Returns True on success False if the account is thread - local and must not be locked . |
24,323 | def release ( self ) : self . parent . send ( ( 'release-account' , self . account_hash ) ) response = self . parent . recv ( ) if isinstance ( response , Exception ) : raise response if response != 'ok' : raise ValueError ( 'unexpected response: ' + repr ( response ) ) | Unlocks the account . |
24,324 | def get_account_from_hash ( self , account_hash ) : for account in self . accounts : if account . __hash__ ( ) == account_hash : return account return None | Returns the account with the given hash or None if no such account is included in the account pool . |
24,325 | def add_account ( self , accounts ) : with self . unlock_cond : for account in to_list ( accounts ) : account . acquired_event . listen ( self . _on_account_acquired ) account . released_event . listen ( self . _on_account_released ) self . accounts . add ( account ) self . unlocked_accounts . append ( account ) self . unlock_cond . notify_all ( ) | Adds one or more account instances to the pool . |
24,326 | def reset ( self ) : with self . unlock_cond : for owner in self . owner2account : self . release_accounts ( owner ) self . _remove_account ( self . accounts . copy ( ) ) self . unlock_cond . notify_all ( ) | Removes all accounts . |
24,327 | def get_account_from_name ( self , name ) : for account in self . accounts : if account . get_name ( ) == name : return account return None | Returns the account with the given name . |
24,328 | def acquire_account ( self , account = None , owner = None ) : with self . unlock_cond : if len ( self . accounts ) == 0 : raise ValueError ( 'account pool is empty' ) if account : while account not in self . unlocked_accounts : self . unlock_cond . wait ( ) self . unlocked_accounts . remove ( account ) else : while len ( self . unlocked_accounts ) == 0 : self . unlock_cond . wait ( ) account = self . unlocked_accounts . popleft ( ) if owner is not None : self . owner2account [ owner ] . append ( account ) self . account2owner [ account ] = owner account . acquire ( False ) self . unlock_cond . notify_all ( ) return account | Waits until an account becomes available then locks and returns it . If an account is not passed the next available account is returned . |
24,329 | def add_pool ( self , pool , match = None ) : if match is None : self . default_pool = pool else : self . pools . append ( ( match , pool ) ) | Adds a new account pool . If the given match argument is None the pool the default pool . Otherwise the match argument is a callback function that is invoked to decide whether or not the given pool should be used for a host . |
24,330 | def get_account_from_hash ( self , account_hash ) : for _ , pool in self . pools : account = pool . get_account_from_hash ( account_hash ) if account is not None : return account return self . default_pool . get_account_from_hash ( account_hash ) | Returns the account with the given hash if it is contained in any of the pools . Returns None otherwise . |
24,331 | def acquire_account ( self , account = None , owner = None ) : if account is not None : for _ , pool in self . pools : if pool . has_account ( account ) : return pool . acquire_account ( account , owner ) if not self . default_pool . has_account ( account ) : account . acquire ( ) return account return self . default_pool . acquire_account ( account , owner ) | Acquires the given account . If no account is given one is chosen from the default pool . |
24,332 | def acquire_account_for ( self , host , owner = None ) : for match , pool in self . pools : if match ( host ) is True : return pool . acquire_account ( owner = owner ) return self . default_pool . acquire_account ( owner = owner ) | Acquires an account for the given host and returns it . The host is passed to each of the match functions that were passed in when adding the pool . The first pool for which the match function returns True is chosen to assign an account . |
24,333 | def eval ( self , command ) : for cmd , response in self . response_list : if not cmd . match ( command ) : continue if response is None : return None elif hasattr ( response , '__call__' ) : return response ( command ) else : return response if self . strict : raise Exception ( 'Undefined command: ' + repr ( command ) ) return None | Evaluate the given string against all registered commands and return the defined response . |
24,334 | def to_host ( host , default_protocol = 'telnet' , default_domain = '' ) : if host is None : raise TypeError ( 'None can not be cast to Host' ) if hasattr ( host , 'get_address' ) : return host if default_domain and not '.' in host : host += '.' + default_domain return Exscript . Host ( host , default_protocol = default_protocol ) | Given a string or a Host object this function returns a Host object . |
24,335 | def to_hosts ( hosts , default_protocol = 'telnet' , default_domain = '' ) : return [ to_host ( h , default_protocol , default_domain ) for h in to_list ( hosts ) ] | Given a string or a Host object or a list of strings or Host objects this function returns a list of Host objects . |
24,336 | def to_regex ( regex , flags = 0 ) : if regex is None : raise TypeError ( 'None can not be cast to re.RegexObject' ) if hasattr ( regex , 'match' ) : return regex return re . compile ( regex , flags ) | Given a string this function returns a new re . RegexObject . Given a re . RegexObject this function just returns the same object . |
24,337 | def is_ip ( string ) : mo = re . match ( r'(\d+)\.(\d+)\.(\d+)\.(\d+)' , string ) if mo is None : return False for group in mo . groups ( ) : if int ( group ) not in list ( range ( 0 , 256 ) ) : return False return True | Returns True if the given string is an IPv4 address False otherwise . |
24,338 | def network ( prefix , default_length = 24 ) : address , pfxlen = parse_prefix ( prefix , default_length ) ip = ip2int ( address ) return int2ip ( ip & pfxlen2mask_int ( pfxlen ) ) | Given a prefix this function returns the corresponding network address . |
24,339 | def matches_prefix ( ip , prefix ) : ip_int = ip2int ( ip ) network , pfxlen = parse_prefix ( prefix ) network_int = ip2int ( network ) mask_int = pfxlen2mask_int ( pfxlen ) return ip_int & mask_int == network_int & mask_int | Returns True if the given IP address is part of the given network returns False otherwise . |
24,340 | def is_private ( ip ) : if matches_prefix ( ip , '10.0.0.0/8' ) : return True if matches_prefix ( ip , '172.16.0.0/12' ) : return True if matches_prefix ( ip , '192.168.0.0/16' ) : return True return False | Returns True if the given IP address is private returns False otherwise . |
24,341 | def sort ( iterable ) : ips = sorted ( normalize_ip ( ip ) for ip in iterable ) return [ clean_ip ( ip ) for ip in ips ] | Given an IP address list this function sorts the list . |
24,342 | def _parse_url ( path ) : if sys . version_info [ 0 ] < 3 : o = urlparse ( urllib . parse . unquote_plus ( path ) . decode ( 'utf8' ) ) else : o = urlparse ( urllib . parse . unquote_plus ( path ) ) path = o . path args = { } multiargs = parse_qs ( o . query , keep_blank_values = True ) for arg , value in list ( multiargs . items ( ) ) : args [ arg ] = value [ 0 ] return path , args | Given a urlencoded path returns the path and the dictionary of query arguments all in Unicode . |
24,343 | def _require_authenticate ( func ) : def wrapped ( self ) : if not hasattr ( self , 'authenticated' ) : self . authenticated = None if self . authenticated : return func ( self ) auth = self . headers . get ( u'Authorization' ) if auth is None : msg = u"You are not allowed to access this page. Please login first!" return _error_401 ( self , msg ) token , fields = auth . split ( ' ' , 1 ) if token != 'Digest' : return _error_401 ( self , 'Unsupported authentication type' ) cred = parse_http_list ( fields ) cred = parse_keqv_list ( cred ) keys = u'realm' , u'username' , u'nonce' , u'uri' , u'response' if not all ( cred . get ( key ) for key in keys ) : return _error_401 ( self , 'Incomplete authentication header' ) if cred [ 'realm' ] != self . server . realm : return _error_401 ( self , 'Incorrect realm' ) if 'qop' in cred and ( 'nc' not in cred or 'cnonce' not in cred ) : return _error_401 ( self , 'qop with missing nc or cnonce' ) username = cred [ 'username' ] password = self . server . get_password ( username ) if not username or password is None : return _error_401 ( self , 'Invalid username or password' ) location = u'%s:%s' % ( self . command , self . path ) location = md5hex ( location . encode ( 'utf8' ) ) pwhash = md5hex ( '%s:%s:%s' % ( username , self . server . realm , password ) ) if 'qop' in cred : info = ( cred [ 'nonce' ] , cred [ 'nc' ] , cred [ 'cnonce' ] , cred [ 'qop' ] , location ) else : info = cred [ 'nonce' ] , location expect = u'%s:%s' % ( pwhash , ':' . join ( info ) ) expect = md5hex ( expect . encode ( 'utf8' ) ) if expect != cred [ 'response' ] : return _error_401 ( self , 'Invalid username or password' ) self . authenticated = True return func ( self ) return wrapped | A decorator to add digest authorization checks to HTTP Request Handlers |
24,344 | def _do_POSTGET ( self , handler ) : self . server . _dbg ( self . path ) self . path , self . args = _parse_url ( self . path ) self . data = u"" . encode ( ) length = self . headers . get ( 'Content-Length' ) if length and length . isdigit ( ) : self . data = self . rfile . read ( int ( length ) ) self . bdata = self . data try : self . data = self . data . decode ( 'utf8' ) except UnicodeDecodeError : self . data = None try : handler ( ) except : self . send_response ( 500 ) self . end_headers ( ) self . wfile . write ( format_exc ( ) . encode ( 'utf8' ) ) | handle an HTTP request |
24,345 | def head ( self , bytes ) : oldpos = self . io . tell ( ) self . io . seek ( 0 ) head = self . io . read ( bytes ) self . io . seek ( oldpos ) return head | Returns the number of given bytes from the head of the buffer . The buffer remains unchanged . |
24,346 | def tail ( self , bytes ) : self . io . seek ( max ( 0 , self . size ( ) - bytes ) ) return self . io . read ( ) | Returns the number of given bytes from the tail of the buffer . The buffer remains unchanged . |
24,347 | def append ( self , data ) : self . io . write ( data ) if not self . monitors : return buf = str ( self ) for item in self . monitors : regex_list , callback , bytepos , limit = item bytepos = max ( bytepos , len ( buf ) - limit ) for i , regex in enumerate ( regex_list ) : match = regex . search ( buf , bytepos ) if match is not None : item [ 2 ] = match . end ( ) callback ( i , match ) | Appends the given data to the buffer and triggers all connected monitors if any of them match the buffer content . |
24,348 | def clear ( self ) : self . io . seek ( 0 ) self . io . truncate ( ) for item in self . monitors : item [ 2 ] = 0 | Removes all data from the buffer . |
24,349 | def add_monitor ( self , pattern , callback , limit = 80 ) : self . monitors . append ( [ to_regexs ( pattern ) , callback , 0 , limit ] ) | Calls the given function whenever the given pattern matches the buffer . |
24,350 | def from_template_string ( string , ** kwargs ) : tmpl = _render_template ( string , ** kwargs ) mail = Mail ( ) mail . set_from_template_string ( tmpl ) return mail | Reads the given SMTP formatted template and creates a new Mail object using the information . |
24,351 | def send ( mail , server = 'localhost' ) : sender = mail . get_sender ( ) rcpt = mail . get_receipients ( ) session = smtplib . SMTP ( server ) message = MIMEMultipart ( ) message [ 'Subject' ] = mail . get_subject ( ) message [ 'From' ] = mail . get_sender ( ) message [ 'To' ] = ', ' . join ( mail . get_to ( ) ) message [ 'Cc' ] = ', ' . join ( mail . get_cc ( ) ) message . preamble = 'Your mail client is not MIME aware.' body = MIMEText ( mail . get_body ( ) . encode ( "utf-8" ) , "plain" , "utf-8" ) body . add_header ( 'Content-Disposition' , 'inline' ) message . attach ( body ) for filename in mail . get_attachments ( ) : message . attach ( _get_mime_object ( filename ) ) session . sendmail ( sender , rcpt , message . as_string ( ) ) | Sends the given mail . |
24,352 | def get_smtp_header ( self ) : header = "From: %s\r\n" % self . get_sender ( ) header += "To: %s\r\n" % ',\r\n ' . join ( self . get_to ( ) ) header += "Cc: %s\r\n" % ',\r\n ' . join ( self . get_cc ( ) ) header += "Bcc: %s\r\n" % ',\r\n ' . join ( self . get_bcc ( ) ) header += "Subject: %s\r\n" % self . get_subject ( ) return header | Returns the SMTP formatted header of the line . |
24,353 | def get_smtp_mail ( self ) : header = self . get_smtp_header ( ) body = self . get_body ( ) . replace ( '\n' , '\r\n' ) return header + '\r\n' + body + '\r\n' | Returns the SMTP formatted email as it may be passed to sendmail . |
24,354 | def status ( logger ) : aborted = logger . get_aborted_actions ( ) succeeded = logger . get_succeeded_actions ( ) total = aborted + succeeded if total == 0 : return 'No actions done' elif total == 1 and succeeded == 1 : return 'One action done (succeeded)' elif total == 1 and succeeded == 0 : return 'One action done (failed)' elif total == succeeded : return '%d actions total (all succeeded)' % total elif succeeded == 0 : return '%d actions total (all failed)' % total else : msg = '%d actions total (%d failed, %d succeeded)' return msg % ( total , aborted , succeeded ) | Creates a one - line summary on the actions that were logged by the given Logger . |
24,355 | def summarize ( logger ) : summary = [ ] for log in logger . get_logs ( ) : thestatus = log . has_error ( ) and log . get_error ( False ) or 'ok' name = log . get_name ( ) summary . append ( name + ': ' + thestatus ) return '\n' . join ( summary ) | Creates a short summary on the actions that were logged by the given Logger . |
24,356 | def format ( logger , show_successful = True , show_errors = True , show_traceback = True ) : output = [ ] errors = logger . get_aborted_actions ( ) if show_errors and errors : output += _underline ( 'Failed actions:' ) for log in logger . get_aborted_logs ( ) : if show_traceback : output . append ( log . get_name ( ) + ':' ) output . append ( log . get_error ( ) ) else : output . append ( log . get_name ( ) + ': ' + log . get_error ( False ) ) output . append ( '' ) if show_successful : output += _underline ( 'Successful actions:' ) for log in logger . get_succeeded_logs ( ) : output . append ( log . get_name ( ) ) output . append ( '' ) return '\n' . join ( output ) . strip ( ) | Prints a report of the actions that were logged by the given Logger . The report contains a list of successful actions as well as the full error message on failed actions . |
24,357 | def get_vars ( self ) : if self . parent is None : vars = { } vars . update ( self . variables ) return vars vars = self . parent . get_vars ( ) vars . update ( self . variables ) return vars | Returns a complete dict of all variables that are defined in this scope including the variables of the parent . |
24,358 | def get_from_name ( self , name ) : with self . condition : try : item_id = self . name2id [ name ] except KeyError : return None return self . id2item [ item_id ] return None | Returns the item with the given name or None if no such item is known . |
24,359 | def append ( self , item , name = None ) : with self . condition : self . queue . append ( item ) uuid = self . _register_item ( name , item ) self . condition . notify_all ( ) return uuid | Adds the given item to the end of the pipeline . |
24,360 | def prioritize ( self , item , force = False ) : with self . condition : if item in self . working or item in self . force : return self . queue . remove ( item ) if force : self . force . append ( item ) else : self . queue . appendleft ( item ) self . condition . notify_all ( ) | Moves the item to the very left of the queue . |
24,361 | def get_hosts_from_file ( filename , default_protocol = 'telnet' , default_domain = '' , remove_duplicates = False , encoding = 'utf-8' ) : if not os . path . exists ( filename ) : raise IOError ( 'No such file: %s' % filename ) have = set ( ) hosts = [ ] with codecs . open ( filename , 'r' , encoding ) as file_handle : for line in file_handle : hostname = line . split ( '#' ) [ 0 ] . strip ( ) if hostname == '' : continue if remove_duplicates and hostname in have : continue have . add ( hostname ) hosts . append ( to_host ( hostname , default_protocol , default_domain ) ) return hosts | Reads a list of hostnames from the file with the given name . |
24,362 | def log_to ( logger ) : logger_id = id ( logger ) def decorator ( function ) : func = add_label ( function , 'log_to' , logger_id = logger_id ) return func return decorator | Wraps a function that has a connection passed such that everything that happens on the connection is logged using the given logger . |
24,363 | def msg ( self , msg , * args ) : if self . debuglevel > 0 : self . stderr . write ( 'Telnet(%s,%d): ' % ( self . host , self . port ) ) if args : self . stderr . write ( msg % args ) else : self . stderr . write ( msg ) self . stderr . write ( '\n' ) | Print a debug message when the debug level is > 0 . |
24,364 | def write ( self , buffer ) : if type ( buffer ) == type ( 0 ) : buffer = chr ( buffer ) elif not isinstance ( buffer , bytes ) : buffer = buffer . encode ( self . encoding ) if IAC in buffer : buffer = buffer . replace ( IAC , IAC + IAC ) self . msg ( "send %s" , repr ( buffer ) ) self . sock . send ( buffer ) | Write a string to the socket doubling any IAC characters . |
24,365 | def read_all ( self ) : self . process_rawq ( ) while not self . eof : self . fill_rawq ( ) self . process_rawq ( ) buf = self . cookedq . getvalue ( ) self . cookedq . seek ( 0 ) self . cookedq . truncate ( ) return buf | Read all data until EOF ; block until connection closed . |
24,366 | def read_eager ( self ) : self . process_rawq ( ) while self . cookedq . tell ( ) == 0 and not self . eof and self . sock_avail ( ) : self . fill_rawq ( ) self . process_rawq ( ) return self . read_very_lazy ( ) | Read readily available data . |
24,367 | def set_receive_callback ( self , callback , * args , ** kwargs ) : self . data_callback = callback self . data_callback_kwargs = kwargs | The callback function called after each receipt of any data . |
24,368 | def set_window_size ( self , rows , cols ) : if not self . can_naws : return self . window_size = rows , cols size = struct . pack ( '!HH' , cols , rows ) self . sock . send ( IAC + SB + NAWS + size + IAC + SE ) | Change the size of the terminal window if the remote end supports NAWS . If it doesn t the method returns silently . |
24,369 | def interact ( self ) : if sys . platform == "win32" : self . mt_interact ( ) return while True : rfd , wfd , xfd = select . select ( [ self , sys . stdin ] , [ ] , [ ] ) if self in rfd : try : text = self . read_eager ( ) except EOFError : print ( '*** Connection closed by remote host ***' ) break if text : self . stdout . write ( text ) self . stdout . flush ( ) if sys . stdin in rfd : line = sys . stdin . readline ( ) if not line : break self . write ( line ) | Interaction function emulates a very dumb telnet client . |
24,370 | def waitfor ( self , relist , timeout = None , cleanup = None ) : return self . _waitfor ( relist , timeout , False , cleanup ) | Read until one from a list of a regular expressions matches . |
24,371 | def read ( path ) : logging . info ( "Checking pidfile '%s'" , path ) try : return int ( open ( path ) . read ( ) ) except IOError as xxx_todo_changeme : ( code , text ) = xxx_todo_changeme . args if code == errno . ENOENT : return None raise | Returns the process id from the given file if it exists or None otherwise . Raises an exception for all other types of OSError while trying to access the file . |
24,372 | def isalive ( path ) : pid = read ( path ) if pid is None : return False try : os . kill ( pid , 0 ) except OSError as xxx_todo_changeme1 : ( code , text ) = xxx_todo_changeme1 . args if code == errno . ESRCH : return False return True | Returns True if the file with the given name contains a process id that is still alive . Returns False otherwise . |
24,373 | def kill ( path ) : pid = read ( path ) if pid is None : return logging . info ( "Killing PID %s" , pid ) try : os . kill ( pid , 9 ) except OSError as xxx_todo_changeme2 : ( code , text ) = xxx_todo_changeme2 . args if code != errno . ESRCH : raise | Kills the process if it still exists . |
24,374 | def write ( path ) : pid = os . getpid ( ) logging . info ( "Writing PID %s to '%s'" , pid , path ) try : pidfile = open ( path , 'wb' ) fcntl . flock ( pidfile . fileno ( ) , fcntl . LOCK_EX | fcntl . LOCK_NB ) pidfile . seek ( 0 ) pidfile . truncate ( 0 ) pidfile . write ( str ( pid ) ) finally : try : pidfile . close ( ) except : pass | Writes the current process id to the given pidfile . |
24,375 | def set_username_prompt ( self , regex = None ) : if regex is None : self . manual_user_re = regex else : self . manual_user_re = to_regexs ( regex ) | Defines a pattern that is used to monitor the response of the connected host for a username prompt . |
24,376 | def set_password_prompt ( self , regex = None ) : if regex is None : self . manual_password_re = regex else : self . manual_password_re = to_regexs ( regex ) | Defines a pattern that is used to monitor the response of the connected host for a password prompt . |
24,377 | def set_login_error_prompt ( self , error = None ) : if error is None : self . manual_login_error_re = error else : self . manual_login_error_re = to_regexs ( error ) | Defines a pattern that is used to monitor the response of the connected host during the authentication procedure . If the pattern matches an error is raised . |
24,378 | def connect ( self , hostname = None , port = None ) : if hostname is not None : self . host = hostname conn = self . _connect_hook ( self . host , port ) self . os_guesser . protocol_info ( self . get_remote_version ( ) ) self . auto_driver = driver_map [ self . guess_os ( ) ] if self . get_banner ( ) : self . os_guesser . data_received ( self . get_banner ( ) , False ) return conn | Opens the connection to the remote host or IP address . |
24,379 | def protocol_authenticate ( self , account = None ) : with self . _get_account ( account ) as account : user = account . get_name ( ) password = account . get_password ( ) key = account . get_key ( ) if key is None : self . _dbg ( 1 , "Attempting to authenticate %s." % user ) self . _protocol_authenticate ( user , password ) else : self . _dbg ( 1 , "Authenticate %s with key." % user ) self . _protocol_authenticate_by_key ( user , key ) self . proto_authenticated = True | Low - level API to perform protocol - level authentication on protocols that support it . |
24,380 | def app_authenticate ( self , account = None , flush = True , bailout = False ) : with self . _get_account ( account ) as account : user = account . get_name ( ) password = account . get_password ( ) self . _dbg ( 1 , "Attempting to app-authenticate %s." % user ) self . _app_authenticate ( account , password , flush , bailout ) self . app_authenticated = True | Attempt to perform application - level authentication . Application level authentication is needed on devices where the username and password are requested from the user after the connection was already accepted by the remote device . |
24,381 | def add_monitor ( self , pattern , callback , limit = 80 ) : self . buffer . add_monitor ( pattern , partial ( callback , self ) , limit ) | Calls the given function whenever the given pattern matches the incoming data . |
24,382 | def _prepare_connection ( func ) : def _wrapped ( job , * args , ** kwargs ) : job_id = id ( job ) to_parent = job . data [ 'pipe' ] host = job . data [ 'host' ] mkaccount = partial ( _account_factory , to_parent , host ) pargs = { 'account_factory' : mkaccount , 'stdout' : job . data [ 'stdout' ] } pargs . update ( host . get_options ( ) ) conn = prepare ( host , ** pargs ) log_options = get_label ( func , 'log_to' ) if log_options is not None : proxy = LoggerProxy ( to_parent , log_options [ 'logger_id' ] ) log_cb = partial ( proxy . log , job_id ) proxy . add_log ( job_id , job . name , job . failures + 1 ) conn . data_received_event . listen ( log_cb ) try : conn . connect ( host . get_address ( ) , host . get_tcp_port ( ) ) result = func ( job , host , conn , * args , ** kwargs ) conn . close ( force = True ) except : proxy . log_aborted ( job_id , serializeable_sys_exc_info ( ) ) raise else : proxy . log_succeeded ( job_id ) finally : conn . data_received_event . disconnect ( log_cb ) else : conn . connect ( host . get_address ( ) , host . get_tcp_port ( ) ) result = func ( job , host , conn , * args , ** kwargs ) conn . close ( force = True ) return result return _wrapped | A decorator that unpacks the host and connection from the job argument and passes them as separate arguments to the wrapped function . |
24,383 | def join ( self ) : self . _dbg ( 2 , 'Waiting for the queue to finish.' ) self . workqueue . wait_until_done ( ) for child in list ( self . pipe_handlers . values ( ) ) : child . join ( ) self . _del_status_bar ( ) self . _print_status_bar ( ) gc . collect ( ) | Waits until all jobs are completed . |
24,384 | def shutdown ( self , force = False ) : if not force : self . join ( ) self . _dbg ( 2 , 'Shutting down queue...' ) self . workqueue . shutdown ( True ) self . _dbg ( 2 , 'Queue shut down.' ) self . _del_status_bar ( ) | Stop executing any further jobs . If the force argument is True the function does not wait until any queued jobs are completed but stops immediately . |
24,385 | def reset ( self ) : self . _dbg ( 2 , 'Resetting queue...' ) self . account_manager . reset ( ) self . workqueue . shutdown ( True ) self . completed = 0 self . total = 0 self . failed = 0 self . status_bar_length = 0 self . _dbg ( 2 , 'Queue reset.' ) self . _del_status_bar ( ) | Remove all accounts hosts etc . |
24,386 | def get ( scope , source , index ) : try : index = int ( index [ 0 ] ) except IndexError : raise ValueError ( 'index variable is required' ) except ValueError : raise ValueError ( 'index is not an integer' ) try : return [ source [ index ] ] except IndexError : raise ValueError ( 'no such item in the list' ) | Returns a copy of the list item with the given index . It is an error if an item with teh given index does not exist . |
24,387 | def execute ( scope , command ) : process = Popen ( command [ 0 ] , shell = True , stdin = PIPE , stdout = PIPE , stderr = STDOUT , close_fds = True ) scope . define ( __response__ = process . stdout . read ( ) ) return True | Executes the given command locally . |
24,388 | def set ( self , key , value , confidence = 100 ) : if value is None : return if key in self . info : old_confidence , old_value = self . info . get ( key ) if old_confidence >= confidence : return self . info [ key ] = ( confidence , value ) | Defines the given value with the given confidence unless the same value is already defined with a higher confidence level . |
24,389 | def get ( self , key , confidence = 0 ) : if key not in self . info : return None conf , value = self . info . get ( key ) if conf >= confidence : return value return None | Returns the info with the given key if it has at least the given confidence . Returns None otherwise . |
24,390 | def bind ( function , * args , ** kwargs ) : def decorated ( * inner_args , ** inner_kwargs ) : kwargs . update ( inner_kwargs ) return function ( * ( inner_args + args ) , ** kwargs ) copy_labels ( function , decorated ) return decorated | Wraps the given function such that when it is called the given arguments are passed in addition to the connection argument . |
24,391 | def problem_glob ( extension = '.py' ) : filenames = glob . glob ( '*[0-9][0-9][0-9]*{}' . format ( extension ) ) return [ ProblemFile ( file ) for file in filenames ] | Returns ProblemFile objects for all valid problem files |
24,392 | def human_time ( timespan , precision = 3 ) : if timespan >= 60.0 : def _format_long_time ( time ) : suffixes = ( 'd' , 'h' , 'm' , 's' ) lengths = ( 24 * 60 * 60 , 60 * 60 , 60 , 1 ) for suffix , length in zip ( suffixes , lengths ) : value = int ( time / length ) if value > 0 : time %= length yield '%i%s' % ( value , suffix ) if time < 1 : break return ' ' . join ( _format_long_time ( timespan ) ) else : units = [ 's' , 'ms' , 'us' , 'ns' ] if hasattr ( sys . stdout , 'encoding' ) and sys . stdout . encoding == 'UTF-8' : try : units [ 2 ] = b'\xc2\xb5s' . decode ( 'utf-8' ) except UnicodeEncodeError : pass scale = [ 1.0 , 1e3 , 1e6 , 1e9 ] if timespan > 0.0 : order = min ( - int ( math . floor ( math . log10 ( timespan ) ) // 3 ) , 3 ) else : order = 3 return '%.*g %s' % ( precision , timespan * scale [ order ] , units [ order ] ) | Formats the timespan in a human readable format |
24,393 | def format_time ( start , end ) : try : cpu_usr = end [ 0 ] - start [ 0 ] cpu_sys = end [ 1 ] - start [ 1 ] except TypeError : return 'Time elapsed: {}' . format ( human_time ( cpu_usr ) ) else : times = ( human_time ( x ) for x in ( cpu_usr , cpu_sys , cpu_usr + cpu_sys ) ) return 'Time elapsed: user: {}, sys: {}, total: {}' . format ( * times ) | Returns string with relevant time information formatted properly |
24,394 | def filename ( self , prefix = '' , suffix = '' , extension = '.py' ) : return BASE_NAME . format ( prefix , self . num , suffix , extension ) | Returns filename padded with leading zeros |
24,395 | def glob ( self ) : file_glob = glob . glob ( BASE_NAME . format ( '*' , self . num , '*' , '.*' ) ) return sorted ( file_glob , key = lambda f : os . path . splitext ( f ) ) | Returns a sorted glob of files belonging to a given problem |
24,396 | def copy_resources ( self ) : if not os . path . isdir ( 'resources' ) : os . mkdir ( 'resources' ) resource_dir = os . path . join ( os . getcwd ( ) , 'resources' , '' ) copied_resources = [ ] for resource in self . resources : src = os . path . join ( EULER_DATA , 'resources' , resource ) if os . path . isfile ( src ) : shutil . copy ( src , resource_dir ) copied_resources . append ( resource ) if copied_resources : copied = ', ' . join ( copied_resources ) path = os . path . relpath ( resource_dir , os . pardir ) msg = "Copied {} to {}." . format ( copied , path ) click . secho ( msg , fg = 'green' ) | Copies the relevant resources to a resources subdirectory |
24,397 | def solution ( self ) : num = self . num solution_file = os . path . join ( EULER_DATA , 'solutions.txt' ) solution_line = linecache . getline ( solution_file , num ) try : answer = solution_line . split ( '. ' ) [ 1 ] . strip ( ) except IndexError : answer = None if answer : return answer else : msg = 'Answer for problem %i not found in solutions.txt.' % num click . secho ( msg , fg = 'red' ) click . echo ( 'If you have an answer, consider submitting a pull ' 'request to EulerPy on GitHub.' ) sys . exit ( 1 ) | Returns the answer to a given problem |
24,398 | def text ( self ) : def _problem_iter ( problem_num ) : problem_file = os . path . join ( EULER_DATA , 'problems.txt' ) with open ( problem_file ) as f : is_problem = False last_line = '' for line in f : if line . strip ( ) == 'Problem %i' % problem_num : is_problem = True if is_problem : if line == last_line == '\n' : break else : yield line [ : - 1 ] last_line = line problem_lines = [ line for line in _problem_iter ( self . num ) ] if problem_lines : return '\n' . join ( problem_lines [ 3 : - 1 ] ) else : msg = 'Problem %i not found in problems.txt.' % self . num click . secho ( msg , fg = 'red' ) click . echo ( 'If this problem exists on Project Euler, consider ' 'submitting a pull request to EulerPy on GitHub.' ) sys . exit ( 1 ) | Parses problems . txt and returns problem text |
24,399 | def cheat ( num ) : solution = click . style ( Problem ( num ) . solution , bold = True ) click . confirm ( "View answer to problem %i?" % num , abort = True ) click . echo ( "The answer to problem {} is {}." . format ( num , solution ) ) | View the answer to a problem . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.