idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
26,800
def PBToPy ( numpb ) : return PhoneNumber ( country_code = numpb . country_code if numpb . HasField ( "country_code" ) else None , national_number = numpb . national_number if numpb . HasField ( "national_number" ) else None , extension = numpb . extension if numpb . HasField ( "extension" ) else None , italian_leading...
Convert phonenumber_pb2 . PhoneNumber to phonenumber . PhoneNumber
26,801
def PyToPB ( numobj ) : numpb = PhoneNumberPB ( ) if numobj . country_code is not None : numpb . country_code = numobj . country_code if numobj . national_number is not None : numpb . national_number = numobj . national_number if numobj . extension is not None : numpb . extension = numobj . extension if numobj . italia...
Convert phonenumber . PhoneNumber to phonenumber_pb2 . PhoneNumber
26,802
def _get_unique_child ( xtag , eltname ) : try : results = xtag . findall ( eltname ) if len ( results ) > 1 : raise Exception ( "Multiple elements found where 0/1 expected" ) elif len ( results ) == 1 : return results [ 0 ] else : return None except Exception : return None
Get the unique child element under xtag with name eltname
26,803
def _get_unique_child_value ( xtag , eltname ) : xelt = _get_unique_child ( xtag , eltname ) if xelt is None : return None else : return xelt . text
Get the text content of the unique child element under xtag with name eltname
26,804
def _extract_lengths ( ll ) : results = set ( ) if ll is None : return [ ] for val in ll . split ( ',' ) : m = _NUM_RE . match ( val ) if m : results . add ( int ( val ) ) else : m = _RANGE_RE . match ( val ) if m is None : raise Exception ( "Unrecognized length specification %s" % ll ) min = int ( m . group ( 'min' ) ...
Extract list of possible lengths from string
26,805
def _standalone ( argv ) : alternate = None short_data = False try : opts , args = getopt . getopt ( argv , "hlsa:" , ( "help" , "lax" , "short" , "alt=" ) ) except getopt . GetoptError : prnt ( __doc__ , file = sys . stderr ) sys . exit ( 1 ) for opt , arg in opts : if opt in ( "-h" , "--help" ) : prnt ( __doc__ , fil...
Parse the given XML file and emit generated code .
26,806
def add_alternate_formats ( self , filename ) : with open ( filename , "r" ) as infile : xtree = etree . parse ( infile ) self . alt_territory = { } xterritories = xtree . find ( TOP_XPATH ) for xterritory in xterritories : if xterritory . tag == TERRITORY_TAG : terrobj = XAlternateTerritory ( xterritory ) id = str ( t...
Add phone number alternate format metadata retrieved from XML
26,807
def emit_metadata_for_region_py ( self , region , region_filename , module_prefix ) : terrobj = self . territory [ region ] with open ( region_filename , "w" ) as outfile : prnt ( _REGION_METADATA_PROLOG % { 'region' : terrobj . identifier ( ) , 'module' : module_prefix } , file = outfile ) prnt ( "PHONE_METADATA_%s = ...
Emit Python code generating the metadata for the given region
26,808
def emit_alt_formats_for_cc_py ( self , cc , cc_filename , module_prefix ) : terrobj = self . alt_territory [ cc ] with open ( cc_filename , "w" ) as outfile : prnt ( _ALT_FORMAT_METADATA_PROLOG % ( cc , module_prefix ) , file = outfile ) prnt ( "PHONE_ALT_FORMAT_%s = %s" % ( cc , terrobj ) , file = outfile )
Emit Python code generating the alternate format metadata for the given country code
26,809
def _create_extn_pattern ( single_extn_symbols ) : return ( _RFC3966_EXTN_PREFIX + _CAPTURING_EXTN_DIGITS + u ( "|" ) + u ( "[ \u00A0\\t,]*(?:e?xt(?:ensi(?:o\u0301?|\u00F3))?n?|" ) + u ( "\uFF45?\uFF58\uFF54\uFF4E?|" ) + u ( "\u0434\u043e\u0431|" ) + u ( "[" ) + single_extn_symbols + u ( "]|int|anexo|\uFF49\uFF4E\uFF54...
Helper initialiser method to create the regular - expression pattern to match extensions allowing the one - char extension symbols provided by single_extn_symbols .
26,810
def _copy_number_format ( other ) : copy = NumberFormat ( pattern = other . pattern , format = other . format , leading_digits_pattern = list ( other . leading_digits_pattern ) , national_prefix_formatting_rule = other . national_prefix_formatting_rule , national_prefix_optional_when_formatting = other . national_prefi...
Return a mutable copy of the given NumberFormat object
26,811
def _extract_possible_number ( number ) : match = _VALID_START_CHAR_PATTERN . search ( number ) if match : number = number [ match . start ( ) : ] trailing_chars_match = _UNWANTED_END_CHAR_PATTERN . search ( number ) if trailing_chars_match : number = number [ : trailing_chars_match . start ( ) ] second_number_match = ...
Attempt to extract a possible number from the string passed in .
26,812
def _is_viable_phone_number ( number ) : if len ( number ) < _MIN_LENGTH_FOR_NSN : return False match = fullmatch ( _VALID_PHONE_NUMBER_PATTERN , number ) return bool ( match )
Checks to see if a string could possibly be a phone number .
26,813
def length_of_geographical_area_code ( numobj ) : metadata = PhoneMetadata . metadata_for_region ( region_code_for_number ( numobj ) , None ) if metadata is None : return 0 if metadata . national_prefix is None and not numobj . italian_leading_zero : return 0 ntype = number_type ( numobj ) country_code = numobj . count...
Return length of the geographical area code for a number .
26,814
def length_of_national_destination_code ( numobj ) : if numobj . extension is not None : copied_numobj = PhoneNumber ( ) copied_numobj . merge_from ( numobj ) copied_numobj . extension = None else : copied_numobj = numobj nsn = format_number ( copied_numobj , PhoneNumberFormat . INTERNATIONAL ) number_groups = re . spl...
Return length of the national destination code code for a number .
26,815
def _normalize_helper ( number , replacements , remove_non_matches ) : normalized_number = [ ] for char in number : new_digit = replacements . get ( char . upper ( ) , None ) if new_digit is not None : normalized_number . append ( new_digit ) elif not remove_non_matches : normalized_number . append ( char ) return U_EM...
Normalizes a string of characters representing a phone number by replacing all characters found in the accompanying map with the values therein and stripping all other characters if remove_non_matches is true .
26,816
def _desc_has_data ( desc ) : if desc is None : return False return ( ( desc . example_number is not None ) or _desc_has_possible_number_data ( desc ) or ( desc . national_number_pattern is not None ) )
Returns true if there is any data set for a particular PhoneNumberDesc .
26,817
def _supported_types_for_metadata ( metadata ) : numtypes = set ( ) for numtype in PhoneNumberType . values ( ) : if numtype in ( PhoneNumberType . FIXED_LINE_OR_MOBILE , PhoneNumberType . UNKNOWN ) : continue if _desc_has_data ( _number_desc_by_type ( metadata , numtype ) ) : numtypes . add ( numtype ) return numtypes
Returns the types we have metadata for based on the PhoneMetadata object passed in which must be non - None .
26,818
def supported_types_for_region ( region_code ) : if not _is_valid_region_code ( region_code ) : return set ( ) metadata = PhoneMetadata . metadata_for_region ( region_code . upper ( ) ) return _supported_types_for_metadata ( metadata )
Returns the types for a given region which the library has metadata for .
26,819
def is_number_type_geographical ( num_type , country_code ) : return ( num_type == PhoneNumberType . FIXED_LINE or num_type == PhoneNumberType . FIXED_LINE_OR_MOBILE or ( ( country_code in _GEO_MOBILE_COUNTRIES ) and num_type == PhoneNumberType . MOBILE ) )
Tests whether a phone number has a geographical association as represented by its type and the country it belongs to .
26,820
def format_number ( numobj , num_format ) : if numobj . national_number == 0 and numobj . raw_input is not None : if len ( numobj . raw_input ) > 0 : return numobj . raw_input country_calling_code = numobj . country_code nsn = national_significant_number ( numobj ) if num_format == PhoneNumberFormat . E164 : return _pr...
Formats a phone number in the specified format using default rules .
26,821
def format_by_pattern ( numobj , number_format , user_defined_formats ) : country_code = numobj . country_code nsn = national_significant_number ( numobj ) if not _has_valid_country_calling_code ( country_code ) : return nsn region_code = region_code_for_country_code ( country_code ) metadata = PhoneMetadata . metadata...
Formats a phone number using client - defined formatting rules .
26,822
def format_national_number_with_carrier_code ( numobj , carrier_code ) : country_code = numobj . country_code nsn = national_significant_number ( numobj ) if not _has_valid_country_calling_code ( country_code ) : return nsn region_code = region_code_for_country_code ( country_code ) metadata = PhoneMetadata . metadata_...
Format a number in national format for dialing using the specified carrier .
26,823
def format_national_number_with_preferred_carrier_code ( numobj , fallback_carrier_code ) : if ( numobj . preferred_domestic_carrier_code is not None and len ( numobj . preferred_domestic_carrier_code ) > 0 ) : carrier_code = numobj . preferred_domestic_carrier_code else : carrier_code = fallback_carrier_code return fo...
Formats a phone number in national format for dialing using the carrier as specified in the preferred_domestic_carrier_code field of the PhoneNumber object passed in . If that is missing use the fallback_carrier_code passed in instead . If there is no preferred_domestic_carrier_code and the fallback_carrier_code contai...
26,824
def format_number_for_mobile_dialing ( numobj , region_calling_from , with_formatting ) : country_calling_code = numobj . country_code if not _has_valid_country_calling_code ( country_calling_code ) : if numobj . raw_input is None : return U_EMPTY_STRING else : return numobj . raw_input formatted_number = U_EMPTY_STRIN...
Returns a number formatted in such a way that it can be dialed from a mobile phone in a specific region .
26,825
def format_in_original_format ( numobj , region_calling_from ) : if ( numobj . raw_input is not None and not _has_formatting_pattern_for_number ( numobj ) ) : return numobj . raw_input if numobj . country_code_source is CountryCodeSource . UNSPECIFIED : return format_number ( numobj , PhoneNumberFormat . NATIONAL ) for...
Format a number using the original format that the number was parsed from .
26,826
def _raw_input_contains_national_prefix ( raw_input , national_prefix , region_code ) : nnn = normalize_digits_only ( raw_input ) if nnn . startswith ( national_prefix ) : try : return is_valid_number ( parse ( nnn [ len ( national_prefix ) : ] , region_code ) ) except NumberParseException : return False return False
Check if raw_input which is assumed to be in the national format has a national prefix . The national prefix is assumed to be in digits - only form .
26,827
def national_significant_number ( numobj ) : national_number = U_EMPTY_STRING if numobj . italian_leading_zero : num_zeros = numobj . number_of_leading_zeros if num_zeros is None : num_zeros = 1 if num_zeros > 0 : national_number = U_ZERO * num_zeros national_number += str ( numobj . national_number ) return national_n...
Gets the national significant number of a phone number .
26,828
def _prefix_number_with_country_calling_code ( country_code , num_format , formatted_number ) : if num_format == PhoneNumberFormat . E164 : return _PLUS_SIGN + unicod ( country_code ) + formatted_number elif num_format == PhoneNumberFormat . INTERNATIONAL : return _PLUS_SIGN + unicod ( country_code ) + U_SPACE + format...
A helper function that is used by format_number and format_by_pattern .
26,829
def _format_nsn ( number , metadata , num_format , carrier_code = None ) : intl_number_formats = metadata . intl_number_format if ( len ( intl_number_formats ) == 0 or num_format == PhoneNumberFormat . NATIONAL ) : available_formats = metadata . number_format else : available_formats = metadata . intl_number_format for...
Format a national number .
26,830
def invalid_example_number ( region_code ) : if not _is_valid_region_code ( region_code ) : return None metadata = PhoneMetadata . metadata_for_region ( region_code . upper ( ) ) desc = _number_desc_by_type ( metadata , PhoneNumberType . FIXED_LINE ) if desc is None or desc . example_number is None : return None exampl...
Gets an invalid number for the specified region .
26,831
def example_number_for_type ( region_code , num_type ) : if region_code is None : return _example_number_anywhere_for_type ( num_type ) if not _is_valid_region_code ( region_code ) : return None metadata = PhoneMetadata . metadata_for_region ( region_code . upper ( ) ) desc = _number_desc_by_type ( metadata , num_type ...
Gets a valid number for the specified region and number type .
26,832
def example_number_for_non_geo_entity ( country_calling_code ) : metadata = PhoneMetadata . metadata_for_nongeo_region ( country_calling_code , None ) if metadata is not None : for desc in ( metadata . mobile , metadata . toll_free , metadata . shared_cost , metadata . voip , metadata . voicemail , metadata . uan , met...
Gets a valid number for the specified country calling code for a non - geographical entity .
26,833
def _maybe_append_formatted_extension ( numobj , metadata , num_format , number ) : if numobj . extension : if num_format == PhoneNumberFormat . RFC3966 : return number + _RFC3966_EXTN_PREFIX + numobj . extension else : if metadata . preferred_extn_prefix is not None : return number + metadata . preferred_extn_prefix +...
Appends the formatted extension of a phone number to formatted number if the phone number had an extension specified .
26,834
def _number_desc_by_type ( metadata , num_type ) : if num_type == PhoneNumberType . PREMIUM_RATE : return metadata . premium_rate elif num_type == PhoneNumberType . TOLL_FREE : return metadata . toll_free elif num_type == PhoneNumberType . MOBILE : return metadata . mobile elif ( num_type == PhoneNumberType . FIXED_LIN...
Return the PhoneNumberDesc of the metadata for the given number type
26,835
def number_type ( numobj ) : region_code = region_code_for_number ( numobj ) metadata = PhoneMetadata . metadata_for_region_or_calling_code ( numobj . country_code , region_code ) if metadata is None : return PhoneNumberType . UNKNOWN national_number = national_significant_number ( numobj ) return _number_type_helper (...
Gets the type of a valid phone number .
26,836
def _number_type_helper ( national_number , metadata ) : if not _is_number_matching_desc ( national_number , metadata . general_desc ) : return PhoneNumberType . UNKNOWN if _is_number_matching_desc ( national_number , metadata . premium_rate ) : return PhoneNumberType . PREMIUM_RATE if _is_number_matching_desc ( nation...
Return the type of the given number against the metadata
26,837
def _is_number_matching_desc ( national_number , number_desc ) : if number_desc is None : return False actual_length = len ( national_number ) possible_lengths = number_desc . possible_length if len ( possible_lengths ) > 0 and actual_length not in possible_lengths : return False return _match_national_number ( nationa...
Determine if the number matches the given PhoneNumberDesc
26,838
def is_valid_number_for_region ( numobj , region_code ) : country_code = numobj . country_code if region_code is None : return False metadata = PhoneMetadata . metadata_for_region_or_calling_code ( country_code , region_code . upper ( ) ) if ( metadata is None or ( region_code != REGION_CODE_FOR_NON_GEO_ENTITY and coun...
Tests whether a phone number is valid for a certain region .
26,839
def region_code_for_number ( numobj ) : country_code = numobj . country_code regions = COUNTRY_CODE_TO_REGION_CODE . get ( country_code , None ) if regions is None : return None if len ( regions ) == 1 : return regions [ 0 ] else : return _region_code_for_number_from_list ( numobj , regions )
Returns the region where a phone number is from .
26,840
def _region_code_for_number_from_list ( numobj , regions ) : national_number = national_significant_number ( numobj ) for region_code in regions : metadata = PhoneMetadata . metadata_for_region ( region_code . upper ( ) , None ) if metadata is None : continue if metadata . leading_digits is not None : leading_digit_re ...
Find the region in a list that matches a number
26,841
def country_code_for_valid_region ( region_code ) : metadata = PhoneMetadata . metadata_for_region ( region_code . upper ( ) , None ) if metadata is None : raise Exception ( "Invalid region code %s" % region_code ) return metadata . country_code
Returns the country calling code for a specific region .
26,842
def ndd_prefix_for_region ( region_code , strip_non_digits ) : if region_code is None : return None metadata = PhoneMetadata . metadata_for_region ( region_code . upper ( ) , None ) if metadata is None : return None national_prefix = metadata . national_prefix if national_prefix is None or len ( national_prefix ) == 0 ...
Returns the national dialling prefix for a specific region .
26,843
def is_possible_number ( numobj ) : result = is_possible_number_with_reason ( numobj ) return ( result == ValidationResult . IS_POSSIBLE or result == ValidationResult . IS_POSSIBLE_LOCAL_ONLY )
Convenience wrapper around is_possible_number_with_reason .
26,844
def is_possible_number_for_type ( numobj , numtype ) : result = is_possible_number_for_type_with_reason ( numobj , numtype ) return ( result == ValidationResult . IS_POSSIBLE or result == ValidationResult . IS_POSSIBLE_LOCAL_ONLY )
Convenience wrapper around is_possible_number_for_type_with_reason .
26,845
def is_possible_number_for_type_with_reason ( numobj , numtype ) : national_number = national_significant_number ( numobj ) country_code = numobj . country_code if not _has_valid_country_calling_code ( country_code ) : return ValidationResult . INVALID_COUNTRY_CODE region_code = region_code_for_country_code ( country_c...
Check whether a phone number is a possible number of a particular type .
26,846
def truncate_too_long_number ( numobj ) : if is_valid_number ( numobj ) : return True numobj_copy = PhoneNumber ( ) numobj_copy . merge_from ( numobj ) national_number = numobj . national_number while not is_valid_number ( numobj_copy ) : national_number = national_number // 10 numobj_copy . national_number = national_...
Truncate a number object that is too long .
26,847
def _extract_country_code ( number ) : if len ( number ) == 0 or number [ 0 ] == U_ZERO : return ( 0 , number ) for ii in range ( 1 , min ( len ( number ) , _MAX_LENGTH_COUNTRY_CODE ) + 1 ) : try : country_code = int ( number [ : ii ] ) if country_code in COUNTRY_CODE_TO_REGION_CODE : return ( country_code , number [ i...
Extracts country calling code from number .
26,848
def _maybe_extract_country_code ( number , metadata , keep_raw_input , numobj ) : if len ( number ) == 0 : return ( 0 , U_EMPTY_STRING ) full_number = number possible_country_idd_prefix = unicod ( "NonMatch" ) if metadata is not None and metadata . international_prefix is not None : possible_country_idd_prefix = metada...
Tries to extract a country calling code from a number .
26,849
def _parse_prefix_as_idd ( idd_pattern , number ) : match = idd_pattern . match ( number ) if match : match_end = match . end ( ) digit_match = _CAPTURING_DIGIT_PATTERN . search ( number [ match_end : ] ) if digit_match : normalized_group = normalize_digits_only ( digit_match . group ( 1 ) ) if normalized_group == U_ZE...
Strips the IDD from the start of the number if present .
26,850
def _maybe_strip_extension ( number ) : match = _EXTN_PATTERN . search ( number ) if match and _is_viable_phone_number ( number [ : match . start ( ) ] ) : for group in match . groups ( ) : if group is not None : return ( group , number [ : match . start ( ) ] ) return ( "" , number )
Strip extension from the end of a number string .
26,851
def _check_region_for_parsing ( number , default_region ) : if not _is_valid_region_code ( default_region ) : if number is None or len ( number ) == 0 : return False match = _PLUS_CHARS_PATTERN . match ( number ) if match is None : return False return True
Checks to see that the region code used is valid or if it is not valid that the number to parse starts with a + symbol so that we can attempt to infer the region from the number . Returns False if it cannot use the region provided and the region cannot be inferred .
26,852
def _set_italian_leading_zeros_for_phone_number ( national_number , numobj ) : if len ( national_number ) > 1 and national_number [ 0 ] == U_ZERO : numobj . italian_leading_zero = True number_of_leading_zeros = 1 while ( number_of_leading_zeros < len ( national_number ) - 1 and national_number [ number_of_leading_zeros...
A helper function to set the values related to leading zeros in a PhoneNumber .
26,853
def parse ( number , region = None , keep_raw_input = False , numobj = None , _check_region = True ) : if numobj is None : numobj = PhoneNumber ( ) if number is None : raise NumberParseException ( NumberParseException . NOT_A_NUMBER , "The phone number supplied was None." ) elif len ( number ) > _MAX_INPUT_STRING_LENGT...
Parse a string and return a corresponding PhoneNumber object .
26,854
def _build_national_number_for_parsing ( number ) : index_of_phone_context = number . find ( _RFC3966_PHONE_CONTEXT ) if index_of_phone_context >= 0 : phone_context_start = index_of_phone_context + len ( _RFC3966_PHONE_CONTEXT ) if ( phone_context_start < ( len ( number ) - 1 ) and number [ phone_context_start ] == _PL...
Converts number to a form that we can parse and return it if it is written in RFC3966 ; otherwise extract a possible number out of it and return it .
26,855
def _copy_core_fields_only ( inobj ) : numobj = PhoneNumber ( ) numobj . country_code = inobj . country_code numobj . national_number = inobj . national_number if inobj . extension is not None and len ( inobj . extension ) > 0 : numobj . extension = inobj . extension if inobj . italian_leading_zero : numobj . italian_l...
Returns a new phone number containing only the fields needed to uniquely identify a phone number rather than any fields that capture the context in which the phone number was created .
26,856
def _is_number_match_OO ( numobj1_in , numobj2_in ) : numobj1 = _copy_core_fields_only ( numobj1_in ) numobj2 = _copy_core_fields_only ( numobj2_in ) if ( numobj1 . extension is not None and numobj2 . extension is not None and numobj1 . extension != numobj2 . extension ) : return MatchType . NO_MATCH country_code1 = nu...
Takes two phone number objects and compares them for equality .
26,857
def _is_national_number_suffix_of_other ( numobj1 , numobj2 ) : nn1 = str ( numobj1 . national_number ) nn2 = str ( numobj2 . national_number ) return nn1 . endswith ( nn2 ) or nn2 . endswith ( nn1 )
Returns true when one national number is the suffix of the other or both are the same .
26,858
def _is_number_match_SS ( number1 , number2 ) : try : numobj1 = parse ( number1 , UNKNOWN_REGION ) return _is_number_match_OS ( numobj1 , number2 ) except NumberParseException : _ , exc , _ = sys . exc_info ( ) if exc . error_type == NumberParseException . INVALID_COUNTRY_CODE : try : numobj2 = parse ( number2 , UNKNOW...
Takes two phone numbers as strings and compares them for equality .
26,859
def _is_number_match_OS ( numobj1 , number2 ) : try : numobj2 = parse ( number2 , UNKNOWN_REGION ) return _is_number_match_OO ( numobj1 , numobj2 ) except NumberParseException : _ , exc , _ = sys . exc_info ( ) if exc . error_type == NumberParseException . INVALID_COUNTRY_CODE : region1 = region_code_for_country_code (...
Wrapper variant of _is_number_match_OO that copes with one PhoneNumber object and one string .
26,860
def is_number_match ( num1 , num2 ) : if isinstance ( num1 , PhoneNumber ) and isinstance ( num2 , PhoneNumber ) : return _is_number_match_OO ( num1 , num2 ) elif isinstance ( num1 , PhoneNumber ) : return _is_number_match_OS ( num1 , num2 ) elif isinstance ( num2 , PhoneNumber ) : return _is_number_match_OS ( num2 , n...
Takes two phone numbers and compares them for equality .
26,861
def can_be_internationally_dialled ( numobj ) : metadata = PhoneMetadata . metadata_for_region ( region_code_for_number ( numobj ) , None ) if metadata is None : return True nsn = national_significant_number ( numobj ) return not _is_number_matching_desc ( nsn , metadata . no_international_dialling )
Returns True if the number can only be dialled from outside the region or unknown .
26,862
def is_mobile_number_portable_region ( region_code ) : metadata = PhoneMetadata . metadata_for_region ( region_code , None ) if metadata is None : return False return metadata . mobile_number_portable_region
Returns true if the supplied region supports mobile number portability . Returns false for invalid unknown or regions that don t support mobile number portability .
26,863
def time_zones_for_geographical_number ( numobj ) : e164_num = format_number ( numobj , PhoneNumberFormat . E164 ) if not e164_num . startswith ( U_PLUS ) : raise Exception ( "Expect E164 number to start with +" ) for prefix_len in range ( TIMEZONE_LONGEST_PREFIX , 0 , - 1 ) : prefix = e164_num [ 1 : ( 1 + prefix_len )...
Returns a list of time zones to which a phone number belongs .
26,864
def is_letter ( uni_char ) : category = Category . get ( uni_char ) return ( category == Category . UPPERCASE_LETTER or category == Category . LOWERCASE_LETTER or category == Category . TITLECASE_LETTER or category == Category . MODIFIER_LETTER or category == Category . OTHER_LETTER )
Determine whether the given Unicode character is a Unicode letter
26,865
def digit ( uni_char , default_value = None ) : uni_char = unicod ( uni_char ) if default_value is not None : return unicodedata . digit ( uni_char , default_value ) else : return unicodedata . digit ( uni_char )
Returns the digit value assigned to the Unicode character uni_char as integer . If no such value is defined default is returned or if not given ValueError is raised .
26,866
def get ( cls , uni_char ) : uni_char = unicod ( uni_char ) code_point = ord ( uni_char ) if Block . _RANGE_KEYS is None : Block . _RANGE_KEYS = sorted ( Block . _RANGES . keys ( ) ) idx = bisect . bisect_left ( Block . _RANGE_KEYS , code_point ) if ( idx > 0 and code_point >= Block . _RANGES [ Block . _RANGE_KEYS [ id...
Return the Unicode block of the given Unicode character
26,867
def _is_mobile ( ntype ) : return ( ntype == PhoneNumberType . MOBILE or ntype == PhoneNumberType . FIXED_LINE_OR_MOBILE or ntype == PhoneNumberType . PAGER )
Checks if the supplied number type supports carrier lookup
26,868
def clear ( self ) : self . country_code = None self . national_number = None self . extension = None self . italian_leading_zero = None self . number_of_leading_zeros = None self . raw_input = None self . country_code_source = CountryCodeSource . UNSPECIFIED self . preferred_domestic_carrier_code = None
Erase the contents of the object
26,869
def merge_from ( self , other ) : if other . country_code is not None : self . country_code = other . country_code if other . national_number is not None : self . national_number = other . national_number if other . extension is not None : self . extension = other . extension if other . italian_leading_zero is not None...
Merge information from another PhoneNumber object into this one .
26,870
def mutating_method ( func ) : def wrapper ( self , * __args , ** __kwargs ) : old_mutable = self . _mutable self . _mutable = True try : return func ( self , * __args , ** __kwargs ) finally : self . _mutable = old_mutable return wrapper
Decorator for methods that are allowed to modify immutable objects
26,871
def fullmatch ( pattern , string , flags = 0 ) : grouped_pattern = re . compile ( "^(?:%s)$" % pattern . pattern , pattern . flags ) m = grouped_pattern . match ( string ) if m and m . end ( ) < len ( string ) : m = None return m
Try to apply the pattern at the start of the string returning a match object if the whole string matches or None if no match was found .
26,872
def load_locale_prefixdata_file ( prefixdata , filename , locale = None , overall_prefix = None , separator = None ) : with open ( filename , "rb" ) as infile : lineno = 0 for line in infile : uline = line . decode ( 'utf-8' ) lineno += 1 dm = DATA_LINE_RE . match ( uline ) if dm : prefix = dm . group ( 'prefix' ) stri...
Load per - prefix data from the given file for the given locale and prefix .
26,873
def load_locale_prefixdata ( indir , separator = None ) : prefixdata = { } for locale in os . listdir ( indir ) : if not os . path . isdir ( os . path . join ( indir , locale ) ) : continue for filename in glob . glob ( os . path . join ( indir , locale , "*%s" % PREFIXDATA_SUFFIX ) ) : overall_prefix , ext = os . path...
Load per - prefix data from the given top - level directory .
26,874
def output_prefixdata_code ( prefixdata , outfilename , module_prefix , varprefix , per_locale , chunks ) : sorted_keys = sorted ( prefixdata . keys ( ) ) total_keys = len ( sorted_keys ) if chunks == - 1 : chunk_size = PREFIXDATA_CHUNK_SIZE total_chunks = int ( math . ceil ( total_keys / float ( chunk_size ) ) ) else ...
Output the per - prefix data in Python form to the given file
26,875
def _standalone ( argv ) : varprefix = "GEOCODE" per_locale = True separator = None chunks = - 1 try : opts , args = getopt . getopt ( argv , "hv:fs:c:" , ( "help" , "var=" , "flat" , "sep=" , "chunks=" ) ) except getopt . GetoptError : prnt ( __doc__ , file = sys . stderr ) sys . exit ( 1 ) for opt , arg in opts : if ...
Parse the given input directory and emit generated code .
26,876
def _limit ( lower , upper ) : if ( ( lower < 0 ) or ( upper <= 0 ) or ( upper < lower ) ) : raise Exception ( "Illegal argument to _limit" ) return unicod ( "{%d,%d}" ) % ( lower , upper )
Returns a regular expression quantifier with an upper and lower limit .
26,877
def _verify ( leniency , numobj , candidate , matcher ) : if leniency == Leniency . POSSIBLE : return is_possible_number ( numobj ) elif leniency == Leniency . VALID : if ( not is_valid_number ( numobj ) or not _contains_only_valid_x_chars ( numobj , candidate ) ) : return False return _is_national_prefix_present_if_re...
Returns True if number is a verified number according to the leniency .
26,878
def _get_national_number_groups_without_pattern ( numobj ) : rfc3966_format = format_number ( numobj , PhoneNumberFormat . RFC3966 ) end_index = rfc3966_format . find ( U_SEMICOLON ) if end_index < 0 : end_index = len ( rfc3966_format ) start_index = rfc3966_format . find ( U_DASH ) + 1 return rfc3966_format [ start_in...
Helper method to get the national - number part of a number formatted without any national prefix and return it as a set of digit blocks that would be formatted together following standard formatting rules .
26,879
def _get_national_number_groups ( numobj , formatting_pattern ) : nsn = national_significant_number ( numobj ) return _format_nsn_using_pattern ( nsn , formatting_pattern , PhoneNumberFormat . RFC3966 ) . split ( U_DASH )
Helper method to get the national - number part of a number formatted without any national prefix and return it as a set of digit blocks that should be formatted together according to the formatting pattern passed in .
26,880
def _find ( self , index ) : match = _PATTERN . search ( self . text , index ) while self . _max_tries > 0 and match is not None : start = match . start ( ) candidate = self . text [ start : match . end ( ) ] candidate = self . _trim_after_first_match ( _SECOND_NUMBER_START_PATTERN , candidate ) match = self . _extract...
Attempts to find the next subsequence in the searched sequence on or after index that represents a phone number . Returns the next match None if none was found .
26,881
def _trim_after_first_match ( self , pattern , candidate ) : trailing_chars_match = pattern . search ( candidate ) if trailing_chars_match : candidate = candidate [ : trailing_chars_match . start ( ) ] return candidate
Trims away any characters after the first match of pattern in candidate returning the trimmed version .
26,882
def _is_latin_letter ( cls , letter ) : if ( not is_letter ( letter ) and Category . get ( letter ) != Category . NON_SPACING_MARK ) : return False block = Block . get ( letter ) return ( block == Block . BASIC_LATIN or block == Block . LATIN_1_SUPPLEMENT or block == Block . LATIN_EXTENDED_A or block == Block . LATIN_E...
Helper method to determine if a character is a Latin - script letter or not . For our purposes combining marks should also return True since we assume they have been added to a preceding Latin character .
26,883
def _extract_match ( self , candidate , offset ) : if ( _SLASH_SEPARATED_DATES . search ( candidate ) ) : return None if _TIME_STAMPS . search ( candidate ) : following_text = self . text [ offset + len ( candidate ) : ] if _TIME_STAMPS_SUFFIX . match ( following_text ) : return None match = self . _parse_and_verify ( ...
Attempts to extract a match from a candidate string .
26,884
def _extract_inner_match ( self , candidate , offset ) : for possible_inner_match in _INNER_MATCHES : group_match = possible_inner_match . search ( candidate ) is_first_match = True while group_match and self . _max_tries > 0 : if is_first_match : group = self . _trim_after_first_match ( _UNWANTED_END_CHAR_PATTERN , ca...
Attempts to extract a match from candidate if the whole candidate does not qualify as a match .
26,885
def _parse_and_verify ( self , candidate , offset ) : try : if ( not fullmatch ( _MATCHING_BRACKETS , candidate ) or _PUB_PAGES . search ( candidate ) ) : return None if self . leniency >= Leniency . VALID : if ( offset > 0 and not _LEAD_PATTERN . match ( candidate ) ) : previous_char = self . text [ offset - 1 ] if ( ...
Parses a phone number from the candidate using phonenumberutil . parse and verifies it matches the requested leniency . If parsing and verification succeed a corresponding PhoneNumberMatch is returned otherwise this method returns None .
26,886
def has_next ( self ) : if self . _state == PhoneNumberMatcher . _NOT_READY : self . _last_match = self . _find ( self . _search_index ) if self . _last_match is None : self . _state = PhoneNumberMatcher . _DONE else : self . _search_index = self . _last_match . end self . _state = PhoneNumberMatcher . _READY return ( ...
Indicates whether there is another match available
26,887
def next ( self ) : if not self . has_next ( ) : raise StopIteration ( "No next match" ) result = self . _last_match self . _last_match = None self . _state = PhoneNumberMatcher . _NOT_READY return result
Return the next match ; raises Exception if no next match available
26,888
def is_possible_short_number_for_region ( short_numobj , region_dialing_from ) : if not _region_dialing_from_matches_number ( short_numobj , region_dialing_from ) : return False metadata = PhoneMetadata . short_metadata_for_region ( region_dialing_from ) if metadata is None : return False short_numlen = len ( national_...
Check whether a short number is a possible number when dialled from a region . This provides a more lenient check than is_valid_short_number_for_region .
26,889
def is_possible_short_number ( numobj ) : region_codes = region_codes_for_country_code ( numobj . country_code ) short_number_len = len ( national_significant_number ( numobj ) ) for region in region_codes : metadata = PhoneMetadata . short_metadata_for_region ( region ) if metadata is None : continue if short_number_l...
Check whether a short number is a possible number .
26,890
def is_valid_short_number_for_region ( short_numobj , region_dialing_from ) : if not _region_dialing_from_matches_number ( short_numobj , region_dialing_from ) : return False metadata = PhoneMetadata . short_metadata_for_region ( region_dialing_from ) if metadata is None : return False short_number = national_significa...
Tests whether a short number matches a valid pattern in a region .
26,891
def is_valid_short_number ( numobj ) : region_codes = region_codes_for_country_code ( numobj . country_code ) region_code = _region_code_for_short_number_from_region_list ( numobj , region_codes ) if len ( region_codes ) > 1 and region_code is not None : return True return is_valid_short_number_for_region ( numobj , re...
Tests whether a short number matches a valid pattern .
26,892
def _region_code_for_short_number_from_region_list ( numobj , region_codes ) : if len ( region_codes ) == 0 : return None elif len ( region_codes ) == 1 : return region_codes [ 0 ] national_number = national_significant_number ( numobj ) for region_code in region_codes : metadata = PhoneMetadata . short_metadata_for_re...
Helper method to get the region code for a given phone number from a list of possible region codes . If the list contains more than one region the first region for which the number is valid is returned .
26,893
def _example_short_number ( region_code ) : metadata = PhoneMetadata . short_metadata_for_region ( region_code ) if metadata is None : return U_EMPTY_STRING desc = metadata . short_code if desc . example_number is not None : return desc . example_number return U_EMPTY_STRING
Gets a valid short number for the specified region .
26,894
def _example_short_number_for_cost ( region_code , cost ) : metadata = PhoneMetadata . short_metadata_for_region ( region_code ) if metadata is None : return U_EMPTY_STRING desc = None if cost == ShortNumberCost . TOLL_FREE : desc = metadata . toll_free elif cost == ShortNumberCost . STANDARD_RATE : desc = metadata . s...
Gets a valid short number for the specified cost category .
26,895
def connection ( cls ) : local = cls . _threadlocal if not getattr ( local , 'connection' , None ) : local . user = cls . user local . password = cls . password local . site = cls . site local . timeout = cls . timeout local . headers = cls . headers local . format = cls . format local . version = cls . version local ....
HTTP connection for the current thread
26,896
def get_prefix_source ( cls ) : try : return cls . override_prefix ( ) except AttributeError : if hasattr ( cls , '_prefix_source' ) : return cls . site + cls . _prefix_source else : return cls . site
Return the prefix source by default derived from site .
26,897
def __encoded_params_for_signature ( cls , params ) : def encoded_pairs ( params ) : for k , v in six . iteritems ( params ) : if k == 'hmac' : continue if k . endswith ( '[]' ) : k = k . rstrip ( '[]' ) v = json . dumps ( list ( map ( str , v ) ) ) k = str ( k ) . replace ( "%" , "%25" ) . replace ( "=" , "%3D" ) v = ...
Sort and combine query parameters into a single string excluding those that should be removed and joining with &
26,898
def calculate ( cls , order_id , shipping = None , refund_line_items = None ) : data = { } if shipping : data [ 'shipping' ] = shipping data [ 'refund_line_items' ] = refund_line_items or [ ] body = { 'refund' : data } resource = cls . post ( "calculate" , order_id = order_id , body = json . dumps ( body ) . encode ( )...
Calculates refund transactions based on line items and shipping . When you want to create a refund you should first use the calculate endpoint to generate accurate refund transactions .
26,899
def help ( cls , task = None ) : if task is None : usage_list = [ ] for task in iter ( cls . _tasks ) : task_func = getattr ( cls , task ) usage_string = " %s %s" % ( cls . _prog , task_func . usage ) desc = task_func . __doc__ . splitlines ( ) [ 0 ] usage_list . append ( ( usage_string , desc ) ) max_len = functools ...
Describe available tasks or one specific task