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 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
MycroftAI/mycroft-precise | runner/precise_runner/runner.py | PreciseRunner.start | def start(self):
"""Start listening from stream"""
if self.stream is None:
from pyaudio import PyAudio, paInt16
self.pa = PyAudio()
self.stream = self.pa.open(
16000, 1, paInt16, True, frames_per_buffer=self.chunk_size
)
self._wrap... | python | def start(self):
"""Start listening from stream"""
if self.stream is None:
from pyaudio import PyAudio, paInt16
self.pa = PyAudio()
self.stream = self.pa.open(
16000, 1, paInt16, True, frames_per_buffer=self.chunk_size
)
self._wrap... | [
"def",
"start",
"(",
"self",
")",
":",
"if",
"self",
".",
"stream",
"is",
"None",
":",
"from",
"pyaudio",
"import",
"PyAudio",
",",
"paInt16",
"self",
".",
"pa",
"=",
"PyAudio",
"(",
")",
"self",
".",
"stream",
"=",
"self",
".",
"pa",
".",
"open",
... | Start listening from stream | [
"Start",
"listening",
"from",
"stream"
] | e17cebdd171906dbd8a16e282d8a7966fba2eeba | https://github.com/MycroftAI/mycroft-precise/blob/e17cebdd171906dbd8a16e282d8a7966fba2eeba/runner/precise_runner/runner.py#L172-L188 | train |
MycroftAI/mycroft-precise | runner/precise_runner/runner.py | PreciseRunner.stop | def stop(self):
"""Stop listening and close stream"""
if self.thread:
self.running = False
if isinstance(self.stream, ReadWriteStream):
self.stream.write(b'\0' * self.chunk_size)
self.thread.join()
self.thread = None
self.engine.st... | python | def stop(self):
"""Stop listening and close stream"""
if self.thread:
self.running = False
if isinstance(self.stream, ReadWriteStream):
self.stream.write(b'\0' * self.chunk_size)
self.thread.join()
self.thread = None
self.engine.st... | [
"def",
"stop",
"(",
"self",
")",
":",
"if",
"self",
".",
"thread",
":",
"self",
".",
"running",
"=",
"False",
"if",
"isinstance",
"(",
"self",
".",
"stream",
",",
"ReadWriteStream",
")",
":",
"self",
".",
"stream",
".",
"write",
"(",
"b'\\0'",
"*",
... | Stop listening and close stream | [
"Stop",
"listening",
"and",
"close",
"stream"
] | e17cebdd171906dbd8a16e282d8a7966fba2eeba | https://github.com/MycroftAI/mycroft-precise/blob/e17cebdd171906dbd8a16e282d8a7966fba2eeba/runner/precise_runner/runner.py#L190-L204 | train |
MycroftAI/mycroft-precise | runner/precise_runner/runner.py | PreciseRunner._handle_predictions | def _handle_predictions(self):
"""Continuously check Precise process output"""
while self.running:
chunk = self.stream.read(self.chunk_size)
if self.is_paused:
continue
prob = self.engine.get_prediction(chunk)
self.on_prediction(prob)
... | python | def _handle_predictions(self):
"""Continuously check Precise process output"""
while self.running:
chunk = self.stream.read(self.chunk_size)
if self.is_paused:
continue
prob = self.engine.get_prediction(chunk)
self.on_prediction(prob)
... | [
"def",
"_handle_predictions",
"(",
"self",
")",
":",
"while",
"self",
".",
"running",
":",
"chunk",
"=",
"self",
".",
"stream",
".",
"read",
"(",
"self",
".",
"chunk_size",
")",
"if",
"self",
".",
"is_paused",
":",
"continue",
"prob",
"=",
"self",
".",... | Continuously check Precise process output | [
"Continuously",
"check",
"Precise",
"process",
"output"
] | e17cebdd171906dbd8a16e282d8a7966fba2eeba | https://github.com/MycroftAI/mycroft-precise/blob/e17cebdd171906dbd8a16e282d8a7966fba2eeba/runner/precise_runner/runner.py#L212-L223 | train |
MycroftAI/mycroft-precise | precise/stats.py | Stats.calc_filenames | def calc_filenames(self, is_correct: bool, actual_output: bool, threshold=0.5) -> list:
"""Find a list of files with the given classification"""
return [
filename
for output, target, filename in zip(self.outputs, self.targets, self.filenames)
if ((output > threshold) ... | python | def calc_filenames(self, is_correct: bool, actual_output: bool, threshold=0.5) -> list:
"""Find a list of files with the given classification"""
return [
filename
for output, target, filename in zip(self.outputs, self.targets, self.filenames)
if ((output > threshold) ... | [
"def",
"calc_filenames",
"(",
"self",
",",
"is_correct",
":",
"bool",
",",
"actual_output",
":",
"bool",
",",
"threshold",
"=",
"0.5",
")",
"->",
"list",
":",
"return",
"[",
"filename",
"for",
"output",
",",
"target",
",",
"filename",
"in",
"zip",
"(",
... | Find a list of files with the given classification | [
"Find",
"a",
"list",
"of",
"files",
"with",
"the",
"given",
"classification"
] | e17cebdd171906dbd8a16e282d8a7966fba2eeba | https://github.com/MycroftAI/mycroft-precise/blob/e17cebdd171906dbd8a16e282d8a7966fba2eeba/precise/stats.py#L90-L96 | train |
MycroftAI/mycroft-precise | precise/scripts/graph.py | get_thresholds | def get_thresholds(points=100, power=3) -> list:
"""Run a function with a series of thresholds between 0 and 1"""
return [(i / (points + 1)) ** power for i in range(1, points + 1)] | python | def get_thresholds(points=100, power=3) -> list:
"""Run a function with a series of thresholds between 0 and 1"""
return [(i / (points + 1)) ** power for i in range(1, points + 1)] | [
"def",
"get_thresholds",
"(",
"points",
"=",
"100",
",",
"power",
"=",
"3",
")",
"->",
"list",
":",
"return",
"[",
"(",
"i",
"/",
"(",
"points",
"+",
"1",
")",
")",
"**",
"power",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"points",
"+",
"1",
... | Run a function with a series of thresholds between 0 and 1 | [
"Run",
"a",
"function",
"with",
"a",
"series",
"of",
"thresholds",
"between",
"0",
"and",
"1"
] | e17cebdd171906dbd8a16e282d8a7966fba2eeba | https://github.com/MycroftAI/mycroft-precise/blob/e17cebdd171906dbd8a16e282d8a7966fba2eeba/precise/scripts/graph.py#L57-L59 | train |
MycroftAI/mycroft-precise | precise/scripts/graph.py | CachedDataLoader.load_for | def load_for(self, model: str) -> Tuple[list, list]:
"""Injects the model parameters, reloading if they changed, and returning the data"""
inject_params(model)
if self.prev_cache != pr.vectorization_md5_hash():
self.prev_cache = pr.vectorization_md5_hash()
self.data = sel... | python | def load_for(self, model: str) -> Tuple[list, list]:
"""Injects the model parameters, reloading if they changed, and returning the data"""
inject_params(model)
if self.prev_cache != pr.vectorization_md5_hash():
self.prev_cache = pr.vectorization_md5_hash()
self.data = sel... | [
"def",
"load_for",
"(",
"self",
",",
"model",
":",
"str",
")",
"->",
"Tuple",
"[",
"list",
",",
"list",
"]",
":",
"inject_params",
"(",
"model",
")",
"if",
"self",
".",
"prev_cache",
"!=",
"pr",
".",
"vectorization_md5_hash",
"(",
")",
":",
"self",
"... | Injects the model parameters, reloading if they changed, and returning the data | [
"Injects",
"the",
"model",
"parameters",
"reloading",
"if",
"they",
"changed",
"and",
"returning",
"the",
"data"
] | e17cebdd171906dbd8a16e282d8a7966fba2eeba | https://github.com/MycroftAI/mycroft-precise/blob/e17cebdd171906dbd8a16e282d8a7966fba2eeba/precise/scripts/graph.py#L75-L81 | train |
MycroftAI/mycroft-precise | precise/util.py | buffer_to_audio | def buffer_to_audio(buffer: bytes) -> np.ndarray:
"""Convert a raw mono audio byte string to numpy array of floats"""
return np.fromstring(buffer, dtype='<i2').astype(np.float32, order='C') / 32768.0 | python | def buffer_to_audio(buffer: bytes) -> np.ndarray:
"""Convert a raw mono audio byte string to numpy array of floats"""
return np.fromstring(buffer, dtype='<i2').astype(np.float32, order='C') / 32768.0 | [
"def",
"buffer_to_audio",
"(",
"buffer",
":",
"bytes",
")",
"->",
"np",
".",
"ndarray",
":",
"return",
"np",
".",
"fromstring",
"(",
"buffer",
",",
"dtype",
"=",
"'<i2'",
")",
".",
"astype",
"(",
"np",
".",
"float32",
",",
"order",
"=",
"'C'",
")",
... | Convert a raw mono audio byte string to numpy array of floats | [
"Convert",
"a",
"raw",
"mono",
"audio",
"byte",
"string",
"to",
"numpy",
"array",
"of",
"floats"
] | e17cebdd171906dbd8a16e282d8a7966fba2eeba | https://github.com/MycroftAI/mycroft-precise/blob/e17cebdd171906dbd8a16e282d8a7966fba2eeba/precise/util.py#L31-L33 | train |
MycroftAI/mycroft-precise | precise/util.py | find_wavs | def find_wavs(folder: str) -> Tuple[List[str], List[str]]:
"""Finds wake-word and not-wake-word wavs in folder"""
return (glob_all(join(folder, 'wake-word'), '*.wav'),
glob_all(join(folder, 'not-wake-word'), '*.wav')) | python | def find_wavs(folder: str) -> Tuple[List[str], List[str]]:
"""Finds wake-word and not-wake-word wavs in folder"""
return (glob_all(join(folder, 'wake-word'), '*.wav'),
glob_all(join(folder, 'not-wake-word'), '*.wav')) | [
"def",
"find_wavs",
"(",
"folder",
":",
"str",
")",
"->",
"Tuple",
"[",
"List",
"[",
"str",
"]",
",",
"List",
"[",
"str",
"]",
"]",
":",
"return",
"(",
"glob_all",
"(",
"join",
"(",
"folder",
",",
"'wake-word'",
")",
",",
"'*.wav'",
")",
",",
"gl... | Finds wake-word and not-wake-word wavs in folder | [
"Finds",
"wake",
"-",
"word",
"and",
"not",
"-",
"wake",
"-",
"word",
"wavs",
"in",
"folder"
] | e17cebdd171906dbd8a16e282d8a7966fba2eeba | https://github.com/MycroftAI/mycroft-precise/blob/e17cebdd171906dbd8a16e282d8a7966fba2eeba/precise/util.py#L98-L101 | train |
MycroftAI/mycroft-precise | precise/scripts/convert.py | convert | def convert(model_path: str, out_file: str):
"""
Converts an HD5F file from Keras to a .pb for use with TensorFlow
Args:
model_path: location of Keras model
out_file: location to write protobuf
"""
print('Converting', model_path, 'to', out_file, '...')
import tensorflow as tf
... | python | def convert(model_path: str, out_file: str):
"""
Converts an HD5F file from Keras to a .pb for use with TensorFlow
Args:
model_path: location of Keras model
out_file: location to write protobuf
"""
print('Converting', model_path, 'to', out_file, '...')
import tensorflow as tf
... | [
"def",
"convert",
"(",
"model_path",
":",
"str",
",",
"out_file",
":",
"str",
")",
":",
"print",
"(",
"'Converting'",
",",
"model_path",
",",
"'to'",
",",
"out_file",
",",
"'...'",
")",
"import",
"tensorflow",
"as",
"tf",
"from",
"precise",
".",
"model",... | Converts an HD5F file from Keras to a .pb for use with TensorFlow
Args:
model_path: location of Keras model
out_file: location to write protobuf | [
"Converts",
"an",
"HD5F",
"file",
"from",
"Keras",
"to",
"a",
".",
"pb",
"for",
"use",
"with",
"TensorFlow"
] | e17cebdd171906dbd8a16e282d8a7966fba2eeba | https://github.com/MycroftAI/mycroft-precise/blob/e17cebdd171906dbd8a16e282d8a7966fba2eeba/precise/scripts/convert.py#L32-L76 | train |
MycroftAI/mycroft-precise | precise/params.py | inject_params | def inject_params(model_name: str) -> ListenerParams:
"""Set the global listener params to a saved model"""
params_file = model_name + '.params'
try:
with open(params_file) as f:
pr.__dict__.update(compatibility_params, **json.load(f))
except (OSError, ValueError, TypeError):
... | python | def inject_params(model_name: str) -> ListenerParams:
"""Set the global listener params to a saved model"""
params_file = model_name + '.params'
try:
with open(params_file) as f:
pr.__dict__.update(compatibility_params, **json.load(f))
except (OSError, ValueError, TypeError):
... | [
"def",
"inject_params",
"(",
"model_name",
":",
"str",
")",
"->",
"ListenerParams",
":",
"params_file",
"=",
"model_name",
"+",
"'.params'",
"try",
":",
"with",
"open",
"(",
"params_file",
")",
"as",
"f",
":",
"pr",
".",
"__dict__",
".",
"update",
"(",
"... | Set the global listener params to a saved model | [
"Set",
"the",
"global",
"listener",
"params",
"to",
"a",
"saved",
"model"
] | e17cebdd171906dbd8a16e282d8a7966fba2eeba | https://github.com/MycroftAI/mycroft-precise/blob/e17cebdd171906dbd8a16e282d8a7966fba2eeba/precise/params.py#L96-L105 | train |
MycroftAI/mycroft-precise | precise/params.py | save_params | def save_params(model_name: str):
"""Save current global listener params to a file"""
with open(model_name + '.params', 'w') as f:
json.dump(pr.__dict__, f) | python | def save_params(model_name: str):
"""Save current global listener params to a file"""
with open(model_name + '.params', 'w') as f:
json.dump(pr.__dict__, f) | [
"def",
"save_params",
"(",
"model_name",
":",
"str",
")",
":",
"with",
"open",
"(",
"model_name",
"+",
"'.params'",
",",
"'w'",
")",
"as",
"f",
":",
"json",
".",
"dump",
"(",
"pr",
".",
"__dict__",
",",
"f",
")"
] | Save current global listener params to a file | [
"Save",
"current",
"global",
"listener",
"params",
"to",
"a",
"file"
] | e17cebdd171906dbd8a16e282d8a7966fba2eeba | https://github.com/MycroftAI/mycroft-precise/blob/e17cebdd171906dbd8a16e282d8a7966fba2eeba/precise/params.py#L108-L111 | train |
MycroftAI/mycroft-precise | precise/scripts/train_incremental.py | IncrementalTrainer.retrain | def retrain(self):
"""Train for a session, pulling in any new data from the filesystem"""
folder = TrainData.from_folder(self.args.folder)
train_data, test_data = folder.load(True, not self.args.no_validation)
train_data = TrainData.merge(train_data, self.sampled_data)
test_data... | python | def retrain(self):
"""Train for a session, pulling in any new data from the filesystem"""
folder = TrainData.from_folder(self.args.folder)
train_data, test_data = folder.load(True, not self.args.no_validation)
train_data = TrainData.merge(train_data, self.sampled_data)
test_data... | [
"def",
"retrain",
"(",
"self",
")",
":",
"folder",
"=",
"TrainData",
".",
"from_folder",
"(",
"self",
".",
"args",
".",
"folder",
")",
"train_data",
",",
"test_data",
"=",
"folder",
".",
"load",
"(",
"True",
",",
"not",
"self",
".",
"args",
".",
"no_... | Train for a session, pulling in any new data from the filesystem | [
"Train",
"for",
"a",
"session",
"pulling",
"in",
"any",
"new",
"data",
"from",
"the",
"filesystem"
] | e17cebdd171906dbd8a16e282d8a7966fba2eeba | https://github.com/MycroftAI/mycroft-precise/blob/e17cebdd171906dbd8a16e282d8a7966fba2eeba/precise/scripts/train_incremental.py#L95-L110 | train |
MycroftAI/mycroft-precise | precise/scripts/train_incremental.py | IncrementalTrainer.train_on_audio | def train_on_audio(self, fn: str):
"""Run through a single audio file"""
save_test = random() > 0.8
audio = load_audio(fn)
num_chunks = len(audio) // self.args.chunk_size
self.listener.clear()
for i, chunk in enumerate(chunk_audio(audio, self.args.chunk_size)):
... | python | def train_on_audio(self, fn: str):
"""Run through a single audio file"""
save_test = random() > 0.8
audio = load_audio(fn)
num_chunks = len(audio) // self.args.chunk_size
self.listener.clear()
for i, chunk in enumerate(chunk_audio(audio, self.args.chunk_size)):
... | [
"def",
"train_on_audio",
"(",
"self",
",",
"fn",
":",
"str",
")",
":",
"save_test",
"=",
"random",
"(",
")",
">",
"0.8",
"audio",
"=",
"load_audio",
"(",
"fn",
")",
"num_chunks",
"=",
"len",
"(",
"audio",
")",
"//",
"self",
".",
"args",
".",
"chunk... | Run through a single audio file | [
"Run",
"through",
"a",
"single",
"audio",
"file"
] | e17cebdd171906dbd8a16e282d8a7966fba2eeba | https://github.com/MycroftAI/mycroft-precise/blob/e17cebdd171906dbd8a16e282d8a7966fba2eeba/precise/scripts/train_incremental.py#L112-L136 | train |
MycroftAI/mycroft-precise | precise/scripts/train_incremental.py | IncrementalTrainer.run | def run(self):
"""
Begin reading through audio files, saving false
activations and retraining when necessary
"""
for fn in glob_all(self.args.random_data_folder, '*.wav'):
if fn in self.trained_fns:
print('Skipping ' + fn + '...')
conti... | python | def run(self):
"""
Begin reading through audio files, saving false
activations and retraining when necessary
"""
for fn in glob_all(self.args.random_data_folder, '*.wav'):
if fn in self.trained_fns:
print('Skipping ' + fn + '...')
conti... | [
"def",
"run",
"(",
"self",
")",
":",
"for",
"fn",
"in",
"glob_all",
"(",
"self",
".",
"args",
".",
"random_data_folder",
",",
"'*.wav'",
")",
":",
"if",
"fn",
"in",
"self",
".",
"trained_fns",
":",
"print",
"(",
"'Skipping '",
"+",
"fn",
"+",
"'...'"... | Begin reading through audio files, saving false
activations and retraining when necessary | [
"Begin",
"reading",
"through",
"audio",
"files",
"saving",
"false",
"activations",
"and",
"retraining",
"when",
"necessary"
] | e17cebdd171906dbd8a16e282d8a7966fba2eeba | https://github.com/MycroftAI/mycroft-precise/blob/e17cebdd171906dbd8a16e282d8a7966fba2eeba/precise/scripts/train_incremental.py#L138-L153 | train |
MycroftAI/mycroft-precise | precise/network_runner.py | TensorFlowRunner.predict | def predict(self, inputs: np.ndarray) -> np.ndarray:
"""Run on multiple inputs"""
return self.sess.run(self.out_var, {self.inp_var: inputs}) | python | def predict(self, inputs: np.ndarray) -> np.ndarray:
"""Run on multiple inputs"""
return self.sess.run(self.out_var, {self.inp_var: inputs}) | [
"def",
"predict",
"(",
"self",
",",
"inputs",
":",
"np",
".",
"ndarray",
")",
"->",
"np",
".",
"ndarray",
":",
"return",
"self",
".",
"sess",
".",
"run",
"(",
"self",
".",
"out_var",
",",
"{",
"self",
".",
"inp_var",
":",
"inputs",
"}",
")"
] | Run on multiple inputs | [
"Run",
"on",
"multiple",
"inputs"
] | e17cebdd171906dbd8a16e282d8a7966fba2eeba | https://github.com/MycroftAI/mycroft-precise/blob/e17cebdd171906dbd8a16e282d8a7966fba2eeba/precise/network_runner.py#L61-L63 | train |
ofek/bit | bit/network/rates.py | satoshi_to_currency | def satoshi_to_currency(num, currency):
"""Converts a given number of satoshi to another currency as a formatted
string rounded down to the proper number of decimal places.
:param num: The number of satoshi.
:type num: ``int``
:param currency: One of the :ref:`supported currencies`.
:type curre... | python | def satoshi_to_currency(num, currency):
"""Converts a given number of satoshi to another currency as a formatted
string rounded down to the proper number of decimal places.
:param num: The number of satoshi.
:type num: ``int``
:param currency: One of the :ref:`supported currencies`.
:type curre... | [
"def",
"satoshi_to_currency",
"(",
"num",
",",
"currency",
")",
":",
"return",
"'{:f}'",
".",
"format",
"(",
"Decimal",
"(",
"num",
"/",
"Decimal",
"(",
"EXCHANGE_RATES",
"[",
"currency",
"]",
"(",
")",
")",
")",
".",
"quantize",
"(",
"Decimal",
"(",
"... | Converts a given number of satoshi to another currency as a formatted
string rounded down to the proper number of decimal places.
:param num: The number of satoshi.
:type num: ``int``
:param currency: One of the :ref:`supported currencies`.
:type currency: ``str``
:rtype: ``str`` | [
"Converts",
"a",
"given",
"number",
"of",
"satoshi",
"to",
"another",
"currency",
"as",
"a",
"formatted",
"string",
"rounded",
"down",
"to",
"the",
"proper",
"number",
"of",
"decimal",
"places",
"."
] | 20fc0e7047946c1f28f868008d99d659905c1af6 | https://github.com/ofek/bit/blob/20fc0e7047946c1f28f868008d99d659905c1af6/bit/network/rates.py#L645-L662 | train |
ofek/bit | bit/network/services.py | NetworkAPI.get_balance | def get_balance(cls, address):
"""Gets the balance of an address in satoshi.
:param address: The address in question.
:type address: ``str``
:raises ConnectionError: If all API services fail.
:rtype: ``int``
"""
for api_call in cls.GET_BALANCE_MAIN:
... | python | def get_balance(cls, address):
"""Gets the balance of an address in satoshi.
:param address: The address in question.
:type address: ``str``
:raises ConnectionError: If all API services fail.
:rtype: ``int``
"""
for api_call in cls.GET_BALANCE_MAIN:
... | [
"def",
"get_balance",
"(",
"cls",
",",
"address",
")",
":",
"for",
"api_call",
"in",
"cls",
".",
"GET_BALANCE_MAIN",
":",
"try",
":",
"return",
"api_call",
"(",
"address",
")",
"except",
"cls",
".",
"IGNORED_ERRORS",
":",
"pass",
"raise",
"ConnectionError",
... | Gets the balance of an address in satoshi.
:param address: The address in question.
:type address: ``str``
:raises ConnectionError: If all API services fail.
:rtype: ``int`` | [
"Gets",
"the",
"balance",
"of",
"an",
"address",
"in",
"satoshi",
"."
] | 20fc0e7047946c1f28f868008d99d659905c1af6 | https://github.com/ofek/bit/blob/20fc0e7047946c1f28f868008d99d659905c1af6/bit/network/services.py#L343-L358 | train |
ofek/bit | bit/network/services.py | NetworkAPI.get_transactions | def get_transactions(cls, address):
"""Gets the ID of all transactions related to an address.
:param address: The address in question.
:type address: ``str``
:raises ConnectionError: If all API services fail.
:rtype: ``list`` of ``str``
"""
for api_call in cls.G... | python | def get_transactions(cls, address):
"""Gets the ID of all transactions related to an address.
:param address: The address in question.
:type address: ``str``
:raises ConnectionError: If all API services fail.
:rtype: ``list`` of ``str``
"""
for api_call in cls.G... | [
"def",
"get_transactions",
"(",
"cls",
",",
"address",
")",
":",
"for",
"api_call",
"in",
"cls",
".",
"GET_TRANSACTIONS_MAIN",
":",
"try",
":",
"return",
"api_call",
"(",
"address",
")",
"except",
"cls",
".",
"IGNORED_ERRORS",
":",
"pass",
"raise",
"Connecti... | Gets the ID of all transactions related to an address.
:param address: The address in question.
:type address: ``str``
:raises ConnectionError: If all API services fail.
:rtype: ``list`` of ``str`` | [
"Gets",
"the",
"ID",
"of",
"all",
"transactions",
"related",
"to",
"an",
"address",
"."
] | 20fc0e7047946c1f28f868008d99d659905c1af6 | https://github.com/ofek/bit/blob/20fc0e7047946c1f28f868008d99d659905c1af6/bit/network/services.py#L379-L394 | train |
ofek/bit | bit/network/services.py | NetworkAPI.get_unspent | def get_unspent(cls, address):
"""Gets all unspent transaction outputs belonging to an address.
:param address: The address in question.
:type address: ``str``
:raises ConnectionError: If all API services fail.
:rtype: ``list`` of :class:`~bit.network.meta.Unspent`
"""
... | python | def get_unspent(cls, address):
"""Gets all unspent transaction outputs belonging to an address.
:param address: The address in question.
:type address: ``str``
:raises ConnectionError: If all API services fail.
:rtype: ``list`` of :class:`~bit.network.meta.Unspent`
"""
... | [
"def",
"get_unspent",
"(",
"cls",
",",
"address",
")",
":",
"for",
"api_call",
"in",
"cls",
".",
"GET_UNSPENT_MAIN",
":",
"try",
":",
"return",
"api_call",
"(",
"address",
")",
"except",
"cls",
".",
"IGNORED_ERRORS",
":",
"pass",
"raise",
"ConnectionError",
... | Gets all unspent transaction outputs belonging to an address.
:param address: The address in question.
:type address: ``str``
:raises ConnectionError: If all API services fail.
:rtype: ``list`` of :class:`~bit.network.meta.Unspent` | [
"Gets",
"all",
"unspent",
"transaction",
"outputs",
"belonging",
"to",
"an",
"address",
"."
] | 20fc0e7047946c1f28f868008d99d659905c1af6 | https://github.com/ofek/bit/blob/20fc0e7047946c1f28f868008d99d659905c1af6/bit/network/services.py#L452-L467 | train |
ofek/bit | bit/network/services.py | NetworkAPI.broadcast_tx | def broadcast_tx(cls, tx_hex): # pragma: no cover
"""Broadcasts a transaction to the blockchain.
:param tx_hex: A signed transaction in hex form.
:type tx_hex: ``str``
:raises ConnectionError: If all API services fail.
"""
success = None
for api_call in cls.BRO... | python | def broadcast_tx(cls, tx_hex): # pragma: no cover
"""Broadcasts a transaction to the blockchain.
:param tx_hex: A signed transaction in hex form.
:type tx_hex: ``str``
:raises ConnectionError: If all API services fail.
"""
success = None
for api_call in cls.BRO... | [
"def",
"broadcast_tx",
"(",
"cls",
",",
"tx_hex",
")",
":",
"# pragma: no cover",
"success",
"=",
"None",
"for",
"api_call",
"in",
"cls",
".",
"BROADCAST_TX_MAIN",
":",
"try",
":",
"success",
"=",
"api_call",
"(",
"tx_hex",
")",
"if",
"not",
"success",
":"... | Broadcasts a transaction to the blockchain.
:param tx_hex: A signed transaction in hex form.
:type tx_hex: ``str``
:raises ConnectionError: If all API services fail. | [
"Broadcasts",
"a",
"transaction",
"to",
"the",
"blockchain",
"."
] | 20fc0e7047946c1f28f868008d99d659905c1af6 | https://github.com/ofek/bit/blob/20fc0e7047946c1f28f868008d99d659905c1af6/bit/network/services.py#L489-L511 | train |
ofek/bit | bit/transaction.py | calculate_preimages | def calculate_preimages(tx_obj, inputs_parameters):
"""Calculates preimages for provided transaction structure and input
values.
:param tx_obj: The transaction object used to calculate preimage from using
a transaction digest algorithm, such as BIP-143 for Segwit
input... | python | def calculate_preimages(tx_obj, inputs_parameters):
"""Calculates preimages for provided transaction structure and input
values.
:param tx_obj: The transaction object used to calculate preimage from using
a transaction digest algorithm, such as BIP-143 for Segwit
input... | [
"def",
"calculate_preimages",
"(",
"tx_obj",
",",
"inputs_parameters",
")",
":",
"# Tx object data:",
"input_count",
"=",
"int_to_varint",
"(",
"len",
"(",
"tx_obj",
".",
"TxIn",
")",
")",
"output_count",
"=",
"int_to_varint",
"(",
"len",
"(",
"tx_obj",
".",
"... | Calculates preimages for provided transaction structure and input
values.
:param tx_obj: The transaction object used to calculate preimage from using
a transaction digest algorithm, such as BIP-143 for Segwit
inputs. This transaction object must hence have scriptCodes
... | [
"Calculates",
"preimages",
"for",
"provided",
"transaction",
"structure",
"and",
"input",
"values",
"."
] | 20fc0e7047946c1f28f868008d99d659905c1af6 | https://github.com/ofek/bit/blob/20fc0e7047946c1f28f868008d99d659905c1af6/bit/transaction.py#L517-L582 | train |
ofek/bit | bit/wallet.py | BaseKey.verify | def verify(self, signature, data):
"""Verifies some data was signed by this private key.
:param signature: The signature to verify.
:type signature: ``bytes``
:param data: The data that was supposedly signed.
:type data: ``bytes``
:rtype: ``bool``
"""
ret... | python | def verify(self, signature, data):
"""Verifies some data was signed by this private key.
:param signature: The signature to verify.
:type signature: ``bytes``
:param data: The data that was supposedly signed.
:type data: ``bytes``
:rtype: ``bool``
"""
ret... | [
"def",
"verify",
"(",
"self",
",",
"signature",
",",
"data",
")",
":",
"return",
"self",
".",
"_pk",
".",
"public_key",
".",
"verify",
"(",
"signature",
",",
"data",
")"
] | Verifies some data was signed by this private key.
:param signature: The signature to verify.
:type signature: ``bytes``
:param data: The data that was supposedly signed.
:type data: ``bytes``
:rtype: ``bool`` | [
"Verifies",
"some",
"data",
"was",
"signed",
"by",
"this",
"private",
"key",
"."
] | 20fc0e7047946c1f28f868008d99d659905c1af6 | https://github.com/ofek/bit/blob/20fc0e7047946c1f28f868008d99d659905c1af6/bit/wallet.py#L89-L98 | train |
ofek/bit | bit/wallet.py | PrivateKey.get_transactions | def get_transactions(self):
"""Fetches transaction history.
:rtype: ``list`` of ``str`` transaction IDs
"""
self.transactions[:] = NetworkAPI.get_transactions(self.address)
if self.segwit_address:
self.transactions += NetworkAPI.get_transactions(self.segwit_address)
... | python | def get_transactions(self):
"""Fetches transaction history.
:rtype: ``list`` of ``str`` transaction IDs
"""
self.transactions[:] = NetworkAPI.get_transactions(self.address)
if self.segwit_address:
self.transactions += NetworkAPI.get_transactions(self.segwit_address)
... | [
"def",
"get_transactions",
"(",
"self",
")",
":",
"self",
".",
"transactions",
"[",
":",
"]",
"=",
"NetworkAPI",
".",
"get_transactions",
"(",
"self",
".",
"address",
")",
"if",
"self",
".",
"segwit_address",
":",
"self",
".",
"transactions",
"+=",
"Networ... | Fetches transaction history.
:rtype: ``list`` of ``str`` transaction IDs | [
"Fetches",
"transaction",
"history",
"."
] | 20fc0e7047946c1f28f868008d99d659905c1af6 | https://github.com/ofek/bit/blob/20fc0e7047946c1f28f868008d99d659905c1af6/bit/wallet.py#L246-L254 | train |
ofek/bit | bit/wallet.py | MultiSig.address | def address(self):
"""The public address you share with others to receive funds."""
if self._address is None:
self._address = multisig_to_address(self.public_keys, self.m,
version=self.version)
return self._address | python | def address(self):
"""The public address you share with others to receive funds."""
if self._address is None:
self._address = multisig_to_address(self.public_keys, self.m,
version=self.version)
return self._address | [
"def",
"address",
"(",
"self",
")",
":",
"if",
"self",
".",
"_address",
"is",
"None",
":",
"self",
".",
"_address",
"=",
"multisig_to_address",
"(",
"self",
".",
"public_keys",
",",
"self",
".",
"m",
",",
"version",
"=",
"self",
".",
"version",
")",
... | The public address you share with others to receive funds. | [
"The",
"public",
"address",
"you",
"share",
"with",
"others",
"to",
"receive",
"funds",
"."
] | 20fc0e7047946c1f28f868008d99d659905c1af6 | https://github.com/ofek/bit/blob/20fc0e7047946c1f28f868008d99d659905c1af6/bit/wallet.py#L925-L930 | train |
ofek/bit | bit/base32.py | bech32_polymod | def bech32_polymod(values):
"""Internal function that computes the Bech32 checksum."""
generator = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3]
chk = 1
for value in values:
top = chk >> 25
chk = (chk & 0x1ffffff) << 5 ^ value
for i in range(5):
chk ^= ... | python | def bech32_polymod(values):
"""Internal function that computes the Bech32 checksum."""
generator = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3]
chk = 1
for value in values:
top = chk >> 25
chk = (chk & 0x1ffffff) << 5 ^ value
for i in range(5):
chk ^= ... | [
"def",
"bech32_polymod",
"(",
"values",
")",
":",
"generator",
"=",
"[",
"0x3b6a57b2",
",",
"0x26508e6d",
",",
"0x1ea119fa",
",",
"0x3d4233dd",
",",
"0x2a1462b3",
"]",
"chk",
"=",
"1",
"for",
"value",
"in",
"values",
":",
"top",
"=",
"chk",
">>",
"25",
... | Internal function that computes the Bech32 checksum. | [
"Internal",
"function",
"that",
"computes",
"the",
"Bech32",
"checksum",
"."
] | 20fc0e7047946c1f28f868008d99d659905c1af6 | https://github.com/ofek/bit/blob/20fc0e7047946c1f28f868008d99d659905c1af6/bit/base32.py#L26-L35 | train |
ofek/bit | bit/base32.py | bech32_hrp_expand | def bech32_hrp_expand(hrp):
"""Expand the HRP into values for checksum computation."""
return [ord(x) >> 5 for x in hrp] + [0] + [ord(x) & 31 for x in hrp] | python | def bech32_hrp_expand(hrp):
"""Expand the HRP into values for checksum computation."""
return [ord(x) >> 5 for x in hrp] + [0] + [ord(x) & 31 for x in hrp] | [
"def",
"bech32_hrp_expand",
"(",
"hrp",
")",
":",
"return",
"[",
"ord",
"(",
"x",
")",
">>",
"5",
"for",
"x",
"in",
"hrp",
"]",
"+",
"[",
"0",
"]",
"+",
"[",
"ord",
"(",
"x",
")",
"&",
"31",
"for",
"x",
"in",
"hrp",
"]"
] | Expand the HRP into values for checksum computation. | [
"Expand",
"the",
"HRP",
"into",
"values",
"for",
"checksum",
"computation",
"."
] | 20fc0e7047946c1f28f868008d99d659905c1af6 | https://github.com/ofek/bit/blob/20fc0e7047946c1f28f868008d99d659905c1af6/bit/base32.py#L38-L40 | train |
ofek/bit | bit/base32.py | bech32_create_checksum | def bech32_create_checksum(hrp, data):
"""Compute the checksum values given HRP and data."""
values = bech32_hrp_expand(hrp) + data
polymod = bech32_polymod(values + [0, 0, 0, 0, 0, 0]) ^ 1
return [(polymod >> 5 * (5 - i)) & 31 for i in range(6)] | python | def bech32_create_checksum(hrp, data):
"""Compute the checksum values given HRP and data."""
values = bech32_hrp_expand(hrp) + data
polymod = bech32_polymod(values + [0, 0, 0, 0, 0, 0]) ^ 1
return [(polymod >> 5 * (5 - i)) & 31 for i in range(6)] | [
"def",
"bech32_create_checksum",
"(",
"hrp",
",",
"data",
")",
":",
"values",
"=",
"bech32_hrp_expand",
"(",
"hrp",
")",
"+",
"data",
"polymod",
"=",
"bech32_polymod",
"(",
"values",
"+",
"[",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
... | Compute the checksum values given HRP and data. | [
"Compute",
"the",
"checksum",
"values",
"given",
"HRP",
"and",
"data",
"."
] | 20fc0e7047946c1f28f868008d99d659905c1af6 | https://github.com/ofek/bit/blob/20fc0e7047946c1f28f868008d99d659905c1af6/bit/base32.py#L48-L52 | train |
ofek/bit | bit/base32.py | bech32_encode | def bech32_encode(hrp, data):
"""Compute a Bech32 string given HRP and data values."""
combined = data + bech32_create_checksum(hrp, data)
return hrp + '1' + ''.join([CHARSET[d] for d in combined]) | python | def bech32_encode(hrp, data):
"""Compute a Bech32 string given HRP and data values."""
combined = data + bech32_create_checksum(hrp, data)
return hrp + '1' + ''.join([CHARSET[d] for d in combined]) | [
"def",
"bech32_encode",
"(",
"hrp",
",",
"data",
")",
":",
"combined",
"=",
"data",
"+",
"bech32_create_checksum",
"(",
"hrp",
",",
"data",
")",
"return",
"hrp",
"+",
"'1'",
"+",
"''",
".",
"join",
"(",
"[",
"CHARSET",
"[",
"d",
"]",
"for",
"d",
"i... | Compute a Bech32 string given HRP and data values. | [
"Compute",
"a",
"Bech32",
"string",
"given",
"HRP",
"and",
"data",
"values",
"."
] | 20fc0e7047946c1f28f868008d99d659905c1af6 | https://github.com/ofek/bit/blob/20fc0e7047946c1f28f868008d99d659905c1af6/bit/base32.py#L55-L58 | train |
ofek/bit | bit/base32.py | convertbits | def convertbits(data, frombits, tobits, pad=True):
"""General power-of-2 base conversion."""
acc = 0
bits = 0
ret = []
maxv = (1 << tobits) - 1
max_acc = (1 << (frombits + tobits - 1)) - 1
for value in data:
if value < 0 or (value >> frombits):
return None
acc = (... | python | def convertbits(data, frombits, tobits, pad=True):
"""General power-of-2 base conversion."""
acc = 0
bits = 0
ret = []
maxv = (1 << tobits) - 1
max_acc = (1 << (frombits + tobits - 1)) - 1
for value in data:
if value < 0 or (value >> frombits):
return None
acc = (... | [
"def",
"convertbits",
"(",
"data",
",",
"frombits",
",",
"tobits",
",",
"pad",
"=",
"True",
")",
":",
"acc",
"=",
"0",
"bits",
"=",
"0",
"ret",
"=",
"[",
"]",
"maxv",
"=",
"(",
"1",
"<<",
"tobits",
")",
"-",
"1",
"max_acc",
"=",
"(",
"1",
"<<... | General power-of-2 base conversion. | [
"General",
"power",
"-",
"of",
"-",
"2",
"base",
"conversion",
"."
] | 20fc0e7047946c1f28f868008d99d659905c1af6 | https://github.com/ofek/bit/blob/20fc0e7047946c1f28f868008d99d659905c1af6/bit/base32.py#L79-L99 | train |
ofek/bit | bit/base32.py | decode | def decode(addr):
"""Decode a segwit address."""
hrpgot, data = bech32_decode(addr)
# if hrpgot != hrp:
if hrpgot not in BECH32_VERSION_SET:
return (None, None)
decoded = convertbits(data[1:], 5, 8, False)
if decoded is None or len(decoded) < 2 or len(decoded) > 40:
return (None,... | python | def decode(addr):
"""Decode a segwit address."""
hrpgot, data = bech32_decode(addr)
# if hrpgot != hrp:
if hrpgot not in BECH32_VERSION_SET:
return (None, None)
decoded = convertbits(data[1:], 5, 8, False)
if decoded is None or len(decoded) < 2 or len(decoded) > 40:
return (None,... | [
"def",
"decode",
"(",
"addr",
")",
":",
"hrpgot",
",",
"data",
"=",
"bech32_decode",
"(",
"addr",
")",
"# if hrpgot != hrp:",
"if",
"hrpgot",
"not",
"in",
"BECH32_VERSION_SET",
":",
"return",
"(",
"None",
",",
"None",
")",
"decoded",
"=",
"convertbits",
"(... | Decode a segwit address. | [
"Decode",
"a",
"segwit",
"address",
"."
] | 20fc0e7047946c1f28f868008d99d659905c1af6 | https://github.com/ofek/bit/blob/20fc0e7047946c1f28f868008d99d659905c1af6/bit/base32.py#L103-L116 | train |
nok/sklearn-porter | sklearn_porter/utils/Shell.py | Shell._run | def _run(method, cmd, cwd=None, shell=True, universal_newlines=True,
stderr=STDOUT):
"""Internal wrapper for `call` amd `check_output`"""
if not cmd:
error_msg = 'Passed empty text or list'
raise AttributeError(error_msg)
if isinstance(cmd, six.string_types):... | python | def _run(method, cmd, cwd=None, shell=True, universal_newlines=True,
stderr=STDOUT):
"""Internal wrapper for `call` amd `check_output`"""
if not cmd:
error_msg = 'Passed empty text or list'
raise AttributeError(error_msg)
if isinstance(cmd, six.string_types):... | [
"def",
"_run",
"(",
"method",
",",
"cmd",
",",
"cwd",
"=",
"None",
",",
"shell",
"=",
"True",
",",
"universal_newlines",
"=",
"True",
",",
"stderr",
"=",
"STDOUT",
")",
":",
"if",
"not",
"cmd",
":",
"error_msg",
"=",
"'Passed empty text or list'",
"raise... | Internal wrapper for `call` amd `check_output` | [
"Internal",
"wrapper",
"for",
"call",
"amd",
"check_output"
] | 04673f768310bde31f9747a68a5e070592441ef2 | https://github.com/nok/sklearn-porter/blob/04673f768310bde31f9747a68a5e070592441ef2/sklearn_porter/utils/Shell.py#L13-L31 | train |
nok/sklearn-porter | sklearn_porter/utils/Shell.py | Shell.call | def call(cmd, shell=True, cwd=None, universal_newlines=True, stderr=STDOUT):
"""Just execute a specific command."""
return Shell._run(call, cmd, shell=shell, cwd=cwd, stderr=stderr,
universal_newlines=universal_newlines) | python | def call(cmd, shell=True, cwd=None, universal_newlines=True, stderr=STDOUT):
"""Just execute a specific command."""
return Shell._run(call, cmd, shell=shell, cwd=cwd, stderr=stderr,
universal_newlines=universal_newlines) | [
"def",
"call",
"(",
"cmd",
",",
"shell",
"=",
"True",
",",
"cwd",
"=",
"None",
",",
"universal_newlines",
"=",
"True",
",",
"stderr",
"=",
"STDOUT",
")",
":",
"return",
"Shell",
".",
"_run",
"(",
"call",
",",
"cmd",
",",
"shell",
"=",
"shell",
",",... | Just execute a specific command. | [
"Just",
"execute",
"a",
"specific",
"command",
"."
] | 04673f768310bde31f9747a68a5e070592441ef2 | https://github.com/nok/sklearn-porter/blob/04673f768310bde31f9747a68a5e070592441ef2/sklearn_porter/utils/Shell.py#L34-L37 | train |
nok/sklearn-porter | sklearn_porter/utils/Logging.py | Logging.get_logger | def get_logger(name, level=0):
"""Setup a logging instance"""
level = 0 if not isinstance(level, int) else level
level = 0 if level < 0 else level
level = 4 if level > 4 else level
console = logging.StreamHandler()
level = [logging.NOTSET, logging.ERROR, logging.WARN, log... | python | def get_logger(name, level=0):
"""Setup a logging instance"""
level = 0 if not isinstance(level, int) else level
level = 0 if level < 0 else level
level = 4 if level > 4 else level
console = logging.StreamHandler()
level = [logging.NOTSET, logging.ERROR, logging.WARN, log... | [
"def",
"get_logger",
"(",
"name",
",",
"level",
"=",
"0",
")",
":",
"level",
"=",
"0",
"if",
"not",
"isinstance",
"(",
"level",
",",
"int",
")",
"else",
"level",
"level",
"=",
"0",
"if",
"level",
"<",
"0",
"else",
"level",
"level",
"=",
"4",
"if"... | Setup a logging instance | [
"Setup",
"a",
"logging",
"instance"
] | 04673f768310bde31f9747a68a5e070592441ef2 | https://github.com/nok/sklearn-porter/blob/04673f768310bde31f9747a68a5e070592441ef2/sklearn_porter/utils/Logging.py#L12-L24 | train |
nok/sklearn-porter | sklearn_porter/Template.py | Template.indent | def indent(self, text, n_indents=1, skipping=False):
"""
Indent text with single spaces.
Parameters
----------
:param text : string
The text which get a specific indentation.
:param n_indents : int, default: 1
The number of indentations.
:... | python | def indent(self, text, n_indents=1, skipping=False):
"""
Indent text with single spaces.
Parameters
----------
:param text : string
The text which get a specific indentation.
:param n_indents : int, default: 1
The number of indentations.
:... | [
"def",
"indent",
"(",
"self",
",",
"text",
",",
"n_indents",
"=",
"1",
",",
"skipping",
"=",
"False",
")",
":",
"lines",
"=",
"text",
".",
"splitlines",
"(",
")",
"space",
"=",
"self",
".",
"TEMPLATES",
".",
"get",
"(",
"self",
".",
"target_language"... | Indent text with single spaces.
Parameters
----------
:param text : string
The text which get a specific indentation.
:param n_indents : int, default: 1
The number of indentations.
:param skipping : boolean, default: False
Whether to skip the ... | [
"Indent",
"text",
"with",
"single",
"spaces",
"."
] | 04673f768310bde31f9747a68a5e070592441ef2 | https://github.com/nok/sklearn-porter/blob/04673f768310bde31f9747a68a5e070592441ef2/sklearn_porter/Template.py#L25-L61 | train |
nok/sklearn-porter | sklearn_porter/Template.py | Template.temp | def temp(self, name, templates=None, n_indents=None, skipping=False):
"""
Get specific template of chosen
programming language.
Parameters
----------
:param param name : string
The key name of the template.
:param param templates : string, default: No... | python | def temp(self, name, templates=None, n_indents=None, skipping=False):
"""
Get specific template of chosen
programming language.
Parameters
----------
:param param name : string
The key name of the template.
:param param templates : string, default: No... | [
"def",
"temp",
"(",
"self",
",",
"name",
",",
"templates",
"=",
"None",
",",
"n_indents",
"=",
"None",
",",
"skipping",
"=",
"False",
")",
":",
"if",
"templates",
"is",
"None",
":",
"templates",
"=",
"self",
".",
"TEMPLATES",
".",
"get",
"(",
"self",... | Get specific template of chosen
programming language.
Parameters
----------
:param param name : string
The key name of the template.
:param param templates : string, default: None
The template with placeholders.
:param param n_indents : int, defau... | [
"Get",
"specific",
"template",
"of",
"chosen",
"programming",
"language",
"."
] | 04673f768310bde31f9747a68a5e070592441ef2 | https://github.com/nok/sklearn-porter/blob/04673f768310bde31f9747a68a5e070592441ef2/sklearn_porter/Template.py#L63-L112 | train |
nok/sklearn-porter | sklearn_porter/utils/Environment.py | Environment.read_sklearn_version | def read_sklearn_version():
"""Determine the installed version of sklearn"""
from sklearn import __version__ as sklearn_ver
sklearn_ver = str(sklearn_ver).split('.')
sklearn_ver = [int(v) for v in sklearn_ver]
major, minor = sklearn_ver[0], sklearn_ver[1]
patch = sklearn_... | python | def read_sklearn_version():
"""Determine the installed version of sklearn"""
from sklearn import __version__ as sklearn_ver
sklearn_ver = str(sklearn_ver).split('.')
sklearn_ver = [int(v) for v in sklearn_ver]
major, minor = sklearn_ver[0], sklearn_ver[1]
patch = sklearn_... | [
"def",
"read_sklearn_version",
"(",
")",
":",
"from",
"sklearn",
"import",
"__version__",
"as",
"sklearn_ver",
"sklearn_ver",
"=",
"str",
"(",
"sklearn_ver",
")",
".",
"split",
"(",
"'.'",
")",
"sklearn_ver",
"=",
"[",
"int",
"(",
"v",
")",
"for",
"v",
"... | Determine the installed version of sklearn | [
"Determine",
"the",
"installed",
"version",
"of",
"sklearn"
] | 04673f768310bde31f9747a68a5e070592441ef2 | https://github.com/nok/sklearn-porter/blob/04673f768310bde31f9747a68a5e070592441ef2/sklearn_porter/utils/Environment.py#L60-L67 | train |
nok/sklearn-porter | sklearn_porter/utils/Environment.py | Environment._platform_is_windows | def _platform_is_windows(platform=sys.platform):
"""Is the current OS a Windows?"""
matched = platform in ('cygwin', 'win32', 'win64')
if matched:
error_msg = "Windows isn't supported yet"
raise OSError(error_msg)
return matched | python | def _platform_is_windows(platform=sys.platform):
"""Is the current OS a Windows?"""
matched = platform in ('cygwin', 'win32', 'win64')
if matched:
error_msg = "Windows isn't supported yet"
raise OSError(error_msg)
return matched | [
"def",
"_platform_is_windows",
"(",
"platform",
"=",
"sys",
".",
"platform",
")",
":",
"matched",
"=",
"platform",
"in",
"(",
"'cygwin'",
",",
"'win32'",
",",
"'win64'",
")",
"if",
"matched",
":",
"error_msg",
"=",
"\"Windows isn't supported yet\"",
"raise",
"... | Is the current OS a Windows? | [
"Is",
"the",
"current",
"OS",
"a",
"Windows?"
] | 04673f768310bde31f9747a68a5e070592441ef2 | https://github.com/nok/sklearn-porter/blob/04673f768310bde31f9747a68a5e070592441ef2/sklearn_porter/utils/Environment.py#L70-L76 | train |
nok/sklearn-porter | sklearn_porter/utils/Environment.py | Environment.check_deps | def check_deps(deps):
"""check whether specific requirements are available."""
if not isinstance(deps, list):
deps = [deps]
checks = list(Environment.has_apps(deps))
if not all(checks):
for name, available in list(dict(zip(deps, checks)).items()):
... | python | def check_deps(deps):
"""check whether specific requirements are available."""
if not isinstance(deps, list):
deps = [deps]
checks = list(Environment.has_apps(deps))
if not all(checks):
for name, available in list(dict(zip(deps, checks)).items()):
... | [
"def",
"check_deps",
"(",
"deps",
")",
":",
"if",
"not",
"isinstance",
"(",
"deps",
",",
"list",
")",
":",
"deps",
"=",
"[",
"deps",
"]",
"checks",
"=",
"list",
"(",
"Environment",
".",
"has_apps",
"(",
"deps",
")",
")",
"if",
"not",
"all",
"(",
... | check whether specific requirements are available. | [
"check",
"whether",
"specific",
"requirements",
"are",
"available",
"."
] | 04673f768310bde31f9747a68a5e070592441ef2 | https://github.com/nok/sklearn-porter/blob/04673f768310bde31f9747a68a5e070592441ef2/sklearn_porter/utils/Environment.py#L94-L104 | train |
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... | python | 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... | [
"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 | train |
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):
"""
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) | [
"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 | train |
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):... | python | 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):... | [
"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 | train |
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,
... | python | 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,
... | [
"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 | train |
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[... | python | 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[... | [
"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 | train |
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)
... | python | 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)
... | [
"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, defaul... | [
"Predict",
"using",
"the",
"transpiled",
"model",
"."
] | 04673f768310bde31f9747a68a5e070592441ef2 | https://github.com/nok/sklearn-porter/blob/04673f768310bde31f9747a68a5e070592441ef2/sklearn_porter/Porter.py#L295-L388 | train |
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... | python | 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... | [
"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
... | [
"Compute",
"the",
"accuracy",
"of",
"the",
"ported",
"classifier",
"."
] | 04673f768310bde31f9747a68a5e070592441ef2 | https://github.com/nok/sklearn-porter/blob/04673f768310bde31f9747a68a5e070592441ef2/sklearn_porter/Porter.py#L390-L434 | train |
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.
R... | python | 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.
R... | [
"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
... | [
"Generate",
"the",
"specific",
"filename",
"."
] | 04673f768310bde31f9747a68a5e070592441ef2 | https://github.com/nok/sklearn-porter/blob/04673f768310bde31f9747a68a5e070592441ef2/sklearn_porter/Porter.py#L456-L488 | train |
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 la... | python | 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 la... | [
"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 targe... | [
"Generate",
"the",
"related",
"compilation",
"and",
"execution",
"commands",
"."
] | 04673f768310bde31f9747a68a5e070592441ef2 | https://github.com/nok/sklearn-porter/blob/04673f768310bde31f9747a68a5e070592441ef2/sklearn_porter/Porter.py#L491-L544 | train |
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_co... | python | 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_co... | [
"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 | train |
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 i... | python | 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 i... | [
"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 | train |
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 appl... | python | 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 appl... | [
"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 | train |
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 p... | python | 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 p... | [
"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 formattin... | [
"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 | train |
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:
... | python | 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:
... | [
"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 | train |
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 ... | python | 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 ... | [
"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 | train |
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 = ... | python | 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 = ... | [
"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 | train |
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 sig... | python | 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 sig... | [
"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 | train |
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
de... | python | 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
de... | [
"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 | train |
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.
... | python | 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.
... | [
"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 | train |
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 ... | python | 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 ... | [
"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 IS... | [
"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 | train |
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
... | python | 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
... | [
"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 f... | [
"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 | train |
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. Th... | python | 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. Th... | [
"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
Arg... | [
"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 | train |
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_NORMALIZATIO... | python | 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_NORMALIZATIO... | [
"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 | train |
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 Pho... | python | 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 Pho... | [
"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 l... | [
"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 | train |
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... | python | 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... | [
"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 | train |
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 = ot... | python | 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 = ot... | [
"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 | train |
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)
... | python | 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)
... | [
"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 | train |
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,
... | python | 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,
... | [
"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 | train |
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 numob... | python | 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 numob... | [
"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 | train |
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]
... | python | 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]
... | [
"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 | train |
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):
"""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 | [
"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 | train |
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 No... | python | 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 No... | [
"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 | train |
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 op... | python | 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 op... | [
"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 | train |
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)
... | python | 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)
... | [
"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 | train |
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... | python | 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... | [
"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 | train |
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_pre... | python | 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_pre... | [
"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 | train |
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 ... | python | 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 ... | [
"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 | train |
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_formatti... | python | 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_formatti... | [
"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 | train |
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 ... | python | 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 ... | [
"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 ... | [
"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 | train |
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 ... | python | 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 ... | [
"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-numbe... | [
"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 | train |
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 ... | python | 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 ... | [
"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... | [
"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 | train |
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... | python | 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... | [
"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 f... | [
"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 | train |
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 --... | python | 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 --... | [
"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 c... | [
"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 | train |
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... | python | 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... | [
"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 | train |
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):
... | python | 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):
... | [
"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 | train |
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 ... | python | 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 ... | [
"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 | train |
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 th... | python | 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 th... | [
"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 | train |
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... | python | 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... | [
"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 supp... | [
"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 | train |
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 n... | python | 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 n... | [
"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 n... | [
"Formats",
"a",
"phone",
"number",
"using",
"client",
"-",
"defined",
"formatting",
"rules",
"."
] | 9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20 | https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L995-L1055 | train |
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 a... | python | 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 a... | [
"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 carri... | [
"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 | train |
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_co... | python | 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_co... | [
"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_car... | [
"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 | train |
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... | python | 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... | [
"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:
numob... | [
"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 | train |
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 in... | python | 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 in... | [
"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 forma... | [
"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 | train |
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(nationa... | python | 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(nationa... | [
"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 | train |
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 ne... | python | 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 ne... | [
"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 numb... | [
"Gets",
"the",
"national",
"significant",
"number",
"of",
"a",
"phone",
"number",
"."
] | 9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20 | https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L1571-L1594 | train |
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 == PhoneNumberFo... | python | 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 == PhoneNumberFo... | [
"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 | train |
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 he... | python | 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 he... | [
"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 | train |
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
cou... | python | 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
cou... | [
"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... | [
"Gets",
"an",
"invalid",
"number",
"for",
"the",
"specified",
"region",
"."
] | 9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20 | https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L1709-L1769 | train |
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.
... | python | 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.
... | [
"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.
Ret... | [
"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 | train |
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. R... | python | 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. R... | [
"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,... | [
"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 | train |
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 + ... | python | 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 + ... | [
"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 | train |
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 == PhoneN... | python | 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 == PhoneN... | [
"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 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.