idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
26,400
def DEFINE_integer ( name , default , help , lower_bound = None , upper_bound = None , flag_values = _flagvalues . FLAGS , ** args ) : parser = _argument_parser . IntegerParser ( lower_bound , upper_bound ) serializer = _argument_parser . ArgumentSerializer ( ) DEFINE ( parser , name , default , help , flag_values , serializer , ** args ) _register_bounds_validator_if_needed ( parser , name , flag_values = flag_values )
Registers a flag whose value must be an integer .
26,401
def DEFINE_enum_class ( name , default , enum_class , help , flag_values = _flagvalues . FLAGS , module_name = None , ** args ) : DEFINE_flag ( _flag . EnumClassFlag ( name , default , help , enum_class , ** args ) , flag_values , module_name )
Registers a flag whose value can be the name of enum members .
26,402
def DEFINE_spaceseplist ( name , default , help , comma_compat = False , flag_values = _flagvalues . FLAGS , ** args ) : parser = _argument_parser . WhitespaceSeparatedListParser ( comma_compat = comma_compat ) serializer = _argument_parser . ListSerializer ( ' ' ) DEFINE ( parser , name , default , help , flag_values , serializer , ** args )
Registers a flag whose value is a whitespace - separated list of strings .
26,403
def DEFINE_multi_enum ( name , default , enum_values , help , flag_values = _flagvalues . FLAGS , case_sensitive = True , ** args ) : parser = _argument_parser . EnumParser ( enum_values , case_sensitive ) serializer = _argument_parser . ArgumentSerializer ( ) DEFINE_multi ( parser , serializer , name , default , help , flag_values , ** args )
Registers a flag whose value can be a list strings from enum_values .
26,404
def DEFINE_multi_enum_class ( name , default , enum_class , help , flag_values = _flagvalues . FLAGS , module_name = None , ** args ) : DEFINE_flag ( _flag . MultiEnumClassFlag ( name , default , help , enum_class ) , flag_values , module_name , ** args )
Registers a flag whose value can be a list of enum members .
26,405
def parse ( self , argument ) : if not isinstance ( argument , six . string_types ) : raise TypeError ( 'flag value must be a string, found "{}"' . format ( type ( argument ) ) ) return argument
Parses the string argument and returns the native value .
26,406
def is_outside_bounds ( self , val ) : return ( ( self . lower_bound is not None and val < self . lower_bound ) or ( self . upper_bound is not None and val > self . upper_bound ) )
Returns whether the value is outside the bounds or not .
26,407
def convert ( self , argument ) : if ( _is_integer_type ( argument ) or isinstance ( argument , float ) or isinstance ( argument , six . string_types ) ) : return float ( argument ) else : raise TypeError ( 'Expect argument to be a string, int, or float, found {}' . format ( type ( argument ) ) )
Returns the float value of argument .
26,408
def convert ( self , argument ) : if _is_integer_type ( argument ) : return argument elif isinstance ( argument , six . string_types ) : base = 10 if len ( argument ) > 2 and argument [ 0 ] == '0' : if argument [ 1 ] == 'o' : base = 8 elif argument [ 1 ] == 'x' : base = 16 return int ( argument , base ) else : raise TypeError ( 'Expect argument to be a string or int, found {}' . format ( type ( argument ) ) )
Returns the int value of argument .
26,409
def parse ( self , argument ) : if isinstance ( argument , self . enum_class ) : return argument if argument not in self . enum_class . __members__ : raise ValueError ( 'value should be one of <%s>' % '|' . join ( self . enum_class . __members__ . keys ( ) ) ) else : return self . enum_class [ argument ]
Determines validity of argument and returns the correct element of enum .
26,410
def parse ( self , argument ) : if isinstance ( argument , list ) : return argument elif not argument : return [ ] else : try : return [ s . strip ( ) for s in list ( csv . reader ( [ argument ] , strict = True ) ) [ 0 ] ] except csv . Error as e : raise ValueError ( 'Unable to parse the value %r as a %s: %s' % ( argument , self . flag_type ( ) , e ) )
Parses argument as comma - separated list of strings .
26,411
def parse ( self , argument ) : if isinstance ( argument , list ) : return argument elif not argument : return [ ] else : if self . _comma_compat : argument = argument . replace ( ',' , ' ' ) return argument . split ( )
Parses argument as whitespace - separated list of strings .
26,412
def set_gnu_getopt ( self , gnu_getopt = True ) : self . __dict__ [ '__use_gnu_getopt' ] = gnu_getopt self . __dict__ [ '__use_gnu_getopt_explicitly_set' ] = True
Sets whether or not to use GNU style scanning .
26,413
def _assert_validators ( self , validators ) : for validator in sorted ( validators , key = lambda validator : validator . insertion_index ) : try : validator . verify ( self ) except _exceptions . ValidationError as e : message = validator . print_flags_with_values ( self ) raise _exceptions . IllegalFlagValueError ( '%s: %s' % ( message , str ( e ) ) )
Asserts if all validators in the list are satisfied .
26,414
def set_default ( self , name , value ) : fl = self . _flags ( ) if name not in fl : self . _set_unknown_flag ( name , value ) return fl [ name ] . _set_default ( value ) self . _assert_validators ( fl [ name ] . validators )
Changes the default value of the named flag object .
26,415
def flag_values_dict ( self ) : return { name : flag . value for name , flag in six . iteritems ( self . _flags ( ) ) }
Returns a dictionary that maps flag names to flag values .
26,416
def get_help ( self , prefix = '' , include_special_flags = True ) : flags_by_module = self . flags_by_module_dict ( ) if flags_by_module : modules = sorted ( flags_by_module ) main_module = sys . argv [ 0 ] if main_module in modules : modules . remove ( main_module ) modules = [ main_module ] + modules return self . _get_help_for_modules ( modules , prefix , include_special_flags ) else : output_lines = [ ] values = six . itervalues ( self . _flags ( ) ) if include_special_flags : values = itertools . chain ( values , six . itervalues ( _helpers . SPECIAL_FLAGS . _flags ( ) ) ) self . _render_flag_list ( values , output_lines , prefix ) return '\n' . join ( output_lines )
Returns a help string for all known flags .
26,417
def _get_help_for_modules ( self , modules , prefix , include_special_flags ) : output_lines = [ ] for module in modules : self . _render_our_module_flags ( module , output_lines , prefix ) if include_special_flags : self . _render_module_flags ( 'absl.flags' , six . itervalues ( _helpers . SPECIAL_FLAGS . _flags ( ) ) , output_lines , prefix ) return '\n' . join ( output_lines )
Returns the help string for a list of modules .
26,418
def _render_our_module_key_flags ( self , module , output_lines , prefix = '' ) : key_flags = self . get_key_flags_for_module ( module ) if key_flags : self . _render_module_flags ( module , key_flags , output_lines , prefix )
Returns a help string for the key flags of a given module .
26,419
def module_help ( self , module ) : helplist = [ ] self . _render_our_module_key_flags ( module , helplist ) return '\n' . join ( helplist )
Describes the key flags of a module .
26,420
def write_help_in_xml_format ( self , outfile = None ) : doc = minidom . Document ( ) all_flag = doc . createElement ( 'AllFlags' ) doc . appendChild ( all_flag ) all_flag . appendChild ( _helpers . create_xml_dom_element ( doc , 'program' , os . path . basename ( sys . argv [ 0 ] ) ) ) usage_doc = sys . modules [ '__main__' ] . __doc__ if not usage_doc : usage_doc = '\nUSAGE: %s [flags]\n' % sys . argv [ 0 ] else : usage_doc = usage_doc . replace ( '%s' , sys . argv [ 0 ] ) all_flag . appendChild ( _helpers . create_xml_dom_element ( doc , 'usage' , usage_doc ) ) key_flags = self . get_key_flags_for_module ( sys . argv [ 0 ] ) flags_by_module = self . flags_by_module_dict ( ) all_module_names = list ( flags_by_module . keys ( ) ) all_module_names . sort ( ) for module_name in all_module_names : flag_list = [ ( f . name , f ) for f in flags_by_module [ module_name ] ] flag_list . sort ( ) for unused_flag_name , flag in flag_list : is_key = flag in key_flags all_flag . appendChild ( flag . _create_xml_dom_element ( doc , module_name , is_key = is_key ) ) outfile = outfile or sys . stdout if six . PY2 : outfile . write ( doc . toprettyxml ( indent = ' ' , encoding = 'utf-8' ) ) else : outfile . write ( doc . toprettyxml ( indent = ' ' , encoding = 'utf-8' ) . decode ( 'utf-8' ) ) outfile . flush ( )
Outputs flag documentation in XML format .
26,421
def absl_to_cpp ( level ) : if not isinstance ( level , int ) : raise TypeError ( 'Expect an int level, found {}' . format ( type ( level ) ) ) if level >= 0 : return 0 else : return - level
Converts an absl log level to a cpp log level .
26,422
def absl_to_standard ( level ) : if not isinstance ( level , int ) : raise TypeError ( 'Expect an int level, found {}' . format ( type ( level ) ) ) if level < ABSL_FATAL : level = ABSL_FATAL if level <= ABSL_DEBUG : return ABSL_TO_STANDARD [ level ] return STANDARD_DEBUG - level + 1
Converts an integer level from the absl value to the standard value .
26,423
def standard_to_absl ( level ) : if not isinstance ( level , int ) : raise TypeError ( 'Expect an int level, found {}' . format ( type ( level ) ) ) if level < 0 : level = 0 if level < STANDARD_DEBUG : return STANDARD_DEBUG - level + 1 elif level < STANDARD_INFO : return ABSL_DEBUG elif level < STANDARD_WARNING : return ABSL_INFO elif level < STANDARD_ERROR : return ABSL_WARNING elif level < STANDARD_CRITICAL : return ABSL_ERROR else : return ABSL_FATAL
Converts an integer level from the standard value to the absl value .
26,424
def parse_flags_with_usage ( args ) : try : return FLAGS ( args ) except flags . Error as error : sys . stderr . write ( 'FATAL Flags parsing error: %s\n' % error ) sys . stderr . write ( 'Pass --helpshort or --helpfull to see help on flags.\n' ) sys . exit ( 1 )
Tries to parse the flags print usage and exit if unparseable .
26,425
def define_help_flags ( ) : global _define_help_flags_called if not _define_help_flags_called : flags . DEFINE_flag ( HelpFlag ( ) ) flags . DEFINE_flag ( HelpshortFlag ( ) ) flags . DEFINE_flag ( HelpfullFlag ( ) ) flags . DEFINE_flag ( HelpXMLFlag ( ) ) _define_help_flags_called = True
Registers help flags . Idempotent .
26,426
def _register_and_parse_flags_with_usage ( argv = None , flags_parser = parse_flags_with_usage , ) : if _register_and_parse_flags_with_usage . done : raise SystemError ( 'Flag registration can be done only once.' ) define_help_flags ( ) original_argv = sys . argv if argv is None else argv args_to_main = flags_parser ( original_argv ) if not FLAGS . is_parsed ( ) : raise Error ( 'FLAGS must be parsed after flags_parser is called.' ) if FLAGS . only_check_args : sys . exit ( 0 ) if FLAGS [ 'verbosity' ] . using_default_value : FLAGS . verbosity = 0 _register_and_parse_flags_with_usage . done = True return args_to_main
Registers help flags parses arguments and shows usage if appropriate .
26,427
def _run_main ( main , argv ) : if FLAGS . run_with_pdb : sys . exit ( pdb . runcall ( main , argv ) ) elif FLAGS . run_with_profiling or FLAGS . profile_file : import atexit if FLAGS . use_cprofile_for_profiling : import cProfile as profile else : import profile profiler = profile . Profile ( ) if FLAGS . profile_file : atexit . register ( profiler . dump_stats , FLAGS . profile_file ) else : atexit . register ( profiler . print_stats ) retval = profiler . runcall ( main , argv ) sys . exit ( retval ) else : sys . exit ( main ( argv ) )
Calls main optionally with pdb or profiler .
26,428
def _call_exception_handlers ( exception ) : for handler in EXCEPTION_HANDLERS : try : if handler . wants ( exception ) : handler . handle ( exception ) except : try : logging . error ( traceback . format_exc ( ) ) except : pass
Calls any installed exception handlers .
26,429
def run ( main , argv = None , flags_parser = parse_flags_with_usage , ) : try : args = _run_init ( sys . argv if argv is None else argv , flags_parser , ) while _init_callbacks : callback = _init_callbacks . popleft ( ) callback ( ) try : _run_main ( main , args ) except UsageError as error : usage ( shorthelp = True , detailed_error = error , exitcode = error . exitcode ) except : if FLAGS . pdb_post_mortem : traceback . print_exc ( ) pdb . post_mortem ( ) raise except Exception as e : _call_exception_handlers ( e ) raise
Begins executing the program .
26,430
def _run_init ( argv , flags_parser , ) : if _run_init . done : return flags_parser ( argv ) command_name . make_process_name_useful ( ) logging . use_absl_handler ( ) args = _register_and_parse_flags_with_usage ( argv = argv , flags_parser = flags_parser , ) if faulthandler : try : faulthandler . enable ( ) except Exception : pass _run_init . done = True return args
Does one - time initialization and re - parses flags on rerun .
26,431
def install_exception_handler ( handler ) : if not isinstance ( handler , ExceptionHandler ) : raise TypeError ( 'handler of type %s does not inherit from ExceptionHandler' % type ( handler ) ) EXCEPTION_HANDLERS . append ( handler )
Installs an exception handler .
26,432
def register_validator ( flag_name , checker , message = 'Flag validation failed' , flag_values = _flagvalues . FLAGS ) : v = SingleFlagValidator ( flag_name , checker , message ) _add_validator ( flag_values , v )
Adds a constraint which will be enforced during program execution .
26,433
def validator ( flag_name , message = 'Flag validation failed' , flag_values = _flagvalues . FLAGS ) : def decorate ( function ) : register_validator ( flag_name , function , message = message , flag_values = flag_values ) return function return decorate
A function decorator for defining a flag validator .
26,434
def mark_flags_as_required ( flag_names , flag_values = _flagvalues . FLAGS ) : for flag_name in flag_names : mark_flag_as_required ( flag_name , flag_values )
Ensures that flags are not None during program execution .
26,435
def mark_flags_as_mutual_exclusive ( flag_names , required = False , flag_values = _flagvalues . FLAGS ) : for flag_name in flag_names : if flag_values [ flag_name ] . default is not None : warnings . warn ( 'Flag --{} has a non-None default value. That does not make sense ' 'with mark_flags_as_mutual_exclusive, which checks whether the ' 'listed flags have a value other than None.' . format ( flag_name ) ) def validate_mutual_exclusion ( flags_dict ) : flag_count = sum ( 1 for val in flags_dict . values ( ) if val is not None ) if flag_count == 1 or ( not required and flag_count == 0 ) : return True raise _exceptions . ValidationError ( '{} one of ({}) must have a value other than None.' . format ( 'Exactly' if required else 'At most' , ', ' . join ( flag_names ) ) ) register_multi_flags_validator ( flag_names , validate_mutual_exclusion , flag_values = flag_values )
Ensures that only one flag among flag_names is not None .
26,436
def mark_bool_flags_as_mutual_exclusive ( flag_names , required = False , flag_values = _flagvalues . FLAGS ) : for flag_name in flag_names : if not flag_values [ flag_name ] . boolean : raise _exceptions . ValidationError ( 'Flag --{} is not Boolean, which is required for flags used in ' 'mark_bool_flags_as_mutual_exclusive.' . format ( flag_name ) ) def validate_boolean_mutual_exclusion ( flags_dict ) : flag_count = sum ( bool ( val ) for val in flags_dict . values ( ) ) if flag_count == 1 or ( not required and flag_count == 0 ) : return True raise _exceptions . ValidationError ( '{} one of ({}) must be True.' . format ( 'Exactly' if required else 'At most' , ', ' . join ( flag_names ) ) ) register_multi_flags_validator ( flag_names , validate_boolean_mutual_exclusion , flag_values = flag_values )
Ensures that only one flag among flag_names is True .
26,437
def _add_validator ( fv , validator_instance ) : for flag_name in validator_instance . get_flags_names ( ) : fv [ flag_name ] . validators . append ( validator_instance )
Register new flags validator to be checked .
26,438
def verify ( self , flag_values ) : param = self . _get_input_to_checker_function ( flag_values ) if not self . checker ( param ) : raise _exceptions . ValidationError ( self . message )
Verifies that constraint is satisfied .
26,439
def _get_input_to_checker_function ( self , flag_values ) : return dict ( [ key , flag_values [ key ] . value ] for key in self . flag_names )
Given flag values returns the input to be given to checker .
26,440
def from_flag ( cls , flagname , flag_values , other_flag_values = None ) : first_module = flag_values . find_module_defining_flag ( flagname , default = '<unknown>' ) if other_flag_values is None : second_module = _helpers . get_calling_module ( ) else : second_module = other_flag_values . find_module_defining_flag ( flagname , default = '<unknown>' ) flag_summary = flag_values [ flagname ] . help msg = ( "The flag '%s' is defined twice. First from %s, Second from %s. " "Description from first occurrence: %s" ) % ( flagname , first_module , second_module , flag_summary ) return cls ( msg )
Creates a DuplicateFlagError by providing flag name and values .
26,441
def set_verbosity ( v ) : try : new_level = int ( v ) except ValueError : new_level = converter . ABSL_NAMES [ v . upper ( ) ] FLAGS . verbosity = new_level
Sets the logging verbosity .
26,442
def set_stderrthreshold ( s ) : if s in converter . ABSL_LEVELS : FLAGS . stderrthreshold = converter . ABSL_LEVELS [ s ] elif isinstance ( s , str ) and s . upper ( ) in converter . ABSL_NAMES : FLAGS . stderrthreshold = s else : raise ValueError ( 'set_stderrthreshold only accepts integer absl logging level ' 'from -3 to 1, or case-insensitive string values ' "'debug', 'info', 'warning', 'error', and 'fatal'. " 'But found "{}" ({}).' . format ( s , type ( s ) ) )
Sets the stderr threshold to the value passed in .
26,443
def log_every_n ( level , msg , n , * args ) : count = _get_next_log_count_per_token ( get_absl_logger ( ) . findCaller ( ) ) log_if ( level , msg , not ( count % n ) , * args )
Logs msg % args at level level once per n times .
26,444
def _seconds_have_elapsed ( token , num_seconds ) : now = timeit . default_timer ( ) then = _log_timer_per_token . get ( token , None ) if then is None or ( now - then ) >= num_seconds : _log_timer_per_token [ token ] = now return True else : return False
Tests if num_seconds have passed since token was requested .
26,445
def log_every_n_seconds ( level , msg , n_seconds , * args ) : should_log = _seconds_have_elapsed ( get_absl_logger ( ) . findCaller ( ) , n_seconds ) log_if ( level , msg , should_log , * args )
Logs msg % args at level level iff n_seconds elapsed since last call .
26,446
def log_if ( level , msg , condition , * args ) : if condition : log ( level , msg , * args )
Logs msg % args at level level only if condition is fulfilled .
26,447
def log ( level , msg , * args , ** kwargs ) : if level > converter . ABSL_DEBUG : standard_level = converter . STANDARD_DEBUG - ( level - 1 ) else : if level < converter . ABSL_FATAL : level = converter . ABSL_FATAL standard_level = converter . absl_to_standard ( level ) _absl_logger . log ( standard_level , msg , * args , ** kwargs )
Logs msg % args at absl logging level level .
26,448
def vlog_is_on ( level ) : if level > converter . ABSL_DEBUG : standard_level = converter . STANDARD_DEBUG - ( level - 1 ) else : if level < converter . ABSL_FATAL : level = converter . ABSL_FATAL standard_level = converter . absl_to_standard ( level ) return _absl_logger . isEnabledFor ( standard_level )
Checks if vlog is enabled for the given level in caller s source file .
26,449
def get_log_file_name ( level = INFO ) : if level not in converter . ABSL_LEVELS : raise ValueError ( 'Invalid absl.logging level {}' . format ( level ) ) stream = get_absl_handler ( ) . python_handler . stream if ( stream == sys . stderr or stream == sys . stdout or not hasattr ( stream , 'name' ) ) : return '' else : return stream . name
Returns the name of the log file .
26,450
def find_log_dir_and_names ( program_name = None , log_dir = None ) : if not program_name : program_name = os . path . splitext ( os . path . basename ( sys . argv [ 0 ] ) ) [ 0 ] program_name = 'py_%s' % program_name actual_log_dir = find_log_dir ( log_dir = log_dir ) try : username = getpass . getuser ( ) except KeyError : if hasattr ( os , 'getuid' ) : username = str ( os . getuid ( ) ) else : username = 'unknown' hostname = socket . gethostname ( ) file_prefix = '%s.%s.%s.log' % ( program_name , hostname , username ) return actual_log_dir , file_prefix , program_name
Computes the directory and filename prefix for log file .
26,451
def find_log_dir ( log_dir = None ) : if log_dir : dirs = [ log_dir ] elif FLAGS [ 'log_dir' ] . value : dirs = [ FLAGS [ 'log_dir' ] . value ] else : dirs = [ '/tmp/' , './' ] for d in dirs : if os . path . isdir ( d ) and os . access ( d , os . W_OK ) : return d _absl_logger . fatal ( "Can't find a writable directory for logs, tried %s" , dirs )
Returns the most suitable directory to put log files into .
26,452
def get_absl_log_prefix ( record ) : created_tuple = time . localtime ( record . created ) created_microsecond = int ( record . created % 1.0 * 1e6 ) critical_prefix = '' level = record . levelno if _is_non_absl_fatal_record ( record ) : level = logging . ERROR critical_prefix = _CRITICAL_PREFIX severity = converter . get_initial_for_level ( level ) return '%c%02d%02d %02d:%02d:%02d.%06d %5d %s:%d] %s' % ( severity , created_tuple . tm_mon , created_tuple . tm_mday , created_tuple . tm_hour , created_tuple . tm_min , created_tuple . tm_sec , created_microsecond , _get_thread_id ( ) , record . filename , record . lineno , critical_prefix )
Returns the absl log prefix for the log record .
26,453
def skip_log_prefix ( func ) : if callable ( func ) : func_code = getattr ( func , '__code__' , None ) if func_code is None : raise ValueError ( 'Input callable does not have a function code object.' ) file_name = func_code . co_filename func_name = func_code . co_name func_lineno = func_code . co_firstlineno elif isinstance ( func , six . string_types ) : file_name = get_absl_logger ( ) . findCaller ( ) [ 0 ] func_name = func func_lineno = None else : raise TypeError ( 'Input is neither callable nor a string.' ) ABSLLogger . register_frame_to_skip ( file_name , func_name , func_lineno ) return func
Skips reporting the prefix of a given function or name by ABSLLogger .
26,454
def use_absl_handler ( ) : absl_handler = get_absl_handler ( ) if absl_handler not in logging . root . handlers : logging . root . addHandler ( absl_handler ) FLAGS [ 'verbosity' ] . _update_logging_levels ( )
Uses the ABSL logging handler for logging if not yet configured .
26,455
def _initialize ( ) : global _absl_logger , _absl_handler if _absl_logger : return original_logger_class = logging . getLoggerClass ( ) logging . setLoggerClass ( ABSLLogger ) _absl_logger = logging . getLogger ( 'absl' ) logging . setLoggerClass ( original_logger_class ) python_logging_formatter = PythonFormatter ( ) _absl_handler = ABSLHandler ( python_logging_formatter ) handlers = [ h for h in logging . root . handlers if isinstance ( h , logging . StreamHandler ) and h . stream == sys . stderr ] for h in handlers : logging . root . removeHandler ( h ) if not logging . root . handlers : logging . root . addHandler ( _absl_handler )
Initializes loggers and handlers .
26,456
def _update_logging_levels ( self ) : if not _absl_logger : return if self . _value <= converter . ABSL_DEBUG : standard_verbosity = converter . absl_to_standard ( self . _value ) else : standard_verbosity = logging . DEBUG - ( self . _value - 1 ) if _absl_handler in logging . root . handlers : logging . root . setLevel ( standard_verbosity )
Updates absl logging levels to the current verbosity .
26,457
def start_logging_to_file ( self , program_name = None , log_dir = None ) : FLAGS . logtostderr = False actual_log_dir , file_prefix , symlink_prefix = find_log_dir_and_names ( program_name = program_name , log_dir = log_dir ) basename = '%s.INFO.%s.%d' % ( file_prefix , time . strftime ( '%Y%m%d-%H%M%S' , time . localtime ( time . time ( ) ) ) , os . getpid ( ) ) filename = os . path . join ( actual_log_dir , basename ) if six . PY2 : self . stream = open ( filename , 'a' ) else : self . stream = open ( filename , 'a' , encoding = 'utf-8' ) if getattr ( os , 'symlink' , None ) : symlink = os . path . join ( actual_log_dir , symlink_prefix + '.INFO' ) try : if os . path . islink ( symlink ) : os . unlink ( symlink ) os . symlink ( os . path . basename ( filename ) , symlink ) except EnvironmentError : pass
Starts logging messages to files instead of standard error .
26,458
def flush ( self ) : self . acquire ( ) try : self . stream . flush ( ) except ( EnvironmentError , ValueError ) : pass finally : self . release ( )
Flushes all log files .
26,459
def _log_to_stderr ( self , record ) : old_stream = self . stream self . stream = sys . stderr try : super ( PythonHandler , self ) . emit ( record ) finally : self . stream = old_stream
Emits the record to stderr .
26,460
def emit ( self , record ) : level = record . levelno if not FLAGS . is_parsed ( ) : global _warn_preinit_stderr if _warn_preinit_stderr : sys . stderr . write ( 'WARNING: Logging before flag parsing goes to stderr.\n' ) _warn_preinit_stderr = False self . _log_to_stderr ( record ) elif FLAGS [ 'logtostderr' ] . value : self . _log_to_stderr ( record ) else : super ( PythonHandler , self ) . emit ( record ) stderr_threshold = converter . string_to_standard ( FLAGS [ 'stderrthreshold' ] . value ) if ( ( FLAGS [ 'alsologtostderr' ] . value or level >= stderr_threshold ) and self . stream != sys . stderr ) : self . _log_to_stderr ( record ) if _is_absl_fatal_record ( record ) : self . flush ( ) os . abort ( )
Prints a record out to some streams .
26,461
def close ( self ) : self . acquire ( ) try : self . flush ( ) try : if self . stream not in ( sys . stderr , sys . stdout ) and ( not hasattr ( self . stream , 'isatty' ) or not self . stream . isatty ( ) ) : self . stream . close ( ) except ValueError : pass super ( PythonHandler , self ) . close ( ) finally : self . release ( )
Closes the stream to which we are writing .
26,462
def format ( self , record ) : if ( not FLAGS [ 'showprefixforinfo' ] . value and FLAGS [ 'verbosity' ] . value == converter . ABSL_INFO and record . levelno == logging . INFO and _absl_handler . python_handler . stream == sys . stderr ) : prefix = '' else : prefix = get_absl_log_prefix ( record ) return prefix + super ( PythonFormatter , self ) . format ( record )
Appends the message from the record to the results of the prefix .
26,463
def findCaller ( self , stack_info = False ) : f_to_skip = ABSLLogger . _frames_to_skip frame = sys . _getframe ( 2 ) while frame : code = frame . f_code if ( _LOGGING_FILE_PREFIX not in code . co_filename and ( code . co_filename , code . co_name , code . co_firstlineno ) not in f_to_skip and ( code . co_filename , code . co_name ) not in f_to_skip ) : if six . PY2 and not stack_info : return ( code . co_filename , frame . f_lineno , code . co_name ) else : sinfo = None if stack_info : out = io . StringIO ( ) out . write ( u'Stack (most recent call last):\n' ) traceback . print_stack ( frame , file = out ) sinfo = out . getvalue ( ) . rstrip ( u'\n' ) return ( code . co_filename , frame . f_lineno , code . co_name , sinfo ) frame = frame . f_back
Finds the frame of the calling method on the stack .
26,464
def fatal ( self , msg , * args , ** kwargs ) : self . log ( logging . FATAL , msg , * args , ** kwargs )
Logs msg % args with severity FATAL .
26,465
def warn ( self , msg , * args , ** kwargs ) : if six . PY3 : warnings . warn ( "The 'warn' method is deprecated, use 'warning' instead" , DeprecationWarning , 2 ) self . log ( logging . WARN , msg , * args , ** kwargs )
Logs msg % args with severity WARN .
26,466
def log ( self , level , msg , * args , ** kwargs ) : if level >= logging . FATAL : extra = kwargs . setdefault ( 'extra' , { } ) extra [ _ABSL_LOG_FATAL ] = True super ( ABSLLogger , self ) . log ( level , msg , * args , ** kwargs )
Logs a message at a cetain level substituting in the supplied arguments .
26,467
def register_frame_to_skip ( cls , file_name , function_name , line_number = None ) : if line_number is not None : cls . _frames_to_skip . add ( ( file_name , function_name , line_number ) ) else : cls . _frames_to_skip . add ( ( file_name , function_name ) )
Registers a function name to skip when walking the stack .
26,468
def _is_undefok ( arg , undefok_names ) : if not arg . startswith ( '-' ) : return False if arg . startswith ( '--' ) : arg_without_dash = arg [ 2 : ] else : arg_without_dash = arg [ 1 : ] if '=' in arg_without_dash : name , _ = arg_without_dash . split ( '=' , 1 ) else : name = arg_without_dash if name in undefok_names : return True return False
Returns whether we can ignore arg based on a set of undefok flag names .
26,469
def _define_absl_flags ( self , absl_flags ) : key_flags = set ( absl_flags . get_key_flags_for_module ( sys . argv [ 0 ] ) ) for name in absl_flags : if name in _BUILT_IN_FLAGS : continue flag_instance = absl_flags [ name ] if name == flag_instance . name : suppress = flag_instance not in key_flags self . _define_absl_flag ( flag_instance , suppress )
Defines flags from absl_flags .
26,470
def _define_absl_flag ( self , flag_instance , suppress ) : flag_name = flag_instance . name short_name = flag_instance . short_name argument_names = [ '--' + flag_name ] if short_name : argument_names . insert ( 0 , '-' + short_name ) if suppress : helptext = argparse . SUPPRESS else : helptext = flag_instance . help . replace ( '%' , '%%' ) if flag_instance . boolean : argument_names . append ( '--no' + flag_name ) self . add_argument ( * argument_names , action = _BooleanFlagAction , help = helptext , metavar = flag_instance . name . upper ( ) , flag_instance = flag_instance ) else : self . add_argument ( * argument_names , action = _FlagAction , help = helptext , metavar = flag_instance . name . upper ( ) , flag_instance = flag_instance )
Defines a flag from the flag_instance .
26,471
def get_module_object_and_name ( globals_dict ) : name = globals_dict . get ( '__name__' , None ) module = sys . modules . get ( name , None ) return _ModuleObjectAndName ( module , ( sys . argv [ 0 ] if name == '__main__' else name ) )
Returns the module that defines a global environment and its name .
26,472
def create_xml_dom_element ( doc , name , value ) : s = str_or_unicode ( value ) if six . PY2 and not isinstance ( s , unicode ) : s = s . decode ( 'utf-8' , 'ignore' ) if isinstance ( value , bool ) : s = s . lower ( ) s = _ILLEGAL_XML_CHARS_REGEX . sub ( u'' , s ) e = doc . createElement ( name ) e . appendChild ( doc . createTextNode ( s ) ) return e
Returns an XML DOM element with name and text value .
26,473
def get_help_width ( ) : if not sys . stdout . isatty ( ) or termios is None or fcntl is None : return _DEFAULT_HELP_WIDTH try : data = fcntl . ioctl ( sys . stdout , termios . TIOCGWINSZ , '1234' ) columns = struct . unpack ( 'hh' , data ) [ 1 ] if columns >= _MIN_HELP_WIDTH : return columns return int ( os . getenv ( 'COLUMNS' , _DEFAULT_HELP_WIDTH ) ) except ( TypeError , IOError , struct . error ) : return _DEFAULT_HELP_WIDTH
Returns the integer width of help lines that is used in TextWrap .
26,474
def get_flag_suggestions ( attempt , longopt_list ) : if len ( attempt ) <= 2 or not longopt_list : return [ ] option_names = [ v . split ( '=' ) [ 0 ] for v in longopt_list ] distances = [ ( _damerau_levenshtein ( attempt , option [ 0 : len ( attempt ) ] ) , option ) for option in option_names ] distances . sort ( ) least_errors , _ = distances [ 0 ] if least_errors >= _SUGGESTION_ERROR_RATE_THRESHOLD * len ( attempt ) : return [ ] suggestions = [ ] for errors , name in distances : if errors == least_errors : suggestions . append ( name ) else : break return suggestions
Returns helpful similar matches for an invalid flag .
26,475
def _damerau_levenshtein ( a , b ) : memo = { } def distance ( x , y ) : if ( x , y ) in memo : return memo [ x , y ] if not x : d = len ( y ) elif not y : d = len ( x ) else : d = min ( distance ( x [ 1 : ] , y ) + 1 , distance ( x , y [ 1 : ] ) + 1 , distance ( x [ 1 : ] , y [ 1 : ] ) + ( x [ 0 ] != y [ 0 ] ) ) if len ( x ) >= 2 and len ( y ) >= 2 and x [ 0 ] == y [ 1 ] and x [ 1 ] == y [ 0 ] : t = distance ( x [ 2 : ] , y [ 2 : ] ) + 1 if d > t : d = t memo [ x , y ] = d return d return distance ( a , b )
Returns Damerau - Levenshtein edit distance from a to b .
26,476
def text_wrap ( text , length = None , indent = '' , firstline_indent = None ) : if length is None : length = get_help_width ( ) if indent is None : indent = '' if firstline_indent is None : firstline_indent = indent if len ( indent ) >= length : raise ValueError ( 'Length of indent exceeds length' ) if len ( firstline_indent ) >= length : raise ValueError ( 'Length of first line indent exceeds length' ) text = text . expandtabs ( 4 ) result = [ ] wrapper = textwrap . TextWrapper ( width = length , initial_indent = firstline_indent , subsequent_indent = indent ) subsequent_wrapper = textwrap . TextWrapper ( width = length , initial_indent = indent , subsequent_indent = indent ) for paragraph in ( p . strip ( ) for p in text . splitlines ( ) ) : if paragraph : result . extend ( wrapper . wrap ( paragraph ) ) else : result . append ( '' ) wrapper = subsequent_wrapper return '\n' . join ( result )
Wraps a given text to a maximum line length and returns it .
26,477
def trim_docstring ( docstring ) : if not docstring : return '' max_indent = 1 << 29 lines = docstring . expandtabs ( ) . splitlines ( ) indent = max_indent for line in lines [ 1 : ] : stripped = line . lstrip ( ) if stripped : indent = min ( indent , len ( line ) - len ( stripped ) ) trimmed = [ lines [ 0 ] . strip ( ) ] if indent < max_indent : for line in lines [ 1 : ] : trimmed . append ( line [ indent : ] . rstrip ( ) ) while trimmed and not trimmed [ - 1 ] : trimmed . pop ( ) while trimmed and not trimmed [ 0 ] : trimmed . pop ( 0 ) return '\n' . join ( trimmed )
Removes indentation from triple - quoted strings .
26,478
def invoke ( self , request_envelope , context ) : if ( self . skill_id is not None and request_envelope . context . system . application . application_id != self . skill_id ) : raise AskSdkException ( "Skill ID Verification failed!!" ) if self . api_client is not None : api_token = request_envelope . context . system . api_access_token api_endpoint = request_envelope . context . system . api_endpoint api_configuration = ApiConfiguration ( serializer = self . serializer , api_client = self . api_client , authorization_value = api_token , api_endpoint = api_endpoint ) factory = ServiceClientFactory ( api_configuration = api_configuration ) else : factory = None attributes_manager = AttributesManager ( request_envelope = request_envelope , persistence_adapter = self . persistence_adapter ) handler_input = HandlerInput ( request_envelope = request_envelope , attributes_manager = attributes_manager , context = context , service_client_factory = factory ) response = self . request_dispatcher . dispatch ( handler_input = handler_input ) session_attributes = None if request_envelope . session is not None : session_attributes = ( handler_input . attributes_manager . session_attributes ) return ResponseEnvelope ( response = response , version = RESPONSE_FORMAT_VERSION , session_attributes = session_attributes , user_agent = user_agent_info ( sdk_version = __version__ , custom_user_agent = self . custom_user_agent ) )
Invokes the dispatcher to handle the request envelope and return a response envelope .
26,479
def dispatch ( self , request , * args , ** kwargs ) : return super ( SkillAdapter , self ) . dispatch ( request )
Inspect the HTTP method and delegate to the view method .
26,480
def post ( self , request , * args , ** kwargs ) : try : content = request . body . decode ( verifier_constants . CHARACTER_ENCODING ) response = self . _webservice_handler . verify_request_and_dispatch ( http_request_headers = request . META , http_request_body = content ) return JsonResponse ( data = response , safe = False ) except VerificationException : logger . exception ( msg = "Request verification failed" ) return HttpResponseBadRequest ( content = "Incoming request failed verification" ) except AskSdkException : logger . exception ( msg = "Skill dispatch exception" ) return HttpResponseServerError ( content = "Exception occurred during skill dispatch" )
The method that handles HTTP POST request on the view .
26,481
def get_orientation ( width , height ) : if width > height : return Orientation . LANDSCAPE elif width < height : return Orientation . PORTRAIT else : return Orientation . EQUAL
Get viewport orientation from given width and height .
26,482
def get_size ( size ) : if size in range ( 0 , 600 ) : return Size . XSMALL elif size in range ( 600 , 960 ) : return Size . SMALL elif size in range ( 960 , 1280 ) : return Size . MEDIUM elif size in range ( 1280 , 1920 ) : return Size . LARGE elif size >= 1920 : return Size . XLARGE raise AskSdkException ( "Unknown size group value: {}" . format ( size ) )
Get viewport size from given size .
26,483
def get_dpi_group ( dpi ) : if dpi in range ( 0 , 121 ) : return Density . XLOW elif dpi in range ( 121 , 161 ) : return Density . LOW elif dpi in range ( 161 , 241 ) : return Density . MEDIUM elif dpi in range ( 241 , 321 ) : return Density . HIGH elif dpi in range ( 321 , 481 ) : return Density . XHIGH elif dpi >= 481 : return Density . XXHIGH raise AskSdkException ( "Unknown dpi group value: {}" . format ( dpi ) )
Get viewport density group from given dpi .
26,484
def get_viewport_profile ( request_envelope ) : viewport_state = request_envelope . context . viewport if viewport_state : shape = viewport_state . shape current_pixel_width = int ( viewport_state . current_pixel_width ) current_pixel_height = int ( viewport_state . current_pixel_height ) dpi = int ( viewport_state . dpi ) orientation = get_orientation ( width = current_pixel_width , height = current_pixel_height ) dpi_group = get_dpi_group ( dpi = dpi ) pixel_width_size_group = get_size ( size = current_pixel_width ) pixel_height_size_group = get_size ( size = current_pixel_height ) if ( shape is Shape . ROUND and orientation is Orientation . EQUAL and dpi_group is Density . LOW and pixel_width_size_group is Size . XSMALL and pixel_height_size_group is Size . XSMALL ) : return ViewportProfile . HUB_ROUND_SMALL elif ( shape is Shape . RECTANGLE and orientation is Orientation . LANDSCAPE and dpi_group is Density . LOW and pixel_width_size_group <= Size . MEDIUM and pixel_height_size_group <= Size . SMALL ) : return ViewportProfile . HUB_LANDSCAPE_MEDIUM elif ( shape is Shape . RECTANGLE and orientation is Orientation . LANDSCAPE and dpi_group is Density . LOW and pixel_width_size_group >= Size . LARGE and pixel_height_size_group >= Size . SMALL ) : return ViewportProfile . HUB_LANDSCAPE_LARGE elif ( shape is Shape . RECTANGLE and orientation is Orientation . LANDSCAPE and dpi_group is Density . MEDIUM and pixel_width_size_group >= Size . MEDIUM and pixel_height_size_group >= Size . SMALL ) : return ViewportProfile . MOBILE_LANDSCAPE_MEDIUM elif ( shape is Shape . RECTANGLE and orientation is Orientation . PORTRAIT and dpi_group is Density . MEDIUM and pixel_width_size_group >= Size . SMALL and pixel_height_size_group >= Size . MEDIUM ) : return ViewportProfile . MOBILE_PORTRAIT_MEDIUM elif ( shape is Shape . RECTANGLE and orientation is Orientation . LANDSCAPE and dpi_group is Density . MEDIUM and pixel_width_size_group >= Size . SMALL and pixel_height_size_group >= Size . XSMALL ) : return ViewportProfile . MOBILE_LANDSCAPE_SMALL elif ( shape is Shape . RECTANGLE and orientation is Orientation . PORTRAIT and dpi_group is Density . MEDIUM and pixel_width_size_group >= Size . XSMALL and pixel_height_size_group >= Size . SMALL ) : return ViewportProfile . MOBILE_PORTRAIT_SMALL elif ( shape is Shape . RECTANGLE and orientation is Orientation . LANDSCAPE and dpi_group >= Density . HIGH and pixel_width_size_group >= Size . XLARGE and pixel_height_size_group >= Size . MEDIUM ) : return ViewportProfile . TV_LANDSCAPE_XLARGE elif ( shape is Shape . RECTANGLE and orientation is Orientation . PORTRAIT and dpi_group >= Density . HIGH and pixel_width_size_group is Size . XSMALL and pixel_height_size_group is Size . XLARGE ) : return ViewportProfile . TV_PORTRAIT_MEDIUM elif ( shape is Shape . RECTANGLE and orientation is Orientation . LANDSCAPE and dpi_group >= Density . HIGH and pixel_width_size_group is Size . MEDIUM and pixel_height_size_group is Size . SMALL ) : return ViewportProfile . TV_LANDSCAPE_MEDIUM return ViewportProfile . UNKNOWN_VIEWPORT_PROFILE
Utility method to get viewport profile .
26,485
def request_handler ( self , can_handle_func ) : def wrapper ( handle_func ) : if not callable ( can_handle_func ) or not callable ( handle_func ) : raise SkillBuilderException ( "Request Handler can_handle_func and handle_func " "input parameters should be callable" ) class_attributes = { "can_handle" : lambda self , handler_input : can_handle_func ( handler_input ) , "handle" : lambda self , handler_input : handle_func ( handler_input ) } request_handler_class = type ( "RequestHandler{}" . format ( handle_func . __name__ . title ( ) . replace ( "_" , "" ) ) , ( AbstractRequestHandler , ) , class_attributes ) self . add_request_handler ( request_handler = request_handler_class ( ) ) return wrapper
Decorator that can be used to add request handlers easily to the builder .
26,486
def exception_handler ( self , can_handle_func ) : def wrapper ( handle_func ) : if not callable ( can_handle_func ) or not callable ( handle_func ) : raise SkillBuilderException ( "Exception Handler can_handle_func and handle_func input " "parameters should be callable" ) class_attributes = { "can_handle" : ( lambda self , handler_input , exception : can_handle_func ( handler_input , exception ) ) , "handle" : lambda self , handler_input , exception : handle_func ( handler_input , exception ) } exception_handler_class = type ( "ExceptionHandler{}" . format ( handle_func . __name__ . title ( ) . replace ( "_" , "" ) ) , ( AbstractExceptionHandler , ) , class_attributes ) self . add_exception_handler ( exception_handler = exception_handler_class ( ) ) return wrapper
Decorator that can be used to add exception handlers easily to the builder .
26,487
def global_request_interceptor ( self ) : def wrapper ( process_func ) : if not callable ( process_func ) : raise SkillBuilderException ( "Global Request Interceptor process_func input parameter " "should be callable" ) class_attributes = { "process" : lambda self , handler_input : process_func ( handler_input ) } request_interceptor = type ( "RequestInterceptor{}" . format ( process_func . __name__ . title ( ) . replace ( "_" , "" ) ) , ( AbstractRequestInterceptor , ) , class_attributes ) self . add_global_request_interceptor ( request_interceptor = request_interceptor ( ) ) return wrapper
Decorator that can be used to add global request interceptors easily to the builder .
26,488
def global_response_interceptor ( self ) : def wrapper ( process_func ) : if not callable ( process_func ) : raise SkillBuilderException ( "Global Response Interceptor process_func input " "parameter should be callable" ) class_attributes = { "process" : ( lambda self , handler_input , response : process_func ( handler_input , response ) ) } response_interceptor = type ( "ResponseInterceptor{}" . format ( process_func . __name__ . title ( ) . replace ( "_" , "" ) ) , ( AbstractResponseInterceptor , ) , class_attributes ) self . add_global_response_interceptor ( response_interceptor = response_interceptor ( ) ) return wrapper
Decorator that can be used to add global response interceptors easily to the builder .
26,489
def get_intent_name ( handler_input ) : request = handler_input . request_envelope . request if isinstance ( request , IntentRequest ) : return request . intent . name raise TypeError ( "The provided request is not an IntentRequest" )
Return the name of the intent request .
26,490
def get_device_id ( handler_input ) : device = handler_input . request_envelope . context . system . device if device : return device . device_id else : return None
Return the device id from the input request .
26,491
def get_dialog_state ( handler_input ) : request = handler_input . request_envelope . request if isinstance ( request , IntentRequest ) : return request . dialog_state raise TypeError ( "The provided request is not an IntentRequest" )
Return the dialog state enum from the intent request .
26,492
def get_slot ( handler_input , slot_name ) : request = handler_input . request_envelope . request if isinstance ( request , IntentRequest ) : if request . intent . slots is not None : return request . intent . slots . get ( slot_name , None ) else : return None raise TypeError ( "The provided request is not an IntentRequest" )
Return the slot information from intent request .
26,493
def get_slot_value ( handler_input , slot_name ) : slot = get_slot ( handler_input = handler_input , slot_name = slot_name ) if slot is not None : return slot . value raise ValueError ( "Provided slot {} doesn't exist in the input request" . format ( slot_name ) )
Return the slot value from intent request .
26,494
def is_new_session ( handler_input ) : session = handler_input . request_envelope . session if session is not None : return session . new raise TypeError ( "The provided request doesn't have a session" )
Return if the session is new for the input request .
26,495
def __set_text_field ( text , text_type ) : if text : if text_type not in [ PLAIN_TEXT_TYPE , RICH_TEXT_TYPE ] : raise ValueError ( "Invalid type provided: {}" . format ( text_type ) ) if text_type == PLAIN_TEXT_TYPE : return PlainText ( text = text ) else : return RichText ( text = text ) else : return None
Helper method to create text field according to text type .
26,496
def speak ( self , speech , play_behavior = None ) : ssml = "<speak>{}</speak>" . format ( self . __trim_outputspeech ( speech_output = speech ) ) self . response . output_speech = SsmlOutputSpeech ( ssml = ssml , play_behavior = play_behavior ) return self
Say the provided speech to the user .
26,497
def ask ( self , reprompt , play_behavior = None ) : ssml = "<speak>{}</speak>" . format ( self . __trim_outputspeech ( speech_output = reprompt ) ) output_speech = SsmlOutputSpeech ( ssml = ssml , play_behavior = play_behavior ) self . response . reprompt = Reprompt ( output_speech = output_speech ) if not self . __is_video_app_launch_directive_present ( ) : self . response . should_end_session = False return self
Provide reprompt speech to the user if no response for 8 seconds .
26,498
def add_directive ( self , directive ) : if self . response . directives is None : self . response . directives = [ ] if ( directive is not None and directive . object_type == "VideoApp.Launch" ) : self . response . should_end_session = None self . response . directives . append ( directive ) return self
Adds directive to response .
26,499
def __is_video_app_launch_directive_present ( self ) : if self . response . directives is None : return False for directive in self . response . directives : if ( directive is not None and directive . object_type == "VideoApp.Launch" ) : return True return False
Checks if the video app launch directive is present or not .