id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
234,600
nok/sklearn-porter
sklearn_porter/estimator/classifier/DecisionTreeClassifier/__init__.py
DecisionTreeClassifier.create_tree
def create_tree(self): """ Parse and build the tree branches. Returns ------- :return : string The tree branches as string. """ feature_indices = [] for i in self.estimator.tree_.feature: n_features = self.n_features if self.n_features > 1 or (self.n_features == 1 and i >= 0): feature_indices.append([str(j) for j in range(n_features)][i]) indentation = 1 if self.target_language in ['java', 'js', 'php', 'ruby'] else 0 return self.create_branches( self.estimator.tree_.children_left, self.estimator.tree_.children_right, self.estimator.tree_.threshold, self.estimator.tree_.value, feature_indices, 0, indentation)
python
def create_tree(self): feature_indices = [] for i in self.estimator.tree_.feature: n_features = self.n_features if self.n_features > 1 or (self.n_features == 1 and i >= 0): feature_indices.append([str(j) for j in range(n_features)][i]) indentation = 1 if self.target_language in ['java', 'js', 'php', 'ruby'] else 0 return self.create_branches( self.estimator.tree_.children_left, self.estimator.tree_.children_right, self.estimator.tree_.threshold, self.estimator.tree_.value, feature_indices, 0, indentation)
[ "def", "create_tree", "(", "self", ")", ":", "feature_indices", "=", "[", "]", "for", "i", "in", "self", ".", "estimator", ".", "tree_", ".", "feature", ":", "n_features", "=", "self", ".", "n_features", "if", "self", ".", "n_features", ">", "1", "or",...
Parse and build the tree branches. Returns ------- :return : string The tree branches as string.
[ "Parse", "and", "build", "the", "tree", "branches", "." ]
04673f768310bde31f9747a68a5e070592441ef2
https://github.com/nok/sklearn-porter/blob/04673f768310bde31f9747a68a5e070592441ef2/sklearn_porter/estimator/classifier/DecisionTreeClassifier/__init__.py#L331-L352
234,601
nok/sklearn-porter
sklearn_porter/estimator/classifier/MLPClassifier/__init__.py
MLPClassifier._get_intercepts
def _get_intercepts(self): """ Concatenate all intercepts of the classifier. """ temp_arr = self.temp('arr') for layer in self.intercepts: inter = ', '.join([self.repr(b) for b in layer]) yield temp_arr.format(inter)
python
def _get_intercepts(self): temp_arr = self.temp('arr') for layer in self.intercepts: inter = ', '.join([self.repr(b) for b in layer]) yield temp_arr.format(inter)
[ "def", "_get_intercepts", "(", "self", ")", ":", "temp_arr", "=", "self", ".", "temp", "(", "'arr'", ")", "for", "layer", "in", "self", ".", "intercepts", ":", "inter", "=", "', '", ".", "join", "(", "[", "self", ".", "repr", "(", "b", ")", "for", ...
Concatenate all intercepts of the classifier.
[ "Concatenate", "all", "intercepts", "of", "the", "classifier", "." ]
04673f768310bde31f9747a68a5e070592441ef2
https://github.com/nok/sklearn-porter/blob/04673f768310bde31f9747a68a5e070592441ef2/sklearn_porter/estimator/classifier/MLPClassifier/__init__.py#L251-L258
234,602
nok/sklearn-porter
sklearn_porter/estimator/classifier/AdaBoostClassifier/__init__.py
AdaBoostClassifier.create_embedded_meth
def create_embedded_meth(self): """ Build the estimator methods or functions. Returns ------- :return : string The built methods as merged string. """ # Generate related trees: fns = [] for idx, estimator in enumerate(self.estimators): tree = self.create_single_method(idx, estimator) fns.append(tree) fns = '\n'.join(fns) # Generate method or function names: fn_names = '' if self.target_language in ['c', 'java']: fn_names = [] temp_method_calls = self.temp('embedded.method_calls', n_indents=2, skipping=True) for idx, estimator in enumerate(self.estimators): cl_name = self.class_name fn_name = self.method_name + '_' + str(idx) fn_name = temp_method_calls.format(class_name=cl_name, method_name=fn_name, method_index=idx) fn_names.append(fn_name) fn_names = '\n'.join(fn_names) fn_names = self.indent(fn_names, n_indents=1, skipping=True) # Merge generated content: n_indents = 1 if self.target_language in ['java', 'js'] else 0 temp_method = self.temp('embedded.method') method = temp_method.format(method_name=self.method_name, class_name=self.class_name, method_calls=fn_names, methods=fns, n_estimators=self.n_estimators, n_classes=self.n_classes) return self.indent(method, n_indents=n_indents, skipping=True)
python
def create_embedded_meth(self): # Generate related trees: fns = [] for idx, estimator in enumerate(self.estimators): tree = self.create_single_method(idx, estimator) fns.append(tree) fns = '\n'.join(fns) # Generate method or function names: fn_names = '' if self.target_language in ['c', 'java']: fn_names = [] temp_method_calls = self.temp('embedded.method_calls', n_indents=2, skipping=True) for idx, estimator in enumerate(self.estimators): cl_name = self.class_name fn_name = self.method_name + '_' + str(idx) fn_name = temp_method_calls.format(class_name=cl_name, method_name=fn_name, method_index=idx) fn_names.append(fn_name) fn_names = '\n'.join(fn_names) fn_names = self.indent(fn_names, n_indents=1, skipping=True) # Merge generated content: n_indents = 1 if self.target_language in ['java', 'js'] else 0 temp_method = self.temp('embedded.method') method = temp_method.format(method_name=self.method_name, class_name=self.class_name, method_calls=fn_names, methods=fns, n_estimators=self.n_estimators, n_classes=self.n_classes) return self.indent(method, n_indents=n_indents, skipping=True)
[ "def", "create_embedded_meth", "(", "self", ")", ":", "# Generate related trees:", "fns", "=", "[", "]", "for", "idx", ",", "estimator", "in", "enumerate", "(", "self", ".", "estimators", ")", ":", "tree", "=", "self", ".", "create_single_method", "(", "idx"...
Build the estimator methods or functions. Returns ------- :return : string The built methods as merged string.
[ "Build", "the", "estimator", "methods", "or", "functions", "." ]
04673f768310bde31f9747a68a5e070592441ef2
https://github.com/nok/sklearn-porter/blob/04673f768310bde31f9747a68a5e070592441ef2/sklearn_porter/estimator/classifier/AdaBoostClassifier/__init__.py#L289-L329
234,603
nok/sklearn-porter
sklearn_porter/Porter.py
Porter._classifiers
def _classifiers(self): """ Get a set of supported classifiers. Returns ------- classifiers : {set} The set of supported classifiers. """ # sklearn version < 0.18.0 classifiers = ( AdaBoostClassifier, BernoulliNB, DecisionTreeClassifier, ExtraTreesClassifier, GaussianNB, KNeighborsClassifier, LinearSVC, NuSVC, RandomForestClassifier, SVC, ) # sklearn version >= 0.18.0 if self.sklearn_ver[:2] >= (0, 18): from sklearn.neural_network.multilayer_perceptron \ import MLPClassifier classifiers += (MLPClassifier, ) return classifiers
python
def _classifiers(self): # sklearn version < 0.18.0 classifiers = ( AdaBoostClassifier, BernoulliNB, DecisionTreeClassifier, ExtraTreesClassifier, GaussianNB, KNeighborsClassifier, LinearSVC, NuSVC, RandomForestClassifier, SVC, ) # sklearn version >= 0.18.0 if self.sklearn_ver[:2] >= (0, 18): from sklearn.neural_network.multilayer_perceptron \ import MLPClassifier classifiers += (MLPClassifier, ) return classifiers
[ "def", "_classifiers", "(", "self", ")", ":", "# sklearn version < 0.18.0", "classifiers", "=", "(", "AdaBoostClassifier", ",", "BernoulliNB", ",", "DecisionTreeClassifier", ",", "ExtraTreesClassifier", ",", "GaussianNB", ",", "KNeighborsClassifier", ",", "LinearSVC", "...
Get a set of supported classifiers. Returns ------- classifiers : {set} The set of supported classifiers.
[ "Get", "a", "set", "of", "supported", "classifiers", "." ]
04673f768310bde31f9747a68a5e070592441ef2
https://github.com/nok/sklearn-porter/blob/04673f768310bde31f9747a68a5e070592441ef2/sklearn_porter/Porter.py#L241-L271
234,604
nok/sklearn-porter
sklearn_porter/Porter.py
Porter._regressors
def _regressors(self): """ Get a set of supported regressors. Returns ------- regressors : {set} The set of supported regressors. """ # sklearn version < 0.18.0 regressors = () # sklearn version >= 0.18.0 if self.sklearn_ver[:2] >= (0, 18): from sklearn.neural_network.multilayer_perceptron \ import MLPRegressor regressors += (MLPRegressor, ) return regressors
python
def _regressors(self): # sklearn version < 0.18.0 regressors = () # sklearn version >= 0.18.0 if self.sklearn_ver[:2] >= (0, 18): from sklearn.neural_network.multilayer_perceptron \ import MLPRegressor regressors += (MLPRegressor, ) return regressors
[ "def", "_regressors", "(", "self", ")", ":", "# sklearn version < 0.18.0", "regressors", "=", "(", ")", "# sklearn version >= 0.18.0", "if", "self", ".", "sklearn_ver", "[", ":", "2", "]", ">=", "(", "0", ",", "18", ")", ":", "from", "sklearn", ".", "neura...
Get a set of supported regressors. Returns ------- regressors : {set} The set of supported regressors.
[ "Get", "a", "set", "of", "supported", "regressors", "." ]
04673f768310bde31f9747a68a5e070592441ef2
https://github.com/nok/sklearn-porter/blob/04673f768310bde31f9747a68a5e070592441ef2/sklearn_porter/Porter.py#L274-L293
234,605
nok/sklearn-porter
sklearn_porter/Porter.py
Porter.predict
def predict(self, X, class_name=None, method_name=None, tnp_dir='tmp', keep_tmp_dir=False, num_format=lambda x: str(x)): """ Predict using the transpiled model. Parameters ---------- :param X : {array-like}, shape (n_features) or (n_samples, n_features) The input data. :param class_name : string, default: None The name for the ported class. :param method_name : string, default: None The name for the ported method. :param tnp_dir : string, default: 'tmp' The path to the temporary directory for storing the transpiled (and compiled) model. :param keep_tmp_dir : bool, default: False Whether to delete the temporary directory or not. :param num_format : lambda x, default: lambda x: str(x) The representation of the floating-point values. Returns ------- y : int or array-like, shape (n_samples,) The predicted class or classes. """ if class_name is None: class_name = self.estimator_name if method_name is None: method_name = self.target_method # Dependencies: if not self._tested_dependencies: self._test_dependencies() self._tested_dependencies = True # Support: if 'predict' not in set(self.template.SUPPORTED_METHODS): error = "Currently the given model method" \ " '{}' isn't supported.".format('predict') raise AttributeError(error) # Cleanup: Shell.call('rm -rf {}'.format(tnp_dir)) Shell.call('mkdir {}'.format(tnp_dir)) # Transpiled model: details = self.export(class_name=class_name, method_name=method_name, num_format=num_format, details=True) filename = Porter._get_filename(class_name, self.target_language) target_file = os.path.join(tnp_dir, filename) with open(target_file, str('w')) as file_: file_.write(details.get('estimator')) # Compilation command: comp_cmd = details.get('cmd').get('compilation') if comp_cmd is not None: Shell.call(comp_cmd, cwd=tnp_dir) # Execution command: exec_cmd = details.get('cmd').get('execution') exec_cmd = str(exec_cmd).split() pred_y = None # Single feature set: if exec_cmd is not None and len(X.shape) == 1: full_exec_cmd = exec_cmd + [str(sample).strip() for sample in X] pred_y = Shell.check_output(full_exec_cmd, cwd=tnp_dir) pred_y = int(pred_y) # Multiple feature sets: if exec_cmd is not None and len(X.shape) > 1: pred_y = np.empty(X.shape[0], dtype=int) for idx, features in enumerate(X): full_exec_cmd = exec_cmd + [str(f).strip() for f in features] pred = Shell.check_output(full_exec_cmd, cwd=tnp_dir) pred_y[idx] = int(pred) # Cleanup: if not keep_tmp_dir: Shell.call('rm -rf {}'.format(tnp_dir)) return pred_y
python
def predict(self, X, class_name=None, method_name=None, tnp_dir='tmp', keep_tmp_dir=False, num_format=lambda x: str(x)): if class_name is None: class_name = self.estimator_name if method_name is None: method_name = self.target_method # Dependencies: if not self._tested_dependencies: self._test_dependencies() self._tested_dependencies = True # Support: if 'predict' not in set(self.template.SUPPORTED_METHODS): error = "Currently the given model method" \ " '{}' isn't supported.".format('predict') raise AttributeError(error) # Cleanup: Shell.call('rm -rf {}'.format(tnp_dir)) Shell.call('mkdir {}'.format(tnp_dir)) # Transpiled model: details = self.export(class_name=class_name, method_name=method_name, num_format=num_format, details=True) filename = Porter._get_filename(class_name, self.target_language) target_file = os.path.join(tnp_dir, filename) with open(target_file, str('w')) as file_: file_.write(details.get('estimator')) # Compilation command: comp_cmd = details.get('cmd').get('compilation') if comp_cmd is not None: Shell.call(comp_cmd, cwd=tnp_dir) # Execution command: exec_cmd = details.get('cmd').get('execution') exec_cmd = str(exec_cmd).split() pred_y = None # Single feature set: if exec_cmd is not None and len(X.shape) == 1: full_exec_cmd = exec_cmd + [str(sample).strip() for sample in X] pred_y = Shell.check_output(full_exec_cmd, cwd=tnp_dir) pred_y = int(pred_y) # Multiple feature sets: if exec_cmd is not None and len(X.shape) > 1: pred_y = np.empty(X.shape[0], dtype=int) for idx, features in enumerate(X): full_exec_cmd = exec_cmd + [str(f).strip() for f in features] pred = Shell.check_output(full_exec_cmd, cwd=tnp_dir) pred_y[idx] = int(pred) # Cleanup: if not keep_tmp_dir: Shell.call('rm -rf {}'.format(tnp_dir)) return pred_y
[ "def", "predict", "(", "self", ",", "X", ",", "class_name", "=", "None", ",", "method_name", "=", "None", ",", "tnp_dir", "=", "'tmp'", ",", "keep_tmp_dir", "=", "False", ",", "num_format", "=", "lambda", "x", ":", "str", "(", "x", ")", ")", ":", "...
Predict using the transpiled model. Parameters ---------- :param X : {array-like}, shape (n_features) or (n_samples, n_features) The input data. :param class_name : string, default: None The name for the ported class. :param method_name : string, default: None The name for the ported method. :param tnp_dir : string, default: 'tmp' The path to the temporary directory for storing the transpiled (and compiled) model. :param keep_tmp_dir : bool, default: False Whether to delete the temporary directory or not. :param num_format : lambda x, default: lambda x: str(x) The representation of the floating-point values. Returns ------- y : int or array-like, shape (n_samples,) The predicted class or classes.
[ "Predict", "using", "the", "transpiled", "model", "." ]
04673f768310bde31f9747a68a5e070592441ef2
https://github.com/nok/sklearn-porter/blob/04673f768310bde31f9747a68a5e070592441ef2/sklearn_porter/Porter.py#L295-L388
234,606
nok/sklearn-porter
sklearn_porter/Porter.py
Porter.integrity_score
def integrity_score(self, X, method='predict', normalize=True, num_format=lambda x: str(x)): """ Compute the accuracy of the ported classifier. Parameters ---------- :param X : ndarray, shape (n_samples, n_features) Input data. :param method : string, default: 'predict' The method which should be tested. :param normalize : bool, default: True If ``False``, return the number of correctly classified samples. Otherwise, return the fraction of correctly classified samples. :param num_format : lambda x, default: lambda x: str(x) The representation of the floating-point values. Returns ------- score : float If ``normalize == True``, return the correctly classified samples (float), else it returns the number of correctly classified samples (int). The best performance is 1 with ``normalize == True`` and the number of samples with ``normalize == False``. """ X = np.array(X) if not X.ndim > 1: X = np.array([X]) method = str(method).strip().lower() if method not in ['predict', 'predict_proba']: error = "The given method '{}' isn't supported.".format(method) raise AttributeError(error) if method == 'predict': y_true = self.estimator.predict(X) y_pred = self.predict(X, tnp_dir='tmp_integrity_score', keep_tmp_dir=True, num_format=num_format) return accuracy_score(y_true, y_pred, normalize=normalize) return False
python
def integrity_score(self, X, method='predict', normalize=True, num_format=lambda x: str(x)): X = np.array(X) if not X.ndim > 1: X = np.array([X]) method = str(method).strip().lower() if method not in ['predict', 'predict_proba']: error = "The given method '{}' isn't supported.".format(method) raise AttributeError(error) if method == 'predict': y_true = self.estimator.predict(X) y_pred = self.predict(X, tnp_dir='tmp_integrity_score', keep_tmp_dir=True, num_format=num_format) return accuracy_score(y_true, y_pred, normalize=normalize) return False
[ "def", "integrity_score", "(", "self", ",", "X", ",", "method", "=", "'predict'", ",", "normalize", "=", "True", ",", "num_format", "=", "lambda", "x", ":", "str", "(", "x", ")", ")", ":", "X", "=", "np", ".", "array", "(", "X", ")", "if", "not",...
Compute the accuracy of the ported classifier. Parameters ---------- :param X : ndarray, shape (n_samples, n_features) Input data. :param method : string, default: 'predict' The method which should be tested. :param normalize : bool, default: True If ``False``, return the number of correctly classified samples. Otherwise, return the fraction of correctly classified samples. :param num_format : lambda x, default: lambda x: str(x) The representation of the floating-point values. Returns ------- score : float If ``normalize == True``, return the correctly classified samples (float), else it returns the number of correctly classified samples (int). The best performance is 1 with ``normalize == True`` and the number of samples with ``normalize == False``.
[ "Compute", "the", "accuracy", "of", "the", "ported", "classifier", "." ]
04673f768310bde31f9747a68a5e070592441ef2
https://github.com/nok/sklearn-porter/blob/04673f768310bde31f9747a68a5e070592441ef2/sklearn_porter/Porter.py#L390-L434
234,607
nok/sklearn-porter
sklearn_porter/Porter.py
Porter._get_filename
def _get_filename(class_name, language): """ Generate the specific filename. Parameters ---------- :param class_name : str The used class name. :param language : {'c', 'go', 'java', 'js', 'php', 'ruby'} The target programming language. Returns ------- filename : str The generated filename. """ name = str(class_name).strip() lang = str(language) # Name: if language in ['java', 'php']: name = "".join([name[0].upper() + name[1:]]) # Suffix: suffix = { 'c': 'c', 'java': 'java', 'js': 'js', 'go': 'go', 'php': 'php', 'ruby': 'rb' } suffix = suffix.get(lang, lang) # Filename: return '{}.{}'.format(name, suffix)
python
def _get_filename(class_name, language): name = str(class_name).strip() lang = str(language) # Name: if language in ['java', 'php']: name = "".join([name[0].upper() + name[1:]]) # Suffix: suffix = { 'c': 'c', 'java': 'java', 'js': 'js', 'go': 'go', 'php': 'php', 'ruby': 'rb' } suffix = suffix.get(lang, lang) # Filename: return '{}.{}'.format(name, suffix)
[ "def", "_get_filename", "(", "class_name", ",", "language", ")", ":", "name", "=", "str", "(", "class_name", ")", ".", "strip", "(", ")", "lang", "=", "str", "(", "language", ")", "# Name:", "if", "language", "in", "[", "'java'", ",", "'php'", "]", "...
Generate the specific filename. Parameters ---------- :param class_name : str The used class name. :param language : {'c', 'go', 'java', 'js', 'php', 'ruby'} The target programming language. Returns ------- filename : str The generated filename.
[ "Generate", "the", "specific", "filename", "." ]
04673f768310bde31f9747a68a5e070592441ef2
https://github.com/nok/sklearn-porter/blob/04673f768310bde31f9747a68a5e070592441ef2/sklearn_porter/Porter.py#L456-L488
234,608
nok/sklearn-porter
sklearn_porter/Porter.py
Porter._get_commands
def _get_commands(filename, class_name, language): """ Generate the related compilation and execution commands. Parameters ---------- :param filename : str The used filename. :param class_name : str The used class name. :param language : {'c', 'go', 'java', 'js', 'php', 'ruby'} The target programming language. Returns ------- comp_cmd, exec_cmd : (str, str) The compilation and execution command. """ cname = str(class_name) fname = str(filename) lang = str(language) # Compilation variants: comp_vars = { # gcc brain.c -o brain 'c': 'gcc {} -lm -o {}'.format(fname, cname), # javac Brain.java 'java': 'javac {}'.format(fname), # go build -o brain brain.go 'go': 'go build -o {} {}.go'.format(cname, cname) } comp_cmd = comp_vars.get(lang, None) # Execution variants: exec_vars = { # ./brain 'c': os.path.join('.', cname), # java -classpath . Brain 'java': 'java -classpath . {}'.format(cname), # node brain.js 'js': 'node {}'.format(fname), # php -f Brain.php 'php': 'php -f {}'.format(fname), # ruby brain.rb 'ruby': 'ruby {}'.format(fname), # ./brain 'go': os.path.join('.', cname), } exec_cmd = exec_vars.get(lang, None) return comp_cmd, exec_cmd
python
def _get_commands(filename, class_name, language): cname = str(class_name) fname = str(filename) lang = str(language) # Compilation variants: comp_vars = { # gcc brain.c -o brain 'c': 'gcc {} -lm -o {}'.format(fname, cname), # javac Brain.java 'java': 'javac {}'.format(fname), # go build -o brain brain.go 'go': 'go build -o {} {}.go'.format(cname, cname) } comp_cmd = comp_vars.get(lang, None) # Execution variants: exec_vars = { # ./brain 'c': os.path.join('.', cname), # java -classpath . Brain 'java': 'java -classpath . {}'.format(cname), # node brain.js 'js': 'node {}'.format(fname), # php -f Brain.php 'php': 'php -f {}'.format(fname), # ruby brain.rb 'ruby': 'ruby {}'.format(fname), # ./brain 'go': os.path.join('.', cname), } exec_cmd = exec_vars.get(lang, None) return comp_cmd, exec_cmd
[ "def", "_get_commands", "(", "filename", ",", "class_name", ",", "language", ")", ":", "cname", "=", "str", "(", "class_name", ")", "fname", "=", "str", "(", "filename", ")", "lang", "=", "str", "(", "language", ")", "# Compilation variants:", "comp_vars", ...
Generate the related compilation and execution commands. Parameters ---------- :param filename : str The used filename. :param class_name : str The used class name. :param language : {'c', 'go', 'java', 'js', 'php', 'ruby'} The target programming language. Returns ------- comp_cmd, exec_cmd : (str, str) The compilation and execution command.
[ "Generate", "the", "related", "compilation", "and", "execution", "commands", "." ]
04673f768310bde31f9747a68a5e070592441ef2
https://github.com/nok/sklearn-porter/blob/04673f768310bde31f9747a68a5e070592441ef2/sklearn_porter/Porter.py#L491-L544
234,609
daviddrysdale/python-phonenumbers
python/phonenumbers/asyoutypeformatter.py
_get_metadata_for_region
def _get_metadata_for_region(region_code): """The metadata needed by this class is the same for all regions sharing the same country calling code. Therefore, we return the metadata for "main" region for this country calling code.""" country_calling_code = country_code_for_region(region_code) main_country = region_code_for_country_code(country_calling_code) # Set to a default instance of the metadata. This allows us to # function with an incorrect region code, even if formatting only # works for numbers specified with "+". return PhoneMetadata.metadata_for_region(main_country, _EMPTY_METADATA)
python
def _get_metadata_for_region(region_code): country_calling_code = country_code_for_region(region_code) main_country = region_code_for_country_code(country_calling_code) # Set to a default instance of the metadata. This allows us to # function with an incorrect region code, even if formatting only # works for numbers specified with "+". return PhoneMetadata.metadata_for_region(main_country, _EMPTY_METADATA)
[ "def", "_get_metadata_for_region", "(", "region_code", ")", ":", "country_calling_code", "=", "country_code_for_region", "(", "region_code", ")", "main_country", "=", "region_code_for_country_code", "(", "country_calling_code", ")", "# Set to a default instance of the metadata. T...
The metadata needed by this class is the same for all regions sharing the same country calling code. Therefore, we return the metadata for "main" region for this country calling code.
[ "The", "metadata", "needed", "by", "this", "class", "is", "the", "same", "for", "all", "regions", "sharing", "the", "same", "country", "calling", "code", ".", "Therefore", "we", "return", "the", "metadata", "for", "main", "region", "for", "this", "country", ...
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/asyoutypeformatter.py#L70-L79
234,610
daviddrysdale/python-phonenumbers
python/phonenumbers/asyoutypeformatter.py
AsYouTypeFormatter._maybe_create_new_template
def _maybe_create_new_template(self): """Returns True if a new template is created as opposed to reusing the existing template. When there are multiple available formats, the formatter uses the first format where a formatting template could be created. """ ii = 0 while ii < len(self._possible_formats): number_format = self._possible_formats[ii] pattern = number_format.pattern if self._current_formatting_pattern == pattern: return False if self._create_formatting_template(number_format): self._current_formatting_pattern = pattern if number_format.national_prefix_formatting_rule is None: self._should_add_space_after_national_prefix = False else: self._should_add_space_after_national_prefix = bool(_NATIONAL_PREFIX_SEPARATORS_PATTERN.search(number_format.national_prefix_formatting_rule)) # With a new formatting template, the matched position using # the old template needs to be reset. self._last_match_position = 0 return True else: # Remove the current number format from _possible_formats del self._possible_formats[ii] ii -= 1 ii += 1 self._able_to_format = False return False
python
def _maybe_create_new_template(self): ii = 0 while ii < len(self._possible_formats): number_format = self._possible_formats[ii] pattern = number_format.pattern if self._current_formatting_pattern == pattern: return False if self._create_formatting_template(number_format): self._current_formatting_pattern = pattern if number_format.national_prefix_formatting_rule is None: self._should_add_space_after_national_prefix = False else: self._should_add_space_after_national_prefix = bool(_NATIONAL_PREFIX_SEPARATORS_PATTERN.search(number_format.national_prefix_formatting_rule)) # With a new formatting template, the matched position using # the old template needs to be reset. self._last_match_position = 0 return True else: # Remove the current number format from _possible_formats del self._possible_formats[ii] ii -= 1 ii += 1 self._able_to_format = False return False
[ "def", "_maybe_create_new_template", "(", "self", ")", ":", "ii", "=", "0", "while", "ii", "<", "len", "(", "self", ".", "_possible_formats", ")", ":", "number_format", "=", "self", ".", "_possible_formats", "[", "ii", "]", "pattern", "=", "number_format", ...
Returns True if a new template is created as opposed to reusing the existing template. When there are multiple available formats, the formatter uses the first format where a formatting template could be created.
[ "Returns", "True", "if", "a", "new", "template", "is", "created", "as", "opposed", "to", "reusing", "the", "existing", "template", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/asyoutypeformatter.py#L97-L125
234,611
daviddrysdale/python-phonenumbers
python/phonenumbers/asyoutypeformatter.py
AsYouTypeFormatter._get_formatting_template
def _get_formatting_template(self, number_pattern, number_format): """Gets a formatting template which can be used to efficiently format a partial number where digits are added one by one.""" # Create a phone number consisting only of the digit 9 that matches the # number_pattern by applying the pattern to the longest_phone_number string. longest_phone_number = unicod("999999999999999") number_re = re.compile(number_pattern) m = number_re.search(longest_phone_number) # this will always succeed a_phone_number = m.group(0) # No formatting template can be created if the number of digits # entered so far is longer than the maximum the current formatting # rule can accommodate. if len(a_phone_number) < len(self._national_number): return U_EMPTY_STRING # Formats the number according to number_format template = re.sub(number_pattern, number_format, a_phone_number) # Replaces each digit with character _DIGIT_PLACEHOLDER template = re.sub("9", _DIGIT_PLACEHOLDER, template) return template
python
def _get_formatting_template(self, number_pattern, number_format): # Create a phone number consisting only of the digit 9 that matches the # number_pattern by applying the pattern to the longest_phone_number string. longest_phone_number = unicod("999999999999999") number_re = re.compile(number_pattern) m = number_re.search(longest_phone_number) # this will always succeed a_phone_number = m.group(0) # No formatting template can be created if the number of digits # entered so far is longer than the maximum the current formatting # rule can accommodate. if len(a_phone_number) < len(self._national_number): return U_EMPTY_STRING # Formats the number according to number_format template = re.sub(number_pattern, number_format, a_phone_number) # Replaces each digit with character _DIGIT_PLACEHOLDER template = re.sub("9", _DIGIT_PLACEHOLDER, template) return template
[ "def", "_get_formatting_template", "(", "self", ",", "number_pattern", ",", "number_format", ")", ":", "# Create a phone number consisting only of the digit 9 that matches the", "# number_pattern by applying the pattern to the longest_phone_number string.", "longest_phone_number", "=", "...
Gets a formatting template which can be used to efficiently format a partial number where digits are added one by one.
[ "Gets", "a", "formatting", "template", "which", "can", "be", "used", "to", "efficiently", "format", "a", "partial", "number", "where", "digits", "are", "added", "one", "by", "one", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/asyoutypeformatter.py#L185-L203
234,612
daviddrysdale/python-phonenumbers
python/phonenumbers/asyoutypeformatter.py
AsYouTypeFormatter.input_digit
def input_digit(self, next_char, remember_position=False): """Formats a phone number on-the-fly as each digit is entered. If remember_position is set, remembers the position where next_char is inserted, so that it can be retrieved later by using get_remembered_position. The remembered position will be automatically adjusted if additional formatting characters are later inserted/removed in front of next_char. Arguments: next_char -- The most recently entered digit of a phone number. Formatting characters are allowed, but as soon as they are encountered this method formats the number as entered and not "as you type" anymore. Full width digits and Arabic-indic digits are allowed, and will be shown as they are. remember_position -- Whether to track the position where next_char is inserted. Returns the partially formatted phone number. """ self._accrued_input += next_char if remember_position: self._original_position = len(self._accrued_input) # We do formatting on-the-fly only when each character entered is # either a digit, or a plus sign (accepted at the start of the number # only). if not self._is_digit_or_leading_plus_sign(next_char): self._able_to_format = False self._input_has_formatting = True else: next_char = self._normalize_and_accrue_digits_and_plus_sign(next_char, remember_position) if not self._able_to_format: # When we are unable to format because of reasons other than that # formatting chars have been entered, it can be due to really long # IDDs or NDDs. If that is the case, we might be able to do # formatting again after extracting them. if self._input_has_formatting: self._current_output = self._accrued_input return self._current_output elif self._attempt_to_extract_idd(): if self._attempt_to_extract_ccc(): self._current_output = self._attempt_to_choose_pattern_with_prefix_extracted() return self._current_output elif self._able_to_extract_longer_ndd(): # Add an additional space to separate long NDD and national # significant number for readability. We don't set # should_add_space_after_national_prefix to True, since we don't # want this to change later when we choose formatting # templates. self._prefix_before_national_number += _SEPARATOR_BEFORE_NATIONAL_NUMBER self._current_output = self._attempt_to_choose_pattern_with_prefix_extracted() return self._current_output self._current_output = self._accrued_input return self._current_output # We start to attempt to format only when at least # MIN_LEADING_DIGITS_LENGTH digits (the plus sign is counted as a # digit as well for this purpose) have been entered. len_input = len(self._accrued_input_without_formatting) if len_input >= 0 and len_input <= 2: self._current_output = self._accrued_input return self._current_output elif len_input == 3: if self._attempt_to_extract_idd(): self._is_expecting_country_calling_code = True else: # No IDD or plus sign is found, might be entering in national format. self._extracted_national_prefix = self._remove_national_prefix_from_national_number() self._current_output = self._attempt_to_choose_formatting_pattern() return self._current_output if self._is_expecting_country_calling_code: if self._attempt_to_extract_ccc(): self._is_expecting_country_calling_code = False self._current_output = self._prefix_before_national_number + self._national_number return self._current_output if len(self._possible_formats) > 0: # The formatting patterns are already chosen. temp_national_number = self._input_digit_helper(next_char) # See if the accrued digits can be formatted properly already. If # not, use the results from input_digit_helper, which does # formatting based on the formatting pattern chosen. formatted_number = self._attempt_to_format_accrued_digits() if len(formatted_number) > 0: self._current_output = formatted_number return self._current_output self._narrow_down_possible_formats(self._national_number) if self._maybe_create_new_template(): self._current_output = self._input_accrued_national_number() return self._current_output if self._able_to_format: self._current_output = self._append_national_number(temp_national_number) return self._current_output else: self._current_output = self._accrued_input return self._current_output else: self._current_output = self._attempt_to_choose_formatting_pattern() return self._current_output
python
def input_digit(self, next_char, remember_position=False): self._accrued_input += next_char if remember_position: self._original_position = len(self._accrued_input) # We do formatting on-the-fly only when each character entered is # either a digit, or a plus sign (accepted at the start of the number # only). if not self._is_digit_or_leading_plus_sign(next_char): self._able_to_format = False self._input_has_formatting = True else: next_char = self._normalize_and_accrue_digits_and_plus_sign(next_char, remember_position) if not self._able_to_format: # When we are unable to format because of reasons other than that # formatting chars have been entered, it can be due to really long # IDDs or NDDs. If that is the case, we might be able to do # formatting again after extracting them. if self._input_has_formatting: self._current_output = self._accrued_input return self._current_output elif self._attempt_to_extract_idd(): if self._attempt_to_extract_ccc(): self._current_output = self._attempt_to_choose_pattern_with_prefix_extracted() return self._current_output elif self._able_to_extract_longer_ndd(): # Add an additional space to separate long NDD and national # significant number for readability. We don't set # should_add_space_after_national_prefix to True, since we don't # want this to change later when we choose formatting # templates. self._prefix_before_national_number += _SEPARATOR_BEFORE_NATIONAL_NUMBER self._current_output = self._attempt_to_choose_pattern_with_prefix_extracted() return self._current_output self._current_output = self._accrued_input return self._current_output # We start to attempt to format only when at least # MIN_LEADING_DIGITS_LENGTH digits (the plus sign is counted as a # digit as well for this purpose) have been entered. len_input = len(self._accrued_input_without_formatting) if len_input >= 0 and len_input <= 2: self._current_output = self._accrued_input return self._current_output elif len_input == 3: if self._attempt_to_extract_idd(): self._is_expecting_country_calling_code = True else: # No IDD or plus sign is found, might be entering in national format. self._extracted_national_prefix = self._remove_national_prefix_from_national_number() self._current_output = self._attempt_to_choose_formatting_pattern() return self._current_output if self._is_expecting_country_calling_code: if self._attempt_to_extract_ccc(): self._is_expecting_country_calling_code = False self._current_output = self._prefix_before_national_number + self._national_number return self._current_output if len(self._possible_formats) > 0: # The formatting patterns are already chosen. temp_national_number = self._input_digit_helper(next_char) # See if the accrued digits can be formatted properly already. If # not, use the results from input_digit_helper, which does # formatting based on the formatting pattern chosen. formatted_number = self._attempt_to_format_accrued_digits() if len(formatted_number) > 0: self._current_output = formatted_number return self._current_output self._narrow_down_possible_formats(self._national_number) if self._maybe_create_new_template(): self._current_output = self._input_accrued_national_number() return self._current_output if self._able_to_format: self._current_output = self._append_national_number(temp_national_number) return self._current_output else: self._current_output = self._accrued_input return self._current_output else: self._current_output = self._attempt_to_choose_formatting_pattern() return self._current_output
[ "def", "input_digit", "(", "self", ",", "next_char", ",", "remember_position", "=", "False", ")", ":", "self", ".", "_accrued_input", "+=", "next_char", "if", "remember_position", ":", "self", ".", "_original_position", "=", "len", "(", "self", ".", "_accrued_...
Formats a phone number on-the-fly as each digit is entered. If remember_position is set, remembers the position where next_char is inserted, so that it can be retrieved later by using get_remembered_position. The remembered position will be automatically adjusted if additional formatting characters are later inserted/removed in front of next_char. Arguments: next_char -- The most recently entered digit of a phone number. Formatting characters are allowed, but as soon as they are encountered this method formats the number as entered and not "as you type" anymore. Full width digits and Arabic-indic digits are allowed, and will be shown as they are. remember_position -- Whether to track the position where next_char is inserted. Returns the partially formatted phone number.
[ "Formats", "a", "phone", "number", "on", "-", "the", "-", "fly", "as", "each", "digit", "is", "entered", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/asyoutypeformatter.py#L254-L353
234,613
daviddrysdale/python-phonenumbers
python/phonenumbers/asyoutypeformatter.py
AsYouTypeFormatter._attempt_to_format_accrued_digits
def _attempt_to_format_accrued_digits(self): """Checks to see if there is an exact pattern match for these digits. If so, we should use this instead of any other formatting template whose leadingDigitsPattern also matches the input. """ for number_format in self._possible_formats: num_re = re.compile(number_format.pattern) if fullmatch(num_re, self._national_number): if number_format.national_prefix_formatting_rule is None: self._should_add_space_after_national_prefix = False else: self._should_add_space_after_national_prefix = bool(_NATIONAL_PREFIX_SEPARATORS_PATTERN.search(number_format.national_prefix_formatting_rule)) formatted_number = re.sub(num_re, number_format.format, self._national_number) return self._append_national_number(formatted_number) return U_EMPTY_STRING
python
def _attempt_to_format_accrued_digits(self): for number_format in self._possible_formats: num_re = re.compile(number_format.pattern) if fullmatch(num_re, self._national_number): if number_format.national_prefix_formatting_rule is None: self._should_add_space_after_national_prefix = False else: self._should_add_space_after_national_prefix = bool(_NATIONAL_PREFIX_SEPARATORS_PATTERN.search(number_format.national_prefix_formatting_rule)) formatted_number = re.sub(num_re, number_format.format, self._national_number) return self._append_national_number(formatted_number) return U_EMPTY_STRING
[ "def", "_attempt_to_format_accrued_digits", "(", "self", ")", ":", "for", "number_format", "in", "self", ".", "_possible_formats", ":", "num_re", "=", "re", ".", "compile", "(", "number_format", ".", "pattern", ")", "if", "fullmatch", "(", "num_re", ",", "self...
Checks to see if there is an exact pattern match for these digits. If so, we should use this instead of any other formatting template whose leadingDigitsPattern also matches the input.
[ "Checks", "to", "see", "if", "there", "is", "an", "exact", "pattern", "match", "for", "these", "digits", ".", "If", "so", "we", "should", "use", "this", "instead", "of", "any", "other", "formatting", "template", "whose", "leadingDigitsPattern", "also", "matc...
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/asyoutypeformatter.py#L385-L398
234,614
daviddrysdale/python-phonenumbers
python/phonenumbers/asyoutypeformatter.py
AsYouTypeFormatter._attempt_to_choose_formatting_pattern
def _attempt_to_choose_formatting_pattern(self): """Attempts to set the formatting template and returns a string which contains the formatted version of the digits entered so far.""" # We start to attempt to format only when at least MIN_LEADING_DIGITS_LENGTH digits of national # number (excluding national prefix) have been entered. if len(self._national_number) >= _MIN_LEADING_DIGITS_LENGTH: self._get_available_formats(self._national_number) # See if the accrued digits can be formatted properly already. formatted_number = self._attempt_to_format_accrued_digits() if len(formatted_number) > 0: return formatted_number if self._maybe_create_new_template(): return self._input_accrued_national_number() else: return self._accrued_input else: return self._append_national_number(self._national_number)
python
def _attempt_to_choose_formatting_pattern(self): # We start to attempt to format only when at least MIN_LEADING_DIGITS_LENGTH digits of national # number (excluding national prefix) have been entered. if len(self._national_number) >= _MIN_LEADING_DIGITS_LENGTH: self._get_available_formats(self._national_number) # See if the accrued digits can be formatted properly already. formatted_number = self._attempt_to_format_accrued_digits() if len(formatted_number) > 0: return formatted_number if self._maybe_create_new_template(): return self._input_accrued_national_number() else: return self._accrued_input else: return self._append_national_number(self._national_number)
[ "def", "_attempt_to_choose_formatting_pattern", "(", "self", ")", ":", "# We start to attempt to format only when at least MIN_LEADING_DIGITS_LENGTH digits of national", "# number (excluding national prefix) have been entered.", "if", "len", "(", "self", ".", "_national_number", ")", "...
Attempts to set the formatting template and returns a string which contains the formatted version of the digits entered so far.
[ "Attempts", "to", "set", "the", "formatting", "template", "and", "returns", "a", "string", "which", "contains", "the", "formatted", "version", "of", "the", "digits", "entered", "so", "far", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/asyoutypeformatter.py#L433-L449
234,615
daviddrysdale/python-phonenumbers
python/phonenumbers/asyoutypeformatter.py
AsYouTypeFormatter._input_accrued_national_number
def _input_accrued_national_number(self): """Invokes input_digit_helper on each digit of the national number accrued, and returns a formatted string in the end.""" length_of_national_number = len(self._national_number) if length_of_national_number > 0: temp_national_number = U_EMPTY_STRING for ii in range(length_of_national_number): temp_national_number = self._input_digit_helper(self._national_number[ii]) if self._able_to_format: return self._append_national_number(temp_national_number) else: return self._accrued_input else: return self._prefix_before_national_number
python
def _input_accrued_national_number(self): length_of_national_number = len(self._national_number) if length_of_national_number > 0: temp_national_number = U_EMPTY_STRING for ii in range(length_of_national_number): temp_national_number = self._input_digit_helper(self._national_number[ii]) if self._able_to_format: return self._append_national_number(temp_national_number) else: return self._accrued_input else: return self._prefix_before_national_number
[ "def", "_input_accrued_national_number", "(", "self", ")", ":", "length_of_national_number", "=", "len", "(", "self", ".", "_national_number", ")", "if", "length_of_national_number", ">", "0", ":", "temp_national_number", "=", "U_EMPTY_STRING", "for", "ii", "in", "r...
Invokes input_digit_helper on each digit of the national number accrued, and returns a formatted string in the end.
[ "Invokes", "input_digit_helper", "on", "each", "digit", "of", "the", "national", "number", "accrued", "and", "returns", "a", "formatted", "string", "in", "the", "end", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/asyoutypeformatter.py#L451-L464
234,616
daviddrysdale/python-phonenumbers
python/phonenumbers/asyoutypeformatter.py
AsYouTypeFormatter._is_nanpa_number_with_national_prefix
def _is_nanpa_number_with_national_prefix(self): """Returns true if the current country is a NANPA country and the national number begins with the national prefix. """ # For NANPA numbers beginning with 1[2-9], treat the 1 as the national # prefix. The reason is that national significant numbers in NANPA # always start with [2-9] after the national prefix. Numbers # beginning with 1[01] can only be short/emergency numbers, which # don't need the national prefix. return (self._current_metadata.country_code == 1 and self._national_number[0] == '1' and self._national_number[1] != '0' and self._national_number[1] != '1')
python
def _is_nanpa_number_with_national_prefix(self): # For NANPA numbers beginning with 1[2-9], treat the 1 as the national # prefix. The reason is that national significant numbers in NANPA # always start with [2-9] after the national prefix. Numbers # beginning with 1[01] can only be short/emergency numbers, which # don't need the national prefix. return (self._current_metadata.country_code == 1 and self._national_number[0] == '1' and self._national_number[1] != '0' and self._national_number[1] != '1')
[ "def", "_is_nanpa_number_with_national_prefix", "(", "self", ")", ":", "# For NANPA numbers beginning with 1[2-9], treat the 1 as the national", "# prefix. The reason is that national significant numbers in NANPA", "# always start with [2-9] after the national prefix. Numbers", "# beginning with ...
Returns true if the current country is a NANPA country and the national number begins with the national prefix.
[ "Returns", "true", "if", "the", "current", "country", "is", "a", "NANPA", "country", "and", "the", "national", "number", "begins", "with", "the", "national", "prefix", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/asyoutypeformatter.py#L466-L476
234,617
daviddrysdale/python-phonenumbers
python/phonenumbers/asyoutypeformatter.py
AsYouTypeFormatter._attempt_to_extract_idd
def _attempt_to_extract_idd(self): """Extracts IDD and plus sign to self._prefix_before_national_number when they are available, and places the remaining input into _national_number. Returns True when accrued_input_without_formatting begins with the plus sign or valid IDD for default_country. """ international_prefix = re.compile(unicod("\\") + _PLUS_SIGN + unicod("|") + (self._current_metadata.international_prefix or U_EMPTY_STRING)) idd_match = international_prefix.match(self._accrued_input_without_formatting) if idd_match: self._is_complete_number = True start_of_country_calling_code = idd_match.end() self._national_number = self._accrued_input_without_formatting[start_of_country_calling_code:] self._prefix_before_national_number = self._accrued_input_without_formatting[:start_of_country_calling_code] if self._accrued_input_without_formatting[0] != _PLUS_SIGN: self._prefix_before_national_number += _SEPARATOR_BEFORE_NATIONAL_NUMBER return True return False
python
def _attempt_to_extract_idd(self): international_prefix = re.compile(unicod("\\") + _PLUS_SIGN + unicod("|") + (self._current_metadata.international_prefix or U_EMPTY_STRING)) idd_match = international_prefix.match(self._accrued_input_without_formatting) if idd_match: self._is_complete_number = True start_of_country_calling_code = idd_match.end() self._national_number = self._accrued_input_without_formatting[start_of_country_calling_code:] self._prefix_before_national_number = self._accrued_input_without_formatting[:start_of_country_calling_code] if self._accrued_input_without_formatting[0] != _PLUS_SIGN: self._prefix_before_national_number += _SEPARATOR_BEFORE_NATIONAL_NUMBER return True return False
[ "def", "_attempt_to_extract_idd", "(", "self", ")", ":", "international_prefix", "=", "re", ".", "compile", "(", "unicod", "(", "\"\\\\\"", ")", "+", "_PLUS_SIGN", "+", "unicod", "(", "\"|\"", ")", "+", "(", "self", ".", "_current_metadata", ".", "internatio...
Extracts IDD and plus sign to self._prefix_before_national_number when they are available, and places the remaining input into _national_number. Returns True when accrued_input_without_formatting begins with the plus sign or valid IDD for default_country.
[ "Extracts", "IDD", "and", "plus", "sign", "to", "self", ".", "_prefix_before_national_number", "when", "they", "are", "available", "and", "places", "the", "remaining", "input", "into", "_national_number", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/asyoutypeformatter.py#L501-L520
234,618
daviddrysdale/python-phonenumbers
python/phonenumbers/asyoutypeformatter.py
AsYouTypeFormatter._attempt_to_extract_ccc
def _attempt_to_extract_ccc(self): """Extracts the country calling code from the beginning of _national_number to _prefix_before_national_number when they are available, and places the remaining input into _national_number. Returns True when a valid country calling code can be found. """ if len(self._national_number) == 0: return False country_code, number_without_ccc = _extract_country_code(self._national_number) if country_code == 0: return False self._national_number = number_without_ccc new_region_code = region_code_for_country_code(country_code) if new_region_code == REGION_CODE_FOR_NON_GEO_ENTITY: self._current_metadata = PhoneMetadata.metadata_for_nongeo_region(country_code) elif new_region_code != self._default_country: self._current_metadata = _get_metadata_for_region(new_region_code) self._prefix_before_national_number += str(country_code) self._prefix_before_national_number += _SEPARATOR_BEFORE_NATIONAL_NUMBER # When we have successfully extracted the IDD, the previously # extracted NDD should be cleared because it is no longer valid. self._extracted_national_prefix = U_EMPTY_STRING return True
python
def _attempt_to_extract_ccc(self): if len(self._national_number) == 0: return False country_code, number_without_ccc = _extract_country_code(self._national_number) if country_code == 0: return False self._national_number = number_without_ccc new_region_code = region_code_for_country_code(country_code) if new_region_code == REGION_CODE_FOR_NON_GEO_ENTITY: self._current_metadata = PhoneMetadata.metadata_for_nongeo_region(country_code) elif new_region_code != self._default_country: self._current_metadata = _get_metadata_for_region(new_region_code) self._prefix_before_national_number += str(country_code) self._prefix_before_national_number += _SEPARATOR_BEFORE_NATIONAL_NUMBER # When we have successfully extracted the IDD, the previously # extracted NDD should be cleared because it is no longer valid. self._extracted_national_prefix = U_EMPTY_STRING return True
[ "def", "_attempt_to_extract_ccc", "(", "self", ")", ":", "if", "len", "(", "self", ".", "_national_number", ")", "==", "0", ":", "return", "False", "country_code", ",", "number_without_ccc", "=", "_extract_country_code", "(", "self", ".", "_national_number", ")"...
Extracts the country calling code from the beginning of _national_number to _prefix_before_national_number when they are available, and places the remaining input into _national_number. Returns True when a valid country calling code can be found.
[ "Extracts", "the", "country", "calling", "code", "from", "the", "beginning", "of", "_national_number", "to", "_prefix_before_national_number", "when", "they", "are", "available", "and", "places", "the", "remaining", "input", "into", "_national_number", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/asyoutypeformatter.py#L522-L548
234,619
daviddrysdale/python-phonenumbers
python/phonenumbers/geocoder.py
country_name_for_number
def country_name_for_number(numobj, lang, script=None, region=None): """Returns the customary display name in the given langauge for the given territory the given PhoneNumber object is from. If it could be from many territories, nothing is returned. Arguments: numobj -- The PhoneNumber object for which we want to get a text description. lang -- A 2-letter lowercase ISO 639-1 language code for the language in which the description should be returned (e.g. "en") script -- A 4-letter titlecase (first letter uppercase, rest lowercase) ISO script code as defined in ISO 15924, separated by an underscore (e.g. "Hant") region -- A 2-letter uppercase ISO 3166-1 country code (e.g. "GB") The script and region parameters are currently ignored. Returns a text description in the given language code, for the given phone number's region, or an empty string if no description is available.""" region_codes = region_codes_for_country_code(numobj.country_code) if len(region_codes) == 1: return _region_display_name(region_codes[0], lang, script, region) else: region_where_number_is_valid = u("ZZ") for region_code in region_codes: if is_valid_number_for_region(numobj, region_code): # If the number has already been found valid for one region, # then we don't know which region it belongs to so we return # nothing. if region_where_number_is_valid != u("ZZ"): return U_EMPTY_STRING region_where_number_is_valid = region_code return _region_display_name(region_where_number_is_valid, lang, script, region)
python
def country_name_for_number(numobj, lang, script=None, region=None): region_codes = region_codes_for_country_code(numobj.country_code) if len(region_codes) == 1: return _region_display_name(region_codes[0], lang, script, region) else: region_where_number_is_valid = u("ZZ") for region_code in region_codes: if is_valid_number_for_region(numobj, region_code): # If the number has already been found valid for one region, # then we don't know which region it belongs to so we return # nothing. if region_where_number_is_valid != u("ZZ"): return U_EMPTY_STRING region_where_number_is_valid = region_code return _region_display_name(region_where_number_is_valid, lang, script, region)
[ "def", "country_name_for_number", "(", "numobj", ",", "lang", ",", "script", "=", "None", ",", "region", "=", "None", ")", ":", "region_codes", "=", "region_codes_for_country_code", "(", "numobj", ".", "country_code", ")", "if", "len", "(", "region_codes", ")"...
Returns the customary display name in the given langauge for the given territory the given PhoneNumber object is from. If it could be from many territories, nothing is returned. Arguments: numobj -- The PhoneNumber object for which we want to get a text description. lang -- A 2-letter lowercase ISO 639-1 language code for the language in which the description should be returned (e.g. "en") script -- A 4-letter titlecase (first letter uppercase, rest lowercase) ISO script code as defined in ISO 15924, separated by an underscore (e.g. "Hant") region -- A 2-letter uppercase ISO 3166-1 country code (e.g. "GB") The script and region parameters are currently ignored. Returns a text description in the given language code, for the given phone number's region, or an empty string if no description is available.
[ "Returns", "the", "customary", "display", "name", "in", "the", "given", "langauge", "for", "the", "given", "territory", "the", "given", "PhoneNumber", "object", "is", "from", ".", "If", "it", "could", "be", "from", "many", "territories", "nothing", "is", "re...
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/geocoder.py#L75-L106
234,620
daviddrysdale/python-phonenumbers
python/phonenumbers/geocoder.py
description_for_valid_number
def description_for_valid_number(numobj, lang, script=None, region=None): """Return a text description of a PhoneNumber object, in the language provided. The description might consist of the name of the country where the phone number is from and/or the name of the geographical area the phone number is from if more detailed information is available. If the phone number is from the same region as the user, only a lower-level description will be returned, if one exists. Otherwise, the phone number's region will be returned, with optionally some more detailed information. For example, for a user from the region "US" (United States), we would show "Mountain View, CA" for a particular number, omitting the United States from the description. For a user from the United Kingdom (region "GB"), for the same number we may show "Mountain View, CA, United States" or even just "United States". This function assumes the validity of the number passed in has already been checked, and that the number is suitable for geocoding. We consider fixed-line and mobile numbers possible candidates for geocoding. Arguments: numobj -- A valid PhoneNumber object for which we want to get a text description. lang -- A 2-letter lowercase ISO 639-1 language code for the language in which the description should be returned (e.g. "en") script -- A 4-letter titlecase (first letter uppercase, rest lowercase) ISO script code as defined in ISO 15924, separated by an underscore (e.g. "Hant") region -- The region code for a given user. This region will be omitted from the description if the phone number comes from this region. It should be a two-letter upper-case CLDR region code. Returns a text description in the given language code, for the given phone number, or an empty string if the number could come from multiple countries, or the country code is in fact invalid.""" number_region = region_code_for_number(numobj) if region is None or region == number_region: mobile_token = country_mobile_token(numobj.country_code) national_number = national_significant_number(numobj) if mobile_token != U_EMPTY_STRING and national_number.startswith(mobile_token): # In some countries, eg. Argentina, mobile numbers have a mobile token # before the national destination code, this should be removed before # geocoding. national_number = national_number[len(mobile_token):] region = region_code_for_country_code(numobj.country_code) try: copied_numobj = parse(national_number, region) except NumberParseException: # If this happens, just re-use what we had. copied_numobj = numobj area_description = _prefix_description_for_number(GEOCODE_DATA, GEOCODE_LONGEST_PREFIX, copied_numobj, lang, script, region) else: area_description = _prefix_description_for_number(GEOCODE_DATA, GEOCODE_LONGEST_PREFIX, numobj, lang, script, region) if area_description != "": return area_description else: # Fall back to the description of the number's region return country_name_for_number(numobj, lang, script, region) else: # Otherwise, we just show the region(country) name for now. return _region_display_name(number_region, lang, script, region)
python
def description_for_valid_number(numobj, lang, script=None, region=None): number_region = region_code_for_number(numobj) if region is None or region == number_region: mobile_token = country_mobile_token(numobj.country_code) national_number = national_significant_number(numobj) if mobile_token != U_EMPTY_STRING and national_number.startswith(mobile_token): # In some countries, eg. Argentina, mobile numbers have a mobile token # before the national destination code, this should be removed before # geocoding. national_number = national_number[len(mobile_token):] region = region_code_for_country_code(numobj.country_code) try: copied_numobj = parse(national_number, region) except NumberParseException: # If this happens, just re-use what we had. copied_numobj = numobj area_description = _prefix_description_for_number(GEOCODE_DATA, GEOCODE_LONGEST_PREFIX, copied_numobj, lang, script, region) else: area_description = _prefix_description_for_number(GEOCODE_DATA, GEOCODE_LONGEST_PREFIX, numobj, lang, script, region) if area_description != "": return area_description else: # Fall back to the description of the number's region return country_name_for_number(numobj, lang, script, region) else: # Otherwise, we just show the region(country) name for now. return _region_display_name(number_region, lang, script, region)
[ "def", "description_for_valid_number", "(", "numobj", ",", "lang", ",", "script", "=", "None", ",", "region", "=", "None", ")", ":", "number_region", "=", "region_code_for_number", "(", "numobj", ")", "if", "region", "is", "None", "or", "region", "==", "numb...
Return a text description of a PhoneNumber object, in the language provided. The description might consist of the name of the country where the phone number is from and/or the name of the geographical area the phone number is from if more detailed information is available. If the phone number is from the same region as the user, only a lower-level description will be returned, if one exists. Otherwise, the phone number's region will be returned, with optionally some more detailed information. For example, for a user from the region "US" (United States), we would show "Mountain View, CA" for a particular number, omitting the United States from the description. For a user from the United Kingdom (region "GB"), for the same number we may show "Mountain View, CA, United States" or even just "United States". This function assumes the validity of the number passed in has already been checked, and that the number is suitable for geocoding. We consider fixed-line and mobile numbers possible candidates for geocoding. Arguments: numobj -- A valid PhoneNumber object for which we want to get a text description. lang -- A 2-letter lowercase ISO 639-1 language code for the language in which the description should be returned (e.g. "en") script -- A 4-letter titlecase (first letter uppercase, rest lowercase) ISO script code as defined in ISO 15924, separated by an underscore (e.g. "Hant") region -- The region code for a given user. This region will be omitted from the description if the phone number comes from this region. It should be a two-letter upper-case CLDR region code. Returns a text description in the given language code, for the given phone number, or an empty string if the number could come from multiple countries, or the country code is in fact invalid.
[ "Return", "a", "text", "description", "of", "a", "PhoneNumber", "object", "in", "the", "language", "provided", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/geocoder.py#L122-L189
234,621
daviddrysdale/python-phonenumbers
python/phonenumbers/geocoder.py
description_for_number
def description_for_number(numobj, lang, script=None, region=None): """Return a text description of a PhoneNumber object for the given language. The description might consist of the name of the country where the phone number is from and/or the name of the geographical area the phone number is from. This function explicitly checks the validity of the number passed in Arguments: numobj -- The PhoneNumber object for which we want to get a text description. lang -- A 2-letter lowercase ISO 639-1 language code for the language in which the description should be returned (e.g. "en") script -- A 4-letter titlecase (first letter uppercase, rest lowercase) ISO script code as defined in ISO 15924, separated by an underscore (e.g. "Hant") region -- The region code for a given user. This region will be omitted from the description if the phone number comes from this region. It should be a two-letter upper-case CLDR region code. Returns a text description in the given language code, for the given phone number, or an empty string if no description is available.""" ntype = number_type(numobj) if ntype == PhoneNumberType.UNKNOWN: return "" elif not is_number_type_geographical(ntype, numobj.country_code): return country_name_for_number(numobj, lang, script, region) return description_for_valid_number(numobj, lang, script, region)
python
def description_for_number(numobj, lang, script=None, region=None): ntype = number_type(numobj) if ntype == PhoneNumberType.UNKNOWN: return "" elif not is_number_type_geographical(ntype, numobj.country_code): return country_name_for_number(numobj, lang, script, region) return description_for_valid_number(numobj, lang, script, region)
[ "def", "description_for_number", "(", "numobj", ",", "lang", ",", "script", "=", "None", ",", "region", "=", "None", ")", ":", "ntype", "=", "number_type", "(", "numobj", ")", "if", "ntype", "==", "PhoneNumberType", ".", "UNKNOWN", ":", "return", "\"\"", ...
Return a text description of a PhoneNumber object for the given language. The description might consist of the name of the country where the phone number is from and/or the name of the geographical area the phone number is from. This function explicitly checks the validity of the number passed in Arguments: numobj -- The PhoneNumber object for which we want to get a text description. lang -- A 2-letter lowercase ISO 639-1 language code for the language in which the description should be returned (e.g. "en") script -- A 4-letter titlecase (first letter uppercase, rest lowercase) ISO script code as defined in ISO 15924, separated by an underscore (e.g. "Hant") region -- The region code for a given user. This region will be omitted from the description if the phone number comes from this region. It should be a two-letter upper-case CLDR region code. Returns a text description in the given language code, for the given phone number, or an empty string if no description is available.
[ "Return", "a", "text", "description", "of", "a", "PhoneNumber", "object", "for", "the", "given", "language", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/geocoder.py#L194-L220
234,622
daviddrysdale/python-phonenumbers
python/phonenumbers/prefix.py
_find_lang
def _find_lang(langdict, lang, script, region): """Return the entry in the dictionary for the given language information.""" # Check if we should map this to a different locale. full_locale = _full_locale(lang, script, region) if (full_locale in _LOCALE_NORMALIZATION_MAP and _LOCALE_NORMALIZATION_MAP[full_locale] in langdict): return langdict[_LOCALE_NORMALIZATION_MAP[full_locale]] # First look for the full locale if full_locale in langdict: return langdict[full_locale] # Then look for lang, script as a combination if script is not None: lang_script = "%s_%s" % (lang, script) if lang_script in langdict: return langdict[lang_script] # Next look for lang, region as a combination if region is not None: lang_region = "%s_%s" % (lang, region) if lang_region in langdict: return langdict[lang_region] # Fall back to bare language code lookup if lang in langdict: return langdict[lang] # Possibly fall back to english if _may_fall_back_to_english(lang): return langdict.get("en", None) else: return None
python
def _find_lang(langdict, lang, script, region): # Check if we should map this to a different locale. full_locale = _full_locale(lang, script, region) if (full_locale in _LOCALE_NORMALIZATION_MAP and _LOCALE_NORMALIZATION_MAP[full_locale] in langdict): return langdict[_LOCALE_NORMALIZATION_MAP[full_locale]] # First look for the full locale if full_locale in langdict: return langdict[full_locale] # Then look for lang, script as a combination if script is not None: lang_script = "%s_%s" % (lang, script) if lang_script in langdict: return langdict[lang_script] # Next look for lang, region as a combination if region is not None: lang_region = "%s_%s" % (lang, region) if lang_region in langdict: return langdict[lang_region] # Fall back to bare language code lookup if lang in langdict: return langdict[lang] # Possibly fall back to english if _may_fall_back_to_english(lang): return langdict.get("en", None) else: return None
[ "def", "_find_lang", "(", "langdict", ",", "lang", ",", "script", ",", "region", ")", ":", "# Check if we should map this to a different locale.", "full_locale", "=", "_full_locale", "(", "lang", ",", "script", ",", "region", ")", "if", "(", "full_locale", "in", ...
Return the entry in the dictionary for the given language information.
[ "Return", "the", "entry", "in", "the", "dictionary", "for", "the", "given", "language", "information", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/prefix.py#L29-L56
234,623
daviddrysdale/python-phonenumbers
python/phonenumbers/prefix.py
_prefix_description_for_number
def _prefix_description_for_number(data, longest_prefix, numobj, lang, script=None, region=None): """Return a text description of a PhoneNumber for the given language. Arguments: data -- Prefix dictionary to lookup up number in. longest_prefix -- Length of the longest key in data. numobj -- The PhoneNumber object for which we want to get a text description. lang -- A 2-letter lowercase ISO 639-1 language code for the language in which the description should be returned (e.g. "en") script -- A 4-letter titlecase (first letter uppercase, rest lowercase) ISO script code as defined in ISO 15924, separated by an underscore (e.g. "Hant") region -- A 2-letter uppercase ISO 3166-1 country code (e.g. "GB") Returns a text description in the given language code, for the given phone number's area, or an empty string if no description is available.""" e164_num = format_number(numobj, PhoneNumberFormat.E164) if not e164_num.startswith(U_PLUS): # pragma no cover # Can only hit this arm if there's an internal error in the rest of # the library raise Exception("Expect E164 number to start with +") for prefix_len in range(longest_prefix, 0, -1): prefix = e164_num[1:(1 + prefix_len)] if prefix in data: # This prefix is present in the geocoding data, as a dictionary # mapping language info to location name. name = _find_lang(data[prefix], lang, script, region) if name is not None: return name else: return U_EMPTY_STRING return U_EMPTY_STRING
python
def _prefix_description_for_number(data, longest_prefix, numobj, lang, script=None, region=None): e164_num = format_number(numobj, PhoneNumberFormat.E164) if not e164_num.startswith(U_PLUS): # pragma no cover # Can only hit this arm if there's an internal error in the rest of # the library raise Exception("Expect E164 number to start with +") for prefix_len in range(longest_prefix, 0, -1): prefix = e164_num[1:(1 + prefix_len)] if prefix in data: # This prefix is present in the geocoding data, as a dictionary # mapping language info to location name. name = _find_lang(data[prefix], lang, script, region) if name is not None: return name else: return U_EMPTY_STRING return U_EMPTY_STRING
[ "def", "_prefix_description_for_number", "(", "data", ",", "longest_prefix", ",", "numobj", ",", "lang", ",", "script", "=", "None", ",", "region", "=", "None", ")", ":", "e164_num", "=", "format_number", "(", "numobj", ",", "PhoneNumberFormat", ".", "E164", ...
Return a text description of a PhoneNumber for the given language. Arguments: data -- Prefix dictionary to lookup up number in. longest_prefix -- Length of the longest key in data. numobj -- The PhoneNumber object for which we want to get a text description. lang -- A 2-letter lowercase ISO 639-1 language code for the language in which the description should be returned (e.g. "en") script -- A 4-letter titlecase (first letter uppercase, rest lowercase) ISO script code as defined in ISO 15924, separated by an underscore (e.g. "Hant") region -- A 2-letter uppercase ISO 3166-1 country code (e.g. "GB") Returns a text description in the given language code, for the given phone number's area, or an empty string if no description is available.
[ "Return", "a", "text", "description", "of", "a", "PhoneNumber", "for", "the", "given", "language", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/prefix.py#L59-L90
234,624
daviddrysdale/python-phonenumbers
python/phonenumbers/phonemetadata.py
NumberFormat.merge_from
def merge_from(self, other): """Merge information from another NumberFormat object into this one.""" if other.pattern is not None: self.pattern = other.pattern if other.format is not None: self.format = other.format self.leading_digits_pattern.extend(other.leading_digits_pattern) if other.national_prefix_formatting_rule is not None: self.national_prefix_formatting_rule = other.national_prefix_formatting_rule if other.national_prefix_optional_when_formatting is not None: self.national_prefix_optional_when_formatting = other.national_prefix_optional_when_formatting if other.domestic_carrier_code_formatting_rule is not None: self.domestic_carrier_code_formatting_rule = other.domestic_carrier_code_formatting_rule
python
def merge_from(self, other): if other.pattern is not None: self.pattern = other.pattern if other.format is not None: self.format = other.format self.leading_digits_pattern.extend(other.leading_digits_pattern) if other.national_prefix_formatting_rule is not None: self.national_prefix_formatting_rule = other.national_prefix_formatting_rule if other.national_prefix_optional_when_formatting is not None: self.national_prefix_optional_when_formatting = other.national_prefix_optional_when_formatting if other.domestic_carrier_code_formatting_rule is not None: self.domestic_carrier_code_formatting_rule = other.domestic_carrier_code_formatting_rule
[ "def", "merge_from", "(", "self", ",", "other", ")", ":", "if", "other", ".", "pattern", "is", "not", "None", ":", "self", ".", "pattern", "=", "other", ".", "pattern", "if", "other", ".", "format", "is", "not", "None", ":", "self", ".", "format", ...
Merge information from another NumberFormat object into this one.
[ "Merge", "information", "from", "another", "NumberFormat", "object", "into", "this", "one", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonemetadata.py#L107-L119
234,625
daviddrysdale/python-phonenumbers
python/phonenumbers/phonemetadata.py
PhoneNumberDesc.merge_from
def merge_from(self, other): """Merge information from another PhoneNumberDesc object into this one.""" if other.national_number_pattern is not None: self.national_number_pattern = other.national_number_pattern if other.example_number is not None: self.example_number = other.example_number
python
def merge_from(self, other): if other.national_number_pattern is not None: self.national_number_pattern = other.national_number_pattern if other.example_number is not None: self.example_number = other.example_number
[ "def", "merge_from", "(", "self", ",", "other", ")", ":", "if", "other", ".", "national_number_pattern", "is", "not", "None", ":", "self", ".", "national_number_pattern", "=", "other", ".", "national_number_pattern", "if", "other", ".", "example_number", "is", ...
Merge information from another PhoneNumberDesc object into this one.
[ "Merge", "information", "from", "another", "PhoneNumberDesc", "object", "into", "this", "one", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonemetadata.py#L193-L198
234,626
daviddrysdale/python-phonenumbers
python/phonenumbers/phonemetadata.py
PhoneMetadata.load_all
def load_all(kls): """Force immediate load of all metadata""" # Force expansion of contents to lists because we invalidate the iterator for region_code, loader in list(kls._region_available.items()): if loader is not None: # pragma no cover loader(region_code) kls._region_available[region_code] = None for country_code, loader in list(kls._country_code_available.items()): if loader is not None: loader(country_code) kls._country_code_available[region_code] = None
python
def load_all(kls): # Force expansion of contents to lists because we invalidate the iterator for region_code, loader in list(kls._region_available.items()): if loader is not None: # pragma no cover loader(region_code) kls._region_available[region_code] = None for country_code, loader in list(kls._country_code_available.items()): if loader is not None: loader(country_code) kls._country_code_available[region_code] = None
[ "def", "load_all", "(", "kls", ")", ":", "# Force expansion of contents to lists because we invalidate the iterator", "for", "region_code", ",", "loader", "in", "list", "(", "kls", ".", "_region_available", ".", "items", "(", ")", ")", ":", "if", "loader", "is", "...
Force immediate load of all metadata
[ "Force", "immediate", "load", "of", "all", "metadata" ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonemetadata.py#L317-L327
234,627
daviddrysdale/python-phonenumbers
python/phonenumbers/pb2/__init__.py
PBToPy
def PBToPy(numpb): """Convert phonenumber_pb2.PhoneNumber to phonenumber.PhoneNumber""" 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_zero=numpb.italian_leading_zero if numpb.HasField("italian_leading_zero") else None, number_of_leading_zeros=numpb.number_of_leading_zeros if numpb.HasField("number_of_leading_zeros") else None, raw_input=numpb.raw_input if numpb.HasField("raw_input") else None, country_code_source=numpb.country_code_source if numpb.HasField("country_code_source") else CountryCodeSource.UNSPECIFIED, preferred_domestic_carrier_code=numpb.preferred_domestic_carrier_code if numpb.HasField("preferred_domestic_carrier_code") else None)
python
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_zero=numpb.italian_leading_zero if numpb.HasField("italian_leading_zero") else None, number_of_leading_zeros=numpb.number_of_leading_zeros if numpb.HasField("number_of_leading_zeros") else None, raw_input=numpb.raw_input if numpb.HasField("raw_input") else None, country_code_source=numpb.country_code_source if numpb.HasField("country_code_source") else CountryCodeSource.UNSPECIFIED, preferred_domestic_carrier_code=numpb.preferred_domestic_carrier_code if numpb.HasField("preferred_domestic_carrier_code") else None)
[ "def", "PBToPy", "(", "numpb", ")", ":", "return", "PhoneNumber", "(", "country_code", "=", "numpb", ".", "country_code", "if", "numpb", ".", "HasField", "(", "\"country_code\"", ")", "else", "None", ",", "national_number", "=", "numpb", ".", "national_number"...
Convert phonenumber_pb2.PhoneNumber to phonenumber.PhoneNumber
[ "Convert", "phonenumber_pb2", ".", "PhoneNumber", "to", "phonenumber", ".", "PhoneNumber" ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/pb2/__init__.py#L42-L51
234,628
daviddrysdale/python-phonenumbers
python/phonenumbers/pb2/__init__.py
PyToPB
def PyToPB(numobj): """Convert phonenumber.PhoneNumber to phonenumber_pb2.PhoneNumber""" 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.italian_leading_zero is not None: numpb.italian_leading_zero = numobj.italian_leading_zero if numobj.number_of_leading_zeros is not None: numpb.number_of_leading_zeros = numobj.number_of_leading_zeros if numobj.raw_input is not None: numpb.raw_input = numobj.raw_input numpb.country_code_source = numobj.country_code_source if numobj.preferred_domestic_carrier_code is not None: numpb.preferred_domestic_carrier_code = numobj.preferred_domestic_carrier_code return numpb
python
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.italian_leading_zero is not None: numpb.italian_leading_zero = numobj.italian_leading_zero if numobj.number_of_leading_zeros is not None: numpb.number_of_leading_zeros = numobj.number_of_leading_zeros if numobj.raw_input is not None: numpb.raw_input = numobj.raw_input numpb.country_code_source = numobj.country_code_source if numobj.preferred_domestic_carrier_code is not None: numpb.preferred_domestic_carrier_code = numobj.preferred_domestic_carrier_code return numpb
[ "def", "PyToPB", "(", "numobj", ")", ":", "numpb", "=", "PhoneNumberPB", "(", ")", "if", "numobj", ".", "country_code", "is", "not", "None", ":", "numpb", ".", "country_code", "=", "numobj", ".", "country_code", "if", "numobj", ".", "national_number", "is"...
Convert phonenumber.PhoneNumber to phonenumber_pb2.PhoneNumber
[ "Convert", "phonenumber", ".", "PhoneNumber", "to", "phonenumber_pb2", ".", "PhoneNumber" ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/pb2/__init__.py#L53-L71
234,629
daviddrysdale/python-phonenumbers
tools/python/buildmetadatafromxml.py
_get_unique_child
def _get_unique_child(xtag, eltname): """Get the unique child element under xtag with name 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
python
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
[ "def", "_get_unique_child", "(", "xtag", ",", "eltname", ")", ":", "try", ":", "results", "=", "xtag", ".", "findall", "(", "eltname", ")", "if", "len", "(", "results", ")", ">", "1", ":", "raise", "Exception", "(", "\"Multiple elements found where 0/1 expec...
Get the unique child element under xtag with name eltname
[ "Get", "the", "unique", "child", "element", "under", "xtag", "with", "name", "eltname" ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/tools/python/buildmetadatafromxml.py#L116-L127
234,630
daviddrysdale/python-phonenumbers
tools/python/buildmetadatafromxml.py
_get_unique_child_value
def _get_unique_child_value(xtag, eltname): """Get the text content of the unique child element under xtag with name eltname""" xelt = _get_unique_child(xtag, eltname) if xelt is None: return None else: return xelt.text
python
def _get_unique_child_value(xtag, eltname): xelt = _get_unique_child(xtag, eltname) if xelt is None: return None else: return xelt.text
[ "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
[ "Get", "the", "text", "content", "of", "the", "unique", "child", "element", "under", "xtag", "with", "name", "eltname" ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/tools/python/buildmetadatafromxml.py#L130-L136
234,631
daviddrysdale/python-phonenumbers
tools/python/buildmetadatafromxml.py
_extract_lengths
def _extract_lengths(ll): """Extract list of possible lengths from string""" 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')) max = int(m.group('max')) for ii in range(min, max + 1): results.add(ii) return sorted(list(results))
python
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')) max = int(m.group('max')) for ii in range(min, max + 1): results.add(ii) return sorted(list(results))
[ "def", "_extract_lengths", "(", "ll", ")", ":", "results", "=", "set", "(", ")", "if", "ll", "is", "None", ":", "return", "[", "]", "for", "val", "in", "ll", ".", "split", "(", "','", ")", ":", "m", "=", "_NUM_RE", ".", "match", "(", "val", ")"...
Extract list of possible lengths from string
[ "Extract", "list", "of", "possible", "lengths", "from", "string" ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/tools/python/buildmetadatafromxml.py#L169-L186
234,632
daviddrysdale/python-phonenumbers
tools/python/buildmetadatafromxml.py
_standalone
def _standalone(argv): """Parse the given XML file and emit generated code.""" 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__, file=sys.stderr) sys.exit(1) elif opt in ("-s", "--short"): short_data = True elif opt in ("-l", "--lax"): global lax lax = True elif opt in ("-a", "--alt"): alternate = arg else: prnt("Unknown option %s" % opt, file=sys.stderr) prnt(__doc__, file=sys.stderr) sys.exit(1) if len(args) != 3: prnt(__doc__, file=sys.stderr) sys.exit(1) pmd = XPhoneNumberMetadata(args[0], short_data) if alternate is not None: pmd.add_alternate_formats(alternate) pmd.emit_metadata_py(args[1], args[2])
python
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__, file=sys.stderr) sys.exit(1) elif opt in ("-s", "--short"): short_data = True elif opt in ("-l", "--lax"): global lax lax = True elif opt in ("-a", "--alt"): alternate = arg else: prnt("Unknown option %s" % opt, file=sys.stderr) prnt(__doc__, file=sys.stderr) sys.exit(1) if len(args) != 3: prnt(__doc__, file=sys.stderr) sys.exit(1) pmd = XPhoneNumberMetadata(args[0], short_data) if alternate is not None: pmd.add_alternate_formats(alternate) pmd.emit_metadata_py(args[1], args[2])
[ "def", "_standalone", "(", "argv", ")", ":", "alternate", "=", "None", "short_data", "=", "False", "try", ":", "opts", ",", "args", "=", "getopt", ".", "getopt", "(", "argv", ",", "\"hlsa:\"", ",", "(", "\"help\"", ",", "\"lax\"", ",", "\"short\"", ","...
Parse the given XML file and emit generated code.
[ "Parse", "the", "given", "XML", "file", "and", "emit", "generated", "code", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/tools/python/buildmetadatafromxml.py#L670-L701
234,633
daviddrysdale/python-phonenumbers
tools/python/buildmetadatafromxml.py
XPhoneNumberMetadata.add_alternate_formats
def add_alternate_formats(self, filename): """Add phone number alternate format metadata retrieved from XML""" with open(filename, "r") as infile: xtree = etree.parse(infile) self.alt_territory = {} # country_code to XAlternateTerritory xterritories = xtree.find(TOP_XPATH) for xterritory in xterritories: if xterritory.tag == TERRITORY_TAG: terrobj = XAlternateTerritory(xterritory) id = str(terrobj.country_code) if id in self.alt_territory: raise Exception("Duplicate entry for %s" % id) self.alt_territory[id] = terrobj else: raise Exception("Unexpected element %s found" % xterritory.tag)
python
def add_alternate_formats(self, filename): with open(filename, "r") as infile: xtree = etree.parse(infile) self.alt_territory = {} # country_code to XAlternateTerritory xterritories = xtree.find(TOP_XPATH) for xterritory in xterritories: if xterritory.tag == TERRITORY_TAG: terrobj = XAlternateTerritory(xterritory) id = str(terrobj.country_code) if id in self.alt_territory: raise Exception("Duplicate entry for %s" % id) self.alt_territory[id] = terrobj else: raise Exception("Unexpected element %s found" % xterritory.tag)
[ "def", "add_alternate_formats", "(", "self", ",", "filename", ")", ":", "with", "open", "(", "filename", ",", "\"r\"", ")", "as", "infile", ":", "xtree", "=", "etree", ".", "parse", "(", "infile", ")", "self", ".", "alt_territory", "=", "{", "}", "# co...
Add phone number alternate format metadata retrieved from XML
[ "Add", "phone", "number", "alternate", "format", "metadata", "retrieved", "from", "XML" ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/tools/python/buildmetadatafromxml.py#L567-L581
234,634
daviddrysdale/python-phonenumbers
tools/python/buildmetadatafromxml.py
XPhoneNumberMetadata.emit_metadata_for_region_py
def emit_metadata_for_region_py(self, region, region_filename, module_prefix): """Emit Python code generating the metadata for the given region""" 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 = %s" % (terrobj.identifier(), terrobj), file=outfile)
python
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 = %s" % (terrobj.identifier(), terrobj), file=outfile)
[ "def", "emit_metadata_for_region_py", "(", "self", ",", "region", ",", "region_filename", ",", "module_prefix", ")", ":", "terrobj", "=", "self", ".", "territory", "[", "region", "]", "with", "open", "(", "region_filename", ",", "\"w\"", ")", "as", "outfile", ...
Emit Python code generating the metadata for the given region
[ "Emit", "Python", "code", "generating", "the", "metadata", "for", "the", "given", "region" ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/tools/python/buildmetadatafromxml.py#L586-L591
234,635
daviddrysdale/python-phonenumbers
tools/python/buildmetadatafromxml.py
XPhoneNumberMetadata.emit_alt_formats_for_cc_py
def emit_alt_formats_for_cc_py(self, cc, cc_filename, module_prefix): """Emit Python code generating the alternate format metadata for the given country code""" 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)
python
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)
[ "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", ":", "prn...
Emit Python code generating the alternate format metadata for the given country code
[ "Emit", "Python", "code", "generating", "the", "alternate", "format", "metadata", "for", "the", "given", "country", "code" ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/tools/python/buildmetadatafromxml.py#L593-L598
234,636
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
_create_extn_pattern
def _create_extn_pattern(single_extn_symbols): """Helper initialiser method to create the regular-expression pattern to match extensions, allowing the one-char extension symbols provided by single_extn_symbols.""" # There are three regular expressions here. The first covers RFC 3966 # format, where the extension is added using ";ext=". The second more # generic one starts with optional white space and ends with an optional # full stop (.), followed by zero or more spaces/tabs/commas and then the # numbers themselves. The other one covers the special case of American # numbers where the extension is written with a hash at the end, such as # "- 503#". Note that the only capturing groups should be around the # digits that you want to capture as part of the extension, or else # parsing will fail! Canonical-equivalence doesn't seem to be an option # with Android java, so we allow two options for representing the accented # o - the character itself, and one in the unicode decomposed form with # the combining acute accent. 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)") + u("[:\\.\uFF0E]?[ \u00A0\\t,-]*") + _CAPTURING_EXTN_DIGITS + u("#?|") + u("[- ]+(") + _DIGITS + u("{1,5})#"))
python
def _create_extn_pattern(single_extn_symbols): # There are three regular expressions here. The first covers RFC 3966 # format, where the extension is added using ";ext=". The second more # generic one starts with optional white space and ends with an optional # full stop (.), followed by zero or more spaces/tabs/commas and then the # numbers themselves. The other one covers the special case of American # numbers where the extension is written with a hash at the end, such as # "- 503#". Note that the only capturing groups should be around the # digits that you want to capture as part of the extension, or else # parsing will fail! Canonical-equivalence doesn't seem to be an option # with Android java, so we allow two options for representing the accented # o - the character itself, and one in the unicode decomposed form with # the combining acute accent. 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)") + u("[:\\.\uFF0E]?[ \u00A0\\t,-]*") + _CAPTURING_EXTN_DIGITS + u("#?|") + u("[- ]+(") + _DIGITS + u("{1,5})#"))
[ "def", "_create_extn_pattern", "(", "single_extn_symbols", ")", ":", "# There are three regular expressions here. The first covers RFC 3966", "# format, where the extension is added using \";ext=\". The second more", "# generic one starts with optional white space and ends with an optional", "# fu...
Helper initialiser method to create the regular-expression pattern to match extensions, allowing the one-char extension symbols provided by single_extn_symbols.
[ "Helper", "initialiser", "method", "to", "create", "the", "regular", "-", "expression", "pattern", "to", "match", "extensions", "allowing", "the", "one", "-", "char", "extension", "symbols", "provided", "by", "single_extn_symbols", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L302-L323
234,637
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
_copy_number_format
def _copy_number_format(other): """Return a mutable copy of the given NumberFormat object""" 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_prefix_optional_when_formatting, domestic_carrier_code_formatting_rule=other.domestic_carrier_code_formatting_rule) copy._mutable = True return copy
python
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_prefix_optional_when_formatting, domestic_carrier_code_formatting_rule=other.domestic_carrier_code_formatting_rule) copy._mutable = True return copy
[ "def", "_copy_number_format", "(", "other", ")", ":", "copy", "=", "NumberFormat", "(", "pattern", "=", "other", ".", "pattern", ",", "format", "=", "other", ".", "format", ",", "leading_digits_pattern", "=", "list", "(", "other", ".", "leading_digits_pattern"...
Return a mutable copy of the given NumberFormat object
[ "Return", "a", "mutable", "copy", "of", "the", "given", "NumberFormat", "object" ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L497-L506
234,638
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
_extract_possible_number
def _extract_possible_number(number): """Attempt to extract a possible number from the string passed in. This currently strips all leading characters that cannot be used to start a phone number. Characters that can be used to start a phone number are defined in the VALID_START_CHAR_PATTERN. If none of these characters are found in the number passed in, an empty string is returned. This function also attempts to strip off any alternative extensions or endings if two or more are present, such as in the case of: (530) 583-6985 x302/x2303. The second extension here makes this actually two phone numbers, (530) 583-6985 x302 and (530) 583-6985 x2303. We remove the second extension so that the first number is parsed correctly. Arguments: number -- The string that might contain a phone number. Returns the number, stripped of any non-phone-number prefix (such as "Tel:") or an empty string if no character used to start phone numbers (such as + or any digit) is found in the number """ match = _VALID_START_CHAR_PATTERN.search(number) if match: number = number[match.start():] # Remove trailing non-alpha non-numberical characters. trailing_chars_match = _UNWANTED_END_CHAR_PATTERN.search(number) if trailing_chars_match: number = number[:trailing_chars_match.start()] # Check for extra numbers at the end. second_number_match = _SECOND_NUMBER_START_PATTERN.search(number) if second_number_match: number = number[:second_number_match.start()] return number else: return U_EMPTY_STRING
python
def _extract_possible_number(number): match = _VALID_START_CHAR_PATTERN.search(number) if match: number = number[match.start():] # Remove trailing non-alpha non-numberical characters. trailing_chars_match = _UNWANTED_END_CHAR_PATTERN.search(number) if trailing_chars_match: number = number[:trailing_chars_match.start()] # Check for extra numbers at the end. second_number_match = _SECOND_NUMBER_START_PATTERN.search(number) if second_number_match: number = number[:second_number_match.start()] return number else: return U_EMPTY_STRING
[ "def", "_extract_possible_number", "(", "number", ")", ":", "match", "=", "_VALID_START_CHAR_PATTERN", ".", "search", "(", "number", ")", "if", "match", ":", "number", "=", "number", "[", "match", ".", "start", "(", ")", ":", "]", "# Remove trailing non-alpha ...
Attempt to extract a possible number from the string passed in. This currently strips all leading characters that cannot be used to start a phone number. Characters that can be used to start a phone number are defined in the VALID_START_CHAR_PATTERN. If none of these characters are found in the number passed in, an empty string is returned. This function also attempts to strip off any alternative extensions or endings if two or more are present, such as in the case of: (530) 583-6985 x302/x2303. The second extension here makes this actually two phone numbers, (530) 583-6985 x302 and (530) 583-6985 x2303. We remove the second extension so that the first number is parsed correctly. Arguments: number -- The string that might contain a phone number. Returns the number, stripped of any non-phone-number prefix (such as "Tel:") or an empty string if no character used to start phone numbers (such as + or any digit) is found in the number
[ "Attempt", "to", "extract", "a", "possible", "number", "from", "the", "string", "passed", "in", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L509-L542
234,639
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
_is_viable_phone_number
def _is_viable_phone_number(number): """Checks to see if a string could possibly be a phone number. At the moment, checks to see that the string begins with at least 2 digits, ignoring any punctuation commonly found in phone numbers. This method does not require the number to be normalized in advance - but does assume that leading non-number symbols have been removed, such as by the method _extract_possible_number. Arguments: number -- string to be checked for viability as a phone number Returns True if the number could be a phone number of some sort, otherwise False """ if len(number) < _MIN_LENGTH_FOR_NSN: return False match = fullmatch(_VALID_PHONE_NUMBER_PATTERN, number) return bool(match)
python
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)
[ "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. At the moment, checks to see that the string begins with at least 2 digits, ignoring any punctuation commonly found in phone numbers. This method does not require the number to be normalized in advance - but does assume that leading non-number symbols have been removed, such as by the method _extract_possible_number. Arguments: number -- string to be checked for viability as a phone number Returns True if the number could be a phone number of some sort, otherwise False
[ "Checks", "to", "see", "if", "a", "string", "could", "possibly", "be", "a", "phone", "number", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L545-L563
234,640
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
length_of_geographical_area_code
def length_of_geographical_area_code(numobj): """Return length of the geographical area code for a number. Gets the length of the geographical area code from the PhoneNumber object passed in, so that clients could use it to split a national significant number into geographical area code and subscriber number. It works in such a way that the resultant subscriber number should be diallable, at least on some devices. An example of how this could be used: >>> import phonenumbers >>> numobj = phonenumbers.parse("16502530000", "US") >>> nsn = phonenumbers.national_significant_number(numobj) >>> ac_len = phonenumbers.length_of_geographical_area_code(numobj) >>> if ac_len > 0: ... area_code = nsn[:ac_len] ... subscriber_number = nsn[ac_len:] ... else: ... area_code = "" ... subscriber_number = nsn N.B.: area code is a very ambiguous concept, so the I18N team generally recommends against using it for most purposes, but recommends using the more general national_number instead. Read the following carefully before deciding to use this method: - geographical area codes change over time, and this method honors those changes; therefore, it doesn't guarantee the stability of the result it produces. - subscriber numbers may not be diallable from all devices (notably mobile devices, which typically require the full national_number to be dialled in most countries). - most non-geographical numbers have no area codes, including numbers from non-geographical entities. - some geographical numbers have no area codes. Arguments: numobj -- The PhoneNumber object to find the length of the area code form. Returns the length of area code of the PhoneNumber object passed in. """ metadata = PhoneMetadata.metadata_for_region(region_code_for_number(numobj), None) if metadata is None: return 0 # If a country doesn't use a national prefix, and this number doesn't have # an Italian leading zero, we assume it is a closed dialling plan with no # area codes. if metadata.national_prefix is None and not numobj.italian_leading_zero: return 0 ntype = number_type(numobj) country_code = numobj.country_code if (ntype == PhoneNumberType.MOBILE and (country_code in _GEO_MOBILE_COUNTRIES_WITHOUT_MOBILE_AREA_CODES)): # Note this is a rough heuristic; it doesn't cover Indonesia well, for # example, where area codes are present for some mobile phones but not # for others. We have no better way of representing this in the # metadata at this point. return 0 if not is_number_type_geographical(ntype, country_code): return 0 return length_of_national_destination_code(numobj)
python
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 a country doesn't use a national prefix, and this number doesn't have # an Italian leading zero, we assume it is a closed dialling plan with no # area codes. if metadata.national_prefix is None and not numobj.italian_leading_zero: return 0 ntype = number_type(numobj) country_code = numobj.country_code if (ntype == PhoneNumberType.MOBILE and (country_code in _GEO_MOBILE_COUNTRIES_WITHOUT_MOBILE_AREA_CODES)): # Note this is a rough heuristic; it doesn't cover Indonesia well, for # example, where area codes are present for some mobile phones but not # for others. We have no better way of representing this in the # metadata at this point. return 0 if not is_number_type_geographical(ntype, country_code): return 0 return length_of_national_destination_code(numobj)
[ "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 a count...
Return length of the geographical area code for a number. Gets the length of the geographical area code from the PhoneNumber object passed in, so that clients could use it to split a national significant number into geographical area code and subscriber number. It works in such a way that the resultant subscriber number should be diallable, at least on some devices. An example of how this could be used: >>> import phonenumbers >>> numobj = phonenumbers.parse("16502530000", "US") >>> nsn = phonenumbers.national_significant_number(numobj) >>> ac_len = phonenumbers.length_of_geographical_area_code(numobj) >>> if ac_len > 0: ... area_code = nsn[:ac_len] ... subscriber_number = nsn[ac_len:] ... else: ... area_code = "" ... subscriber_number = nsn N.B.: area code is a very ambiguous concept, so the I18N team generally recommends against using it for most purposes, but recommends using the more general national_number instead. Read the following carefully before deciding to use this method: - geographical area codes change over time, and this method honors those changes; therefore, it doesn't guarantee the stability of the result it produces. - subscriber numbers may not be diallable from all devices (notably mobile devices, which typically require the full national_number to be dialled in most countries). - most non-geographical numbers have no area codes, including numbers from non-geographical entities. - some geographical numbers have no area codes. Arguments: numobj -- The PhoneNumber object to find the length of the area code form. Returns the length of area code of the PhoneNumber object passed in.
[ "Return", "length", "of", "the", "geographical", "area", "code", "for", "a", "number", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L638-L701
234,641
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
length_of_national_destination_code
def length_of_national_destination_code(numobj): """Return length of the national destination code code for a number. Gets the length of the national destination code (NDC) from the PhoneNumber object passed in, so that clients could use it to split a national significant number into NDC and subscriber number. The NDC of a phone number is normally the first group of digit(s) right after the country calling code when the number is formatted in the international format, if there is a subscriber number part that follows. N.B.: similar to an area code, not all numbers have an NDC! An example of how this could be used: >>> import phonenumbers >>> numobj = phonenumbers.parse("18002530000", "US") >>> nsn = phonenumbers.national_significant_number(numobj) >>> ndc_len = phonenumbers.length_of_national_destination_code(numobj) >>> if ndc_len > 0: ... national_destination_code = nsn[:ndc_len] ... subscriber_number = nsn[ndc_len:] ... else: ... national_destination_code = "" ... subscriber_number = nsn Refer to the unittests to see the difference between this function and length_of_geographical_area_code. Arguments: numobj -- The PhoneNumber object to find the length of the NDC from. Returns the length of NDC of the PhoneNumber object passed in, which could be zero. """ if numobj.extension is not None: # We don't want to alter the object given to us, but we don't want to # include the extension when we format it, so we copy it and clear the # extension here. 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.split(NON_DIGITS_PATTERN, nsn) # The pattern will start with "+COUNTRY_CODE " so the first group will # always be the empty string (before the + symbol) and the second group # will be the country calling code. The third group will be area code if # it is not the last group. if len(number_groups) <= 3: return 0 if number_type(numobj) == PhoneNumberType.MOBILE: # For example Argentinian mobile numbers, when formatted in the # international format, are in the form of +54 9 NDC XXXX... As a # result, we take the length of the third group (NDC) and add the # length of the second group (which is the mobile token), which also # forms part of the national significant number. This assumes that # the mobile token is always formatted separately from the rest of the # phone number. mobile_token = country_mobile_token(numobj.country_code) if mobile_token != U_EMPTY_STRING: return len(number_groups[2]) + len(number_groups[3]) return len(number_groups[2])
python
def length_of_national_destination_code(numobj): if numobj.extension is not None: # We don't want to alter the object given to us, but we don't want to # include the extension when we format it, so we copy it and clear the # extension here. 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.split(NON_DIGITS_PATTERN, nsn) # The pattern will start with "+COUNTRY_CODE " so the first group will # always be the empty string (before the + symbol) and the second group # will be the country calling code. The third group will be area code if # it is not the last group. if len(number_groups) <= 3: return 0 if number_type(numobj) == PhoneNumberType.MOBILE: # For example Argentinian mobile numbers, when formatted in the # international format, are in the form of +54 9 NDC XXXX... As a # result, we take the length of the third group (NDC) and add the # length of the second group (which is the mobile token), which also # forms part of the national significant number. This assumes that # the mobile token is always formatted separately from the rest of the # phone number. mobile_token = country_mobile_token(numobj.country_code) if mobile_token != U_EMPTY_STRING: return len(number_groups[2]) + len(number_groups[3]) return len(number_groups[2])
[ "def", "length_of_national_destination_code", "(", "numobj", ")", ":", "if", "numobj", ".", "extension", "is", "not", "None", ":", "# We don't want to alter the object given to us, but we don't want to", "# include the extension when we format it, so we copy it and clear the", "# ext...
Return length of the national destination code code for a number. Gets the length of the national destination code (NDC) from the PhoneNumber object passed in, so that clients could use it to split a national significant number into NDC and subscriber number. The NDC of a phone number is normally the first group of digit(s) right after the country calling code when the number is formatted in the international format, if there is a subscriber number part that follows. N.B.: similar to an area code, not all numbers have an NDC! An example of how this could be used: >>> import phonenumbers >>> numobj = phonenumbers.parse("18002530000", "US") >>> nsn = phonenumbers.national_significant_number(numobj) >>> ndc_len = phonenumbers.length_of_national_destination_code(numobj) >>> if ndc_len > 0: ... national_destination_code = nsn[:ndc_len] ... subscriber_number = nsn[ndc_len:] ... else: ... national_destination_code = "" ... subscriber_number = nsn Refer to the unittests to see the difference between this function and length_of_geographical_area_code. Arguments: numobj -- The PhoneNumber object to find the length of the NDC from. Returns the length of NDC of the PhoneNumber object passed in, which could be zero.
[ "Return", "length", "of", "the", "national", "destination", "code", "code", "for", "a", "number", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L704-L769
234,642
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
_normalize_helper
def _normalize_helper(number, replacements, remove_non_matches): """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. Arguments: number -- a string representing a phone number replacements -- a mapping of characters to what they should be replaced by in the normalized version of the phone number remove_non_matches -- indicates whether characters that are not able to be replaced should be stripped from the number. If this is False, they will be left unchanged in the number. Returns the normalized string version of the phone number. """ 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) # If neither of the above are true, we remove this character return U_EMPTY_STRING.join(normalized_number)
python
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) # If neither of the above are true, we remove this character return U_EMPTY_STRING.join(normalized_number)
[ "def", "_normalize_helper", "(", "number", ",", "replacements", ",", "remove_non_matches", ")", ":", "normalized_number", "=", "[", "]", "for", "char", "in", "number", ":", "new_digit", "=", "replacements", ".", "get", "(", "char", ".", "upper", "(", ")", ...
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. Arguments: number -- a string representing a phone number replacements -- a mapping of characters to what they should be replaced by in the normalized version of the phone number remove_non_matches -- indicates whether characters that are not able to be replaced should be stripped from the number. If this is False, they will be left unchanged in the number. Returns the normalized string version of the phone number.
[ "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", "i...
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L784-L807
234,643
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
_desc_has_data
def _desc_has_data(desc): """Returns true if there is any data set for a particular PhoneNumberDesc.""" if desc is None: return False # Checking most properties since we don't know what's present, since a custom build may have # stripped just one of them (e.g. liteBuild strips exampleNumber). We don't bother checking the # possibleLengthsLocalOnly, since if this is the only thing that's present we don't really # support the type at all: no type-specific methods will work with only this data. return ((desc.example_number is not None) or _desc_has_possible_number_data(desc) or (desc.national_number_pattern is not None))
python
def _desc_has_data(desc): if desc is None: return False # Checking most properties since we don't know what's present, since a custom build may have # stripped just one of them (e.g. liteBuild strips exampleNumber). We don't bother checking the # possibleLengthsLocalOnly, since if this is the only thing that's present we don't really # support the type at all: no type-specific methods will work with only this data. return ((desc.example_number is not None) or _desc_has_possible_number_data(desc) or (desc.national_number_pattern is not None))
[ "def", "_desc_has_data", "(", "desc", ")", ":", "if", "desc", "is", "None", ":", "return", "False", "# Checking most properties since we don't know what's present, since a custom build may have", "# stripped just one of them (e.g. liteBuild strips exampleNumber). We don't bother checking...
Returns true if there is any data set for a particular PhoneNumberDesc.
[ "Returns", "true", "if", "there", "is", "any", "data", "set", "for", "a", "particular", "PhoneNumberDesc", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L836-L846
234,644
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
_supported_types_for_metadata
def _supported_types_for_metadata(metadata): """Returns the types we have metadata for based on the PhoneMetadata object passed in, which must be non-None.""" numtypes = set() for numtype in PhoneNumberType.values(): if numtype in (PhoneNumberType.FIXED_LINE_OR_MOBILE, PhoneNumberType.UNKNOWN): # Never return FIXED_LINE_OR_MOBILE (it is a convenience type, and represents that a # particular number type can't be determined) or UNKNOWN (the non-type). continue if _desc_has_data(_number_desc_by_type(metadata, numtype)): numtypes.add(numtype) return numtypes
python
def _supported_types_for_metadata(metadata): numtypes = set() for numtype in PhoneNumberType.values(): if numtype in (PhoneNumberType.FIXED_LINE_OR_MOBILE, PhoneNumberType.UNKNOWN): # Never return FIXED_LINE_OR_MOBILE (it is a convenience type, and represents that a # particular number type can't be determined) or UNKNOWN (the non-type). continue if _desc_has_data(_number_desc_by_type(metadata, numtype)): numtypes.add(numtype) return numtypes
[ "def", "_supported_types_for_metadata", "(", "metadata", ")", ":", "numtypes", "=", "set", "(", ")", "for", "numtype", "in", "PhoneNumberType", ".", "values", "(", ")", ":", "if", "numtype", "in", "(", "PhoneNumberType", ".", "FIXED_LINE_OR_MOBILE", ",", "Phon...
Returns the types we have metadata for based on the PhoneMetadata object passed in, which must be non-None.
[ "Returns", "the", "types", "we", "have", "metadata", "for", "based", "on", "the", "PhoneMetadata", "object", "passed", "in", "which", "must", "be", "non", "-", "None", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L849-L859
234,645
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
supported_types_for_region
def supported_types_for_region(region_code): """Returns the types for a given region which the library has metadata for. Will not include FIXED_LINE_OR_MOBILE (if numbers in this region could be classified as FIXED_LINE_OR_MOBILE, both FIXED_LINE and MOBILE would be present) and UNKNOWN. No types will be returned for invalid or unknown region codes. """ if not _is_valid_region_code(region_code): return set() metadata = PhoneMetadata.metadata_for_region(region_code.upper()) return _supported_types_for_metadata(metadata)
python
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)
[ "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", "(", ...
Returns the types for a given region which the library has metadata for. Will not include FIXED_LINE_OR_MOBILE (if numbers in this region could be classified as FIXED_LINE_OR_MOBILE, both FIXED_LINE and MOBILE would be present) and UNKNOWN. No types will be returned for invalid or unknown region codes.
[ "Returns", "the", "types", "for", "a", "given", "region", "which", "the", "library", "has", "metadata", "for", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L862-L874
234,646
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
is_number_type_geographical
def is_number_type_geographical(num_type, country_code): """Tests whether a phone number has a geographical association, as represented by its type and the country it belongs to. This version of isNumberGeographical exists since calculating the phone number type is expensive; if we have already done this, we don't want to do it again. """ 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))
python
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))
[ "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",...
Tests whether a phone number has a geographical association, as represented by its type and the country it belongs to. This version of isNumberGeographical exists since calculating the phone number type is expensive; if we have already done this, we don't want to do it again.
[ "Tests", "whether", "a", "phone", "number", "has", "a", "geographical", "association", "as", "represented", "by", "its", "type", "and", "the", "country", "it", "belongs", "to", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L914-L925
234,647
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
format_number
def format_number(numobj, num_format): """Formats a phone number in the specified format using default rules. Note that this does not promise to produce a phone number that the user can dial from where they are - although we do format in either 'national' or 'international' format depending on what the client asks for, we do not currently support a more abbreviated format, such as for users in the same "area" who could potentially dial the number without area code. Note that if the phone number has a country calling code of 0 or an otherwise invalid country calling code, we cannot work out which formatting rules to apply so we return the national significant number with no formatting applied. Arguments: numobj -- The phone number to be formatted. num_format -- The format the phone number should be formatted into Returns the formatted phone number. """ if numobj.national_number == 0 and numobj.raw_input is not None: # Unparseable numbers that kept their raw input just use that. This # is the only case where a number can be formatted as E164 without a # leading '+' symbol (but the original number wasn't parseable # anyway). # TODO: Consider removing the 'if' above so that unparseable strings # without raw input format to the empty string instead of "+00". 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: # Early exit for E164 case (even if the country calling code is # invalid) since no formatting of the national number needs to be # applied. Extensions are not formatted. return _prefix_number_with_country_calling_code(country_calling_code, num_format, nsn) if not _has_valid_country_calling_code(country_calling_code): return nsn # Note region_code_for_country_code() is used because formatting # information for regions which share a country calling code is contained # by only one region for performance reasons. For example, for NANPA # regions it will be contained in the metadata for US. region_code = region_code_for_country_code(country_calling_code) # Metadata cannot be None because the country calling code is valid (which # means that the region code cannot be ZZ and must be one of our supported # region codes). metadata = PhoneMetadata.metadata_for_region_or_calling_code(country_calling_code, region_code.upper()) formatted_number = _format_nsn(nsn, metadata, num_format) formatted_number = _maybe_append_formatted_extension(numobj, metadata, num_format, formatted_number) return _prefix_number_with_country_calling_code(country_calling_code, num_format, formatted_number)
python
def format_number(numobj, num_format): if numobj.national_number == 0 and numobj.raw_input is not None: # Unparseable numbers that kept their raw input just use that. This # is the only case where a number can be formatted as E164 without a # leading '+' symbol (but the original number wasn't parseable # anyway). # TODO: Consider removing the 'if' above so that unparseable strings # without raw input format to the empty string instead of "+00". 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: # Early exit for E164 case (even if the country calling code is # invalid) since no formatting of the national number needs to be # applied. Extensions are not formatted. return _prefix_number_with_country_calling_code(country_calling_code, num_format, nsn) if not _has_valid_country_calling_code(country_calling_code): return nsn # Note region_code_for_country_code() is used because formatting # information for regions which share a country calling code is contained # by only one region for performance reasons. For example, for NANPA # regions it will be contained in the metadata for US. region_code = region_code_for_country_code(country_calling_code) # Metadata cannot be None because the country calling code is valid (which # means that the region code cannot be ZZ and must be one of our supported # region codes). metadata = PhoneMetadata.metadata_for_region_or_calling_code(country_calling_code, region_code.upper()) formatted_number = _format_nsn(nsn, metadata, num_format) formatted_number = _maybe_append_formatted_extension(numobj, metadata, num_format, formatted_number) return _prefix_number_with_country_calling_code(country_calling_code, num_format, formatted_number)
[ "def", "format_number", "(", "numobj", ",", "num_format", ")", ":", "if", "numobj", ".", "national_number", "==", "0", "and", "numobj", ".", "raw_input", "is", "not", "None", ":", "# Unparseable numbers that kept their raw input just use that. This", "# is the only cas...
Formats a phone number in the specified format using default rules. Note that this does not promise to produce a phone number that the user can dial from where they are - although we do format in either 'national' or 'international' format depending on what the client asks for, we do not currently support a more abbreviated format, such as for users in the same "area" who could potentially dial the number without area code. Note that if the phone number has a country calling code of 0 or an otherwise invalid country calling code, we cannot work out which formatting rules to apply so we return the national significant number with no formatting applied. Arguments: numobj -- The phone number to be formatted. num_format -- The format the phone number should be formatted into Returns the formatted phone number.
[ "Formats", "a", "phone", "number", "in", "the", "specified", "format", "using", "default", "rules", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L939-L992
234,648
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
format_by_pattern
def format_by_pattern(numobj, number_format, user_defined_formats): """Formats a phone number using client-defined formatting rules." Note that if the phone number has a country calling code of zero or an otherwise invalid country calling code, we cannot work out things like whether there should be a national prefix applied, or how to format extensions, so we return the national significant number with no formatting applied. Arguments: numobj -- The phone number to be formatted num_format -- The format the phone number should be formatted into user_defined_formats -- formatting rules specified by clients Returns the formatted phone number. """ country_code = numobj.country_code nsn = national_significant_number(numobj) if not _has_valid_country_calling_code(country_code): return nsn # Note region_code_for_country_code() is used because formatting # information for regions which share a country calling code is contained # by only one region for performance reasons. For example, for NANPA # regions it will be contained in the metadata for US. region_code = region_code_for_country_code(country_code) # Metadata cannot be None because the country calling code is valid. metadata = PhoneMetadata.metadata_for_region_or_calling_code(country_code, region_code) formatted_number = U_EMPTY_STRING formatting_pattern = _choose_formatting_pattern_for_number(user_defined_formats, nsn) if formatting_pattern is None: # If no pattern above is matched, we format the number as a whole. formatted_number = nsn else: num_format_copy = _copy_number_format(formatting_pattern) # Before we do a replacement of the national prefix pattern $NP with # the national prefix, we need to copy the rule so that subsequent # replacements for different numbers have the appropriate national # prefix. np_formatting_rule = formatting_pattern.national_prefix_formatting_rule if np_formatting_rule: national_prefix = metadata.national_prefix if national_prefix: # Replace $NP with national prefix and $FG with the first # group (\1) matcher. np_formatting_rule = np_formatting_rule.replace(_NP_STRING, national_prefix) np_formatting_rule = np_formatting_rule.replace(_FG_STRING, unicod("\\1")) num_format_copy.national_prefix_formatting_rule = np_formatting_rule else: # We don't want to have a rule for how to format the national # prefix if there isn't one. num_format_copy.national_prefix_formatting_rule = None formatted_number = _format_nsn_using_pattern(nsn, num_format_copy, number_format) formatted_number = _maybe_append_formatted_extension(numobj, metadata, number_format, formatted_number) formatted_number = _prefix_number_with_country_calling_code(country_code, number_format, formatted_number) return formatted_number
python
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 # Note region_code_for_country_code() is used because formatting # information for regions which share a country calling code is contained # by only one region for performance reasons. For example, for NANPA # regions it will be contained in the metadata for US. region_code = region_code_for_country_code(country_code) # Metadata cannot be None because the country calling code is valid. metadata = PhoneMetadata.metadata_for_region_or_calling_code(country_code, region_code) formatted_number = U_EMPTY_STRING formatting_pattern = _choose_formatting_pattern_for_number(user_defined_formats, nsn) if formatting_pattern is None: # If no pattern above is matched, we format the number as a whole. formatted_number = nsn else: num_format_copy = _copy_number_format(formatting_pattern) # Before we do a replacement of the national prefix pattern $NP with # the national prefix, we need to copy the rule so that subsequent # replacements for different numbers have the appropriate national # prefix. np_formatting_rule = formatting_pattern.national_prefix_formatting_rule if np_formatting_rule: national_prefix = metadata.national_prefix if national_prefix: # Replace $NP with national prefix and $FG with the first # group (\1) matcher. np_formatting_rule = np_formatting_rule.replace(_NP_STRING, national_prefix) np_formatting_rule = np_formatting_rule.replace(_FG_STRING, unicod("\\1")) num_format_copy.national_prefix_formatting_rule = np_formatting_rule else: # We don't want to have a rule for how to format the national # prefix if there isn't one. num_format_copy.national_prefix_formatting_rule = None formatted_number = _format_nsn_using_pattern(nsn, num_format_copy, number_format) formatted_number = _maybe_append_formatted_extension(numobj, metadata, number_format, formatted_number) formatted_number = _prefix_number_with_country_calling_code(country_code, number_format, formatted_number) return formatted_number
[ "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", "...
Formats a phone number using client-defined formatting rules." Note that if the phone number has a country calling code of zero or an otherwise invalid country calling code, we cannot work out things like whether there should be a national prefix applied, or how to format extensions, so we return the national significant number with no formatting applied. Arguments: numobj -- The phone number to be formatted num_format -- The format the phone number should be formatted into user_defined_formats -- formatting rules specified by clients Returns the formatted phone number.
[ "Formats", "a", "phone", "number", "using", "client", "-", "defined", "formatting", "rules", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L995-L1055
234,649
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
format_national_number_with_carrier_code
def format_national_number_with_carrier_code(numobj, carrier_code): """Format a number in national format for dialing using the specified carrier. The carrier-code will always be used regardless of whether the phone number already has a preferred domestic carrier code stored. If carrier_code contains an empty string, returns the number in national format without any carrier code. Arguments: numobj -- The phone number to be formatted carrier_code -- The carrier selection code to be used Returns the formatted phone number in national format for dialing using the carrier as specified in the carrier_code. """ country_code = numobj.country_code nsn = national_significant_number(numobj) if not _has_valid_country_calling_code(country_code): return nsn # Note region_code_for_country_code() is used because formatting # information for regions which share a country calling code is contained # by only one region for performance reasons. For example, for NANPA # regions it will be contained in the metadata for US. region_code = region_code_for_country_code(country_code) # Metadata cannot be None because the country calling code is valid metadata = PhoneMetadata.metadata_for_region_or_calling_code(country_code, region_code) formatted_number = _format_nsn(nsn, metadata, PhoneNumberFormat.NATIONAL, carrier_code) formatted_number = _maybe_append_formatted_extension(numobj, metadata, PhoneNumberFormat.NATIONAL, formatted_number) formatted_number = _prefix_number_with_country_calling_code(country_code, PhoneNumberFormat.NATIONAL, formatted_number) return formatted_number
python
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 # Note region_code_for_country_code() is used because formatting # information for regions which share a country calling code is contained # by only one region for performance reasons. For example, for NANPA # regions it will be contained in the metadata for US. region_code = region_code_for_country_code(country_code) # Metadata cannot be None because the country calling code is valid metadata = PhoneMetadata.metadata_for_region_or_calling_code(country_code, region_code) formatted_number = _format_nsn(nsn, metadata, PhoneNumberFormat.NATIONAL, carrier_code) formatted_number = _maybe_append_formatted_extension(numobj, metadata, PhoneNumberFormat.NATIONAL, formatted_number) formatted_number = _prefix_number_with_country_calling_code(country_code, PhoneNumberFormat.NATIONAL, formatted_number) return formatted_number
[ "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", "(", "coun...
Format a number in national format for dialing using the specified carrier. The carrier-code will always be used regardless of whether the phone number already has a preferred domestic carrier code stored. If carrier_code contains an empty string, returns the number in national format without any carrier code. Arguments: numobj -- The phone number to be formatted carrier_code -- The carrier selection code to be used Returns the formatted phone number in national format for dialing using the carrier as specified in the carrier_code.
[ "Format", "a", "number", "in", "national", "format", "for", "dialing", "using", "the", "specified", "carrier", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L1058-L1095
234,650
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
format_national_number_with_preferred_carrier_code
def format_national_number_with_preferred_carrier_code(numobj, fallback_carrier_code): """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 contains an empty string, return the number in national format without any carrier code. Use format_national_number_with_carrier_code instead if the carrier code passed in should take precedence over the number's preferred_domestic_carrier_code when formatting. Arguments: numobj -- The phone number to be formatted carrier_code -- The carrier selection code to be used, if none is found in the phone number itself. Returns the formatted phone number in national format for dialing using the number's preferred_domestic_carrier_code, or the fallback_carrier_code pass in if none is found. """ # Historically, we set this to an empty string when parsing with raw input # if none was found in the input string. However, this doesn't result in a # number we can dial. For this reason, we treat the empty string the same # as if it isn't set at all. 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 format_national_number_with_carrier_code(numobj, carrier_code)
python
def format_national_number_with_preferred_carrier_code(numobj, fallback_carrier_code): # Historically, we set this to an empty string when parsing with raw input # if none was found in the input string. However, this doesn't result in a # number we can dial. For this reason, we treat the empty string the same # as if it isn't set at all. 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 format_national_number_with_carrier_code(numobj, carrier_code)
[ "def", "format_national_number_with_preferred_carrier_code", "(", "numobj", ",", "fallback_carrier_code", ")", ":", "# Historically, we set this to an empty string when parsing with raw input", "# if none was found in the input string. However, this doesn't result in a", "# number we can dial. F...
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 contains an empty string, return the number in national format without any carrier code. Use format_national_number_with_carrier_code instead if the carrier code passed in should take precedence over the number's preferred_domestic_carrier_code when formatting. Arguments: numobj -- The phone number to be formatted carrier_code -- The carrier selection code to be used, if none is found in the phone number itself. Returns the formatted phone number in national format for dialing using the number's preferred_domestic_carrier_code, or the fallback_carrier_code pass in if none is found.
[ "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",...
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L1098-L1129
234,651
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
format_number_for_mobile_dialing
def format_number_for_mobile_dialing(numobj, region_calling_from, with_formatting): """Returns a number formatted in such a way that it can be dialed from a mobile phone in a specific region. If the number cannot be reached from the region (e.g. some countries block toll-free numbers from being called outside of the country), the method returns an empty string. Arguments: numobj -- The phone number to be formatted region_calling_from -- The region where the call is being placed. with_formatting -- whether the number should be returned with formatting symbols, such as spaces and dashes. Returns the formatted phone number. """ 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_STRING # Clear the extension, as that part cannot normally be dialed together with the main number. numobj_no_ext = PhoneNumber() numobj_no_ext.merge_from(numobj) numobj_no_ext.extension = None region_code = region_code_for_country_code(country_calling_code) numobj_type = number_type(numobj_no_ext) is_valid_number = (numobj_type != PhoneNumberType.UNKNOWN) if region_calling_from == region_code: is_fixed_line_or_mobile = ((numobj_type == PhoneNumberType.FIXED_LINE) or (numobj_type == PhoneNumberType.MOBILE) or (numobj_type == PhoneNumberType.FIXED_LINE_OR_MOBILE)) # Carrier codes may be needed in some countries. We handle this here. if region_code == "CO" and numobj_type == PhoneNumberType.FIXED_LINE: formatted_number = format_national_number_with_carrier_code(numobj_no_ext, _COLOMBIA_MOBILE_TO_FIXED_LINE_PREFIX) elif region_code == "BR" and is_fixed_line_or_mobile: # Historically, we set this to an empty string when parsing with # raw input if none was found in the input string. However, this # doesn't result in a number we can dial. For this reason, we # treat the empty string the same as if it isn't set at all. if (numobj_no_ext.preferred_domestic_carrier_code is not None and len(numobj_no_ext.preferred_domestic_carrier_code) > 0): formatted_number = format_national_number_with_preferred_carrier_code(numobj_no_ext, "") else: # Brazilian fixed line and mobile numbers need to be dialed with a # carrier code when called within Brazil. Without that, most of # the carriers won't connect the call. Because of that, we return # an empty string here. formatted_number = U_EMPTY_STRING elif is_valid_number and region_code == "HU": # The national format for HU numbers doesn't contain the national # prefix, because that is how numbers are normally written # down. However, the national prefix is obligatory when dialing # from a mobile phone, except for short numbers. As a result, we # add it back here if it is a valid regular length phone number. formatted_number = (ndd_prefix_for_region(region_code, True) + # strip non-digits U_SPACE + format_number(numobj_no_ext, PhoneNumberFormat.NATIONAL)) elif country_calling_code == _NANPA_COUNTRY_CODE: # For NANPA countries, we output international format for numbers # that can be dialed internationally, since that always works, # except for numbers which might potentially be short numbers, # which are always dialled in national format. metadata = PhoneMetadata.metadata_for_region(region_calling_from) if (can_be_internationally_dialled(numobj_no_ext) and _test_number_length(national_significant_number(numobj_no_ext), metadata) != ValidationResult.TOO_SHORT): formatted_number = format_number(numobj_no_ext, PhoneNumberFormat.INTERNATIONAL) else: formatted_number = format_number(numobj_no_ext, PhoneNumberFormat.NATIONAL) else: # For non-geographical countries, and Mexican, Chilean, and Uzbek # fixed line and mobile numbers, we output international format for # numbers that can be dialed internationally as that always works. if ((region_code == REGION_CODE_FOR_NON_GEO_ENTITY or ((region_code == unicod("MX") or region_code == unicod("CL") or region_code == unicod("UZ")) and is_fixed_line_or_mobile)) and can_be_internationally_dialled(numobj_no_ext)): # MX fixed line and mobile numbers should always be formatted # in international format, even when dialed within MX. For # national format to work, a carrier code needs to be used, # and the correct carrier code depends on if the caller and # callee are from the same local area. It is trickier to get # that to work correctly than using international format, # which is tested to work fine on all carriers. # CL fixed line numbers need the national prefix when dialing # in the national format, but don't have it when used for # display. The reverse is true for mobile numbers. As a # result, we output them in the international format to make # it work. # UZ mobile and fixed-line numbers have to be formatted in # international format or prefixed with special codes like 03, # 04 (for fixed-line) and 05 (for mobile) for dialling # successfully from mobile devices. As we do not have complete # information on special codes and to be consistent with # formatting across all phone types we return the number in # international format here. formatted_number = format_number(numobj_no_ext, PhoneNumberFormat.INTERNATIONAL) else: formatted_number = format_number(numobj_no_ext, PhoneNumberFormat.NATIONAL) elif is_valid_number and can_be_internationally_dialled(numobj_no_ext): # We assume that short numbers are not diallable from outside their # region, so if a number is not a valid regular length phone number, # we treat it as if it cannot be internationally dialled. if with_formatting: return format_number(numobj_no_ext, PhoneNumberFormat.INTERNATIONAL) else: return format_number(numobj_no_ext, PhoneNumberFormat.E164) if with_formatting: return formatted_number else: return normalize_diallable_chars_only(formatted_number)
python
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_STRING # Clear the extension, as that part cannot normally be dialed together with the main number. numobj_no_ext = PhoneNumber() numobj_no_ext.merge_from(numobj) numobj_no_ext.extension = None region_code = region_code_for_country_code(country_calling_code) numobj_type = number_type(numobj_no_ext) is_valid_number = (numobj_type != PhoneNumberType.UNKNOWN) if region_calling_from == region_code: is_fixed_line_or_mobile = ((numobj_type == PhoneNumberType.FIXED_LINE) or (numobj_type == PhoneNumberType.MOBILE) or (numobj_type == PhoneNumberType.FIXED_LINE_OR_MOBILE)) # Carrier codes may be needed in some countries. We handle this here. if region_code == "CO" and numobj_type == PhoneNumberType.FIXED_LINE: formatted_number = format_national_number_with_carrier_code(numobj_no_ext, _COLOMBIA_MOBILE_TO_FIXED_LINE_PREFIX) elif region_code == "BR" and is_fixed_line_or_mobile: # Historically, we set this to an empty string when parsing with # raw input if none was found in the input string. However, this # doesn't result in a number we can dial. For this reason, we # treat the empty string the same as if it isn't set at all. if (numobj_no_ext.preferred_domestic_carrier_code is not None and len(numobj_no_ext.preferred_domestic_carrier_code) > 0): formatted_number = format_national_number_with_preferred_carrier_code(numobj_no_ext, "") else: # Brazilian fixed line and mobile numbers need to be dialed with a # carrier code when called within Brazil. Without that, most of # the carriers won't connect the call. Because of that, we return # an empty string here. formatted_number = U_EMPTY_STRING elif is_valid_number and region_code == "HU": # The national format for HU numbers doesn't contain the national # prefix, because that is how numbers are normally written # down. However, the national prefix is obligatory when dialing # from a mobile phone, except for short numbers. As a result, we # add it back here if it is a valid regular length phone number. formatted_number = (ndd_prefix_for_region(region_code, True) + # strip non-digits U_SPACE + format_number(numobj_no_ext, PhoneNumberFormat.NATIONAL)) elif country_calling_code == _NANPA_COUNTRY_CODE: # For NANPA countries, we output international format for numbers # that can be dialed internationally, since that always works, # except for numbers which might potentially be short numbers, # which are always dialled in national format. metadata = PhoneMetadata.metadata_for_region(region_calling_from) if (can_be_internationally_dialled(numobj_no_ext) and _test_number_length(national_significant_number(numobj_no_ext), metadata) != ValidationResult.TOO_SHORT): formatted_number = format_number(numobj_no_ext, PhoneNumberFormat.INTERNATIONAL) else: formatted_number = format_number(numobj_no_ext, PhoneNumberFormat.NATIONAL) else: # For non-geographical countries, and Mexican, Chilean, and Uzbek # fixed line and mobile numbers, we output international format for # numbers that can be dialed internationally as that always works. if ((region_code == REGION_CODE_FOR_NON_GEO_ENTITY or ((region_code == unicod("MX") or region_code == unicod("CL") or region_code == unicod("UZ")) and is_fixed_line_or_mobile)) and can_be_internationally_dialled(numobj_no_ext)): # MX fixed line and mobile numbers should always be formatted # in international format, even when dialed within MX. For # national format to work, a carrier code needs to be used, # and the correct carrier code depends on if the caller and # callee are from the same local area. It is trickier to get # that to work correctly than using international format, # which is tested to work fine on all carriers. # CL fixed line numbers need the national prefix when dialing # in the national format, but don't have it when used for # display. The reverse is true for mobile numbers. As a # result, we output them in the international format to make # it work. # UZ mobile and fixed-line numbers have to be formatted in # international format or prefixed with special codes like 03, # 04 (for fixed-line) and 05 (for mobile) for dialling # successfully from mobile devices. As we do not have complete # information on special codes and to be consistent with # formatting across all phone types we return the number in # international format here. formatted_number = format_number(numobj_no_ext, PhoneNumberFormat.INTERNATIONAL) else: formatted_number = format_number(numobj_no_ext, PhoneNumberFormat.NATIONAL) elif is_valid_number and can_be_internationally_dialled(numobj_no_ext): # We assume that short numbers are not diallable from outside their # region, so if a number is not a valid regular length phone number, # we treat it as if it cannot be internationally dialled. if with_formatting: return format_number(numobj_no_ext, PhoneNumberFormat.INTERNATIONAL) else: return format_number(numobj_no_ext, PhoneNumberFormat.E164) if with_formatting: return formatted_number else: return normalize_diallable_chars_only(formatted_number)
[ "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",...
Returns a number formatted in such a way that it can be dialed from a mobile phone in a specific region. If the number cannot be reached from the region (e.g. some countries block toll-free numbers from being called outside of the country), the method returns an empty string. Arguments: numobj -- The phone number to be formatted region_calling_from -- The region where the call is being placed. with_formatting -- whether the number should be returned with formatting symbols, such as spaces and dashes. Returns the formatted phone number.
[ "Returns", "a", "number", "formatted", "in", "such", "a", "way", "that", "it", "can", "be", "dialed", "from", "a", "mobile", "phone", "in", "a", "specific", "region", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L1132-L1248
234,652
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
format_in_original_format
def format_in_original_format(numobj, region_calling_from): """Format a number using the original format that the number was parsed from. The original format is embedded in the country_code_source field of the PhoneNumber object passed in. If such information is missing, the number will be formatted into the NATIONAL format by default. When we don't have a formatting pattern for the number, the method returns the raw input when it is available. Note this method guarantees no digit will be inserted, removed or modified as a result of formatting. Arguments: number -- The phone number that needs to be formatted in its original number format region_calling_from -- The region whose IDD needs to be prefixed if the original number has one. Returns the formatted phone number in its original number format. """ if (numobj.raw_input is not None and not _has_formatting_pattern_for_number(numobj)): # We check if we have the formatting pattern because without that, we # might format the number as a group without national prefix. return numobj.raw_input if numobj.country_code_source is CountryCodeSource.UNSPECIFIED: return format_number(numobj, PhoneNumberFormat.NATIONAL) formatted_number = _format_original_allow_mods(numobj, region_calling_from) num_raw_input = numobj.raw_input # If no digit is inserted/removed/modified as a result of our formatting, # we return the formatted phone number; otherwise we return the raw input # the user entered. if (formatted_number is not None and num_raw_input): normalized_formatted_number = normalize_diallable_chars_only(formatted_number) normalized_raw_input = normalize_diallable_chars_only(num_raw_input) if normalized_formatted_number != normalized_raw_input: formatted_number = num_raw_input return formatted_number
python
def format_in_original_format(numobj, region_calling_from): if (numobj.raw_input is not None and not _has_formatting_pattern_for_number(numobj)): # We check if we have the formatting pattern because without that, we # might format the number as a group without national prefix. return numobj.raw_input if numobj.country_code_source is CountryCodeSource.UNSPECIFIED: return format_number(numobj, PhoneNumberFormat.NATIONAL) formatted_number = _format_original_allow_mods(numobj, region_calling_from) num_raw_input = numobj.raw_input # If no digit is inserted/removed/modified as a result of our formatting, # we return the formatted phone number; otherwise we return the raw input # the user entered. if (formatted_number is not None and num_raw_input): normalized_formatted_number = normalize_diallable_chars_only(formatted_number) normalized_raw_input = normalize_diallable_chars_only(num_raw_input) if normalized_formatted_number != normalized_raw_input: formatted_number = num_raw_input return formatted_number
[ "def", "format_in_original_format", "(", "numobj", ",", "region_calling_from", ")", ":", "if", "(", "numobj", ".", "raw_input", "is", "not", "None", "and", "not", "_has_formatting_pattern_for_number", "(", "numobj", ")", ")", ":", "# We check if we have the formatting...
Format a number using the original format that the number was parsed from. The original format is embedded in the country_code_source field of the PhoneNumber object passed in. If such information is missing, the number will be formatted into the NATIONAL format by default. When we don't have a formatting pattern for the number, the method returns the raw input when it is available. Note this method guarantees no digit will be inserted, removed or modified as a result of formatting. Arguments: number -- The phone number that needs to be formatted in its original number format region_calling_from -- The region whose IDD needs to be prefixed if the original number has one. Returns the formatted phone number in its original number format.
[ "Format", "a", "number", "using", "the", "original", "format", "that", "the", "number", "was", "parsed", "from", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L1333-L1371
234,653
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
_raw_input_contains_national_prefix
def _raw_input_contains_national_prefix(raw_input, national_prefix, region_code): """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.""" nnn = normalize_digits_only(raw_input) if nnn.startswith(national_prefix): try: # Some Japanese numbers (e.g. 00777123) might be mistaken to # contain the national prefix when written without it # (e.g. 0777123) if we just do prefix matching. To tackle that, we # check the validity of the number if the assumed national prefix # is removed (777123 won't be valid in Japan). return is_valid_number(parse(nnn[len(national_prefix):], region_code)) except NumberParseException: return False return False
python
def _raw_input_contains_national_prefix(raw_input, national_prefix, region_code): nnn = normalize_digits_only(raw_input) if nnn.startswith(national_prefix): try: # Some Japanese numbers (e.g. 00777123) might be mistaken to # contain the national prefix when written without it # (e.g. 0777123) if we just do prefix matching. To tackle that, we # check the validity of the number if the assumed national prefix # is removed (777123 won't be valid in Japan). return is_valid_number(parse(nnn[len(national_prefix):], region_code)) except NumberParseException: return False return False
[ "def", "_raw_input_contains_national_prefix", "(", "raw_input", ",", "national_prefix", ",", "region_code", ")", ":", "nnn", "=", "normalize_digits_only", "(", "raw_input", ")", "if", "nnn", ".", "startswith", "(", "national_prefix", ")", ":", "try", ":", "# Some ...
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.
[ "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", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L1428-L1443
234,654
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
national_significant_number
def national_significant_number(numobj): """Gets the national significant number of a phone number. Note that a national significant number doesn't contain a national prefix or any formatting. Arguments: numobj -- The PhoneNumber object for which the national significant number is needed. Returns the national significant number of the PhoneNumber object passed in. """ # If leading zero(s) have been set, we prefix this now. Note this is not a # national prefix. 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_number
python
def national_significant_number(numobj): # If leading zero(s) have been set, we prefix this now. Note this is not a # national prefix. 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_number
[ "def", "national_significant_number", "(", "numobj", ")", ":", "# If leading zero(s) have been set, we prefix this now. Note this is not a", "# national prefix.", "national_number", "=", "U_EMPTY_STRING", "if", "numobj", ".", "italian_leading_zero", ":", "num_zeros", "=", "numobj...
Gets the national significant number of a phone number. Note that a national significant number doesn't contain a national prefix or any formatting. Arguments: numobj -- The PhoneNumber object for which the national significant number is needed. Returns the national significant number of the PhoneNumber object passed in.
[ "Gets", "the", "national", "significant", "number", "of", "a", "phone", "number", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L1571-L1594
234,655
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
_prefix_number_with_country_calling_code
def _prefix_number_with_country_calling_code(country_code, num_format, formatted_number): """A helper function that is used by format_number and format_by_pattern.""" 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 + formatted_number elif num_format == PhoneNumberFormat.RFC3966: return _RFC3966_PREFIX + _PLUS_SIGN + unicod(country_code) + U_DASH + formatted_number else: return formatted_number
python
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 + formatted_number elif num_format == PhoneNumberFormat.RFC3966: return _RFC3966_PREFIX + _PLUS_SIGN + unicod(country_code) + U_DASH + formatted_number else: return formatted_number
[ "def", "_prefix_number_with_country_calling_code", "(", "country_code", ",", "num_format", ",", "formatted_number", ")", ":", "if", "num_format", "==", "PhoneNumberFormat", ".", "E164", ":", "return", "_PLUS_SIGN", "+", "unicod", "(", "country_code", ")", "+", "form...
A helper function that is used by format_number and format_by_pattern.
[ "A", "helper", "function", "that", "is", "used", "by", "format_number", "and", "format_by_pattern", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L1597-L1606
234,656
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
_format_nsn
def _format_nsn(number, metadata, num_format, carrier_code=None): """Format a national number.""" # Note in some regions, the national number can be written in two # completely different ways depending on whether it forms part of the # NATIONAL format or INTERNATIONAL format. The num_format parameter here # is used to specify which format to use for those cases. If a carrier_code # is specified, this will be inserted into the formatted string to replace # $CC. intl_number_formats = metadata.intl_number_format # When the intl_number_formats exists, we use that to format national # number for the INTERNATIONAL format instead of using the # number_desc.number_formats. if (len(intl_number_formats) == 0 or num_format == PhoneNumberFormat.NATIONAL): available_formats = metadata.number_format else: available_formats = metadata.intl_number_format formatting_pattern = _choose_formatting_pattern_for_number(available_formats, number) if formatting_pattern is None: return number else: return _format_nsn_using_pattern(number, formatting_pattern, num_format, carrier_code)
python
def _format_nsn(number, metadata, num_format, carrier_code=None): # Note in some regions, the national number can be written in two # completely different ways depending on whether it forms part of the # NATIONAL format or INTERNATIONAL format. The num_format parameter here # is used to specify which format to use for those cases. If a carrier_code # is specified, this will be inserted into the formatted string to replace # $CC. intl_number_formats = metadata.intl_number_format # When the intl_number_formats exists, we use that to format national # number for the INTERNATIONAL format instead of using the # number_desc.number_formats. if (len(intl_number_formats) == 0 or num_format == PhoneNumberFormat.NATIONAL): available_formats = metadata.number_format else: available_formats = metadata.intl_number_format formatting_pattern = _choose_formatting_pattern_for_number(available_formats, number) if formatting_pattern is None: return number else: return _format_nsn_using_pattern(number, formatting_pattern, num_format, carrier_code)
[ "def", "_format_nsn", "(", "number", ",", "metadata", ",", "num_format", ",", "carrier_code", "=", "None", ")", ":", "# Note in some regions, the national number can be written in two", "# completely different ways depending on whether it forms part of the", "# NATIONAL format or INT...
Format a national number.
[ "Format", "a", "national", "number", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L1609-L1631
234,657
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
invalid_example_number
def invalid_example_number(region_code): """Gets an invalid number for the specified region. This is useful for unit-testing purposes, where you want to test what will happen with an invalid number. Note that the number that is returned will always be able to be parsed and will have the correct country code. It may also be a valid *short* number/code for this region. Validity checking such numbers is handled with shortnumberinfo. Arguments: region_code -- The region for which an example number is needed. Returns an invalid number for the specified region. Returns None when an unsupported region or the region 001 (Earth) is passed in. """ if not _is_valid_region_code(region_code): return None # We start off with a valid fixed-line number since every country # supports this. Alternatively we could start with a different number # type, since fixed-line numbers typically have a wide breadth of valid # number lengths and we may have to make it very short before we get an # invalid number. 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: # This shouldn't happen; we have a test for this. return None # pragma no cover example_number = desc.example_number # Try and make the number invalid. We do this by changing the length. We # try reducing the length of the number, since currently no region has a # number that is the same length as MIN_LENGTH_FOR_NSN. This is probably # quicker than making the number longer, which is another # alternative. We could also use the possible number pattern to extract # the possible lengths of the number to make this faster, but this # method is only for unit-testing so simplicity is preferred to # performance. We don't want to return a number that can't be parsed, # so we check the number is long enough. We try all possible lengths # because phone number plans often have overlapping prefixes so the # number 123456 might be valid as a fixed-line number, and 12345 as a # mobile number. It would be faster to loop in a different order, but we # prefer numbers that look closer to real numbers (and it gives us a # variety of different lengths for the resulting phone numbers - # otherwise they would all be MIN_LENGTH_FOR_NSN digits long.) phone_number_length = len(example_number) - 1 while phone_number_length >= _MIN_LENGTH_FOR_NSN: number_to_try = example_number[:phone_number_length] try: possibly_valid_number = parse(number_to_try, region_code) if not is_valid_number(possibly_valid_number): return possibly_valid_number except NumberParseException: # pragma no cover # Shouldn't happen: we have already checked the length, we know # example numbers have only valid digits, and we know the region # code is fine. pass phone_number_length -= 1 # We have a test to check that this doesn't happen for any of our # supported regions. return None
python
def invalid_example_number(region_code): if not _is_valid_region_code(region_code): return None # We start off with a valid fixed-line number since every country # supports this. Alternatively we could start with a different number # type, since fixed-line numbers typically have a wide breadth of valid # number lengths and we may have to make it very short before we get an # invalid number. 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: # This shouldn't happen; we have a test for this. return None # pragma no cover example_number = desc.example_number # Try and make the number invalid. We do this by changing the length. We # try reducing the length of the number, since currently no region has a # number that is the same length as MIN_LENGTH_FOR_NSN. This is probably # quicker than making the number longer, which is another # alternative. We could also use the possible number pattern to extract # the possible lengths of the number to make this faster, but this # method is only for unit-testing so simplicity is preferred to # performance. We don't want to return a number that can't be parsed, # so we check the number is long enough. We try all possible lengths # because phone number plans often have overlapping prefixes so the # number 123456 might be valid as a fixed-line number, and 12345 as a # mobile number. It would be faster to loop in a different order, but we # prefer numbers that look closer to real numbers (and it gives us a # variety of different lengths for the resulting phone numbers - # otherwise they would all be MIN_LENGTH_FOR_NSN digits long.) phone_number_length = len(example_number) - 1 while phone_number_length >= _MIN_LENGTH_FOR_NSN: number_to_try = example_number[:phone_number_length] try: possibly_valid_number = parse(number_to_try, region_code) if not is_valid_number(possibly_valid_number): return possibly_valid_number except NumberParseException: # pragma no cover # Shouldn't happen: we have already checked the length, we know # example numbers have only valid digits, and we know the region # code is fine. pass phone_number_length -= 1 # We have a test to check that this doesn't happen for any of our # supported regions. return None
[ "def", "invalid_example_number", "(", "region_code", ")", ":", "if", "not", "_is_valid_region_code", "(", "region_code", ")", ":", "return", "None", "# We start off with a valid fixed-line number since every country", "# supports this. Alternatively we could start with a different nu...
Gets an invalid number for the specified region. This is useful for unit-testing purposes, where you want to test what will happen with an invalid number. Note that the number that is returned will always be able to be parsed and will have the correct country code. It may also be a valid *short* number/code for this region. Validity checking such numbers is handled with shortnumberinfo. Arguments: region_code -- The region for which an example number is needed. Returns an invalid number for the specified region. Returns None when an unsupported region or the region 001 (Earth) is passed in.
[ "Gets", "an", "invalid", "number", "for", "the", "specified", "region", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L1709-L1769
234,658
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
example_number_for_type
def example_number_for_type(region_code, num_type): """Gets a valid number for the specified region and number type. If None is given as the region_code, then the returned number object may belong to any country. Arguments: region_code -- The region for which an example number is needed, or None. num_type -- The type of number that is needed. Returns a valid number for the specified region and type. Returns None when the metadata does not contain such information or if an invalid region or region 001 was specified. For 001 (representing non-geographical numbers), call example_number_for_non_geo_entity instead. """ if region_code is None: return _example_number_anywhere_for_type(num_type) # Check the region code is valid. 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) if desc is not None and desc.example_number is not None: try: return parse(desc.example_number, region_code) except NumberParseException: # pragma no cover pass return None
python
def example_number_for_type(region_code, num_type): if region_code is None: return _example_number_anywhere_for_type(num_type) # Check the region code is valid. 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) if desc is not None and desc.example_number is not None: try: return parse(desc.example_number, region_code) except NumberParseException: # pragma no cover pass return None
[ "def", "example_number_for_type", "(", "region_code", ",", "num_type", ")", ":", "if", "region_code", "is", "None", ":", "return", "_example_number_anywhere_for_type", "(", "num_type", ")", "# Check the region code is valid.", "if", "not", "_is_valid_region_code", "(", ...
Gets a valid number for the specified region and number type. If None is given as the region_code, then the returned number object may belong to any country. Arguments: region_code -- The region for which an example number is needed, or None. num_type -- The type of number that is needed. Returns a valid number for the specified region and type. Returns None when the metadata does not contain such information or if an invalid region or region 001 was specified. For 001 (representing non-geographical numbers), call example_number_for_non_geo_entity instead.
[ "Gets", "a", "valid", "number", "for", "the", "specified", "region", "and", "number", "type", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L1772-L1799
234,659
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
example_number_for_non_geo_entity
def example_number_for_non_geo_entity(country_calling_code): """Gets a valid number for the specified country calling code for a non-geographical entity. Arguments: country_calling_code -- The country calling code for a non-geographical entity. Returns a valid number for the non-geographical entity. Returns None when the metadata does not contain such information, or the country calling code passed in does not belong to a non-geographical entity. """ metadata = PhoneMetadata.metadata_for_nongeo_region(country_calling_code, None) if metadata is not None: # For geographical entities, fixed-line data is always present. However, for non-geographical # entities, this is not the case, so we have to go through different types to find the # example number. We don't check fixed-line or personal number since they aren't used by # non-geographical entities (if this changes, a unit-test will catch this.) for desc in (metadata.mobile, metadata.toll_free, metadata.shared_cost, metadata.voip, metadata.voicemail, metadata.uan, metadata.premium_rate): try: if (desc is not None and desc.example_number is not None): return parse(_PLUS_SIGN + unicod(country_calling_code) + desc.example_number, UNKNOWN_REGION) except NumberParseException: pass return None
python
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 geographical entities, fixed-line data is always present. However, for non-geographical # entities, this is not the case, so we have to go through different types to find the # example number. We don't check fixed-line or personal number since they aren't used by # non-geographical entities (if this changes, a unit-test will catch this.) for desc in (metadata.mobile, metadata.toll_free, metadata.shared_cost, metadata.voip, metadata.voicemail, metadata.uan, metadata.premium_rate): try: if (desc is not None and desc.example_number is not None): return parse(_PLUS_SIGN + unicod(country_calling_code) + desc.example_number, UNKNOWN_REGION) except NumberParseException: pass return None
[ "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 geographical entities,...
Gets a valid number for the specified country calling code for a non-geographical entity. Arguments: country_calling_code -- The country calling code for a non-geographical entity. Returns a valid number for the non-geographical entity. Returns None when the metadata does not contain such information, or the country calling code passed in does not belong to a non-geographical entity.
[ "Gets", "a", "valid", "number", "for", "the", "specified", "country", "calling", "code", "for", "a", "non", "-", "geographical", "entity", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L1830-L1853
234,660
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
_maybe_append_formatted_extension
def _maybe_append_formatted_extension(numobj, metadata, num_format, number): """Appends the formatted extension of a phone number to formatted number, if the phone number had an extension specified. """ 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 + numobj.extension else: return number + _DEFAULT_EXTN_PREFIX + numobj.extension return number
python
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 + numobj.extension else: return number + _DEFAULT_EXTN_PREFIX + numobj.extension return number
[ "def", "_maybe_append_formatted_extension", "(", "numobj", ",", "metadata", ",", "num_format", ",", "number", ")", ":", "if", "numobj", ".", "extension", ":", "if", "num_format", "==", "PhoneNumberFormat", ".", "RFC3966", ":", "return", "number", "+", "_RFC3966_...
Appends the formatted extension of a phone number to formatted number, if the phone number had an extension specified.
[ "Appends", "the", "formatted", "extension", "of", "a", "phone", "number", "to", "formatted", "number", "if", "the", "phone", "number", "had", "an", "extension", "specified", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L1856-L1868
234,661
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
_number_desc_by_type
def _number_desc_by_type(metadata, num_type): """Return the PhoneNumberDesc of the metadata for the given number 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_LINE or num_type == PhoneNumberType.FIXED_LINE_OR_MOBILE): return metadata.fixed_line elif num_type == PhoneNumberType.SHARED_COST: return metadata.shared_cost elif num_type == PhoneNumberType.VOIP: return metadata.voip elif num_type == PhoneNumberType.PERSONAL_NUMBER: return metadata.personal_number elif num_type == PhoneNumberType.PAGER: return metadata.pager elif num_type == PhoneNumberType.UAN: return metadata.uan elif num_type == PhoneNumberType.VOICEMAIL: return metadata.voicemail else: return metadata.general_desc
python
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_LINE or num_type == PhoneNumberType.FIXED_LINE_OR_MOBILE): return metadata.fixed_line elif num_type == PhoneNumberType.SHARED_COST: return metadata.shared_cost elif num_type == PhoneNumberType.VOIP: return metadata.voip elif num_type == PhoneNumberType.PERSONAL_NUMBER: return metadata.personal_number elif num_type == PhoneNumberType.PAGER: return metadata.pager elif num_type == PhoneNumberType.UAN: return metadata.uan elif num_type == PhoneNumberType.VOICEMAIL: return metadata.voicemail else: return metadata.general_desc
[ "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",...
Return the PhoneNumberDesc of the metadata for the given number type
[ "Return", "the", "PhoneNumberDesc", "of", "the", "metadata", "for", "the", "given", "number", "type" ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L1871-L1895
234,662
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
number_type
def number_type(numobj): """Gets the type of a valid phone number. Arguments: numobj -- The PhoneNumber object that we want to know the type of. Returns the type of the phone number, as a PhoneNumberType value; returns PhoneNumberType.UNKNOWN if it is invalid. """ 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(national_number, metadata)
python
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(national_number, metadata)
[ "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", "metadat...
Gets the type of a valid phone number. Arguments: numobj -- The PhoneNumber object that we want to know the type of. Returns the type of the phone number, as a PhoneNumberType value; returns PhoneNumberType.UNKNOWN if it is invalid.
[ "Gets", "the", "type", "of", "a", "valid", "phone", "number", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L1898-L1912
234,663
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
_number_type_helper
def _number_type_helper(national_number, metadata): """Return the type of the given number against the 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(national_number, metadata.toll_free): return PhoneNumberType.TOLL_FREE if _is_number_matching_desc(national_number, metadata.shared_cost): return PhoneNumberType.SHARED_COST if _is_number_matching_desc(national_number, metadata.voip): return PhoneNumberType.VOIP if _is_number_matching_desc(national_number, metadata.personal_number): return PhoneNumberType.PERSONAL_NUMBER if _is_number_matching_desc(national_number, metadata.pager): return PhoneNumberType.PAGER if _is_number_matching_desc(national_number, metadata.uan): return PhoneNumberType.UAN if _is_number_matching_desc(national_number, metadata.voicemail): return PhoneNumberType.VOICEMAIL if _is_number_matching_desc(national_number, metadata.fixed_line): if metadata.same_mobile_and_fixed_line_pattern: return PhoneNumberType.FIXED_LINE_OR_MOBILE elif _is_number_matching_desc(national_number, metadata.mobile): return PhoneNumberType.FIXED_LINE_OR_MOBILE return PhoneNumberType.FIXED_LINE # Otherwise, test to see if the number is mobile. Only do this if certain # that the patterns for mobile and fixed line aren't the same. if (not metadata.same_mobile_and_fixed_line_pattern and _is_number_matching_desc(national_number, metadata.mobile)): return PhoneNumberType.MOBILE return PhoneNumberType.UNKNOWN
python
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(national_number, metadata.toll_free): return PhoneNumberType.TOLL_FREE if _is_number_matching_desc(national_number, metadata.shared_cost): return PhoneNumberType.SHARED_COST if _is_number_matching_desc(national_number, metadata.voip): return PhoneNumberType.VOIP if _is_number_matching_desc(national_number, metadata.personal_number): return PhoneNumberType.PERSONAL_NUMBER if _is_number_matching_desc(national_number, metadata.pager): return PhoneNumberType.PAGER if _is_number_matching_desc(national_number, metadata.uan): return PhoneNumberType.UAN if _is_number_matching_desc(national_number, metadata.voicemail): return PhoneNumberType.VOICEMAIL if _is_number_matching_desc(national_number, metadata.fixed_line): if metadata.same_mobile_and_fixed_line_pattern: return PhoneNumberType.FIXED_LINE_OR_MOBILE elif _is_number_matching_desc(national_number, metadata.mobile): return PhoneNumberType.FIXED_LINE_OR_MOBILE return PhoneNumberType.FIXED_LINE # Otherwise, test to see if the number is mobile. Only do this if certain # that the patterns for mobile and fixed line aren't the same. if (not metadata.same_mobile_and_fixed_line_pattern and _is_number_matching_desc(national_number, metadata.mobile)): return PhoneNumberType.MOBILE return PhoneNumberType.UNKNOWN
[ "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_de...
Return the type of the given number against the metadata
[ "Return", "the", "type", "of", "the", "given", "number", "against", "the", "metadata" ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L1915-L1948
234,664
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
_is_number_matching_desc
def _is_number_matching_desc(national_number, number_desc): """Determine if the number matches the given PhoneNumberDesc""" # Check if any possible number lengths are present; if so, we use them to avoid checking the # validation pattern if they don't match. If they are absent, this means they match the general # description, which we have already checked before checking a specific number type. 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(national_number, number_desc, False)
python
def _is_number_matching_desc(national_number, number_desc): # Check if any possible number lengths are present; if so, we use them to avoid checking the # validation pattern if they don't match. If they are absent, this means they match the general # description, which we have already checked before checking a specific number type. 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(national_number, number_desc, False)
[ "def", "_is_number_matching_desc", "(", "national_number", ",", "number_desc", ")", ":", "# Check if any possible number lengths are present; if so, we use them to avoid checking the", "# validation pattern if they don't match. If they are absent, this means they match the general", "# descripti...
Determine if the number matches the given PhoneNumberDesc
[ "Determine", "if", "the", "number", "matches", "the", "given", "PhoneNumberDesc" ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L1951-L1962
234,665
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
is_valid_number_for_region
def is_valid_number_for_region(numobj, region_code): """Tests whether a phone number is valid for a certain region. Note this doesn't verify the number is actually in use, which is impossible to tell by just looking at a number itself. If the country calling code is not the same as the country calling code for the region, this immediately exits with false. After this, the specific number pattern rules for the region are examined. This is useful for determining for example whether a particular number is valid for Canada, rather than just a valid NANPA number. Warning: In most cases, you want to use is_valid_number instead. For example, this method will mark numbers from British Crown dependencies such as the Isle of Man as invalid for the region "GB" (United Kingdom), since it has its own region code, "IM", which may be undesirable. Arguments: numobj -- The phone number object that we want to validate. region_code -- The region that we want to validate the phone number for. Returns a boolean that indicates whether the number is of a valid pattern. """ 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 country_code != country_code_for_valid_region(region_code))): # Either the region code was invalid, or the country calling code for # this number does not match that of the region code. return False nsn = national_significant_number(numobj) return (_number_type_helper(nsn, metadata) != PhoneNumberType.UNKNOWN)
python
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 country_code != country_code_for_valid_region(region_code))): # Either the region code was invalid, or the country calling code for # this number does not match that of the region code. return False nsn = national_significant_number(numobj) return (_number_type_helper(nsn, metadata) != PhoneNumberType.UNKNOWN)
[ "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...
Tests whether a phone number is valid for a certain region. Note this doesn't verify the number is actually in use, which is impossible to tell by just looking at a number itself. If the country calling code is not the same as the country calling code for the region, this immediately exits with false. After this, the specific number pattern rules for the region are examined. This is useful for determining for example whether a particular number is valid for Canada, rather than just a valid NANPA number. Warning: In most cases, you want to use is_valid_number instead. For example, this method will mark numbers from British Crown dependencies such as the Isle of Man as invalid for the region "GB" (United Kingdom), since it has its own region code, "IM", which may be undesirable. Arguments: numobj -- The phone number object that we want to validate. region_code -- The region that we want to validate the phone number for. Returns a boolean that indicates whether the number is of a valid pattern.
[ "Tests", "whether", "a", "phone", "number", "is", "valid", "for", "a", "certain", "region", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L1986-L2019
234,666
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
region_code_for_number
def region_code_for_number(numobj): """Returns the region where a phone number is from. This could be used for geocoding at the region level. Only guarantees correct results for valid, full numbers (not short-codes, or invalid numbers). Arguments: numobj -- The phone number object whose origin we want to know Returns the region where the phone number is from, or None if no region matches this calling code. """ 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)
python
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)
[ "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", ...
Returns the region where a phone number is from. This could be used for geocoding at the region level. Only guarantees correct results for valid, full numbers (not short-codes, or invalid numbers). Arguments: numobj -- The phone number object whose origin we want to know Returns the region where the phone number is from, or None if no region matches this calling code.
[ "Returns", "the", "region", "where", "a", "phone", "number", "is", "from", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L2022-L2044
234,667
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
_region_code_for_number_from_list
def _region_code_for_number_from_list(numobj, regions): """Find the region in a list that matches a number""" national_number = national_significant_number(numobj) for region_code in regions: # If leading_digits is present, use this. Otherwise, do full # validation. # Metadata cannot be None because the region codes come from # the country calling code map. metadata = PhoneMetadata.metadata_for_region(region_code.upper(), None) if metadata is None: continue if metadata.leading_digits is not None: leading_digit_re = re.compile(metadata.leading_digits) match = leading_digit_re.match(national_number) if match: return region_code elif _number_type_helper(national_number, metadata) != PhoneNumberType.UNKNOWN: return region_code return None
python
def _region_code_for_number_from_list(numobj, regions): national_number = national_significant_number(numobj) for region_code in regions: # If leading_digits is present, use this. Otherwise, do full # validation. # Metadata cannot be None because the region codes come from # the country calling code map. metadata = PhoneMetadata.metadata_for_region(region_code.upper(), None) if metadata is None: continue if metadata.leading_digits is not None: leading_digit_re = re.compile(metadata.leading_digits) match = leading_digit_re.match(national_number) if match: return region_code elif _number_type_helper(national_number, metadata) != PhoneNumberType.UNKNOWN: return region_code return None
[ "def", "_region_code_for_number_from_list", "(", "numobj", ",", "regions", ")", ":", "national_number", "=", "national_significant_number", "(", "numobj", ")", "for", "region_code", "in", "regions", ":", "# If leading_digits is present, use this. Otherwise, do full", "# valid...
Find the region in a list that matches a number
[ "Find", "the", "region", "in", "a", "list", "that", "matches", "a", "number" ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L2047-L2065
234,668
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
country_code_for_valid_region
def country_code_for_valid_region(region_code): """Returns the country calling code for a specific region. For example, this would be 1 for the United States, and 64 for New Zealand. Assumes the region is already valid. Arguments: region_code -- The region that we want to get the country calling code for. Returns the country calling code for the region denoted by 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
python
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
[ "def", "country_code_for_valid_region", "(", "region_code", ")", ":", "metadata", "=", "PhoneMetadata", ".", "metadata_for_region", "(", "region_code", ".", "upper", "(", ")", ",", "None", ")", "if", "metadata", "is", "None", ":", "raise", "Exception", "(", "\...
Returns the country calling code for a specific region. For example, this would be 1 for the United States, and 64 for New Zealand. Assumes the region is already valid. Arguments: region_code -- The region that we want to get the country calling code for. Returns the country calling code for the region denoted by region_code.
[ "Returns", "the", "country", "calling", "code", "for", "a", "specific", "region", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L2116-L2130
234,669
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
ndd_prefix_for_region
def ndd_prefix_for_region(region_code, strip_non_digits): """Returns the national dialling prefix for a specific region. For example, this would be 1 for the United States, and 0 for New Zealand. Set strip_non_digits to True to strip symbols like "~" (which indicates a wait for a dialling tone) from the prefix returned. If no national prefix is present, we return None. Warning: Do not use this method for do-your-own formatting - for some regions, the national dialling prefix is used only for certain types of numbers. Use the library's formatting functions to prefix the national prefix when required. Arguments: region_code -- The region that we want to get the dialling prefix for. strip_non_digits -- whether to strip non-digits from the national dialling prefix. Returns the dialling prefix for the region denoted by region_code. """ 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: return None if strip_non_digits: # Note: if any other non-numeric symbols are ever used in national # prefixes, these would have to be removed here as well. national_prefix = re.sub(U_TILDE, U_EMPTY_STRING, national_prefix) return national_prefix
python
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: return None if strip_non_digits: # Note: if any other non-numeric symbols are ever used in national # prefixes, these would have to be removed here as well. national_prefix = re.sub(U_TILDE, U_EMPTY_STRING, national_prefix) return national_prefix
[ "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"...
Returns the national dialling prefix for a specific region. For example, this would be 1 for the United States, and 0 for New Zealand. Set strip_non_digits to True to strip symbols like "~" (which indicates a wait for a dialling tone) from the prefix returned. If no national prefix is present, we return None. Warning: Do not use this method for do-your-own formatting - for some regions, the national dialling prefix is used only for certain types of numbers. Use the library's formatting functions to prefix the national prefix when required. Arguments: region_code -- The region that we want to get the dialling prefix for. strip_non_digits -- whether to strip non-digits from the national dialling prefix. Returns the dialling prefix for the region denoted by region_code.
[ "Returns", "the", "national", "dialling", "prefix", "for", "a", "specific", "region", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L2133-L2165
234,670
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
is_possible_number
def is_possible_number(numobj): """Convenience wrapper around is_possible_number_with_reason. Instead of returning the reason for failure, this method returns true if the number is either a possible fully-qualified number (containing the area code and country code), or if the number could be a possible local number (with a country code, but missing an area code). Local numbers are considered possible if they could be possibly dialled in this format: if the area code is needed for a call to connect, the number is not considered possible without it. Arguments: numobj -- the number object that needs to be checked Returns True if the number is possible """ result = is_possible_number_with_reason(numobj) return (result == ValidationResult.IS_POSSIBLE or result == ValidationResult.IS_POSSIBLE_LOCAL_ONLY)
python
def is_possible_number(numobj): result = is_possible_number_with_reason(numobj) return (result == ValidationResult.IS_POSSIBLE or result == ValidationResult.IS_POSSIBLE_LOCAL_ONLY)
[ "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. Instead of returning the reason for failure, this method returns true if the number is either a possible fully-qualified number (containing the area code and country code), or if the number could be a possible local number (with a country code, but missing an area code). Local numbers are considered possible if they could be possibly dialled in this format: if the area code is needed for a call to connect, the number is not considered possible without it. Arguments: numobj -- the number object that needs to be checked Returns True if the number is possible
[ "Convenience", "wrapper", "around", "is_possible_number_with_reason", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L2197-L2216
234,671
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
is_possible_number_for_type
def is_possible_number_for_type(numobj, numtype): """Convenience wrapper around is_possible_number_for_type_with_reason. Instead of returning the reason for failure, this method returns true if the number is either a possible fully-qualified number (containing the area code and country code), or if the number could be a possible local number (with a country code, but missing an area code). Local numbers are considered possible if they could be possibly dialled in this format: if the area code is needed for a call to connect, the number is not considered possible without it. Arguments: numobj -- the number object that needs to be checked numtype -- the type we are interested in Returns True if the number is possible """ result = is_possible_number_for_type_with_reason(numobj, numtype) return (result == ValidationResult.IS_POSSIBLE or result == ValidationResult.IS_POSSIBLE_LOCAL_ONLY)
python
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)
[ "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", "==", ...
Convenience wrapper around is_possible_number_for_type_with_reason. Instead of returning the reason for failure, this method returns true if the number is either a possible fully-qualified number (containing the area code and country code), or if the number could be a possible local number (with a country code, but missing an area code). Local numbers are considered possible if they could be possibly dialled in this format: if the area code is needed for a call to connect, the number is not considered possible without it. Arguments: numobj -- the number object that needs to be checked numtype -- the type we are interested in Returns True if the number is possible
[ "Convenience", "wrapper", "around", "is_possible_number_for_type_with_reason", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L2219-L2239
234,672
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
is_possible_number_for_type_with_reason
def is_possible_number_for_type_with_reason(numobj, numtype): """Check whether a phone number is a possible number of a particular type. For types that don't exist in a particular region, this will return a result that isn't so useful; it is recommended that you use supported_types_for_region or supported_types_for_non_geo_entity respectively before calling this method to determine whether you should call it for this number at all. This provides a more lenient check than is_valid_number in the following sense: - It only checks the length of phone numbers. In particular, it doesn't check starting digits of the number. - For some numbers (particularly fixed-line), many regions have the concept of area code, which together with subscriber number constitute the national significant number. It is sometimes okay to dial only the subscriber number when dialing in the same area. This function will return IS_POSSIBLE_LOCAL_ONLY if the subscriber-number-only version is passed in. On the other hand, because is_valid_number validates using information on both starting digits (for fixed line numbers, that would most likely be area codes) and length (obviously includes the length of area codes for fixed line numbers), it will return false for the subscriber-number-only version. Arguments: numobj -- The number object that needs to be checked numtype -- The type we are interested in Returns a value from ValidationResult which indicates whether the number is possible """ national_number = national_significant_number(numobj) country_code = numobj.country_code # Note: For regions that share a country calling code, like NANPA numbers, # we just use the rules from the default region (US in this case) since the # region_code_for_number will not work if the number is possible but not # valid. There is in fact one country calling code (290) where the possible # number pattern differs between various regions (Saint Helena and Tristan # da Cuñha), but this is handled by putting all possible lengths for any # country with this country calling code in the metadata for the default # region in this case. if not _has_valid_country_calling_code(country_code): return ValidationResult.INVALID_COUNTRY_CODE region_code = region_code_for_country_code(country_code) # Metadata cannot be None because the country calling code is valid. metadata = PhoneMetadata.metadata_for_region_or_calling_code(country_code, region_code) return _test_number_length(national_number, metadata, numtype)
python
def is_possible_number_for_type_with_reason(numobj, numtype): national_number = national_significant_number(numobj) country_code = numobj.country_code # Note: For regions that share a country calling code, like NANPA numbers, # we just use the rules from the default region (US in this case) since the # region_code_for_number will not work if the number is possible but not # valid. There is in fact one country calling code (290) where the possible # number pattern differs between various regions (Saint Helena and Tristan # da Cuñha), but this is handled by putting all possible lengths for any # country with this country calling code in the metadata for the default # region in this case. if not _has_valid_country_calling_code(country_code): return ValidationResult.INVALID_COUNTRY_CODE region_code = region_code_for_country_code(country_code) # Metadata cannot be None because the country calling code is valid. metadata = PhoneMetadata.metadata_for_region_or_calling_code(country_code, region_code) return _test_number_length(national_number, metadata, numtype)
[ "def", "is_possible_number_for_type_with_reason", "(", "numobj", ",", "numtype", ")", ":", "national_number", "=", "national_significant_number", "(", "numobj", ")", "country_code", "=", "numobj", ".", "country_code", "# Note: For regions that share a country calling code, like...
Check whether a phone number is a possible number of a particular type. For types that don't exist in a particular region, this will return a result that isn't so useful; it is recommended that you use supported_types_for_region or supported_types_for_non_geo_entity respectively before calling this method to determine whether you should call it for this number at all. This provides a more lenient check than is_valid_number in the following sense: - It only checks the length of phone numbers. In particular, it doesn't check starting digits of the number. - For some numbers (particularly fixed-line), many regions have the concept of area code, which together with subscriber number constitute the national significant number. It is sometimes okay to dial only the subscriber number when dialing in the same area. This function will return IS_POSSIBLE_LOCAL_ONLY if the subscriber-number-only version is passed in. On the other hand, because is_valid_number validates using information on both starting digits (for fixed line numbers, that would most likely be area codes) and length (obviously includes the length of area codes for fixed line numbers), it will return false for the subscriber-number-only version. Arguments: numobj -- The number object that needs to be checked numtype -- The type we are interested in Returns a value from ValidationResult which indicates whether the number is possible
[ "Check", "whether", "a", "phone", "number", "is", "a", "possible", "number", "of", "a", "particular", "type", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L2318-L2365
234,673
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
truncate_too_long_number
def truncate_too_long_number(numobj): """Truncate a number object that is too long. Attempts to extract a valid number from a phone number that is too long to be valid, and resets the PhoneNumber object passed in to that valid version. If no valid number could be extracted, the PhoneNumber object passed in will not be modified. Arguments: numobj -- A PhoneNumber object which contains a number that is too long to be valid. Returns True if a valid phone number can be successfully extracted. """ 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): # Strip a digit off the RHS national_number = national_number // 10 numobj_copy.national_number = national_number validation_result = is_possible_number_with_reason(numobj_copy) if (validation_result == ValidationResult.TOO_SHORT or national_number == 0): return False # To reach here, numobj_copy is a valid number. Modify the original object numobj.national_number = national_number return True
python
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): # Strip a digit off the RHS national_number = national_number // 10 numobj_copy.national_number = national_number validation_result = is_possible_number_with_reason(numobj_copy) if (validation_result == ValidationResult.TOO_SHORT or national_number == 0): return False # To reach here, numobj_copy is a valid number. Modify the original object numobj.national_number = national_number return True
[ "def", "truncate_too_long_number", "(", "numobj", ")", ":", "if", "is_valid_number", "(", "numobj", ")", ":", "return", "True", "numobj_copy", "=", "PhoneNumber", "(", ")", "numobj_copy", ".", "merge_from", "(", "numobj", ")", "national_number", "=", "numobj", ...
Truncate a number object that is too long. Attempts to extract a valid number from a phone number that is too long to be valid, and resets the PhoneNumber object passed in to that valid version. If no valid number could be extracted, the PhoneNumber object passed in will not be modified. Arguments: numobj -- A PhoneNumber object which contains a number that is too long to be valid. Returns True if a valid phone number can be successfully extracted.
[ "Truncate", "a", "number", "object", "that", "is", "too", "long", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L2399-L2429
234,674
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
_extract_country_code
def _extract_country_code(number): """Extracts country calling code from number. Returns a 2-tuple of (country_calling_code, rest_of_number). It assumes that the leading plus sign or IDD has already been removed. Returns (0, number) if number doesn't start with a valid country calling code. """ if len(number) == 0 or number[0] == U_ZERO: # Country codes do not begin with a '0'. 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[ii:]) except Exception: pass return (0, number)
python
def _extract_country_code(number): if len(number) == 0 or number[0] == U_ZERO: # Country codes do not begin with a '0'. 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[ii:]) except Exception: pass return (0, number)
[ "def", "_extract_country_code", "(", "number", ")", ":", "if", "len", "(", "number", ")", "==", "0", "or", "number", "[", "0", "]", "==", "U_ZERO", ":", "# Country codes do not begin with a '0'.", "return", "(", "0", ",", "number", ")", "for", "ii", "in", ...
Extracts country calling code from number. Returns a 2-tuple of (country_calling_code, rest_of_number). It assumes that the leading plus sign or IDD has already been removed. Returns (0, number) if number doesn't start with a valid country calling code.
[ "Extracts", "country", "calling", "code", "from", "number", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L2432-L2450
234,675
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
_maybe_extract_country_code
def _maybe_extract_country_code(number, metadata, keep_raw_input, numobj): """Tries to extract a country calling code from a number. This method will return zero if no country calling code is considered to be present. Country calling codes are extracted in the following ways: - by stripping the international dialing prefix of the region the person is dialing from, if this is present in the number, and looking at the next digits - by stripping the '+' sign if present and then looking at the next digits - by comparing the start of the number and the country calling code of the default region. If the number is not considered possible for the numbering plan of the default region initially, but starts with the country calling code of this region, validation will be reattempted after stripping this country calling code. If this number is considered a possible number, then the first digits will be considered the country calling code and removed as such. It will raise a NumberParseException if the number starts with a '+' but the country calling code supplied after this does not match that of any known region. Arguments: number -- non-normalized telephone number that we wish to extract a country calling code from; may begin with '+' metadata -- metadata about the region this number may be from, or None keep_raw_input -- True if the country_code_source and preferred_carrier_code fields of numobj should be populated. numobj -- The PhoneNumber object where the country_code and country_code_source need to be populated. Note the country_code is always populated, whereas country_code_source is only populated when keep_raw_input is True. Returns a 2-tuple containing: - the country calling code extracted or 0 if none could be extracted - a string holding the national significant number, in the case that a country calling code was extracted. If no country calling code was extracted, this will be empty. """ if len(number) == 0: return (0, U_EMPTY_STRING) full_number = number # Set the default prefix to be something that will never match. possible_country_idd_prefix = unicod("NonMatch") if metadata is not None and metadata.international_prefix is not None: possible_country_idd_prefix = metadata.international_prefix country_code_source, full_number = _maybe_strip_i18n_prefix_and_normalize(full_number, possible_country_idd_prefix) if keep_raw_input: numobj.country_code_source = country_code_source if country_code_source != CountryCodeSource.FROM_DEFAULT_COUNTRY: if len(full_number) <= _MIN_LENGTH_FOR_NSN: raise NumberParseException(NumberParseException.TOO_SHORT_AFTER_IDD, "Phone number had an IDD, but after this was not " + "long enough to be a viable phone number.") potential_country_code, rest_of_number = _extract_country_code(full_number) if potential_country_code != 0: numobj.country_code = potential_country_code return (potential_country_code, rest_of_number) # If this fails, they must be using a strange country calling code # that we don't recognize, or that doesn't exist. raise NumberParseException(NumberParseException.INVALID_COUNTRY_CODE, "Country calling code supplied was not recognised.") elif metadata is not None: # Check to see if the number starts with the country calling code for # the default region. If so, we remove the country calling code, and # do some checks on the validity of the number before and after. default_country_code = metadata.country_code default_country_code_str = str(metadata.country_code) normalized_number = full_number if normalized_number.startswith(default_country_code_str): potential_national_number = full_number[len(default_country_code_str):] general_desc = metadata.general_desc _, potential_national_number, _ = _maybe_strip_national_prefix_carrier_code(potential_national_number, metadata) # If the number was not valid before but is valid now, or if it # was too long before, we consider the number with the country # calling code stripped to be a better result and keep that # instead. if ((not _match_national_number(full_number, general_desc, False) and _match_national_number(potential_national_number, general_desc, False)) or (_test_number_length(full_number, metadata) == ValidationResult.TOO_LONG)): if keep_raw_input: numobj.country_code_source = CountryCodeSource.FROM_NUMBER_WITHOUT_PLUS_SIGN numobj.country_code = default_country_code return (default_country_code, potential_national_number) # No country calling code present. numobj.country_code = 0 return (0, U_EMPTY_STRING)
python
def _maybe_extract_country_code(number, metadata, keep_raw_input, numobj): if len(number) == 0: return (0, U_EMPTY_STRING) full_number = number # Set the default prefix to be something that will never match. possible_country_idd_prefix = unicod("NonMatch") if metadata is not None and metadata.international_prefix is not None: possible_country_idd_prefix = metadata.international_prefix country_code_source, full_number = _maybe_strip_i18n_prefix_and_normalize(full_number, possible_country_idd_prefix) if keep_raw_input: numobj.country_code_source = country_code_source if country_code_source != CountryCodeSource.FROM_DEFAULT_COUNTRY: if len(full_number) <= _MIN_LENGTH_FOR_NSN: raise NumberParseException(NumberParseException.TOO_SHORT_AFTER_IDD, "Phone number had an IDD, but after this was not " + "long enough to be a viable phone number.") potential_country_code, rest_of_number = _extract_country_code(full_number) if potential_country_code != 0: numobj.country_code = potential_country_code return (potential_country_code, rest_of_number) # If this fails, they must be using a strange country calling code # that we don't recognize, or that doesn't exist. raise NumberParseException(NumberParseException.INVALID_COUNTRY_CODE, "Country calling code supplied was not recognised.") elif metadata is not None: # Check to see if the number starts with the country calling code for # the default region. If so, we remove the country calling code, and # do some checks on the validity of the number before and after. default_country_code = metadata.country_code default_country_code_str = str(metadata.country_code) normalized_number = full_number if normalized_number.startswith(default_country_code_str): potential_national_number = full_number[len(default_country_code_str):] general_desc = metadata.general_desc _, potential_national_number, _ = _maybe_strip_national_prefix_carrier_code(potential_national_number, metadata) # If the number was not valid before but is valid now, or if it # was too long before, we consider the number with the country # calling code stripped to be a better result and keep that # instead. if ((not _match_national_number(full_number, general_desc, False) and _match_national_number(potential_national_number, general_desc, False)) or (_test_number_length(full_number, metadata) == ValidationResult.TOO_LONG)): if keep_raw_input: numobj.country_code_source = CountryCodeSource.FROM_NUMBER_WITHOUT_PLUS_SIGN numobj.country_code = default_country_code return (default_country_code, potential_national_number) # No country calling code present. numobj.country_code = 0 return (0, U_EMPTY_STRING)
[ "def", "_maybe_extract_country_code", "(", "number", ",", "metadata", ",", "keep_raw_input", ",", "numobj", ")", ":", "if", "len", "(", "number", ")", "==", "0", ":", "return", "(", "0", ",", "U_EMPTY_STRING", ")", "full_number", "=", "number", "# Set the de...
Tries to extract a country calling code from a number. This method will return zero if no country calling code is considered to be present. Country calling codes are extracted in the following ways: - by stripping the international dialing prefix of the region the person is dialing from, if this is present in the number, and looking at the next digits - by stripping the '+' sign if present and then looking at the next digits - by comparing the start of the number and the country calling code of the default region. If the number is not considered possible for the numbering plan of the default region initially, but starts with the country calling code of this region, validation will be reattempted after stripping this country calling code. If this number is considered a possible number, then the first digits will be considered the country calling code and removed as such. It will raise a NumberParseException if the number starts with a '+' but the country calling code supplied after this does not match that of any known region. Arguments: number -- non-normalized telephone number that we wish to extract a country calling code from; may begin with '+' metadata -- metadata about the region this number may be from, or None keep_raw_input -- True if the country_code_source and preferred_carrier_code fields of numobj should be populated. numobj -- The PhoneNumber object where the country_code and country_code_source need to be populated. Note the country_code is always populated, whereas country_code_source is only populated when keep_raw_input is True. Returns a 2-tuple containing: - the country calling code extracted or 0 if none could be extracted - a string holding the national significant number, in the case that a country calling code was extracted. If no country calling code was extracted, this will be empty.
[ "Tries", "to", "extract", "a", "country", "calling", "code", "from", "a", "number", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L2453-L2549
234,676
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
_parse_prefix_as_idd
def _parse_prefix_as_idd(idd_pattern, number): """Strips the IDD from the start of the number if present. Helper function used by _maybe_strip_i18n_prefix_and_normalize(). Returns a 2-tuple: - Boolean indicating if IDD was stripped - Number with IDD stripped """ match = idd_pattern.match(number) if match: match_end = match.end() # Only strip this if the first digit after the match is not a 0, since # country calling codes cannot begin with 0. 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_ZERO: return (False, number) return (True, number[match_end:]) return (False, number)
python
def _parse_prefix_as_idd(idd_pattern, number): match = idd_pattern.match(number) if match: match_end = match.end() # Only strip this if the first digit after the match is not a 0, since # country calling codes cannot begin with 0. 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_ZERO: return (False, number) return (True, number[match_end:]) return (False, number)
[ "def", "_parse_prefix_as_idd", "(", "idd_pattern", ",", "number", ")", ":", "match", "=", "idd_pattern", ".", "match", "(", "number", ")", "if", "match", ":", "match_end", "=", "match", ".", "end", "(", ")", "# Only strip this if the first digit after the match is...
Strips the IDD from the start of the number if present. Helper function used by _maybe_strip_i18n_prefix_and_normalize(). Returns a 2-tuple: - Boolean indicating if IDD was stripped - Number with IDD stripped
[ "Strips", "the", "IDD", "from", "the", "start", "of", "the", "number", "if", "present", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L2552-L2572
234,677
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
_maybe_strip_extension
def _maybe_strip_extension(number): """Strip extension from the end of a number string. Strips any extension (as in, the part of the number dialled after the call is connected, usually indicated with extn, ext, x or similar) from the end of the number, and returns it. Arguments: number -- the non-normalized telephone number that we wish to strip the extension from. Returns a 2-tuple of: - the phone extension (or "" or not present) - the number before the extension. """ match = _EXTN_PATTERN.search(number) # If we find a potential extension, and the number preceding this is a # viable number, we assume it is an extension. if match and _is_viable_phone_number(number[:match.start()]): # The numbers are captured into groups in the regular expression. for group in match.groups(): # We go through the capturing groups until we find one that # captured some digits. If none did, then we will return the empty # string. if group is not None: return (group, number[:match.start()]) return ("", number)
python
def _maybe_strip_extension(number): match = _EXTN_PATTERN.search(number) # If we find a potential extension, and the number preceding this is a # viable number, we assume it is an extension. if match and _is_viable_phone_number(number[:match.start()]): # The numbers are captured into groups in the regular expression. for group in match.groups(): # We go through the capturing groups until we find one that # captured some digits. If none did, then we will return the empty # string. if group is not None: return (group, number[:match.start()]) return ("", number)
[ "def", "_maybe_strip_extension", "(", "number", ")", ":", "match", "=", "_EXTN_PATTERN", ".", "search", "(", "number", ")", "# If we find a potential extension, and the number preceding this is a", "# viable number, we assume it is an extension.", "if", "match", "and", "_is_via...
Strip extension from the end of a number string. Strips any extension (as in, the part of the number dialled after the call is connected, usually indicated with extn, ext, x or similar) from the end of the number, and returns it. Arguments: number -- the non-normalized telephone number that we wish to strip the extension from. Returns a 2-tuple of: - the phone extension (or "" or not present) - the number before the extension.
[ "Strip", "extension", "from", "the", "end", "of", "a", "number", "string", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L2676-L2701
234,678
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
_check_region_for_parsing
def _check_region_for_parsing(number, default_region): """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. """ if not _is_valid_region_code(default_region): # If the number is None or empty, we can't infer the 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
python
def _check_region_for_parsing(number, default_region): if not _is_valid_region_code(default_region): # If the number is None or empty, we can't infer the 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
[ "def", "_check_region_for_parsing", "(", "number", ",", "default_region", ")", ":", "if", "not", "_is_valid_region_code", "(", "default_region", ")", ":", "# If the number is None or empty, we can't infer the region.", "if", "number", "is", "None", "or", "len", "(", "nu...
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.
[ "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", ...
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L2704-L2717
234,679
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
_set_italian_leading_zeros_for_phone_number
def _set_italian_leading_zeros_for_phone_number(national_number, numobj): """A helper function to set the values related to leading zeros in a PhoneNumber.""" if len(national_number) > 1 and national_number[0] == U_ZERO: numobj.italian_leading_zero = True number_of_leading_zeros = 1 # Note that if the number is all "0"s, the last "0" is not counted as # a leading zero. while (number_of_leading_zeros < len(national_number) - 1 and national_number[number_of_leading_zeros] == U_ZERO): number_of_leading_zeros += 1 if number_of_leading_zeros != 1: numobj.number_of_leading_zeros = number_of_leading_zeros
python
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 # Note that if the number is all "0"s, the last "0" is not counted as # a leading zero. while (number_of_leading_zeros < len(national_number) - 1 and national_number[number_of_leading_zeros] == U_ZERO): number_of_leading_zeros += 1 if number_of_leading_zeros != 1: numobj.number_of_leading_zeros = number_of_leading_zeros
[ "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", "=", "...
A helper function to set the values related to leading zeros in a PhoneNumber.
[ "A", "helper", "function", "to", "set", "the", "values", "related", "to", "leading", "zeros", "in", "a", "PhoneNumber", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L2720-L2732
234,680
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
parse
def parse(number, region=None, keep_raw_input=False, numobj=None, _check_region=True): """Parse a string and return a corresponding PhoneNumber object. The method is quite lenient and looks for a number in the input text (raw input) and does not check whether the string is definitely only a phone number. To do this, it ignores punctuation and white-space, as well as any text before the number (e.g. a leading "Tel: ") and trims the non-number bits. It will accept a number in any format (E164, national, international etc), assuming it can be interpreted with the defaultRegion supplied. It also attempts to convert any alpha characters into digits if it thinks this is a vanity number of the type "1800 MICROSOFT". This method will throw a NumberParseException if the number is not considered to be a possible number. Note that validation of whether the number is actually a valid number for a particular region is not performed. This can be done separately with is_valid_number. Note this method canonicalizes the phone number such that different representations can be easily compared, no matter what form it was originally entered in (e.g. national, international). If you want to record context about the number being parsed, such as the raw input that was entered, how the country code was derived etc. then ensure keep_raw_input is set. Note if any new field is added to this method that should always be filled in, even when keep_raw_input is False, it should also be handled in the _copy_core_fields_only() function. Arguments: number -- The number that we are attempting to parse. This can contain formatting such as +, ( and -, as well as a phone number extension. It can also be provided in RFC3966 format. region -- The region that we are expecting the number to be from. This is only used if the number being parsed is not written in international format. The country_code for the number in this case would be stored as that of the default region supplied. If the number is guaranteed to start with a '+' followed by the country calling code, then None or UNKNOWN_REGION can be supplied. keep_raw_input -- Whether to populate the raw_input field of the PhoneNumber object with number (as well as the country_code_source field). numobj -- An optional existing PhoneNumber object to receive the parsing results _check_region -- Whether to check the supplied region parameter; should always be True for external callers. Returns a PhoneNumber object filled with the parse number. Raises: NumberParseException if the string is not considered to be a viable phone number (e.g. too few or too many digits) or if no default region was supplied and the number is not in international format (does not start with +). """ 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_LENGTH: raise NumberParseException(NumberParseException.TOO_LONG, "The string supplied was too long to parse.") national_number = _build_national_number_for_parsing(number) if not _is_viable_phone_number(national_number): raise NumberParseException(NumberParseException.NOT_A_NUMBER, "The string supplied did not seem to be a phone number.") # Check the region supplied is valid, or that the extracted number starts # with some sort of + sign so the number's region can be determined. if _check_region and not _check_region_for_parsing(national_number, region): raise NumberParseException(NumberParseException.INVALID_COUNTRY_CODE, "Missing or invalid default region.") if keep_raw_input: numobj.raw_input = number # Attempt to parse extension first, since it doesn't require # region-specific data and we want to have the non-normalised number here. extension, national_number = _maybe_strip_extension(national_number) if len(extension) > 0: numobj.extension = extension if region is None: metadata = None else: metadata = PhoneMetadata.metadata_for_region(region.upper(), None) country_code = 0 try: country_code, normalized_national_number = _maybe_extract_country_code(national_number, metadata, keep_raw_input, numobj) except NumberParseException: _, e, _ = sys.exc_info() matchobj = _PLUS_CHARS_PATTERN.match(national_number) if (e.error_type == NumberParseException.INVALID_COUNTRY_CODE and matchobj is not None): # Strip the plus-char, and try again. country_code, normalized_national_number = _maybe_extract_country_code(national_number[matchobj.end():], metadata, keep_raw_input, numobj) if country_code == 0: raise NumberParseException(NumberParseException.INVALID_COUNTRY_CODE, "Could not interpret numbers after plus-sign.") else: raise if country_code != 0: number_region = region_code_for_country_code(country_code) if number_region != region: # Metadata cannot be null because the country calling code is valid. metadata = PhoneMetadata.metadata_for_region_or_calling_code(country_code, number_region) else: # If no extracted country calling code, use the region supplied # instead. The national number is just the normalized version of the # number we were given to parse. normalized_national_number += _normalize(national_number) if region is not None: country_code = metadata.country_code numobj.country_code = country_code elif keep_raw_input: numobj.country_code_source = CountryCodeSource.UNSPECIFIED if len(normalized_national_number) < _MIN_LENGTH_FOR_NSN: raise NumberParseException(NumberParseException.TOO_SHORT_NSN, "The string supplied is too short to be a phone number.") if metadata is not None: potential_national_number = normalized_national_number carrier_code, potential_national_number, _ = _maybe_strip_national_prefix_carrier_code(potential_national_number, metadata) # We require that the NSN remaining after stripping the national # prefix and carrier code be long enough to be a possible length for # the region. Otherwise, we don't do the stripping, since the original # number could be a valid short number. validation_result = _test_number_length(potential_national_number, metadata) if validation_result not in (ValidationResult.TOO_SHORT, ValidationResult.IS_POSSIBLE_LOCAL_ONLY, ValidationResult.INVALID_LENGTH): normalized_national_number = potential_national_number if keep_raw_input and carrier_code is not None and len(carrier_code) > 0: numobj.preferred_domestic_carrier_code = carrier_code len_national_number = len(normalized_national_number) if len_national_number < _MIN_LENGTH_FOR_NSN: # pragma no cover # Check of _is_viable_phone_number() at the top of this function makes # this effectively unhittable. raise NumberParseException(NumberParseException.TOO_SHORT_NSN, "The string supplied is too short to be a phone number.") if len_national_number > _MAX_LENGTH_FOR_NSN: raise NumberParseException(NumberParseException.TOO_LONG, "The string supplied is too long to be a phone number.") _set_italian_leading_zeros_for_phone_number(normalized_national_number, numobj) numobj.national_number = to_long(normalized_national_number) return numobj
python
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_LENGTH: raise NumberParseException(NumberParseException.TOO_LONG, "The string supplied was too long to parse.") national_number = _build_national_number_for_parsing(number) if not _is_viable_phone_number(national_number): raise NumberParseException(NumberParseException.NOT_A_NUMBER, "The string supplied did not seem to be a phone number.") # Check the region supplied is valid, or that the extracted number starts # with some sort of + sign so the number's region can be determined. if _check_region and not _check_region_for_parsing(national_number, region): raise NumberParseException(NumberParseException.INVALID_COUNTRY_CODE, "Missing or invalid default region.") if keep_raw_input: numobj.raw_input = number # Attempt to parse extension first, since it doesn't require # region-specific data and we want to have the non-normalised number here. extension, national_number = _maybe_strip_extension(national_number) if len(extension) > 0: numobj.extension = extension if region is None: metadata = None else: metadata = PhoneMetadata.metadata_for_region(region.upper(), None) country_code = 0 try: country_code, normalized_national_number = _maybe_extract_country_code(national_number, metadata, keep_raw_input, numobj) except NumberParseException: _, e, _ = sys.exc_info() matchobj = _PLUS_CHARS_PATTERN.match(national_number) if (e.error_type == NumberParseException.INVALID_COUNTRY_CODE and matchobj is not None): # Strip the plus-char, and try again. country_code, normalized_national_number = _maybe_extract_country_code(national_number[matchobj.end():], metadata, keep_raw_input, numobj) if country_code == 0: raise NumberParseException(NumberParseException.INVALID_COUNTRY_CODE, "Could not interpret numbers after plus-sign.") else: raise if country_code != 0: number_region = region_code_for_country_code(country_code) if number_region != region: # Metadata cannot be null because the country calling code is valid. metadata = PhoneMetadata.metadata_for_region_or_calling_code(country_code, number_region) else: # If no extracted country calling code, use the region supplied # instead. The national number is just the normalized version of the # number we were given to parse. normalized_national_number += _normalize(national_number) if region is not None: country_code = metadata.country_code numobj.country_code = country_code elif keep_raw_input: numobj.country_code_source = CountryCodeSource.UNSPECIFIED if len(normalized_national_number) < _MIN_LENGTH_FOR_NSN: raise NumberParseException(NumberParseException.TOO_SHORT_NSN, "The string supplied is too short to be a phone number.") if metadata is not None: potential_national_number = normalized_national_number carrier_code, potential_national_number, _ = _maybe_strip_national_prefix_carrier_code(potential_national_number, metadata) # We require that the NSN remaining after stripping the national # prefix and carrier code be long enough to be a possible length for # the region. Otherwise, we don't do the stripping, since the original # number could be a valid short number. validation_result = _test_number_length(potential_national_number, metadata) if validation_result not in (ValidationResult.TOO_SHORT, ValidationResult.IS_POSSIBLE_LOCAL_ONLY, ValidationResult.INVALID_LENGTH): normalized_national_number = potential_national_number if keep_raw_input and carrier_code is not None and len(carrier_code) > 0: numobj.preferred_domestic_carrier_code = carrier_code len_national_number = len(normalized_national_number) if len_national_number < _MIN_LENGTH_FOR_NSN: # pragma no cover # Check of _is_viable_phone_number() at the top of this function makes # this effectively unhittable. raise NumberParseException(NumberParseException.TOO_SHORT_NSN, "The string supplied is too short to be a phone number.") if len_national_number > _MAX_LENGTH_FOR_NSN: raise NumberParseException(NumberParseException.TOO_LONG, "The string supplied is too long to be a phone number.") _set_italian_leading_zeros_for_phone_number(normalized_national_number, numobj) numobj.national_number = to_long(normalized_national_number) return numobj
[ "def", "parse", "(", "number", ",", "region", "=", "None", ",", "keep_raw_input", "=", "False", ",", "numobj", "=", "None", ",", "_check_region", "=", "True", ")", ":", "if", "numobj", "is", "None", ":", "numobj", "=", "PhoneNumber", "(", ")", "if", ...
Parse a string and return a corresponding PhoneNumber object. The method is quite lenient and looks for a number in the input text (raw input) and does not check whether the string is definitely only a phone number. To do this, it ignores punctuation and white-space, as well as any text before the number (e.g. a leading "Tel: ") and trims the non-number bits. It will accept a number in any format (E164, national, international etc), assuming it can be interpreted with the defaultRegion supplied. It also attempts to convert any alpha characters into digits if it thinks this is a vanity number of the type "1800 MICROSOFT". This method will throw a NumberParseException if the number is not considered to be a possible number. Note that validation of whether the number is actually a valid number for a particular region is not performed. This can be done separately with is_valid_number. Note this method canonicalizes the phone number such that different representations can be easily compared, no matter what form it was originally entered in (e.g. national, international). If you want to record context about the number being parsed, such as the raw input that was entered, how the country code was derived etc. then ensure keep_raw_input is set. Note if any new field is added to this method that should always be filled in, even when keep_raw_input is False, it should also be handled in the _copy_core_fields_only() function. Arguments: number -- The number that we are attempting to parse. This can contain formatting such as +, ( and -, as well as a phone number extension. It can also be provided in RFC3966 format. region -- The region that we are expecting the number to be from. This is only used if the number being parsed is not written in international format. The country_code for the number in this case would be stored as that of the default region supplied. If the number is guaranteed to start with a '+' followed by the country calling code, then None or UNKNOWN_REGION can be supplied. keep_raw_input -- Whether to populate the raw_input field of the PhoneNumber object with number (as well as the country_code_source field). numobj -- An optional existing PhoneNumber object to receive the parsing results _check_region -- Whether to check the supplied region parameter; should always be True for external callers. Returns a PhoneNumber object filled with the parse number. Raises: NumberParseException if the string is not considered to be a viable phone number (e.g. too few or too many digits) or if no default region was supplied and the number is not in international format (does not start with +).
[ "Parse", "a", "string", "and", "return", "a", "corresponding", "PhoneNumber", "object", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L2735-L2893
234,681
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
_build_national_number_for_parsing
def _build_national_number_for_parsing(number): """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.""" 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 the phone context contains a phone number prefix, we need to # capture it, whereas domains will be ignored. if (phone_context_start < (len(number) - 1) and number[phone_context_start] == _PLUS_SIGN): # Additional parameters might follow the phone context. If so, we # will remove them here because the parameters after phone context # are not important for parsing the phone number. phone_context_end = number.find(U_SEMICOLON, phone_context_start) if phone_context_end > 0: national_number = number[phone_context_start:phone_context_end] else: national_number = number[phone_context_start:] else: national_number = U_EMPTY_STRING # Now append everything between the "tel:" prefix and the # phone-context. This should include the national number, an optional # extension or isdn-subaddress component. Note we also handle the case # when "tel:" is missing, as we have seen in some of the phone number # inputs. In that case we append everything from the beginning. index_of_rfc3996_prefix = number.find(_RFC3966_PREFIX) index_of_national_number = ((index_of_rfc3996_prefix + len(_RFC3966_PREFIX)) if (index_of_rfc3996_prefix >= 0) else 0) national_number += number[index_of_national_number:index_of_phone_context] else: # Extract a possible number from the string passed in (this strips leading characters that # could not be the start of a phone number.) national_number = _extract_possible_number(number) # Delete the isdn-subaddress and everything after it if it is # present. Note extension won't appear at the same time with # isdn-subaddress according to paragraph 5.3 of the RFC3966 spec, index_of_isdn = national_number.find(_RFC3966_ISDN_SUBADDRESS) if index_of_isdn > 0: national_number = national_number[:index_of_isdn] # If both phone context and isdn-subaddress are absent but other # parameters are present, the parameters are left in national_number. This # is because we are concerned about deleting content from a potential # number string when there is no strong evidence that the number is # actually written in RFC3966. return national_number
python
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 the phone context contains a phone number prefix, we need to # capture it, whereas domains will be ignored. if (phone_context_start < (len(number) - 1) and number[phone_context_start] == _PLUS_SIGN): # Additional parameters might follow the phone context. If so, we # will remove them here because the parameters after phone context # are not important for parsing the phone number. phone_context_end = number.find(U_SEMICOLON, phone_context_start) if phone_context_end > 0: national_number = number[phone_context_start:phone_context_end] else: national_number = number[phone_context_start:] else: national_number = U_EMPTY_STRING # Now append everything between the "tel:" prefix and the # phone-context. This should include the national number, an optional # extension or isdn-subaddress component. Note we also handle the case # when "tel:" is missing, as we have seen in some of the phone number # inputs. In that case we append everything from the beginning. index_of_rfc3996_prefix = number.find(_RFC3966_PREFIX) index_of_national_number = ((index_of_rfc3996_prefix + len(_RFC3966_PREFIX)) if (index_of_rfc3996_prefix >= 0) else 0) national_number += number[index_of_national_number:index_of_phone_context] else: # Extract a possible number from the string passed in (this strips leading characters that # could not be the start of a phone number.) national_number = _extract_possible_number(number) # Delete the isdn-subaddress and everything after it if it is # present. Note extension won't appear at the same time with # isdn-subaddress according to paragraph 5.3 of the RFC3966 spec, index_of_isdn = national_number.find(_RFC3966_ISDN_SUBADDRESS) if index_of_isdn > 0: national_number = national_number[:index_of_isdn] # If both phone context and isdn-subaddress are absent but other # parameters are present, the parameters are left in national_number. This # is because we are concerned about deleting content from a potential # number string when there is no strong evidence that the number is # actually written in RFC3966. return national_number
[ "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", "+", "le...
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.
[ "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", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L2896-L2941
234,682
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
_copy_core_fields_only
def _copy_core_fields_only(inobj): """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. """ 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_leading_zero = True # This field is only relevant if there are leading zeros at all. numobj.number_of_leading_zeros = inobj.number_of_leading_zeros if numobj.number_of_leading_zeros is None: # No number set is implicitly a count of 1; make it explicit. numobj.number_of_leading_zeros = 1 return numobj
python
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_leading_zero = True # This field is only relevant if there are leading zeros at all. numobj.number_of_leading_zeros = inobj.number_of_leading_zeros if numobj.number_of_leading_zeros is None: # No number set is implicitly a count of 1; make it explicit. numobj.number_of_leading_zeros = 1 return numobj
[ "def", "_copy_core_fields_only", "(", "inobj", ")", ":", "numobj", "=", "PhoneNumber", "(", ")", "numobj", ".", "country_code", "=", "inobj", ".", "country_code", "numobj", ".", "national_number", "=", "inobj", ".", "national_number", "if", "inobj", ".", "exte...
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.
[ "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", ...
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L2944-L2961
234,683
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
_is_number_match_OO
def _is_number_match_OO(numobj1_in, numobj2_in): """Takes two phone number objects and compares them for equality.""" # We only care about the fields that uniquely define a number, so we copy these across explicitly. numobj1 = _copy_core_fields_only(numobj1_in) numobj2 = _copy_core_fields_only(numobj2_in) # Early exit if both had extensions and these are different. if (numobj1.extension is not None and numobj2.extension is not None and numobj1.extension != numobj2.extension): return MatchType.NO_MATCH country_code1 = numobj1.country_code country_code2 = numobj2.country_code # Both had country_code specified. if country_code1 != 0 and country_code2 != 0: if numobj1 == numobj2: return MatchType.EXACT_MATCH elif (country_code1 == country_code2 and _is_national_number_suffix_of_other(numobj1, numobj2)): # A SHORT_NSN_MATCH occurs if there is a difference because of the # presence or absence of an 'Italian leading zero', the presence # or absence of an extension, or one NSN being a shorter variant # of the other. return MatchType.SHORT_NSN_MATCH # This is not a match. return MatchType.NO_MATCH # Checks cases where one or both country_code fields were not # specified. To make equality checks easier, we first set the country_code # fields to be equal. numobj1.country_code = country_code2 # If all else was the same, then this is an NSN_MATCH. if numobj1 == numobj2: return MatchType.NSN_MATCH if _is_national_number_suffix_of_other(numobj1, numobj2): return MatchType.SHORT_NSN_MATCH return MatchType.NO_MATCH
python
def _is_number_match_OO(numobj1_in, numobj2_in): # We only care about the fields that uniquely define a number, so we copy these across explicitly. numobj1 = _copy_core_fields_only(numobj1_in) numobj2 = _copy_core_fields_only(numobj2_in) # Early exit if both had extensions and these are different. if (numobj1.extension is not None and numobj2.extension is not None and numobj1.extension != numobj2.extension): return MatchType.NO_MATCH country_code1 = numobj1.country_code country_code2 = numobj2.country_code # Both had country_code specified. if country_code1 != 0 and country_code2 != 0: if numobj1 == numobj2: return MatchType.EXACT_MATCH elif (country_code1 == country_code2 and _is_national_number_suffix_of_other(numobj1, numobj2)): # A SHORT_NSN_MATCH occurs if there is a difference because of the # presence or absence of an 'Italian leading zero', the presence # or absence of an extension, or one NSN being a shorter variant # of the other. return MatchType.SHORT_NSN_MATCH # This is not a match. return MatchType.NO_MATCH # Checks cases where one or both country_code fields were not # specified. To make equality checks easier, we first set the country_code # fields to be equal. numobj1.country_code = country_code2 # If all else was the same, then this is an NSN_MATCH. if numobj1 == numobj2: return MatchType.NSN_MATCH if _is_national_number_suffix_of_other(numobj1, numobj2): return MatchType.SHORT_NSN_MATCH return MatchType.NO_MATCH
[ "def", "_is_number_match_OO", "(", "numobj1_in", ",", "numobj2_in", ")", ":", "# We only care about the fields that uniquely define a number, so we copy these across explicitly.", "numobj1", "=", "_copy_core_fields_only", "(", "numobj1_in", ")", "numobj2", "=", "_copy_core_fields_o...
Takes two phone number objects and compares them for equality.
[ "Takes", "two", "phone", "number", "objects", "and", "compares", "them", "for", "equality", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L2964-L3001
234,684
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
_is_national_number_suffix_of_other
def _is_national_number_suffix_of_other(numobj1, numobj2): """Returns true when one national number is the suffix of the other or both are the same. """ nn1 = str(numobj1.national_number) nn2 = str(numobj2.national_number) # Note that endswith returns True if the numbers are equal. return nn1.endswith(nn2) or nn2.endswith(nn1)
python
def _is_national_number_suffix_of_other(numobj1, numobj2): nn1 = str(numobj1.national_number) nn2 = str(numobj2.national_number) # Note that endswith returns True if the numbers are equal. return nn1.endswith(nn2) or nn2.endswith(nn1)
[ "def", "_is_national_number_suffix_of_other", "(", "numobj1", ",", "numobj2", ")", ":", "nn1", "=", "str", "(", "numobj1", ".", "national_number", ")", "nn2", "=", "str", "(", "numobj2", ".", "national_number", ")", "# Note that endswith returns True if the numbers ar...
Returns true when one national number is the suffix of the other or both are the same.
[ "Returns", "true", "when", "one", "national", "number", "is", "the", "suffix", "of", "the", "other", "or", "both", "are", "the", "same", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L3004-L3011
234,685
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
_is_number_match_SS
def _is_number_match_SS(number1, number2): """Takes two phone numbers as strings and compares them for equality. This is a convenience wrapper for _is_number_match_OO/_is_number_match_OS. No default region is known. """ 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, UNKNOWN_REGION) return _is_number_match_OS(numobj2, number1) except NumberParseException: _, exc2, _ = sys.exc_info() if exc2.error_type == NumberParseException.INVALID_COUNTRY_CODE: try: numobj1 = parse(number1, None, keep_raw_input=False, _check_region=False, numobj=None) numobj2 = parse(number2, None, keep_raw_input=False, _check_region=False, numobj=None) return _is_number_match_OO(numobj1, numobj2) except NumberParseException: return MatchType.NOT_A_NUMBER # One or more of the phone numbers we are trying to match is not a viable # phone number. return MatchType.NOT_A_NUMBER
python
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, UNKNOWN_REGION) return _is_number_match_OS(numobj2, number1) except NumberParseException: _, exc2, _ = sys.exc_info() if exc2.error_type == NumberParseException.INVALID_COUNTRY_CODE: try: numobj1 = parse(number1, None, keep_raw_input=False, _check_region=False, numobj=None) numobj2 = parse(number2, None, keep_raw_input=False, _check_region=False, numobj=None) return _is_number_match_OO(numobj1, numobj2) except NumberParseException: return MatchType.NOT_A_NUMBER # One or more of the phone numbers we are trying to match is not a viable # phone number. return MatchType.NOT_A_NUMBER
[ "def", "_is_number_match_SS", "(", "number1", ",", "number2", ")", ":", "try", ":", "numobj1", "=", "parse", "(", "number1", ",", "UNKNOWN_REGION", ")", "return", "_is_number_match_OS", "(", "numobj1", ",", "number2", ")", "except", "NumberParseException", ":", ...
Takes two phone numbers as strings and compares them for equality. This is a convenience wrapper for _is_number_match_OO/_is_number_match_OS. No default region is known.
[ "Takes", "two", "phone", "numbers", "as", "strings", "and", "compares", "them", "for", "equality", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L3014-L3043
234,686
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
_is_number_match_OS
def _is_number_match_OS(numobj1, number2): """Wrapper variant of _is_number_match_OO that copes with one PhoneNumber object and one string.""" # First see if the second number has an implicit country calling code, by # attempting to parse it. 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: # The second number has no country calling code. EXACT_MATCH is no # longer possible. We parse it as if the region was the same as # that for the first number, and if EXACT_MATCH is returned, we # replace this with NSN_MATCH. region1 = region_code_for_country_code(numobj1.country_code) try: if region1 != UNKNOWN_REGION: numobj2 = parse(number2, region1) match = _is_number_match_OO(numobj1, numobj2) if match == MatchType.EXACT_MATCH: return MatchType.NSN_MATCH else: return match else: # If the first number didn't have a valid country calling # code, then we parse the second number without one as # well. numobj2 = parse(number2, None, keep_raw_input=False, _check_region=False, numobj=None) return _is_number_match_OO(numobj1, numobj2) except NumberParseException: return MatchType.NOT_A_NUMBER # One or more of the phone numbers we are trying to match is not a viable # phone number. return MatchType.NOT_A_NUMBER
python
def _is_number_match_OS(numobj1, number2): # First see if the second number has an implicit country calling code, by # attempting to parse it. 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: # The second number has no country calling code. EXACT_MATCH is no # longer possible. We parse it as if the region was the same as # that for the first number, and if EXACT_MATCH is returned, we # replace this with NSN_MATCH. region1 = region_code_for_country_code(numobj1.country_code) try: if region1 != UNKNOWN_REGION: numobj2 = parse(number2, region1) match = _is_number_match_OO(numobj1, numobj2) if match == MatchType.EXACT_MATCH: return MatchType.NSN_MATCH else: return match else: # If the first number didn't have a valid country calling # code, then we parse the second number without one as # well. numobj2 = parse(number2, None, keep_raw_input=False, _check_region=False, numobj=None) return _is_number_match_OO(numobj1, numobj2) except NumberParseException: return MatchType.NOT_A_NUMBER # One or more of the phone numbers we are trying to match is not a viable # phone number. return MatchType.NOT_A_NUMBER
[ "def", "_is_number_match_OS", "(", "numobj1", ",", "number2", ")", ":", "# First see if the second number has an implicit country calling code, by", "# attempting to parse it.", "try", ":", "numobj2", "=", "parse", "(", "number2", ",", "UNKNOWN_REGION", ")", "return", "_is_...
Wrapper variant of _is_number_match_OO that copes with one PhoneNumber object and one string.
[ "Wrapper", "variant", "of", "_is_number_match_OO", "that", "copes", "with", "one", "PhoneNumber", "object", "and", "one", "string", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L3046-L3081
234,687
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
is_number_match
def is_number_match(num1, num2): """Takes two phone numbers and compares them for equality. For example, the numbers +1 345 657 1234 and 657 1234 are a SHORT_NSN_MATCH. The numbers +1 345 657 1234 and 345 657 are a NO_MATCH. Arguments num1 -- First number object or string to compare. Can contain formatting, and can have country calling code specified with + at the start. num2 -- Second number object or string to compare. Can contain formatting, and can have country calling code specified with + at the start. Returns: - EXACT_MATCH if the country_code, NSN, presence of a leading zero for Italian numbers and any extension present are the same. - NSN_MATCH if either or both has no region specified, and the NSNs and extensions are the same. - SHORT_NSN_MATCH if either or both has no region specified, or the region specified is the same, and one NSN could be a shorter version of the other number. This includes the case where one has an extension specified, and the other does not. - NO_MATCH otherwise. """ 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, num1) else: return _is_number_match_SS(num1, num2)
python
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, num1) else: return _is_number_match_SS(num1, num2)
[ "def", "is_number_match", "(", "num1", ",", "num2", ")", ":", "if", "isinstance", "(", "num1", ",", "PhoneNumber", ")", "and", "isinstance", "(", "num2", ",", "PhoneNumber", ")", ":", "return", "_is_number_match_OO", "(", "num1", ",", "num2", ")", "elif", ...
Takes two phone numbers and compares them for equality. For example, the numbers +1 345 657 1234 and 657 1234 are a SHORT_NSN_MATCH. The numbers +1 345 657 1234 and 345 657 are a NO_MATCH. Arguments num1 -- First number object or string to compare. Can contain formatting, and can have country calling code specified with + at the start. num2 -- Second number object or string to compare. Can contain formatting, and can have country calling code specified with + at the start. Returns: - EXACT_MATCH if the country_code, NSN, presence of a leading zero for Italian numbers and any extension present are the same. - NSN_MATCH if either or both has no region specified, and the NSNs and extensions are the same. - SHORT_NSN_MATCH if either or both has no region specified, or the region specified is the same, and one NSN could be a shorter version of the other number. This includes the case where one has an extension specified, and the other does not. - NO_MATCH otherwise.
[ "Takes", "two", "phone", "numbers", "and", "compares", "them", "for", "equality", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L3084-L3114
234,688
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
can_be_internationally_dialled
def can_be_internationally_dialled(numobj): """Returns True if the number can only be dialled from outside the region, or unknown. If the number can only be dialled from within the region as well, returns False. Does not check the number is a valid number. Note that, at the moment, this method does not handle short numbers (which are currently all presumed to not be diallable from outside their country). Arguments: numobj -- the phone number objectfor which we want to know whether it is diallable from outside the region. """ metadata = PhoneMetadata.metadata_for_region(region_code_for_number(numobj), None) if metadata is None: # Note numbers belonging to non-geographical entities (e.g. +800 # numbers) are always internationally diallable, and will be caught # here. return True nsn = national_significant_number(numobj) return not _is_number_matching_desc(nsn, metadata.no_international_dialling)
python
def can_be_internationally_dialled(numobj): metadata = PhoneMetadata.metadata_for_region(region_code_for_number(numobj), None) if metadata is None: # Note numbers belonging to non-geographical entities (e.g. +800 # numbers) are always internationally diallable, and will be caught # here. return True nsn = national_significant_number(numobj) return not _is_number_matching_desc(nsn, metadata.no_international_dialling)
[ "def", "can_be_internationally_dialled", "(", "numobj", ")", ":", "metadata", "=", "PhoneMetadata", ".", "metadata_for_region", "(", "region_code_for_number", "(", "numobj", ")", ",", "None", ")", "if", "metadata", "is", "None", ":", "# Note numbers belonging to non-g...
Returns True if the number can only be dialled from outside the region, or unknown. If the number can only be dialled from within the region as well, returns False. Does not check the number is a valid number. Note that, at the moment, this method does not handle short numbers (which are currently all presumed to not be diallable from outside their country). Arguments: numobj -- the phone number objectfor which we want to know whether it is diallable from outside the region.
[ "Returns", "True", "if", "the", "number", "can", "only", "be", "dialled", "from", "outside", "the", "region", "or", "unknown", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L3117-L3137
234,689
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
is_mobile_number_portable_region
def is_mobile_number_portable_region(region_code): """Returns true if the supplied region supports mobile number portability. Returns false for invalid, unknown or regions that don't support mobile number portability. Arguments: region_code -- the region for which we want to know whether it supports mobile number portability or not. """ metadata = PhoneMetadata.metadata_for_region(region_code, None) if metadata is None: return False return metadata.mobile_number_portable_region
python
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
[ "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_...
Returns true if the supplied region supports mobile number portability. Returns false for invalid, unknown or regions that don't support mobile number portability. Arguments: region_code -- the region for which we want to know whether it supports mobile number portability or not.
[ "Returns", "true", "if", "the", "supplied", "region", "supports", "mobile", "number", "portability", ".", "Returns", "false", "for", "invalid", "unknown", "or", "regions", "that", "don", "t", "support", "mobile", "number", "portability", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L3140-L3152
234,690
daviddrysdale/python-phonenumbers
python/phonenumbers/timezone.py
time_zones_for_geographical_number
def time_zones_for_geographical_number(numobj): """Returns a list of time zones to which a phone number belongs. This method assumes the validity of the number passed in has already been checked, and that the number is geo-localizable. We consider fixed-line and mobile numbers possible candidates for geo-localization. Arguments: numobj -- a valid phone number for which we want to get the time zones to which it belongs Returns a list of the corresponding time zones or a single element list with the default unknown time zone if no other time zone was found or if the number was invalid""" e164_num = format_number(numobj, PhoneNumberFormat.E164) if not e164_num.startswith(U_PLUS): # pragma no cover # Can only hit this arm if there's an internal error in the rest of # the library 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)] if prefix in TIMEZONE_DATA: return TIMEZONE_DATA[prefix] return _UNKNOWN_TIME_ZONE_LIST
python
def time_zones_for_geographical_number(numobj): e164_num = format_number(numobj, PhoneNumberFormat.E164) if not e164_num.startswith(U_PLUS): # pragma no cover # Can only hit this arm if there's an internal error in the rest of # the library 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)] if prefix in TIMEZONE_DATA: return TIMEZONE_DATA[prefix] return _UNKNOWN_TIME_ZONE_LIST
[ "def", "time_zones_for_geographical_number", "(", "numobj", ")", ":", "e164_num", "=", "format_number", "(", "numobj", ",", "PhoneNumberFormat", ".", "E164", ")", "if", "not", "e164_num", ".", "startswith", "(", "U_PLUS", ")", ":", "# pragma no cover", "# Can only...
Returns a list of time zones to which a phone number belongs. This method assumes the validity of the number passed in has already been checked, and that the number is geo-localizable. We consider fixed-line and mobile numbers possible candidates for geo-localization. Arguments: numobj -- a valid phone number for which we want to get the time zones to which it belongs Returns a list of the corresponding time zones or a single element list with the default unknown time zone if no other time zone was found or if the number was invalid
[ "Returns", "a", "list", "of", "time", "zones", "to", "which", "a", "phone", "number", "belongs", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/timezone.py#L64-L86
234,691
daviddrysdale/python-phonenumbers
python/phonenumbers/unicode_util.py
is_letter
def is_letter(uni_char): """Determine whether the given Unicode character is a Unicode letter""" 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)
python
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)
[ "def", "is_letter", "(", "uni_char", ")", ":", "category", "=", "Category", ".", "get", "(", "uni_char", ")", "return", "(", "category", "==", "Category", ".", "UPPERCASE_LETTER", "or", "category", "==", "Category", ".", "LOWERCASE_LETTER", "or", "category", ...
Determine whether the given Unicode character is a Unicode letter
[ "Determine", "whether", "the", "given", "Unicode", "character", "is", "a", "Unicode", "letter" ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/unicode_util.py#L128-L135
234,692
daviddrysdale/python-phonenumbers
python/phonenumbers/unicode_util.py
digit
def digit(uni_char, default_value=None): """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.""" uni_char = unicod(uni_char) # Force to Unicode. if default_value is not None: return unicodedata.digit(uni_char, default_value) else: return unicodedata.digit(uni_char)
python
def digit(uni_char, default_value=None): uni_char = unicod(uni_char) # Force to Unicode. if default_value is not None: return unicodedata.digit(uni_char, default_value) else: return unicodedata.digit(uni_char)
[ "def", "digit", "(", "uni_char", ",", "default_value", "=", "None", ")", ":", "uni_char", "=", "unicod", "(", "uni_char", ")", "# Force to Unicode.", "if", "default_value", "is", "not", "None", ":", "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.
[ "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", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/unicode_util.py#L397-L405
234,693
daviddrysdale/python-phonenumbers
python/phonenumbers/unicode_util.py
Block.get
def get(cls, uni_char): """Return the Unicode block of the given Unicode character""" uni_char = unicod(uni_char) # Force to Unicode 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[idx - 1]].start and code_point <= Block._RANGES[Block._RANGE_KEYS[idx - 1]].end): return Block._RANGES[Block._RANGE_KEYS[idx - 1]] elif (idx < len(Block._RANGES) and code_point >= Block._RANGES[Block._RANGE_KEYS[idx]].start and code_point <= Block._RANGES[Block._RANGE_KEYS[idx]].end): return Block._RANGES[Block._RANGE_KEYS[idx]] else: return Block.UNKNOWN
python
def get(cls, uni_char): uni_char = unicod(uni_char) # Force to Unicode 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[idx - 1]].start and code_point <= Block._RANGES[Block._RANGE_KEYS[idx - 1]].end): return Block._RANGES[Block._RANGE_KEYS[idx - 1]] elif (idx < len(Block._RANGES) and code_point >= Block._RANGES[Block._RANGE_KEYS[idx]].start and code_point <= Block._RANGES[Block._RANGE_KEYS[idx]].end): return Block._RANGES[Block._RANGE_KEYS[idx]] else: return Block.UNKNOWN
[ "def", "get", "(", "cls", ",", "uni_char", ")", ":", "uni_char", "=", "unicod", "(", "uni_char", ")", "# Force to Unicode", "code_point", "=", "ord", "(", "uni_char", ")", "if", "Block", ".", "_RANGE_KEYS", "is", "None", ":", "Block", ".", "_RANGE_KEYS", ...
Return the Unicode block of the given Unicode character
[ "Return", "the", "Unicode", "block", "of", "the", "given", "Unicode", "character" ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/unicode_util.py#L378-L394
234,694
daviddrysdale/python-phonenumbers
python/phonenumbers/carrier.py
_is_mobile
def _is_mobile(ntype): """Checks if the supplied number type supports carrier lookup""" return (ntype == PhoneNumberType.MOBILE or ntype == PhoneNumberType.FIXED_LINE_OR_MOBILE or ntype == PhoneNumberType.PAGER)
python
def _is_mobile(ntype): return (ntype == PhoneNumberType.MOBILE or ntype == PhoneNumberType.FIXED_LINE_OR_MOBILE or ntype == PhoneNumberType.PAGER)
[ "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
[ "Checks", "if", "the", "supplied", "number", "type", "supports", "carrier", "lookup" ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/carrier.py#L136-L140
234,695
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumber.py
PhoneNumber.clear
def clear(self): """Erase the contents of the object""" 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
python
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
[ "def", "clear", "(", "self", ")", ":", "self", ".", "country_code", "=", "None", "self", ".", "national_number", "=", "None", "self", ".", "extension", "=", "None", "self", ".", "italian_leading_zero", "=", "None", "self", ".", "number_of_leading_zeros", "="...
Erase the contents of the object
[ "Erase", "the", "contents", "of", "the", "object" ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumber.py#L168-L177
234,696
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumber.py
PhoneNumber.merge_from
def merge_from(self, other): """Merge information from another PhoneNumber object into this one.""" 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: self.italian_leading_zero = other.italian_leading_zero if other.number_of_leading_zeros is not None: self.number_of_leading_zeros = other.number_of_leading_zeros if other.raw_input is not None: self.raw_input = other.raw_input if other.country_code_source is not CountryCodeSource.UNSPECIFIED: self.country_code_source = other.country_code_source if other.preferred_domestic_carrier_code is not None: self.preferred_domestic_carrier_code = other.preferred_domestic_carrier_code
python
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: self.italian_leading_zero = other.italian_leading_zero if other.number_of_leading_zeros is not None: self.number_of_leading_zeros = other.number_of_leading_zeros if other.raw_input is not None: self.raw_input = other.raw_input if other.country_code_source is not CountryCodeSource.UNSPECIFIED: self.country_code_source = other.country_code_source if other.preferred_domestic_carrier_code is not None: self.preferred_domestic_carrier_code = other.preferred_domestic_carrier_code
[ "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...
Merge information from another PhoneNumber object into this one.
[ "Merge", "information", "from", "another", "PhoneNumber", "object", "into", "this", "one", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumber.py#L179-L196
234,697
daviddrysdale/python-phonenumbers
python/phonenumbers/util.py
mutating_method
def mutating_method(func): """Decorator for methods that are allowed to modify immutable objects""" def wrapper(self, *__args, **__kwargs): old_mutable = self._mutable self._mutable = True try: # Call the wrapped function return func(self, *__args, **__kwargs) finally: self._mutable = old_mutable return wrapper
python
def mutating_method(func): def wrapper(self, *__args, **__kwargs): old_mutable = self._mutable self._mutable = True try: # Call the wrapped function return func(self, *__args, **__kwargs) finally: self._mutable = old_mutable return wrapper
[ "def", "mutating_method", "(", "func", ")", ":", "def", "wrapper", "(", "self", ",", "*", "__args", ",", "*", "*", "__kwargs", ")", ":", "old_mutable", "=", "self", ".", "_mutable", "self", ".", "_mutable", "=", "True", "try", ":", "# Call the wrapped fu...
Decorator for methods that are allowed to modify immutable objects
[ "Decorator", "for", "methods", "that", "are", "allowed", "to", "modify", "immutable", "objects" ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/util.py#L169-L179
234,698
daviddrysdale/python-phonenumbers
python/phonenumbers/re_util.py
fullmatch
def fullmatch(pattern, string, flags=0): """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.""" # Build a version of the pattern with a non-capturing group around it. # This is needed to get m.end() to correctly report the size of the # matched expression (as per the final doctest above). grouped_pattern = re.compile("^(?:%s)$" % pattern.pattern, pattern.flags) m = grouped_pattern.match(string) if m and m.end() < len(string): # Incomplete match (which should never happen because of the $ at the # end of the regexp), treat as failure. m = None # pragma no cover return m
python
def fullmatch(pattern, string, flags=0): # Build a version of the pattern with a non-capturing group around it. # This is needed to get m.end() to correctly report the size of the # matched expression (as per the final doctest above). grouped_pattern = re.compile("^(?:%s)$" % pattern.pattern, pattern.flags) m = grouped_pattern.match(string) if m and m.end() < len(string): # Incomplete match (which should never happen because of the $ at the # end of the regexp), treat as failure. m = None # pragma no cover return m
[ "def", "fullmatch", "(", "pattern", ",", "string", ",", "flags", "=", "0", ")", ":", "# Build a version of the pattern with a non-capturing group around it.", "# This is needed to get m.end() to correctly report the size of the", "# matched expression (as per the final doctest above).", ...
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.
[ "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", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/re_util.py#L27-L39
234,699
daviddrysdale/python-phonenumbers
tools/python/buildprefixdata.py
load_locale_prefixdata_file
def load_locale_prefixdata_file(prefixdata, filename, locale=None, overall_prefix=None, separator=None): """Load per-prefix data from the given file, for the given locale and prefix. We assume that this file: - is encoded in UTF-8 - may have comment lines (starting with #) and blank lines - has data lines of the form '<prefix>|<stringdata>' - contains only data for prefixes that are extensions of the filename. If overall_prefix is specified, lines are checked to ensure their prefix falls within this value. If locale is specified, prefixdata[prefix][locale] is filled in; otherwise, just prefixdata[prefix]. If separator is specified, the string data will be split on this separator, and the output values in the dict will be tuples of strings rather than strings. """ 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') stringdata = dm.group('stringdata') if stringdata != stringdata.rstrip(): print ("%s:%d: Warning: stripping trailing whitespace" % (filename, lineno)) stringdata = stringdata.rstrip() if overall_prefix is not None and not prefix.startswith(overall_prefix): raise Exception("%s:%d: Prefix %s is not within %s" % (filename, lineno, prefix, overall_prefix)) if separator is not None: stringdata = tuple(stringdata.split(separator)) if prefix not in prefixdata: prefixdata[prefix] = {} if locale is not None: prefixdata[prefix][locale] = stringdata else: prefixdata[prefix] = stringdata elif BLANK_LINE_RE.match(uline): pass elif COMMENT_LINE_RE.match(uline): pass else: raise Exception("%s:%d: Unexpected line format: %s" % (filename, lineno, line))
python
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') stringdata = dm.group('stringdata') if stringdata != stringdata.rstrip(): print ("%s:%d: Warning: stripping trailing whitespace" % (filename, lineno)) stringdata = stringdata.rstrip() if overall_prefix is not None and not prefix.startswith(overall_prefix): raise Exception("%s:%d: Prefix %s is not within %s" % (filename, lineno, prefix, overall_prefix)) if separator is not None: stringdata = tuple(stringdata.split(separator)) if prefix not in prefixdata: prefixdata[prefix] = {} if locale is not None: prefixdata[prefix][locale] = stringdata else: prefixdata[prefix] = stringdata elif BLANK_LINE_RE.match(uline): pass elif COMMENT_LINE_RE.match(uline): pass else: raise Exception("%s:%d: Unexpected line format: %s" % (filename, lineno, line))
[ "def", "load_locale_prefixdata_file", "(", "prefixdata", ",", "filename", ",", "locale", "=", "None", ",", "overall_prefix", "=", "None", ",", "separator", "=", "None", ")", ":", "with", "open", "(", "filename", ",", "\"rb\"", ")", "as", "infile", ":", "li...
Load per-prefix data from the given file, for the given locale and prefix. We assume that this file: - is encoded in UTF-8 - may have comment lines (starting with #) and blank lines - has data lines of the form '<prefix>|<stringdata>' - contains only data for prefixes that are extensions of the filename. If overall_prefix is specified, lines are checked to ensure their prefix falls within this value. If locale is specified, prefixdata[prefix][locale] is filled in; otherwise, just prefixdata[prefix]. If separator is specified, the string data will be split on this separator, and the output values in the dict will be tuples of strings rather than strings.
[ "Load", "per", "-", "prefix", "data", "from", "the", "given", "file", "for", "the", "given", "locale", "and", "prefix", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/tools/python/buildprefixdata.py#L83-L128