repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
neptune-ml/steppy | steppy/base.py | Step.persist_upstream_diagram | def persist_upstream_diagram(self, filepath):
"""Creates upstream steps diagram and persists it to disk as png file.
Pydot graph is created and persisted to disk as png file under the filepath directory.
Args:
filepath (str): filepath to which the png with steps visualization shoul... | python | def persist_upstream_diagram(self, filepath):
"""Creates upstream steps diagram and persists it to disk as png file.
Pydot graph is created and persisted to disk as png file under the filepath directory.
Args:
filepath (str): filepath to which the png with steps visualization shoul... | [
"def",
"persist_upstream_diagram",
"(",
"self",
",",
"filepath",
")",
":",
"assert",
"isinstance",
"(",
"filepath",
",",
"str",
")",
",",
"'Step {} error, filepath must be str. Got {} instead'",
".",
"format",
"(",
"self",
".",
"name",
",",
"type",
"(",
"filepath"... | Creates upstream steps diagram and persists it to disk as png file.
Pydot graph is created and persisted to disk as png file under the filepath directory.
Args:
filepath (str): filepath to which the png with steps visualization should
be persisted | [
"Creates",
"upstream",
"steps",
"diagram",
"and",
"persists",
"it",
"to",
"disk",
"as",
"png",
"file",
"."
] | train | https://github.com/neptune-ml/steppy/blob/856b95f1f5189e1d2ca122b891bc670adac9692b/steppy/base.py#L513-L524 |
neptune-ml/steppy | steppy/base.py | BaseTransformer.fit_transform | def fit_transform(self, *args, **kwargs):
"""Performs fit followed by transform.
This method simply combines fit and transform.
Args:
args: positional arguments (can be anything)
kwargs: keyword arguments (can be anything)
Returns:
dict: output
... | python | def fit_transform(self, *args, **kwargs):
"""Performs fit followed by transform.
This method simply combines fit and transform.
Args:
args: positional arguments (can be anything)
kwargs: keyword arguments (can be anything)
Returns:
dict: output
... | [
"def",
"fit_transform",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"fit",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"self",
".",
"transform",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Performs fit followed by transform.
This method simply combines fit and transform.
Args:
args: positional arguments (can be anything)
kwargs: keyword arguments (can be anything)
Returns:
dict: output | [
"Performs",
"fit",
"followed",
"by",
"transform",
"."
] | train | https://github.com/neptune-ml/steppy/blob/856b95f1f5189e1d2ca122b891bc670adac9692b/steppy/base.py#L773-L786 |
dveselov/python-yandex-translate | yandex_translate/__init__.py | YandexTranslate.url | def url(self, endpoint):
"""
Returns full URL for specified API endpoint
>>> translate = YandexTranslate("trnsl.1.1.20130421T140201Z.323e508a33e9d84b.f1e0d9ca9bcd0a00b0ef71d82e6cf4158183d09e")
>>> translate.url("langs")
'https://translate.yandex.net/api/v1.5/tr.json/getLangs'
>>> translate.url("... | python | def url(self, endpoint):
"""
Returns full URL for specified API endpoint
>>> translate = YandexTranslate("trnsl.1.1.20130421T140201Z.323e508a33e9d84b.f1e0d9ca9bcd0a00b0ef71d82e6cf4158183d09e")
>>> translate.url("langs")
'https://translate.yandex.net/api/v1.5/tr.json/getLangs'
>>> translate.url("... | [
"def",
"url",
"(",
"self",
",",
"endpoint",
")",
":",
"return",
"self",
".",
"api_url",
".",
"format",
"(",
"version",
"=",
"self",
".",
"api_version",
",",
"endpoint",
"=",
"self",
".",
"api_endpoints",
"[",
"endpoint",
"]",
")"
] | Returns full URL for specified API endpoint
>>> translate = YandexTranslate("trnsl.1.1.20130421T140201Z.323e508a33e9d84b.f1e0d9ca9bcd0a00b0ef71d82e6cf4158183d09e")
>>> translate.url("langs")
'https://translate.yandex.net/api/v1.5/tr.json/getLangs'
>>> translate.url("detect")
'https://translate.yande... | [
"Returns",
"full",
"URL",
"for",
"specified",
"API",
"endpoint",
">>>",
"translate",
"=",
"YandexTranslate",
"(",
"trnsl",
".",
"1",
".",
"1",
".",
"20130421T140201Z",
".",
"323e508a33e9d84b",
".",
"f1e0d9ca9bcd0a00b0ef71d82e6cf4158183d09e",
")",
">>>",
"translate",... | train | https://github.com/dveselov/python-yandex-translate/blob/f26e624f683f10b4e7bf630b40d97241d82d5b01/yandex_translate/__init__.py#L47-L59 |
dveselov/python-yandex-translate | yandex_translate/__init__.py | YandexTranslate.directions | def directions(self, proxies=None):
"""
Returns list with translate directions
>>> translate = YandexTranslate("trnsl.1.1.20130421T140201Z.323e508a33e9d84b.f1e0d9ca9bcd0a00b0ef71d82e6cf4158183d09e")
>>> directions = translate.directions
>>> len(directions) > 0
True
"""
try:
respons... | python | def directions(self, proxies=None):
"""
Returns list with translate directions
>>> translate = YandexTranslate("trnsl.1.1.20130421T140201Z.323e508a33e9d84b.f1e0d9ca9bcd0a00b0ef71d82e6cf4158183d09e")
>>> directions = translate.directions
>>> len(directions) > 0
True
"""
try:
respons... | [
"def",
"directions",
"(",
"self",
",",
"proxies",
"=",
"None",
")",
":",
"try",
":",
"response",
"=",
"requests",
".",
"get",
"(",
"self",
".",
"url",
"(",
"\"langs\"",
")",
",",
"params",
"=",
"{",
"\"key\"",
":",
"self",
".",
"api_key",
"}",
",",... | Returns list with translate directions
>>> translate = YandexTranslate("trnsl.1.1.20130421T140201Z.323e508a33e9d84b.f1e0d9ca9bcd0a00b0ef71d82e6cf4158183d09e")
>>> directions = translate.directions
>>> len(directions) > 0
True | [
"Returns",
"list",
"with",
"translate",
"directions",
">>>",
"translate",
"=",
"YandexTranslate",
"(",
"trnsl",
".",
"1",
".",
"1",
".",
"20130421T140201Z",
".",
"323e508a33e9d84b",
".",
"f1e0d9ca9bcd0a00b0ef71d82e6cf4158183d09e",
")",
">>>",
"directions",
"=",
"tra... | train | https://github.com/dveselov/python-yandex-translate/blob/f26e624f683f10b4e7bf630b40d97241d82d5b01/yandex_translate/__init__.py#L62-L79 |
dveselov/python-yandex-translate | yandex_translate/__init__.py | YandexTranslate.detect | def detect(self, text, proxies=None, format="plain"):
"""
Specifies language of text
>>> translate = YandexTranslate("trnsl.1.1.20130421T140201Z.323e508a33e9d84b.f1e0d9ca9bcd0a00b0ef71d82e6cf4158183d09e")
>>> result = translate.detect(text="Hello world!")
>>> result == "en"
True
"""
data... | python | def detect(self, text, proxies=None, format="plain"):
"""
Specifies language of text
>>> translate = YandexTranslate("trnsl.1.1.20130421T140201Z.323e508a33e9d84b.f1e0d9ca9bcd0a00b0ef71d82e6cf4158183d09e")
>>> result = translate.detect(text="Hello world!")
>>> result == "en"
True
"""
data... | [
"def",
"detect",
"(",
"self",
",",
"text",
",",
"proxies",
"=",
"None",
",",
"format",
"=",
"\"plain\"",
")",
":",
"data",
"=",
"{",
"\"text\"",
":",
"text",
",",
"\"format\"",
":",
"format",
",",
"\"key\"",
":",
"self",
".",
"api_key",
",",
"}",
"... | Specifies language of text
>>> translate = YandexTranslate("trnsl.1.1.20130421T140201Z.323e508a33e9d84b.f1e0d9ca9bcd0a00b0ef71d82e6cf4158183d09e")
>>> result = translate.detect(text="Hello world!")
>>> result == "en"
True | [
"Specifies",
"language",
"of",
"text",
">>>",
"translate",
"=",
"YandexTranslate",
"(",
"trnsl",
".",
"1",
".",
"1",
".",
"20130421T140201Z",
".",
"323e508a33e9d84b",
".",
"f1e0d9ca9bcd0a00b0ef71d82e6cf4158183d09e",
")",
">>>",
"result",
"=",
"translate",
".",
"de... | train | https://github.com/dveselov/python-yandex-translate/blob/f26e624f683f10b4e7bf630b40d97241d82d5b01/yandex_translate/__init__.py#L92-L119 |
dveselov/python-yandex-translate | yandex_translate/__init__.py | YandexTranslate.translate | def translate(self, text, lang, proxies=None, format="plain"):
"""
Translates text to passed language
>>> translate = YandexTranslate("trnsl.1.1.20130421T140201Z.323e508a33e9d84b.f1e0d9ca9bcd0a00b0ef71d82e6cf4158183d09e")
>>> result = translate.translate(lang="ru", text="Hello, world!")
>>> result["... | python | def translate(self, text, lang, proxies=None, format="plain"):
"""
Translates text to passed language
>>> translate = YandexTranslate("trnsl.1.1.20130421T140201Z.323e508a33e9d84b.f1e0d9ca9bcd0a00b0ef71d82e6cf4158183d09e")
>>> result = translate.translate(lang="ru", text="Hello, world!")
>>> result["... | [
"def",
"translate",
"(",
"self",
",",
"text",
",",
"lang",
",",
"proxies",
"=",
"None",
",",
"format",
"=",
"\"plain\"",
")",
":",
"data",
"=",
"{",
"\"text\"",
":",
"text",
",",
"\"format\"",
":",
"format",
",",
"\"lang\"",
":",
"lang",
",",
"\"key\... | Translates text to passed language
>>> translate = YandexTranslate("trnsl.1.1.20130421T140201Z.323e508a33e9d84b.f1e0d9ca9bcd0a00b0ef71d82e6cf4158183d09e")
>>> result = translate.translate(lang="ru", text="Hello, world!")
>>> result["code"] == 200
True
>>> result["lang"] == "en-ru"
True | [
"Translates",
"text",
"to",
"passed",
"language",
">>>",
"translate",
"=",
"YandexTranslate",
"(",
"trnsl",
".",
"1",
".",
"1",
".",
"20130421T140201Z",
".",
"323e508a33e9d84b",
".",
"f1e0d9ca9bcd0a00b0ef71d82e6cf4158183d09e",
")",
">>>",
"result",
"=",
"translate",... | train | https://github.com/dveselov/python-yandex-translate/blob/f26e624f683f10b4e7bf630b40d97241d82d5b01/yandex_translate/__init__.py#L121-L146 |
lepture/otpauth | otpauth.py | generate_hotp | def generate_hotp(secret, counter=4):
"""Generate a HOTP code.
:param secret: A secret token for the authentication.
:param counter: HOTP is a counter based algorithm.
"""
# https://tools.ietf.org/html/rfc4226
msg = struct.pack('>Q', counter)
digest = hmac.new(to_bytes(secret), msg, hashlib... | python | def generate_hotp(secret, counter=4):
"""Generate a HOTP code.
:param secret: A secret token for the authentication.
:param counter: HOTP is a counter based algorithm.
"""
# https://tools.ietf.org/html/rfc4226
msg = struct.pack('>Q', counter)
digest = hmac.new(to_bytes(secret), msg, hashlib... | [
"def",
"generate_hotp",
"(",
"secret",
",",
"counter",
"=",
"4",
")",
":",
"# https://tools.ietf.org/html/rfc4226",
"msg",
"=",
"struct",
".",
"pack",
"(",
"'>Q'",
",",
"counter",
")",
"digest",
"=",
"hmac",
".",
"new",
"(",
"to_bytes",
"(",
"secret",
")",... | Generate a HOTP code.
:param secret: A secret token for the authentication.
:param counter: HOTP is a counter based algorithm. | [
"Generate",
"a",
"HOTP",
"code",
"."
] | train | https://github.com/lepture/otpauth/blob/49914d83d36dbcd33c9e26f65002b21ce09a6303/otpauth.py#L143-L160 |
lepture/otpauth | otpauth.py | generate_totp | def generate_totp(secret, period=30, timestamp=None):
"""Generate a TOTP code.
A TOTP code is an extension of HOTP algorithm.
:param secret: A secret token for the authentication.
:param period: A period that a TOTP code is valid in seconds
:param timestamp: Current time stamp.
"""
if time... | python | def generate_totp(secret, period=30, timestamp=None):
"""Generate a TOTP code.
A TOTP code is an extension of HOTP algorithm.
:param secret: A secret token for the authentication.
:param period: A period that a TOTP code is valid in seconds
:param timestamp: Current time stamp.
"""
if time... | [
"def",
"generate_totp",
"(",
"secret",
",",
"period",
"=",
"30",
",",
"timestamp",
"=",
"None",
")",
":",
"if",
"timestamp",
"is",
"None",
":",
"timestamp",
"=",
"time",
".",
"time",
"(",
")",
"counter",
"=",
"int",
"(",
"timestamp",
")",
"//",
"peri... | Generate a TOTP code.
A TOTP code is an extension of HOTP algorithm.
:param secret: A secret token for the authentication.
:param period: A period that a TOTP code is valid in seconds
:param timestamp: Current time stamp. | [
"Generate",
"a",
"TOTP",
"code",
"."
] | train | https://github.com/lepture/otpauth/blob/49914d83d36dbcd33c9e26f65002b21ce09a6303/otpauth.py#L163-L175 |
lepture/otpauth | otpauth.py | OtpAuth.valid_hotp | def valid_hotp(self, code, last=0, trials=100):
"""Valid a HOTP code.
:param code: A number that is less than 6 characters.
:param last: Guess HOTP code from last + 1 range.
:param trials: Guest HOTP code end at last + trials + 1.
"""
if not valid_code(code):
... | python | def valid_hotp(self, code, last=0, trials=100):
"""Valid a HOTP code.
:param code: A number that is less than 6 characters.
:param last: Guess HOTP code from last + 1 range.
:param trials: Guest HOTP code end at last + trials + 1.
"""
if not valid_code(code):
... | [
"def",
"valid_hotp",
"(",
"self",
",",
"code",
",",
"last",
"=",
"0",
",",
"trials",
"=",
"100",
")",
":",
"if",
"not",
"valid_code",
"(",
"code",
")",
":",
"return",
"False",
"code",
"=",
"bytes",
"(",
"int",
"(",
"code",
")",
")",
"for",
"i",
... | Valid a HOTP code.
:param code: A number that is less than 6 characters.
:param last: Guess HOTP code from last + 1 range.
:param trials: Guest HOTP code end at last + trials + 1. | [
"Valid",
"a",
"HOTP",
"code",
"."
] | train | https://github.com/lepture/otpauth/blob/49914d83d36dbcd33c9e26f65002b21ce09a6303/otpauth.py#L67-L81 |
lepture/otpauth | otpauth.py | OtpAuth.valid_totp | def valid_totp(self, code, period=30, timestamp=None):
"""Valid a TOTP code.
:param code: A number that is less than 6 characters.
:param period: A period that a TOTP code is valid in seconds
:param timestamp: Validate TOTP at this given timestamp
"""
if not valid_code(c... | python | def valid_totp(self, code, period=30, timestamp=None):
"""Valid a TOTP code.
:param code: A number that is less than 6 characters.
:param period: A period that a TOTP code is valid in seconds
:param timestamp: Validate TOTP at this given timestamp
"""
if not valid_code(c... | [
"def",
"valid_totp",
"(",
"self",
",",
"code",
",",
"period",
"=",
"30",
",",
"timestamp",
"=",
"None",
")",
":",
"if",
"not",
"valid_code",
"(",
"code",
")",
":",
"return",
"False",
"return",
"compare_digest",
"(",
"bytes",
"(",
"self",
".",
"totp",
... | Valid a TOTP code.
:param code: A number that is less than 6 characters.
:param period: A period that a TOTP code is valid in seconds
:param timestamp: Validate TOTP at this given timestamp | [
"Valid",
"a",
"TOTP",
"code",
"."
] | train | https://github.com/lepture/otpauth/blob/49914d83d36dbcd33c9e26f65002b21ce09a6303/otpauth.py#L83-L95 |
lepture/otpauth | otpauth.py | OtpAuth.to_uri | def to_uri(self, type, label, issuer, counter=None):
"""Generate the otpauth protocal string.
:param type: Algorithm type, hotp or totp.
:param label: Label of the identifier.
:param issuer: The company, the organization or something else.
:param counter: Counter of the HOTP alg... | python | def to_uri(self, type, label, issuer, counter=None):
"""Generate the otpauth protocal string.
:param type: Algorithm type, hotp or totp.
:param label: Label of the identifier.
:param issuer: The company, the organization or something else.
:param counter: Counter of the HOTP alg... | [
"def",
"to_uri",
"(",
"self",
",",
"type",
",",
"label",
",",
"issuer",
",",
"counter",
"=",
"None",
")",
":",
"type",
"=",
"type",
".",
"lower",
"(",
")",
"if",
"type",
"not",
"in",
"(",
"'hotp'",
",",
"'totp'",
")",
":",
"raise",
"ValueError",
... | Generate the otpauth protocal string.
:param type: Algorithm type, hotp or totp.
:param label: Label of the identifier.
:param issuer: The company, the organization or something else.
:param counter: Counter of the HOTP algorithm. | [
"Generate",
"the",
"otpauth",
"protocal",
"string",
"."
] | train | https://github.com/lepture/otpauth/blob/49914d83d36dbcd33c9e26f65002b21ce09a6303/otpauth.py#L105-L131 |
lepture/otpauth | otpauth.py | OtpAuth.to_google | def to_google(self, type, label, issuer, counter=None):
"""Generate the otpauth protocal string for Google Authenticator.
.. deprecated:: 0.2.0
Use :func:`to_uri` instead.
"""
warnings.warn('deprecated, use to_uri instead', DeprecationWarning)
return self.to_uri(type,... | python | def to_google(self, type, label, issuer, counter=None):
"""Generate the otpauth protocal string for Google Authenticator.
.. deprecated:: 0.2.0
Use :func:`to_uri` instead.
"""
warnings.warn('deprecated, use to_uri instead', DeprecationWarning)
return self.to_uri(type,... | [
"def",
"to_google",
"(",
"self",
",",
"type",
",",
"label",
",",
"issuer",
",",
"counter",
"=",
"None",
")",
":",
"warnings",
".",
"warn",
"(",
"'deprecated, use to_uri instead'",
",",
"DeprecationWarning",
")",
"return",
"self",
".",
"to_uri",
"(",
"type",
... | Generate the otpauth protocal string for Google Authenticator.
.. deprecated:: 0.2.0
Use :func:`to_uri` instead. | [
"Generate",
"the",
"otpauth",
"protocal",
"string",
"for",
"Google",
"Authenticator",
"."
] | train | https://github.com/lepture/otpauth/blob/49914d83d36dbcd33c9e26f65002b21ce09a6303/otpauth.py#L133-L140 |
nap/jaro-winkler-distance | pyjarowinkler/distance.py | get_jaro_distance | def get_jaro_distance(first, second, winkler=True, winkler_ajustment=True, scaling=0.1):
"""
:param first: word to calculate distance for
:param second: word to calculate distance with
:param winkler: same as winkler_ajustment
:param winkler_ajustment: add an adjustment factor to the Jaro of the dis... | python | def get_jaro_distance(first, second, winkler=True, winkler_ajustment=True, scaling=0.1):
"""
:param first: word to calculate distance for
:param second: word to calculate distance with
:param winkler: same as winkler_ajustment
:param winkler_ajustment: add an adjustment factor to the Jaro of the dis... | [
"def",
"get_jaro_distance",
"(",
"first",
",",
"second",
",",
"winkler",
"=",
"True",
",",
"winkler_ajustment",
"=",
"True",
",",
"scaling",
"=",
"0.1",
")",
":",
"if",
"not",
"first",
"or",
"not",
"second",
":",
"raise",
"JaroDistanceException",
"(",
"\"C... | :param first: word to calculate distance for
:param second: word to calculate distance with
:param winkler: same as winkler_ajustment
:param winkler_ajustment: add an adjustment factor to the Jaro of the distance
:param scaling: scaling factor for the Winkler adjustment
:return: Jaro distance adjust... | [
":",
"param",
"first",
":",
"word",
"to",
"calculate",
"distance",
"for",
":",
"param",
"second",
":",
"word",
"to",
"calculate",
"distance",
"with",
":",
"param",
"winkler",
":",
"same",
"as",
"winkler_ajustment",
":",
"param",
"winkler_ajustment",
":",
"ad... | train | https://github.com/nap/jaro-winkler-distance/blob/835bede1913232a8255c9e18533c430989c55bde/pyjarowinkler/distance.py#L18-L38 |
carlospalol/money | money/exchange.py | ExchangeRates.install | def install(self, backend='money.exchange.SimpleBackend'):
"""Install an exchange rates backend using a python path string"""
# RADAR: Python2
if isinstance(backend, money.six.string_types):
path, name = backend.rsplit('.', 1)
module = importlib.import_module(path)
... | python | def install(self, backend='money.exchange.SimpleBackend'):
"""Install an exchange rates backend using a python path string"""
# RADAR: Python2
if isinstance(backend, money.six.string_types):
path, name = backend.rsplit('.', 1)
module = importlib.import_module(path)
... | [
"def",
"install",
"(",
"self",
",",
"backend",
"=",
"'money.exchange.SimpleBackend'",
")",
":",
"# RADAR: Python2",
"if",
"isinstance",
"(",
"backend",
",",
"money",
".",
"six",
".",
"string_types",
")",
":",
"path",
",",
"name",
"=",
"backend",
".",
"rsplit... | Install an exchange rates backend using a python path string | [
"Install",
"an",
"exchange",
"rates",
"backend",
"using",
"a",
"python",
"path",
"string"
] | train | https://github.com/carlospalol/money/blob/1e51f651f93edd62c16eb3d7aa034fec03096046/money/exchange.py#L81-L93 |
carlospalol/money | money/exchange.py | ExchangeRates.rate | def rate(self, currency):
"""Return quotation between the base and another currency"""
if not self._backend:
raise ExchangeBackendNotInstalled()
return self._backend.rate(currency) | python | def rate(self, currency):
"""Return quotation between the base and another currency"""
if not self._backend:
raise ExchangeBackendNotInstalled()
return self._backend.rate(currency) | [
"def",
"rate",
"(",
"self",
",",
"currency",
")",
":",
"if",
"not",
"self",
".",
"_backend",
":",
"raise",
"ExchangeBackendNotInstalled",
"(",
")",
"return",
"self",
".",
"_backend",
".",
"rate",
"(",
"currency",
")"
] | Return quotation between the base and another currency | [
"Return",
"quotation",
"between",
"the",
"base",
"and",
"another",
"currency"
] | train | https://github.com/carlospalol/money/blob/1e51f651f93edd62c16eb3d7aa034fec03096046/money/exchange.py#L113-L117 |
carlospalol/money | money/exchange.py | ExchangeRates.quotation | def quotation(self, origin, target):
"""Return quotation between two currencies (origin, target)"""
if not self._backend:
raise ExchangeBackendNotInstalled()
return self._backend.quotation(origin, target) | python | def quotation(self, origin, target):
"""Return quotation between two currencies (origin, target)"""
if not self._backend:
raise ExchangeBackendNotInstalled()
return self._backend.quotation(origin, target) | [
"def",
"quotation",
"(",
"self",
",",
"origin",
",",
"target",
")",
":",
"if",
"not",
"self",
".",
"_backend",
":",
"raise",
"ExchangeBackendNotInstalled",
"(",
")",
"return",
"self",
".",
"_backend",
".",
"quotation",
"(",
"origin",
",",
"target",
")"
] | Return quotation between two currencies (origin, target) | [
"Return",
"quotation",
"between",
"two",
"currencies",
"(",
"origin",
"target",
")"
] | train | https://github.com/carlospalol/money/blob/1e51f651f93edd62c16eb3d7aa034fec03096046/money/exchange.py#L119-L123 |
anntzer/mplcursors | lib/mplcursors/_pick_info.py | _register_scatter | def _register_scatter():
"""
Patch `PathCollection` and `scatter` to register their return values.
This registration allows us to distinguish `PathCollection`s created by
`Axes.scatter`, which should use point-like picking, from others, which
should use path-like picking. The former is more common... | python | def _register_scatter():
"""
Patch `PathCollection` and `scatter` to register their return values.
This registration allows us to distinguish `PathCollection`s created by
`Axes.scatter`, which should use point-like picking, from others, which
should use path-like picking. The former is more common... | [
"def",
"_register_scatter",
"(",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"PathCollection",
".",
"__init__",
")",
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_nonscatter_pathcollections",
".",
"add",
"(",
"... | Patch `PathCollection` and `scatter` to register their return values.
This registration allows us to distinguish `PathCollection`s created by
`Axes.scatter`, which should use point-like picking, from others, which
should use path-like picking. The former is more common, so we store the
latter instead;... | [
"Patch",
"PathCollection",
"and",
"scatter",
"to",
"register",
"their",
"return",
"values",
"."
] | train | https://github.com/anntzer/mplcursors/blob/a4bce17a978162b5a1837cc419114c910e7992f9/lib/mplcursors/_pick_info.py#L37-L60 |
anntzer/mplcursors | lib/mplcursors/_pick_info.py | _compute_projection_pick | def _compute_projection_pick(artist, path, xy):
"""
Project *xy* on *path* to obtain a `Selection` for *artist*.
*path* is first transformed to screen coordinates using the artist
transform, and the target of the returned `Selection` is transformed
back to data coordinates using the artist *axes* i... | python | def _compute_projection_pick(artist, path, xy):
"""
Project *xy* on *path* to obtain a `Selection` for *artist*.
*path* is first transformed to screen coordinates using the artist
transform, and the target of the returned `Selection` is transformed
back to data coordinates using the artist *axes* i... | [
"def",
"_compute_projection_pick",
"(",
"artist",
",",
"path",
",",
"xy",
")",
":",
"transform",
"=",
"artist",
".",
"get_transform",
"(",
")",
".",
"frozen",
"(",
")",
"tpath",
"=",
"(",
"path",
".",
"cleaned",
"(",
"transform",
")",
"if",
"transform",
... | Project *xy* on *path* to obtain a `Selection` for *artist*.
*path* is first transformed to screen coordinates using the artist
transform, and the target of the returned `Selection` is transformed
back to data coordinates using the artist *axes* inverse transform. The
`Selection` `index` is returned a... | [
"Project",
"*",
"xy",
"*",
"on",
"*",
"path",
"*",
"to",
"obtain",
"a",
"Selection",
"for",
"*",
"artist",
"*",
"."
] | train | https://github.com/anntzer/mplcursors/blob/a4bce17a978162b5a1837cc419114c910e7992f9/lib/mplcursors/_pick_info.py#L201-L252 |
anntzer/mplcursors | lib/mplcursors/_pick_info.py | _untransform | def _untransform(orig_xy, screen_xy, ax):
"""
Return data coordinates to place an annotation at screen coordinates
*screen_xy* in axes *ax*.
*orig_xy* are the "original" coordinates as stored by the artist; they are
transformed to *screen_xy* by whatever transform the artist uses. If the
artis... | python | def _untransform(orig_xy, screen_xy, ax):
"""
Return data coordinates to place an annotation at screen coordinates
*screen_xy* in axes *ax*.
*orig_xy* are the "original" coordinates as stored by the artist; they are
transformed to *screen_xy* by whatever transform the artist uses. If the
artis... | [
"def",
"_untransform",
"(",
"orig_xy",
",",
"screen_xy",
",",
"ax",
")",
":",
"tr_xy",
"=",
"ax",
".",
"transData",
".",
"transform",
"(",
"orig_xy",
")",
"return",
"(",
"orig_xy",
"if",
"(",
"(",
"tr_xy",
"==",
"screen_xy",
")",
"|",
"np",
".",
"isn... | Return data coordinates to place an annotation at screen coordinates
*screen_xy* in axes *ax*.
*orig_xy* are the "original" coordinates as stored by the artist; they are
transformed to *screen_xy* by whatever transform the artist uses. If the
artist uses ``ax.transData``, just return *orig_xy*; else, ... | [
"Return",
"data",
"coordinates",
"to",
"place",
"an",
"annotation",
"at",
"screen",
"coordinates",
"*",
"screen_xy",
"*",
"in",
"axes",
"*",
"ax",
"*",
"."
] | train | https://github.com/anntzer/mplcursors/blob/a4bce17a978162b5a1837cc419114c910e7992f9/lib/mplcursors/_pick_info.py#L255-L270 |
anntzer/mplcursors | lib/mplcursors/_pick_info.py | _call_with_selection | def _call_with_selection(func):
"""Decorator that passes a `Selection` built from the non-kwonly args."""
wrapped_kwonly_params = [
param for param in inspect.signature(func).parameters.values()
if param.kind == param.KEYWORD_ONLY]
sel_sig = inspect.signature(Selection)
default_sel_sig =... | python | def _call_with_selection(func):
"""Decorator that passes a `Selection` built from the non-kwonly args."""
wrapped_kwonly_params = [
param for param in inspect.signature(func).parameters.values()
if param.kind == param.KEYWORD_ONLY]
sel_sig = inspect.signature(Selection)
default_sel_sig =... | [
"def",
"_call_with_selection",
"(",
"func",
")",
":",
"wrapped_kwonly_params",
"=",
"[",
"param",
"for",
"param",
"in",
"inspect",
".",
"signature",
"(",
"func",
")",
".",
"parameters",
".",
"values",
"(",
")",
"if",
"param",
".",
"kind",
"==",
"param",
... | Decorator that passes a `Selection` built from the non-kwonly args. | [
"Decorator",
"that",
"passes",
"a",
"Selection",
"built",
"from",
"the",
"non",
"-",
"kwonly",
"args",
"."
] | train | https://github.com/anntzer/mplcursors/blob/a4bce17a978162b5a1837cc419114c910e7992f9/lib/mplcursors/_pick_info.py#L481-L508 |
anntzer/mplcursors | lib/mplcursors/_pick_info.py | _set_valid_props | def _set_valid_props(artist, kwargs):
"""Set valid properties for the artist, dropping the others."""
artist.set(**{k: kwargs[k] for k in kwargs if hasattr(artist, "set_" + k)})
return artist | python | def _set_valid_props(artist, kwargs):
"""Set valid properties for the artist, dropping the others."""
artist.set(**{k: kwargs[k] for k in kwargs if hasattr(artist, "set_" + k)})
return artist | [
"def",
"_set_valid_props",
"(",
"artist",
",",
"kwargs",
")",
":",
"artist",
".",
"set",
"(",
"*",
"*",
"{",
"k",
":",
"kwargs",
"[",
"k",
"]",
"for",
"k",
"in",
"kwargs",
"if",
"hasattr",
"(",
"artist",
",",
"\"set_\"",
"+",
"k",
")",
"}",
")",
... | Set valid properties for the artist, dropping the others. | [
"Set",
"valid",
"properties",
"for",
"the",
"artist",
"dropping",
"the",
"others",
"."
] | train | https://github.com/anntzer/mplcursors/blob/a4bce17a978162b5a1837cc419114c910e7992f9/lib/mplcursors/_pick_info.py#L765-L768 |
carlospalol/money | money/money.py | Money.to | def to(self, currency):
"""Return equivalent money object in another currency"""
if currency == self._currency:
return self
rate = xrates.quotation(self._currency, currency)
if rate is None:
raise ExchangeRateNotFound(xrates.backend_name,
... | python | def to(self, currency):
"""Return equivalent money object in another currency"""
if currency == self._currency:
return self
rate = xrates.quotation(self._currency, currency)
if rate is None:
raise ExchangeRateNotFound(xrates.backend_name,
... | [
"def",
"to",
"(",
"self",
",",
"currency",
")",
":",
"if",
"currency",
"==",
"self",
".",
"_currency",
":",
"return",
"self",
"rate",
"=",
"xrates",
".",
"quotation",
"(",
"self",
".",
"_currency",
",",
"currency",
")",
"if",
"rate",
"is",
"None",
":... | Return equivalent money object in another currency | [
"Return",
"equivalent",
"money",
"object",
"in",
"another",
"currency"
] | train | https://github.com/carlospalol/money/blob/1e51f651f93edd62c16eb3d7aa034fec03096046/money/money.py#L245-L254 |
carlospalol/money | money/money.py | Money.format | def format(self, locale=LC_NUMERIC, pattern=None, currency_digits=True,
format_type='standard'):
"""
Return a locale-aware, currency-formatted string.
This method emulates babel.numbers.format_currency().
A specific locale identifier (language[_territory]... | python | def format(self, locale=LC_NUMERIC, pattern=None, currency_digits=True,
format_type='standard'):
"""
Return a locale-aware, currency-formatted string.
This method emulates babel.numbers.format_currency().
A specific locale identifier (language[_territory]... | [
"def",
"format",
"(",
"self",
",",
"locale",
"=",
"LC_NUMERIC",
",",
"pattern",
"=",
"None",
",",
"currency_digits",
"=",
"True",
",",
"format_type",
"=",
"'standard'",
")",
":",
"if",
"BABEL_AVAILABLE",
":",
"if",
"BABEL_VERSION",
"<",
"StrictVersion",
"(",... | Return a locale-aware, currency-formatted string.
This method emulates babel.numbers.format_currency().
A specific locale identifier (language[_territory]) can be passed,
otherwise the system's default locale will be used. A custom
formatting pattern of the form "¤#,##0... | [
"Return",
"a",
"locale",
"-",
"aware",
"currency",
"-",
"formatted",
"string",
".",
"This",
"method",
"emulates",
"babel",
".",
"numbers",
".",
"format_currency",
"()",
".",
"A",
"specific",
"locale",
"identifier",
"(",
"language",
"[",
"_territory",
"]",
")... | train | https://github.com/carlospalol/money/blob/1e51f651f93edd62c16eb3d7aa034fec03096046/money/money.py#L256-L292 |
carlospalol/money | money/money.py | Money.loads | def loads(cls, s):
"""Parse from a string representation (repr)"""
try:
currency, amount = s.strip().split(' ')
return cls(amount, currency)
except ValueError as err:
# RADAR: Python2
money.six.raise_from(ValueError("failed to parse string "
... | python | def loads(cls, s):
"""Parse from a string representation (repr)"""
try:
currency, amount = s.strip().split(' ')
return cls(amount, currency)
except ValueError as err:
# RADAR: Python2
money.six.raise_from(ValueError("failed to parse string "
... | [
"def",
"loads",
"(",
"cls",
",",
"s",
")",
":",
"try",
":",
"currency",
",",
"amount",
"=",
"s",
".",
"strip",
"(",
")",
".",
"split",
"(",
"' '",
")",
"return",
"cls",
"(",
"amount",
",",
"currency",
")",
"except",
"ValueError",
"as",
"err",
":"... | Parse from a string representation (repr) | [
"Parse",
"from",
"a",
"string",
"representation",
"(",
"repr",
")"
] | train | https://github.com/carlospalol/money/blob/1e51f651f93edd62c16eb3d7aa034fec03096046/money/money.py#L295-L303 |
anntzer/mplcursors | lib/mplcursors/_mplcursors.py | _get_rounded_intersection_area | def _get_rounded_intersection_area(bbox_1, bbox_2):
"""Compute the intersection area between two bboxes rounded to 8 digits."""
# The rounding allows sorting areas without floating point issues.
bbox = bbox_1.intersection(bbox_1, bbox_2)
return round(bbox.width * bbox.height, 8) if bbox else 0 | python | def _get_rounded_intersection_area(bbox_1, bbox_2):
"""Compute the intersection area between two bboxes rounded to 8 digits."""
# The rounding allows sorting areas without floating point issues.
bbox = bbox_1.intersection(bbox_1, bbox_2)
return round(bbox.width * bbox.height, 8) if bbox else 0 | [
"def",
"_get_rounded_intersection_area",
"(",
"bbox_1",
",",
"bbox_2",
")",
":",
"# The rounding allows sorting areas without floating point issues.",
"bbox",
"=",
"bbox_1",
".",
"intersection",
"(",
"bbox_1",
",",
"bbox_2",
")",
"return",
"round",
"(",
"bbox",
".",
"... | Compute the intersection area between two bboxes rounded to 8 digits. | [
"Compute",
"the",
"intersection",
"area",
"between",
"two",
"bboxes",
"rounded",
"to",
"8",
"digits",
"."
] | train | https://github.com/anntzer/mplcursors/blob/a4bce17a978162b5a1837cc419114c910e7992f9/lib/mplcursors/_mplcursors.py#L66-L70 |
anntzer/mplcursors | lib/mplcursors/_mplcursors.py | _iter_axes_subartists | def _iter_axes_subartists(ax):
r"""Yield all child `Artist`\s (*not* `Container`\s) of *ax*."""
yield from ax.collections
yield from ax.images
yield from ax.lines
yield from ax.patches
yield from ax.texts | python | def _iter_axes_subartists(ax):
r"""Yield all child `Artist`\s (*not* `Container`\s) of *ax*."""
yield from ax.collections
yield from ax.images
yield from ax.lines
yield from ax.patches
yield from ax.texts | [
"def",
"_iter_axes_subartists",
"(",
"ax",
")",
":",
"yield",
"from",
"ax",
".",
"collections",
"yield",
"from",
"ax",
".",
"images",
"yield",
"from",
"ax",
".",
"lines",
"yield",
"from",
"ax",
".",
"patches",
"yield",
"from",
"ax",
".",
"texts"
] | r"""Yield all child `Artist`\s (*not* `Container`\s) of *ax*. | [
"r",
"Yield",
"all",
"child",
"Artist",
"\\",
"s",
"(",
"*",
"not",
"*",
"Container",
"\\",
"s",
")",
"of",
"*",
"ax",
"*",
"."
] | train | https://github.com/anntzer/mplcursors/blob/a4bce17a978162b5a1837cc419114c910e7992f9/lib/mplcursors/_mplcursors.py#L73-L79 |
anntzer/mplcursors | lib/mplcursors/_mplcursors.py | _is_alive | def _is_alive(artist):
"""Check whether *artist* is still present on its parent axes."""
return bool(artist
and artist.axes
and (artist.container in artist.axes.containers
if isinstance(artist, _pick_info.ContainerArtist) else
artist in _... | python | def _is_alive(artist):
"""Check whether *artist* is still present on its parent axes."""
return bool(artist
and artist.axes
and (artist.container in artist.axes.containers
if isinstance(artist, _pick_info.ContainerArtist) else
artist in _... | [
"def",
"_is_alive",
"(",
"artist",
")",
":",
"return",
"bool",
"(",
"artist",
"and",
"artist",
".",
"axes",
"and",
"(",
"artist",
".",
"container",
"in",
"artist",
".",
"axes",
".",
"containers",
"if",
"isinstance",
"(",
"artist",
",",
"_pick_info",
".",... | Check whether *artist* is still present on its parent axes. | [
"Check",
"whether",
"*",
"artist",
"*",
"is",
"still",
"present",
"on",
"its",
"parent",
"axes",
"."
] | train | https://github.com/anntzer/mplcursors/blob/a4bce17a978162b5a1837cc419114c910e7992f9/lib/mplcursors/_mplcursors.py#L82-L88 |
anntzer/mplcursors | lib/mplcursors/_mplcursors.py | _reassigned_axes_event | def _reassigned_axes_event(event, ax):
"""Reassign *event* to *ax*."""
event = copy.copy(event)
event.xdata, event.ydata = (
ax.transData.inverted().transform_point((event.x, event.y)))
return event | python | def _reassigned_axes_event(event, ax):
"""Reassign *event* to *ax*."""
event = copy.copy(event)
event.xdata, event.ydata = (
ax.transData.inverted().transform_point((event.x, event.y)))
return event | [
"def",
"_reassigned_axes_event",
"(",
"event",
",",
"ax",
")",
":",
"event",
"=",
"copy",
".",
"copy",
"(",
"event",
")",
"event",
".",
"xdata",
",",
"event",
".",
"ydata",
"=",
"(",
"ax",
".",
"transData",
".",
"inverted",
"(",
")",
".",
"transform_... | Reassign *event* to *ax*. | [
"Reassign",
"*",
"event",
"*",
"to",
"*",
"ax",
"*",
"."
] | train | https://github.com/anntzer/mplcursors/blob/a4bce17a978162b5a1837cc419114c910e7992f9/lib/mplcursors/_mplcursors.py#L91-L96 |
anntzer/mplcursors | lib/mplcursors/_mplcursors.py | cursor | def cursor(pickables=None, **kwargs):
"""
Create a `Cursor` for a list of artists, containers, and axes.
Parameters
----------
pickables : Optional[List[Union[Artist, Container, Axes, Figure]]]
All artists and containers in the list or on any of the axes or
figures passed in the li... | python | def cursor(pickables=None, **kwargs):
"""
Create a `Cursor` for a list of artists, containers, and axes.
Parameters
----------
pickables : Optional[List[Union[Artist, Container, Axes, Figure]]]
All artists and containers in the list or on any of the axes or
figures passed in the li... | [
"def",
"cursor",
"(",
"pickables",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"pickables",
"is",
"None",
":",
"# Do not import pyplot ourselves to avoid forcing the backend.",
"plt",
"=",
"sys",
".",
"modules",
".",
"get",
"(",
"\"matplotlib.pyplot\"",
... | Create a `Cursor` for a list of artists, containers, and axes.
Parameters
----------
pickables : Optional[List[Union[Artist, Container, Axes, Figure]]]
All artists and containers in the list or on any of the axes or
figures passed in the list are selectable by the constructed `Cursor`.
... | [
"Create",
"a",
"Cursor",
"for",
"a",
"list",
"of",
"artists",
"containers",
"and",
"axes",
"."
] | train | https://github.com/anntzer/mplcursors/blob/a4bce17a978162b5a1837cc419114c910e7992f9/lib/mplcursors/_mplcursors.py#L546-L601 |
anntzer/mplcursors | lib/mplcursors/_mplcursors.py | Cursor.selections | def selections(self):
r"""The tuple of current `Selection`\s."""
for sel in self._selections:
if sel.annotation.axes is None:
raise RuntimeError("Annotation unexpectedly removed; "
"use 'cursor.remove_selection' instead")
return tupl... | python | def selections(self):
r"""The tuple of current `Selection`\s."""
for sel in self._selections:
if sel.annotation.axes is None:
raise RuntimeError("Annotation unexpectedly removed; "
"use 'cursor.remove_selection' instead")
return tupl... | [
"def",
"selections",
"(",
"self",
")",
":",
"for",
"sel",
"in",
"self",
".",
"_selections",
":",
"if",
"sel",
".",
"annotation",
".",
"axes",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"\"Annotation unexpectedly removed; \"",
"\"use 'cursor.remove_selection'... | r"""The tuple of current `Selection`\s. | [
"r",
"The",
"tuple",
"of",
"current",
"Selection",
"\\",
"s",
"."
] | train | https://github.com/anntzer/mplcursors/blob/a4bce17a978162b5a1837cc419114c910e7992f9/lib/mplcursors/_mplcursors.py#L259-L265 |
anntzer/mplcursors | lib/mplcursors/_mplcursors.py | Cursor.add_selection | def add_selection(self, pi):
"""
Create an annotation for a `Selection` and register it.
Returns a new `Selection`, that has been registered by the `Cursor`,
with the added annotation set in the :attr:`annotation` field and, if
applicable, the highlighting artist in the :attr:`e... | python | def add_selection(self, pi):
"""
Create an annotation for a `Selection` and register it.
Returns a new `Selection`, that has been registered by the `Cursor`,
with the added annotation set in the :attr:`annotation` field and, if
applicable, the highlighting artist in the :attr:`e... | [
"def",
"add_selection",
"(",
"self",
",",
"pi",
")",
":",
"# pi: \"pick_info\", i.e. an incomplete selection.",
"# Pre-fetch the figure and axes, as callbacks may actually unset them.",
"figure",
"=",
"pi",
".",
"artist",
".",
"figure",
"axes",
"=",
"pi",
".",
"artist",
"... | Create an annotation for a `Selection` and register it.
Returns a new `Selection`, that has been registered by the `Cursor`,
with the added annotation set in the :attr:`annotation` field and, if
applicable, the highlighting artist in the :attr:`extras` field.
Emits the ``"add"`` event ... | [
"Create",
"an",
"annotation",
"for",
"a",
"Selection",
"and",
"register",
"it",
"."
] | train | https://github.com/anntzer/mplcursors/blob/a4bce17a978162b5a1837cc419114c910e7992f9/lib/mplcursors/_mplcursors.py#L284-L372 |
anntzer/mplcursors | lib/mplcursors/_mplcursors.py | Cursor.add_highlight | def add_highlight(self, artist, *args, **kwargs):
"""
Create, add, and return a highlighting artist.
This method is should be called with an "unpacked" `Selection`,
possibly with some fields set to None.
It is up to the caller to register the artist with the proper
`Sel... | python | def add_highlight(self, artist, *args, **kwargs):
"""
Create, add, and return a highlighting artist.
This method is should be called with an "unpacked" `Selection`,
possibly with some fields set to None.
It is up to the caller to register the artist with the proper
`Sel... | [
"def",
"add_highlight",
"(",
"self",
",",
"artist",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"hl",
"=",
"_pick_info",
".",
"make_highlight",
"(",
"artist",
",",
"*",
"args",
",",
"*",
"*",
"ChainMap",
"(",
"{",
"\"highlight_kwargs\"",
":",
... | Create, add, and return a highlighting artist.
This method is should be called with an "unpacked" `Selection`,
possibly with some fields set to None.
It is up to the caller to register the artist with the proper
`Selection` (by calling ``sel.extras.append`` on the result of this
... | [
"Create",
"add",
"and",
"return",
"a",
"highlighting",
"artist",
"."
] | train | https://github.com/anntzer/mplcursors/blob/a4bce17a978162b5a1837cc419114c910e7992f9/lib/mplcursors/_mplcursors.py#L374-L390 |
anntzer/mplcursors | lib/mplcursors/_mplcursors.py | Cursor.connect | def connect(self, event, func=None):
"""
Connect a callback to a `Cursor` event; return the callback.
Two events can be connected to:
- callbacks connected to the ``"add"`` event are called when a
`Selection` is added, with that selection as only argument;
- callbacks... | python | def connect(self, event, func=None):
"""
Connect a callback to a `Cursor` event; return the callback.
Two events can be connected to:
- callbacks connected to the ``"add"`` event are called when a
`Selection` is added, with that selection as only argument;
- callbacks... | [
"def",
"connect",
"(",
"self",
",",
"event",
",",
"func",
"=",
"None",
")",
":",
"if",
"event",
"not",
"in",
"self",
".",
"_callbacks",
":",
"raise",
"ValueError",
"(",
"\"{!r} is not a valid cursor event\"",
".",
"format",
"(",
"event",
")",
")",
"if",
... | Connect a callback to a `Cursor` event; return the callback.
Two events can be connected to:
- callbacks connected to the ``"add"`` event are called when a
`Selection` is added, with that selection as only argument;
- callbacks connected to the ``"remove"`` event are called when a
... | [
"Connect",
"a",
"callback",
"to",
"a",
"Cursor",
"event",
";",
"return",
"the",
"callback",
"."
] | train | https://github.com/anntzer/mplcursors/blob/a4bce17a978162b5a1837cc419114c910e7992f9/lib/mplcursors/_mplcursors.py#L392-L424 |
anntzer/mplcursors | lib/mplcursors/_mplcursors.py | Cursor.disconnect | def disconnect(self, event, cb):
"""
Disconnect a previously connected callback.
If a callback is connected multiple times, only one connection is
removed.
"""
try:
self._callbacks[event].remove(cb)
except KeyError:
raise ValueError("{!r} ... | python | def disconnect(self, event, cb):
"""
Disconnect a previously connected callback.
If a callback is connected multiple times, only one connection is
removed.
"""
try:
self._callbacks[event].remove(cb)
except KeyError:
raise ValueError("{!r} ... | [
"def",
"disconnect",
"(",
"self",
",",
"event",
",",
"cb",
")",
":",
"try",
":",
"self",
".",
"_callbacks",
"[",
"event",
"]",
".",
"remove",
"(",
"cb",
")",
"except",
"KeyError",
":",
"raise",
"ValueError",
"(",
"\"{!r} is not a valid cursor event\"",
"."... | Disconnect a previously connected callback.
If a callback is connected multiple times, only one connection is
removed. | [
"Disconnect",
"a",
"previously",
"connected",
"callback",
"."
] | train | https://github.com/anntzer/mplcursors/blob/a4bce17a978162b5a1837cc419114c910e7992f9/lib/mplcursors/_mplcursors.py#L426-L438 |
anntzer/mplcursors | lib/mplcursors/_mplcursors.py | Cursor.remove | def remove(self):
"""
Remove a cursor.
Remove all `Selection`\\s, disconnect all callbacks, and allow the
cursor to be garbage collected.
"""
for disconnectors in self._disconnectors:
disconnectors()
for sel in self.selections:
self.remove... | python | def remove(self):
"""
Remove a cursor.
Remove all `Selection`\\s, disconnect all callbacks, and allow the
cursor to be garbage collected.
"""
for disconnectors in self._disconnectors:
disconnectors()
for sel in self.selections:
self.remove... | [
"def",
"remove",
"(",
"self",
")",
":",
"for",
"disconnectors",
"in",
"self",
".",
"_disconnectors",
":",
"disconnectors",
"(",
")",
"for",
"sel",
"in",
"self",
".",
"selections",
":",
"self",
".",
"remove_selection",
"(",
"sel",
")",
"for",
"s",
"in",
... | Remove a cursor.
Remove all `Selection`\\s, disconnect all callbacks, and allow the
cursor to be garbage collected. | [
"Remove",
"a",
"cursor",
"."
] | train | https://github.com/anntzer/mplcursors/blob/a4bce17a978162b5a1837cc419114c910e7992f9/lib/mplcursors/_mplcursors.py#L440-L453 |
anntzer/mplcursors | lib/mplcursors/_mplcursors.py | Cursor.remove_selection | def remove_selection(self, sel):
"""Remove a `Selection`."""
self._selections.remove(sel)
# <artist>.figure will be unset so we save them first.
figures = {artist.figure for artist in [sel.annotation] + sel.extras}
# ValueError is raised if the artist has already been removed.
... | python | def remove_selection(self, sel):
"""Remove a `Selection`."""
self._selections.remove(sel)
# <artist>.figure will be unset so we save them first.
figures = {artist.figure for artist in [sel.annotation] + sel.extras}
# ValueError is raised if the artist has already been removed.
... | [
"def",
"remove_selection",
"(",
"self",
",",
"sel",
")",
":",
"self",
".",
"_selections",
".",
"remove",
"(",
"sel",
")",
"# <artist>.figure will be unset so we save them first.",
"figures",
"=",
"{",
"artist",
".",
"figure",
"for",
"artist",
"in",
"[",
"sel",
... | Remove a `Selection`. | [
"Remove",
"a",
"Selection",
"."
] | train | https://github.com/anntzer/mplcursors/blob/a4bce17a978162b5a1837cc419114c910e7992f9/lib/mplcursors/_mplcursors.py#L529-L543 |
mozilla/jupyter-notebook-gist | src/jupyter_notebook_gist/handlers.py | extract_code_from_args | def extract_code_from_args(args):
"""
Extracts the access code from the arguments dictionary (given back
from github)
"""
if args is None:
raise_error("Couldn't extract GitHub authentication code "
"from response")
# TODO: Is there a case where the length of the erro... | python | def extract_code_from_args(args):
"""
Extracts the access code from the arguments dictionary (given back
from github)
"""
if args is None:
raise_error("Couldn't extract GitHub authentication code "
"from response")
# TODO: Is there a case where the length of the erro... | [
"def",
"extract_code_from_args",
"(",
"args",
")",
":",
"if",
"args",
"is",
"None",
":",
"raise_error",
"(",
"\"Couldn't extract GitHub authentication code \"",
"\"from response\"",
")",
"# TODO: Is there a case where the length of the error will be < 0?",
"error",
"=",
"args",... | Extracts the access code from the arguments dictionary (given back
from github) | [
"Extracts",
"the",
"access",
"code",
"from",
"the",
"arguments",
"dictionary",
"(",
"given",
"back",
"from",
"github",
")"
] | train | https://github.com/mozilla/jupyter-notebook-gist/blob/dae052f0998fa80dff515345cd516b586eff8e43/src/jupyter_notebook_gist/handlers.py#L163-L191 |
mozilla/jupyter-notebook-gist | src/jupyter_notebook_gist/handlers.py | BaseHandler.request_access_token | def request_access_token(self, access_code):
"Request access token from GitHub"
token_response = request_session.post(
"https://github.com/login/oauth/access_token",
data={
"client_id": self.oauth_client_id,
"client_secret": self.oauth_client_secre... | python | def request_access_token(self, access_code):
"Request access token from GitHub"
token_response = request_session.post(
"https://github.com/login/oauth/access_token",
data={
"client_id": self.oauth_client_id,
"client_secret": self.oauth_client_secre... | [
"def",
"request_access_token",
"(",
"self",
",",
"access_code",
")",
":",
"token_response",
"=",
"request_session",
".",
"post",
"(",
"\"https://github.com/login/oauth/access_token\"",
",",
"data",
"=",
"{",
"\"client_id\"",
":",
"self",
".",
"oauth_client_id",
",",
... | Request access token from GitHub | [
"Request",
"access",
"token",
"from",
"GitHub"
] | train | https://github.com/mozilla/jupyter-notebook-gist/blob/dae052f0998fa80dff515345cd516b586eff8e43/src/jupyter_notebook_gist/handlers.py#L39-L50 |
rdobson/python-hwinfo | hwinfo/util/__init__.py | combine_dicts | def combine_dicts(recs):
"""Combine a list of recs, appending values to matching keys"""
if not recs:
return None
if len(recs) == 1:
return recs.pop()
new_rec = {}
for rec in recs:
for k, v in rec.iteritems():
if k in new_rec:
new_rec[k] = "%s, %... | python | def combine_dicts(recs):
"""Combine a list of recs, appending values to matching keys"""
if not recs:
return None
if len(recs) == 1:
return recs.pop()
new_rec = {}
for rec in recs:
for k, v in rec.iteritems():
if k in new_rec:
new_rec[k] = "%s, %... | [
"def",
"combine_dicts",
"(",
"recs",
")",
":",
"if",
"not",
"recs",
":",
"return",
"None",
"if",
"len",
"(",
"recs",
")",
"==",
"1",
":",
"return",
"recs",
".",
"pop",
"(",
")",
"new_rec",
"=",
"{",
"}",
"for",
"rec",
"in",
"recs",
":",
"for",
... | Combine a list of recs, appending values to matching keys | [
"Combine",
"a",
"list",
"of",
"recs",
"appending",
"values",
"to",
"matching",
"keys"
] | train | https://github.com/rdobson/python-hwinfo/blob/ba93a112dac6863396a053636ea87df027daa5de/hwinfo/util/__init__.py#L5-L20 |
rdobson/python-hwinfo | hwinfo/tools/inspector.py | combine_recs | def combine_recs(rec_list, key):
"""Use a common key to combine a list of recs"""
final_recs = {}
for rec in rec_list:
rec_key = rec[key]
if rec_key in final_recs:
for k, v in rec.iteritems():
if k in final_recs[rec_key] and final_recs[rec_key][k] != v:
... | python | def combine_recs(rec_list, key):
"""Use a common key to combine a list of recs"""
final_recs = {}
for rec in rec_list:
rec_key = rec[key]
if rec_key in final_recs:
for k, v in rec.iteritems():
if k in final_recs[rec_key] and final_recs[rec_key][k] != v:
... | [
"def",
"combine_recs",
"(",
"rec_list",
",",
"key",
")",
":",
"final_recs",
"=",
"{",
"}",
"for",
"rec",
"in",
"rec_list",
":",
"rec_key",
"=",
"rec",
"[",
"key",
"]",
"if",
"rec_key",
"in",
"final_recs",
":",
"for",
"k",
",",
"v",
"in",
"rec",
"."... | Use a common key to combine a list of recs | [
"Use",
"a",
"common",
"key",
"to",
"combine",
"a",
"list",
"of",
"recs"
] | train | https://github.com/rdobson/python-hwinfo/blob/ba93a112dac6863396a053636ea87df027daa5de/hwinfo/tools/inspector.py#L195-L207 |
rdobson/python-hwinfo | hwinfo/tools/inspector.py | main | def main():
"""Entry Point"""
parser = ArgumentParser(prog="hwinfo")
filter_choices = ['bios', 'nic', 'storage', 'gpu', 'cpu']
parser.add_argument("-f", "--filter", choices=filter_choices, help="Query a specific class.")
parser.add_argument("-m", "--machine", default='localhost', help="Remote host... | python | def main():
"""Entry Point"""
parser = ArgumentParser(prog="hwinfo")
filter_choices = ['bios', 'nic', 'storage', 'gpu', 'cpu']
parser.add_argument("-f", "--filter", choices=filter_choices, help="Query a specific class.")
parser.add_argument("-m", "--machine", default='localhost', help="Remote host... | [
"def",
"main",
"(",
")",
":",
"parser",
"=",
"ArgumentParser",
"(",
"prog",
"=",
"\"hwinfo\"",
")",
"filter_choices",
"=",
"[",
"'bios'",
",",
"'nic'",
",",
"'storage'",
",",
"'gpu'",
",",
"'cpu'",
"]",
"parser",
".",
"add_argument",
"(",
"\"-f\"",
",",
... | Entry Point | [
"Entry",
"Point"
] | train | https://github.com/rdobson/python-hwinfo/blob/ba93a112dac6863396a053636ea87df027daa5de/hwinfo/tools/inspector.py#L398-L434 |
rdobson/python-hwinfo | hwinfo/tools/inspector.py | HostFromTarball._load_from_file | def _load_from_file(self, filename):
"""Find filename in tar, and load it"""
if filename in self.fdata:
return self.fdata[filename]
else:
filepath = find_in_tarball(self.tarloc, filename)
return read_from_tarball(self.tarloc, filepath) | python | def _load_from_file(self, filename):
"""Find filename in tar, and load it"""
if filename in self.fdata:
return self.fdata[filename]
else:
filepath = find_in_tarball(self.tarloc, filename)
return read_from_tarball(self.tarloc, filepath) | [
"def",
"_load_from_file",
"(",
"self",
",",
"filename",
")",
":",
"if",
"filename",
"in",
"self",
".",
"fdata",
":",
"return",
"self",
".",
"fdata",
"[",
"filename",
"]",
"else",
":",
"filepath",
"=",
"find_in_tarball",
"(",
"self",
".",
"tarloc",
",",
... | Find filename in tar, and load it | [
"Find",
"filename",
"in",
"tar",
"and",
"load",
"it"
] | train | https://github.com/rdobson/python-hwinfo/blob/ba93a112dac6863396a053636ea87df027daa5de/hwinfo/tools/inspector.py#L272-L278 |
LuminosoInsight/langcodes | langcodes/tag_parser.py | parse_tag | def parse_tag(tag):
"""
Parse the syntax of a language tag, without looking up anything in the
registry, yet. Returns a list of (type, value) tuples indicating what
information will need to be looked up.
"""
tag = normalize_characters(tag)
if tag in EXCEPTIONS:
return [('grandfathere... | python | def parse_tag(tag):
"""
Parse the syntax of a language tag, without looking up anything in the
registry, yet. Returns a list of (type, value) tuples indicating what
information will need to be looked up.
"""
tag = normalize_characters(tag)
if tag in EXCEPTIONS:
return [('grandfathere... | [
"def",
"parse_tag",
"(",
"tag",
")",
":",
"tag",
"=",
"normalize_characters",
"(",
"tag",
")",
"if",
"tag",
"in",
"EXCEPTIONS",
":",
"return",
"[",
"(",
"'grandfathered'",
",",
"tag",
")",
"]",
"else",
":",
"# The first subtag is always either the language code,... | Parse the syntax of a language tag, without looking up anything in the
registry, yet. Returns a list of (type, value) tuples indicating what
information will need to be looked up. | [
"Parse",
"the",
"syntax",
"of",
"a",
"language",
"tag",
"without",
"looking",
"up",
"anything",
"in",
"the",
"registry",
"yet",
".",
"Returns",
"a",
"list",
"of",
"(",
"type",
"value",
")",
"tuples",
"indicating",
"what",
"information",
"will",
"need",
"to... | train | https://github.com/LuminosoInsight/langcodes/blob/0cedf9ca257ebf7250de5d3a63ec33a7d198db58/langcodes/tag_parser.py#L105-L130 |
LuminosoInsight/langcodes | langcodes/tag_parser.py | parse_subtags | def parse_subtags(subtags, expect=EXTLANG):
"""
Parse everything that comes after the language tag: scripts, regions,
variants, and assorted extensions.
"""
# We parse the parts of a language code recursively: each step of
# language code parsing handles one component of the code, recurses
#... | python | def parse_subtags(subtags, expect=EXTLANG):
"""
Parse everything that comes after the language tag: scripts, regions,
variants, and assorted extensions.
"""
# We parse the parts of a language code recursively: each step of
# language code parsing handles one component of the code, recurses
#... | [
"def",
"parse_subtags",
"(",
"subtags",
",",
"expect",
"=",
"EXTLANG",
")",
":",
"# We parse the parts of a language code recursively: each step of",
"# language code parsing handles one component of the code, recurses",
"# to handle the rest of the code, and adds what it found onto the",
... | Parse everything that comes after the language tag: scripts, regions,
variants, and assorted extensions. | [
"Parse",
"everything",
"that",
"comes",
"after",
"the",
"language",
"tag",
":",
"scripts",
"regions",
"variants",
"and",
"assorted",
"extensions",
"."
] | train | https://github.com/LuminosoInsight/langcodes/blob/0cedf9ca257ebf7250de5d3a63ec33a7d198db58/langcodes/tag_parser.py#L133-L249 |
LuminosoInsight/langcodes | langcodes/tag_parser.py | parse_extlang | def parse_extlang(subtags):
"""
Parse an 'extended language' tag, which consists of 1 to 3 three-letter
language codes.
Extended languages are used for distinguishing dialects/sublanguages
(depending on your view) of macrolanguages such as Arabic, Bahasa Malay,
and Chinese.
It's supposed t... | python | def parse_extlang(subtags):
"""
Parse an 'extended language' tag, which consists of 1 to 3 three-letter
language codes.
Extended languages are used for distinguishing dialects/sublanguages
(depending on your view) of macrolanguages such as Arabic, Bahasa Malay,
and Chinese.
It's supposed t... | [
"def",
"parse_extlang",
"(",
"subtags",
")",
":",
"index",
"=",
"0",
"parsed",
"=",
"[",
"]",
"while",
"index",
"<",
"len",
"(",
"subtags",
")",
"and",
"len",
"(",
"subtags",
"[",
"index",
"]",
")",
"==",
"3",
"and",
"index",
"<",
"3",
":",
"pars... | Parse an 'extended language' tag, which consists of 1 to 3 three-letter
language codes.
Extended languages are used for distinguishing dialects/sublanguages
(depending on your view) of macrolanguages such as Arabic, Bahasa Malay,
and Chinese.
It's supposed to also be acceptable to just use the sub... | [
"Parse",
"an",
"extended",
"language",
"tag",
"which",
"consists",
"of",
"1",
"to",
"3",
"three",
"-",
"letter",
"language",
"codes",
"."
] | train | https://github.com/LuminosoInsight/langcodes/blob/0cedf9ca257ebf7250de5d3a63ec33a7d198db58/langcodes/tag_parser.py#L252-L272 |
LuminosoInsight/langcodes | langcodes/tag_parser.py | parse_extension | def parse_extension(subtags):
"""
An extension tag consists of a 'singleton' -- a one-character subtag --
followed by other subtags. Extension tags are in the BCP 47 syntax, but
their meaning is outside the scope of the standard.
For example, there's the u- extension, which is used for setting Unic... | python | def parse_extension(subtags):
"""
An extension tag consists of a 'singleton' -- a one-character subtag --
followed by other subtags. Extension tags are in the BCP 47 syntax, but
their meaning is outside the scope of the standard.
For example, there's the u- extension, which is used for setting Unic... | [
"def",
"parse_extension",
"(",
"subtags",
")",
":",
"subtag",
"=",
"subtags",
"[",
"0",
"]",
"if",
"len",
"(",
"subtags",
")",
"==",
"1",
":",
"raise",
"LanguageTagError",
"(",
"\"The subtag %r must be followed by something\"",
"%",
"subtag",
")",
"if",
"subta... | An extension tag consists of a 'singleton' -- a one-character subtag --
followed by other subtags. Extension tags are in the BCP 47 syntax, but
their meaning is outside the scope of the standard.
For example, there's the u- extension, which is used for setting Unicode
properties in some context I'm not... | [
"An",
"extension",
"tag",
"consists",
"of",
"a",
"singleton",
"--",
"a",
"one",
"-",
"character",
"subtag",
"--",
"followed",
"by",
"other",
"subtags",
".",
"Extension",
"tags",
"are",
"in",
"the",
"BCP",
"47",
"syntax",
"but",
"their",
"meaning",
"is",
... | train | https://github.com/LuminosoInsight/langcodes/blob/0cedf9ca257ebf7250de5d3a63ec33a7d198db58/langcodes/tag_parser.py#L275-L308 |
LuminosoInsight/langcodes | langcodes/tag_parser.py | order_error | def order_error(subtag, got, expected):
"""
Output an error indicating that tags were out of order.
"""
options = SUBTAG_TYPES[expected:]
if len(options) == 1:
expect_str = options[0]
elif len(options) == 2:
expect_str = '%s or %s' % (options[0], options[1])
else:
exp... | python | def order_error(subtag, got, expected):
"""
Output an error indicating that tags were out of order.
"""
options = SUBTAG_TYPES[expected:]
if len(options) == 1:
expect_str = options[0]
elif len(options) == 2:
expect_str = '%s or %s' % (options[0], options[1])
else:
exp... | [
"def",
"order_error",
"(",
"subtag",
",",
"got",
",",
"expected",
")",
":",
"options",
"=",
"SUBTAG_TYPES",
"[",
"expected",
":",
"]",
"if",
"len",
"(",
"options",
")",
"==",
"1",
":",
"expect_str",
"=",
"options",
"[",
"0",
"]",
"elif",
"len",
"(",
... | Output an error indicating that tags were out of order. | [
"Output",
"an",
"error",
"indicating",
"that",
"tags",
"were",
"out",
"of",
"order",
"."
] | train | https://github.com/LuminosoInsight/langcodes/blob/0cedf9ca257ebf7250de5d3a63ec33a7d198db58/langcodes/tag_parser.py#L315-L328 |
LuminosoInsight/langcodes | langcodes/__init__.py | standardize_tag | def standardize_tag(tag: {str, Language}, macro: bool=False) -> str:
"""
Standardize a language tag:
- Replace deprecated values with their updated versions (if those exist)
- Remove script tags that are redundant with the language
- If *macro* is True, use a macrolanguage to represent the most com... | python | def standardize_tag(tag: {str, Language}, macro: bool=False) -> str:
"""
Standardize a language tag:
- Replace deprecated values with their updated versions (if those exist)
- Remove script tags that are redundant with the language
- If *macro* is True, use a macrolanguage to represent the most com... | [
"def",
"standardize_tag",
"(",
"tag",
":",
"{",
"str",
",",
"Language",
"}",
",",
"macro",
":",
"bool",
"=",
"False",
")",
"->",
"str",
":",
"langdata",
"=",
"Language",
".",
"get",
"(",
"tag",
",",
"normalize",
"=",
"True",
")",
"if",
"macro",
":"... | Standardize a language tag:
- Replace deprecated values with their updated versions (if those exist)
- Remove script tags that are redundant with the language
- If *macro* is True, use a macrolanguage to represent the most common
standardized language within that macrolanguage. For example, 'cmn'
... | [
"Standardize",
"a",
"language",
"tag",
":"
] | train | https://github.com/LuminosoInsight/langcodes/blob/0cedf9ca257ebf7250de5d3a63ec33a7d198db58/langcodes/__init__.py#L955-L1018 |
LuminosoInsight/langcodes | langcodes/__init__.py | tag_match_score | def tag_match_score(desired: {str, Language}, supported: {str, Language}) -> int:
"""
Return a number from 0 to 100 indicating the strength of match between the
language the user desires, D, and a supported language, S. Higher numbers
are better. A reasonable cutoff for not messing with your users is to... | python | def tag_match_score(desired: {str, Language}, supported: {str, Language}) -> int:
"""
Return a number from 0 to 100 indicating the strength of match between the
language the user desires, D, and a supported language, S. Higher numbers
are better. A reasonable cutoff for not messing with your users is to... | [
"def",
"tag_match_score",
"(",
"desired",
":",
"{",
"str",
",",
"Language",
"}",
",",
"supported",
":",
"{",
"str",
",",
"Language",
"}",
")",
"->",
"int",
":",
"desired_ld",
"=",
"Language",
".",
"get",
"(",
"desired",
")",
"supported_ld",
"=",
"Langu... | Return a number from 0 to 100 indicating the strength of match between the
language the user desires, D, and a supported language, S. Higher numbers
are better. A reasonable cutoff for not messing with your users is to
only accept scores of 75 or more.
A score of 100 means the languages are the same, p... | [
"Return",
"a",
"number",
"from",
"0",
"to",
"100",
"indicating",
"the",
"strength",
"of",
"match",
"between",
"the",
"language",
"the",
"user",
"desires",
"D",
"and",
"a",
"supported",
"language",
"S",
".",
"Higher",
"numbers",
"are",
"better",
".",
"A",
... | train | https://github.com/LuminosoInsight/langcodes/blob/0cedf9ca257ebf7250de5d3a63ec33a7d198db58/langcodes/__init__.py#L1021-L1159 |
LuminosoInsight/langcodes | langcodes/__init__.py | best_match | def best_match(desired_language: {str, Language}, supported_languages: list,
min_score: int=75) -> (str, int):
"""
You have software that supports any of the `supported_languages`. You want
to use `desired_language`. This function lets you choose the right language,
even if there isn't an... | python | def best_match(desired_language: {str, Language}, supported_languages: list,
min_score: int=75) -> (str, int):
"""
You have software that supports any of the `supported_languages`. You want
to use `desired_language`. This function lets you choose the right language,
even if there isn't an... | [
"def",
"best_match",
"(",
"desired_language",
":",
"{",
"str",
",",
"Language",
"}",
",",
"supported_languages",
":",
"list",
",",
"min_score",
":",
"int",
"=",
"75",
")",
"->",
"(",
"str",
",",
"int",
")",
":",
"# Quickly return if the desired language is dir... | You have software that supports any of the `supported_languages`. You want
to use `desired_language`. This function lets you choose the right language,
even if there isn't an exact match.
Returns:
- The best-matching language code, which will be one of the
`supported_languages` or 'und'
- Th... | [
"You",
"have",
"software",
"that",
"supports",
"any",
"of",
"the",
"supported_languages",
".",
"You",
"want",
"to",
"use",
"desired_language",
".",
"This",
"function",
"lets",
"you",
"choose",
"the",
"right",
"language",
"even",
"if",
"there",
"isn",
"t",
"a... | train | https://github.com/LuminosoInsight/langcodes/blob/0cedf9ca257ebf7250de5d3a63ec33a7d198db58/langcodes/__init__.py#L1162-L1229 |
LuminosoInsight/langcodes | langcodes/__init__.py | Language.make | def make(cls, language=None, extlangs=None, script=None,
region=None, variants=None, extensions=None, private=None):
"""
Create a Language object by giving any subset of its attributes.
If this value has been created before, return the existing value.
"""
values = (... | python | def make(cls, language=None, extlangs=None, script=None,
region=None, variants=None, extensions=None, private=None):
"""
Create a Language object by giving any subset of its attributes.
If this value has been created before, return the existing value.
"""
values = (... | [
"def",
"make",
"(",
"cls",
",",
"language",
"=",
"None",
",",
"extlangs",
"=",
"None",
",",
"script",
"=",
"None",
",",
"region",
"=",
"None",
",",
"variants",
"=",
"None",
",",
"extensions",
"=",
"None",
",",
"private",
"=",
"None",
")",
":",
"val... | Create a Language object by giving any subset of its attributes.
If this value has been created before, return the existing value. | [
"Create",
"a",
"Language",
"object",
"by",
"giving",
"any",
"subset",
"of",
"its",
"attributes",
"."
] | train | https://github.com/LuminosoInsight/langcodes/blob/0cedf9ca257ebf7250de5d3a63ec33a7d198db58/langcodes/__init__.py#L104-L122 |
LuminosoInsight/langcodes | langcodes/__init__.py | Language.get | def get(tag: {str, 'Language'}, normalize=True) -> 'Language':
"""
Create a Language object from a language tag string.
If normalize=True, non-standard or overlong tags will be replaced as
they're interpreted. This is recommended.
Here are several examples of language codes, wh... | python | def get(tag: {str, 'Language'}, normalize=True) -> 'Language':
"""
Create a Language object from a language tag string.
If normalize=True, non-standard or overlong tags will be replaced as
they're interpreted. This is recommended.
Here are several examples of language codes, wh... | [
"def",
"get",
"(",
"tag",
":",
"{",
"str",
",",
"'Language'",
"}",
",",
"normalize",
"=",
"True",
")",
"->",
"'Language'",
":",
"if",
"isinstance",
"(",
"tag",
",",
"Language",
")",
":",
"if",
"not",
"normalize",
":",
"# shortcut: we have the tag already",... | Create a Language object from a language tag string.
If normalize=True, non-standard or overlong tags will be replaced as
they're interpreted. This is recommended.
Here are several examples of language codes, which are also test cases.
Most language codes are straightforward, but these... | [
"Create",
"a",
"Language",
"object",
"from",
"a",
"language",
"tag",
"string",
"."
] | train | https://github.com/LuminosoInsight/langcodes/blob/0cedf9ca257ebf7250de5d3a63ec33a7d198db58/langcodes/__init__.py#L125-L290 |
LuminosoInsight/langcodes | langcodes/__init__.py | Language.to_tag | def to_tag(self) -> str:
"""
Convert a Language back to a standard language tag, as a string.
This is also the str() representation of a Language object.
>>> Language.make(language='en', region='GB').to_tag()
'en-GB'
>>> Language.make(language='yue', script='Hant', regi... | python | def to_tag(self) -> str:
"""
Convert a Language back to a standard language tag, as a string.
This is also the str() representation of a Language object.
>>> Language.make(language='en', region='GB').to_tag()
'en-GB'
>>> Language.make(language='yue', script='Hant', regi... | [
"def",
"to_tag",
"(",
"self",
")",
"->",
"str",
":",
"if",
"self",
".",
"_str_tag",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_str_tag",
"subtags",
"=",
"[",
"'und'",
"]",
"if",
"self",
".",
"language",
":",
"subtags",
"[",
"0",
"]",
"=",
... | Convert a Language back to a standard language tag, as a string.
This is also the str() representation of a Language object.
>>> Language.make(language='en', region='GB').to_tag()
'en-GB'
>>> Language.make(language='yue', script='Hant', region='HK').to_tag()
'yue-Hant-HK'
... | [
"Convert",
"a",
"Language",
"back",
"to",
"a",
"standard",
"language",
"tag",
"as",
"a",
"string",
".",
"This",
"is",
"also",
"the",
"str",
"()",
"representation",
"of",
"a",
"Language",
"object",
"."
] | train | https://github.com/LuminosoInsight/langcodes/blob/0cedf9ca257ebf7250de5d3a63ec33a7d198db58/langcodes/__init__.py#L292-L330 |
LuminosoInsight/langcodes | langcodes/__init__.py | Language.simplify_script | def simplify_script(self) -> 'Language':
"""
Remove the script from some parsed language data, if the script is
redundant with the language.
>>> Language.make(language='en', script='Latn').simplify_script()
Language.make(language='en')
>>> Language.make(language='yi', s... | python | def simplify_script(self) -> 'Language':
"""
Remove the script from some parsed language data, if the script is
redundant with the language.
>>> Language.make(language='en', script='Latn').simplify_script()
Language.make(language='en')
>>> Language.make(language='yi', s... | [
"def",
"simplify_script",
"(",
"self",
")",
"->",
"'Language'",
":",
"if",
"self",
".",
"_simplified",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_simplified",
"if",
"self",
".",
"language",
"and",
"self",
".",
"script",
":",
"if",
"DEFAULT_SCRIPTS"... | Remove the script from some parsed language data, if the script is
redundant with the language.
>>> Language.make(language='en', script='Latn').simplify_script()
Language.make(language='en')
>>> Language.make(language='yi', script='Latn').simplify_script()
Language.make(languag... | [
"Remove",
"the",
"script",
"from",
"some",
"parsed",
"language",
"data",
"if",
"the",
"script",
"is",
"redundant",
"with",
"the",
"language",
"."
] | train | https://github.com/LuminosoInsight/langcodes/blob/0cedf9ca257ebf7250de5d3a63ec33a7d198db58/langcodes/__init__.py#L332-L356 |
LuminosoInsight/langcodes | langcodes/__init__.py | Language.assume_script | def assume_script(self) -> 'Language':
"""
Fill in the script if it's missing, and if it can be assumed from the
language subtag. This is the opposite of `simplify_script`.
>>> Language.make(language='en').assume_script()
Language.make(language='en', script='Latn')
>>> ... | python | def assume_script(self) -> 'Language':
"""
Fill in the script if it's missing, and if it can be assumed from the
language subtag. This is the opposite of `simplify_script`.
>>> Language.make(language='en').assume_script()
Language.make(language='en', script='Latn')
>>> ... | [
"def",
"assume_script",
"(",
"self",
")",
"->",
"'Language'",
":",
"if",
"self",
".",
"_assumed",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_assumed",
"if",
"self",
".",
"language",
"and",
"not",
"self",
".",
"script",
":",
"try",
":",
"self",
... | Fill in the script if it's missing, and if it can be assumed from the
language subtag. This is the opposite of `simplify_script`.
>>> Language.make(language='en').assume_script()
Language.make(language='en', script='Latn')
>>> Language.make(language='yi').assume_script()
Langua... | [
"Fill",
"in",
"the",
"script",
"if",
"it",
"s",
"missing",
"and",
"if",
"it",
"can",
"be",
"assumed",
"from",
"the",
"language",
"subtag",
".",
"This",
"is",
"the",
"opposite",
"of",
"simplify_script",
"."
] | train | https://github.com/LuminosoInsight/langcodes/blob/0cedf9ca257ebf7250de5d3a63ec33a7d198db58/langcodes/__init__.py#L358-L395 |
LuminosoInsight/langcodes | langcodes/__init__.py | Language.prefer_macrolanguage | def prefer_macrolanguage(self) -> 'Language':
"""
BCP 47 doesn't specify what to do with macrolanguages and the languages
they contain. The Unicode CLDR, on the other hand, says that when a
macrolanguage has a dominant standardized language, the macrolanguage
code should be used ... | python | def prefer_macrolanguage(self) -> 'Language':
"""
BCP 47 doesn't specify what to do with macrolanguages and the languages
they contain. The Unicode CLDR, on the other hand, says that when a
macrolanguage has a dominant standardized language, the macrolanguage
code should be used ... | [
"def",
"prefer_macrolanguage",
"(",
"self",
")",
"->",
"'Language'",
":",
"if",
"self",
".",
"_macrolanguage",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_macrolanguage",
"language",
"=",
"self",
".",
"language",
"or",
"'und'",
"if",
"language",
"in",... | BCP 47 doesn't specify what to do with macrolanguages and the languages
they contain. The Unicode CLDR, on the other hand, says that when a
macrolanguage has a dominant standardized language, the macrolanguage
code should be used for that language. For example, Mandarin Chinese
is 'zh', ... | [
"BCP",
"47",
"doesn",
"t",
"specify",
"what",
"to",
"do",
"with",
"macrolanguages",
"and",
"the",
"languages",
"they",
"contain",
".",
"The",
"Unicode",
"CLDR",
"on",
"the",
"other",
"hand",
"says",
"that",
"when",
"a",
"macrolanguage",
"has",
"a",
"domina... | train | https://github.com/LuminosoInsight/langcodes/blob/0cedf9ca257ebf7250de5d3a63ec33a7d198db58/langcodes/__init__.py#L397-L433 |
LuminosoInsight/langcodes | langcodes/__init__.py | Language.broaden | def broaden(self) -> 'List[Language]':
"""
Iterate through increasingly general versions of this parsed language tag.
This isn't actually that useful for matching two arbitrary language tags
against each other, but it is useful for matching them against a known
standardized form... | python | def broaden(self) -> 'List[Language]':
"""
Iterate through increasingly general versions of this parsed language tag.
This isn't actually that useful for matching two arbitrary language tags
against each other, but it is useful for matching them against a known
standardized form... | [
"def",
"broaden",
"(",
"self",
")",
"->",
"'List[Language]'",
":",
"if",
"self",
".",
"_broader",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_broader",
"self",
".",
"_broader",
"=",
"[",
"self",
"]",
"seen",
"=",
"set",
"(",
"self",
".",
"to_t... | Iterate through increasingly general versions of this parsed language tag.
This isn't actually that useful for matching two arbitrary language tags
against each other, but it is useful for matching them against a known
standardized form, such as in the CLDR data.
The list of broader ve... | [
"Iterate",
"through",
"increasingly",
"general",
"versions",
"of",
"this",
"parsed",
"language",
"tag",
"."
] | train | https://github.com/LuminosoInsight/langcodes/blob/0cedf9ca257ebf7250de5d3a63ec33a7d198db58/langcodes/__init__.py#L435-L466 |
LuminosoInsight/langcodes | langcodes/__init__.py | Language.maximize | def maximize(self) -> 'Language':
"""
The Unicode CLDR contains a "likelySubtags" data file, which can guess
reasonable values for fields that are missing from a language tag.
This is particularly useful for comparing, for example, "zh-Hant" and
"zh-TW", two common language tags... | python | def maximize(self) -> 'Language':
"""
The Unicode CLDR contains a "likelySubtags" data file, which can guess
reasonable values for fields that are missing from a language tag.
This is particularly useful for comparing, for example, "zh-Hant" and
"zh-TW", two common language tags... | [
"def",
"maximize",
"(",
"self",
")",
"->",
"'Language'",
":",
"if",
"self",
".",
"_filled",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_filled",
"for",
"broader",
"in",
"self",
".",
"broaden",
"(",
")",
":",
"tag",
"=",
"broader",
".",
"to_tag... | The Unicode CLDR contains a "likelySubtags" data file, which can guess
reasonable values for fields that are missing from a language tag.
This is particularly useful for comparing, for example, "zh-Hant" and
"zh-TW", two common language tags that say approximately the same thing
via rat... | [
"The",
"Unicode",
"CLDR",
"contains",
"a",
"likelySubtags",
"data",
"file",
"which",
"can",
"guess",
"reasonable",
"values",
"for",
"fields",
"that",
"are",
"missing",
"from",
"a",
"language",
"tag",
"."
] | train | https://github.com/LuminosoInsight/langcodes/blob/0cedf9ca257ebf7250de5d3a63ec33a7d198db58/langcodes/__init__.py#L477-L524 |
LuminosoInsight/langcodes | langcodes/__init__.py | Language.match_score | def match_score(self, supported: 'Language') -> int:
"""
Suppose that `self` is the language that the user desires, and
`supported` is a language that is actually supported. This method
returns a number from 0 to 100 indicating how similar the supported
language is (higher number... | python | def match_score(self, supported: 'Language') -> int:
"""
Suppose that `self` is the language that the user desires, and
`supported` is a language that is actually supported. This method
returns a number from 0 to 100 indicating how similar the supported
language is (higher number... | [
"def",
"match_score",
"(",
"self",
",",
"supported",
":",
"'Language'",
")",
"->",
"int",
":",
"if",
"supported",
"==",
"self",
":",
"return",
"100",
"desired_complete",
"=",
"self",
".",
"prefer_macrolanguage",
"(",
")",
".",
"maximize",
"(",
")",
"suppor... | Suppose that `self` is the language that the user desires, and
`supported` is a language that is actually supported. This method
returns a number from 0 to 100 indicating how similar the supported
language is (higher numbers are better). This is not a symmetric
relation.
The alg... | [
"Suppose",
"that",
"self",
"is",
"the",
"language",
"that",
"the",
"user",
"desires",
"and",
"supported",
"is",
"a",
"language",
"that",
"is",
"actually",
"supported",
".",
"This",
"method",
"returns",
"a",
"number",
"from",
"0",
"to",
"100",
"indicating",
... | train | https://github.com/LuminosoInsight/langcodes/blob/0cedf9ca257ebf7250de5d3a63ec33a7d198db58/langcodes/__init__.py#L529-L555 |
LuminosoInsight/langcodes | langcodes/__init__.py | Language.language_name | def language_name(self, language=DEFAULT_LANGUAGE, min_score: int=75) -> str:
"""
Give the name of the language (not the entire tag, just the language part)
in a natural language. The target language can be given as a string or
another Language object.
By default, things are nam... | python | def language_name(self, language=DEFAULT_LANGUAGE, min_score: int=75) -> str:
"""
Give the name of the language (not the entire tag, just the language part)
in a natural language. The target language can be given as a string or
another Language object.
By default, things are nam... | [
"def",
"language_name",
"(",
"self",
",",
"language",
"=",
"DEFAULT_LANGUAGE",
",",
"min_score",
":",
"int",
"=",
"75",
")",
"->",
"str",
":",
"return",
"self",
".",
"_get_name",
"(",
"'language'",
",",
"language",
",",
"min_score",
")"
] | Give the name of the language (not the entire tag, just the language part)
in a natural language. The target language can be given as a string or
another Language object.
By default, things are named in English:
>>> Language.get('fr').language_name()
'French'
>>> Langua... | [
"Give",
"the",
"name",
"of",
"the",
"language",
"(",
"not",
"the",
"entire",
"tag",
"just",
"the",
"language",
"part",
")",
"in",
"a",
"natural",
"language",
".",
"The",
"target",
"language",
"can",
"be",
"given",
"as",
"a",
"string",
"or",
"another",
... | train | https://github.com/LuminosoInsight/langcodes/blob/0cedf9ca257ebf7250de5d3a63ec33a7d198db58/langcodes/__init__.py#L578-L609 |
LuminosoInsight/langcodes | langcodes/__init__.py | Language.autonym | def autonym(self, min_score: int=95) -> str:
"""
Give the name of this language *in* this language.
>>> Language.get('fr').autonym()
'français'
>>> Language.get('es').autonym()
'español'
>>> Language.get('ja').autonym()
'日本語'
This doesn't give th... | python | def autonym(self, min_score: int=95) -> str:
"""
Give the name of this language *in* this language.
>>> Language.get('fr').autonym()
'français'
>>> Language.get('es').autonym()
'español'
>>> Language.get('ja').autonym()
'日本語'
This doesn't give th... | [
"def",
"autonym",
"(",
"self",
",",
"min_score",
":",
"int",
"=",
"95",
")",
"->",
"str",
":",
"return",
"self",
".",
"language_name",
"(",
"language",
"=",
"self",
",",
"min_score",
"=",
"min_score",
")"
] | Give the name of this language *in* this language.
>>> Language.get('fr').autonym()
'français'
>>> Language.get('es').autonym()
'español'
>>> Language.get('ja').autonym()
'日本語'
This doesn't give the name of the region or script, but in some cases
the lan... | [
"Give",
"the",
"name",
"of",
"this",
"language",
"*",
"in",
"*",
"this",
"language",
"."
] | train | https://github.com/LuminosoInsight/langcodes/blob/0cedf9ca257ebf7250de5d3a63ec33a7d198db58/langcodes/__init__.py#L611-L637 |
LuminosoInsight/langcodes | langcodes/__init__.py | Language.script_name | def script_name(self, language=DEFAULT_LANGUAGE, min_score: int=75) -> str:
"""
Describe the script part of the language tag in a natural language.
"""
return self._get_name('script', language, min_score) | python | def script_name(self, language=DEFAULT_LANGUAGE, min_score: int=75) -> str:
"""
Describe the script part of the language tag in a natural language.
"""
return self._get_name('script', language, min_score) | [
"def",
"script_name",
"(",
"self",
",",
"language",
"=",
"DEFAULT_LANGUAGE",
",",
"min_score",
":",
"int",
"=",
"75",
")",
"->",
"str",
":",
"return",
"self",
".",
"_get_name",
"(",
"'script'",
",",
"language",
",",
"min_score",
")"
] | Describe the script part of the language tag in a natural language. | [
"Describe",
"the",
"script",
"part",
"of",
"the",
"language",
"tag",
"in",
"a",
"natural",
"language",
"."
] | train | https://github.com/LuminosoInsight/langcodes/blob/0cedf9ca257ebf7250de5d3a63ec33a7d198db58/langcodes/__init__.py#L639-L643 |
LuminosoInsight/langcodes | langcodes/__init__.py | Language.region_name | def region_name(self, language=DEFAULT_LANGUAGE, min_score: int=75) -> str:
"""
Describe the region part of the language tag in a natural language.
"""
return self._get_name('region', language, min_score) | python | def region_name(self, language=DEFAULT_LANGUAGE, min_score: int=75) -> str:
"""
Describe the region part of the language tag in a natural language.
"""
return self._get_name('region', language, min_score) | [
"def",
"region_name",
"(",
"self",
",",
"language",
"=",
"DEFAULT_LANGUAGE",
",",
"min_score",
":",
"int",
"=",
"75",
")",
"->",
"str",
":",
"return",
"self",
".",
"_get_name",
"(",
"'region'",
",",
"language",
",",
"min_score",
")"
] | Describe the region part of the language tag in a natural language. | [
"Describe",
"the",
"region",
"part",
"of",
"the",
"language",
"tag",
"in",
"a",
"natural",
"language",
"."
] | train | https://github.com/LuminosoInsight/langcodes/blob/0cedf9ca257ebf7250de5d3a63ec33a7d198db58/langcodes/__init__.py#L645-L649 |
LuminosoInsight/langcodes | langcodes/__init__.py | Language.variant_names | def variant_names(self, language=DEFAULT_LANGUAGE, min_score: int=75) -> list:
"""
Describe each of the variant parts of the language tag in a natural
language.
"""
names = []
for variant in self.variants:
var_names = code_to_names('variant', variant)
... | python | def variant_names(self, language=DEFAULT_LANGUAGE, min_score: int=75) -> list:
"""
Describe each of the variant parts of the language tag in a natural
language.
"""
names = []
for variant in self.variants:
var_names = code_to_names('variant', variant)
... | [
"def",
"variant_names",
"(",
"self",
",",
"language",
"=",
"DEFAULT_LANGUAGE",
",",
"min_score",
":",
"int",
"=",
"75",
")",
"->",
"list",
":",
"names",
"=",
"[",
"]",
"for",
"variant",
"in",
"self",
".",
"variants",
":",
"var_names",
"=",
"code_to_names... | Describe each of the variant parts of the language tag in a natural
language. | [
"Describe",
"each",
"of",
"the",
"variant",
"parts",
"of",
"the",
"language",
"tag",
"in",
"a",
"natural",
"language",
"."
] | train | https://github.com/LuminosoInsight/langcodes/blob/0cedf9ca257ebf7250de5d3a63ec33a7d198db58/langcodes/__init__.py#L651-L660 |
LuminosoInsight/langcodes | langcodes/__init__.py | Language.describe | def describe(self, language=DEFAULT_LANGUAGE, min_score: int=75) -> dict:
"""
Return a dictionary that describes a given language tag in a specified
natural language.
See `language_name` and related methods for more specific versions of this.
The desired `language` will in fact... | python | def describe(self, language=DEFAULT_LANGUAGE, min_score: int=75) -> dict:
"""
Return a dictionary that describes a given language tag in a specified
natural language.
See `language_name` and related methods for more specific versions of this.
The desired `language` will in fact... | [
"def",
"describe",
"(",
"self",
",",
"language",
"=",
"DEFAULT_LANGUAGE",
",",
"min_score",
":",
"int",
"=",
"75",
")",
"->",
"dict",
":",
"names",
"=",
"{",
"}",
"if",
"self",
".",
"language",
":",
"names",
"[",
"'language'",
"]",
"=",
"self",
".",
... | Return a dictionary that describes a given language tag in a specified
natural language.
See `language_name` and related methods for more specific versions of this.
The desired `language` will in fact be matched against the available
options using the matching technique that this modul... | [
"Return",
"a",
"dictionary",
"that",
"describes",
"a",
"given",
"language",
"tag",
"in",
"a",
"specified",
"natural",
"language",
"."
] | train | https://github.com/LuminosoInsight/langcodes/blob/0cedf9ca257ebf7250de5d3a63ec33a7d198db58/langcodes/__init__.py#L662-L727 |
LuminosoInsight/langcodes | langcodes/__init__.py | Language.find_name | def find_name(tagtype: str, name: str, language: {str, 'Language', None}=None):
"""
Find the subtag of a particular `tagtype` that has the given `name`.
The default language, "und", will allow matching names in any language,
so you can get the code 'fr' by looking up "French", "Français... | python | def find_name(tagtype: str, name: str, language: {str, 'Language', None}=None):
"""
Find the subtag of a particular `tagtype` that has the given `name`.
The default language, "und", will allow matching names in any language,
so you can get the code 'fr' by looking up "French", "Français... | [
"def",
"find_name",
"(",
"tagtype",
":",
"str",
",",
"name",
":",
"str",
",",
"language",
":",
"{",
"str",
",",
"'Language'",
",",
"None",
"}",
"=",
"None",
")",
":",
"# No matter what form of language we got, normalize it to a single",
"# language subtag",
"if",
... | Find the subtag of a particular `tagtype` that has the given `name`.
The default language, "und", will allow matching names in any language,
so you can get the code 'fr' by looking up "French", "Français", or
"francés".
Occasionally, names are ambiguous in a way that can be resolved by... | [
"Find",
"the",
"subtag",
"of",
"a",
"particular",
"tagtype",
"that",
"has",
"the",
"given",
"name",
"."
] | train | https://github.com/LuminosoInsight/langcodes/blob/0cedf9ca257ebf7250de5d3a63ec33a7d198db58/langcodes/__init__.py#L730-L817 |
LuminosoInsight/langcodes | langcodes/__init__.py | Language.to_dict | def to_dict(self):
"""
Get a dictionary of the attributes of this Language object, which
can be useful for constructing a similar object.
"""
if self._dict is not None:
return self._dict
result = {}
for key in self.ATTRIBUTES:
value = geta... | python | def to_dict(self):
"""
Get a dictionary of the attributes of this Language object, which
can be useful for constructing a similar object.
"""
if self._dict is not None:
return self._dict
result = {}
for key in self.ATTRIBUTES:
value = geta... | [
"def",
"to_dict",
"(",
"self",
")",
":",
"if",
"self",
".",
"_dict",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_dict",
"result",
"=",
"{",
"}",
"for",
"key",
"in",
"self",
".",
"ATTRIBUTES",
":",
"value",
"=",
"getattr",
"(",
"self",
",",
... | Get a dictionary of the attributes of this Language object, which
can be useful for constructing a similar object. | [
"Get",
"a",
"dictionary",
"of",
"the",
"attributes",
"of",
"this",
"Language",
"object",
"which",
"can",
"be",
"useful",
"for",
"constructing",
"a",
"similar",
"object",
"."
] | train | https://github.com/LuminosoInsight/langcodes/blob/0cedf9ca257ebf7250de5d3a63ec33a7d198db58/langcodes/__init__.py#L845-L859 |
LuminosoInsight/langcodes | langcodes/__init__.py | Language.update | def update(self, other: 'Language') -> 'Language':
"""
Update this Language with the fields of another Language.
"""
return Language.make(
language=other.language or self.language,
extlangs=other.extlangs or self.extlangs,
script=other.script or self.s... | python | def update(self, other: 'Language') -> 'Language':
"""
Update this Language with the fields of another Language.
"""
return Language.make(
language=other.language or self.language,
extlangs=other.extlangs or self.extlangs,
script=other.script or self.s... | [
"def",
"update",
"(",
"self",
",",
"other",
":",
"'Language'",
")",
"->",
"'Language'",
":",
"return",
"Language",
".",
"make",
"(",
"language",
"=",
"other",
".",
"language",
"or",
"self",
".",
"language",
",",
"extlangs",
"=",
"other",
".",
"extlangs",... | Update this Language with the fields of another Language. | [
"Update",
"this",
"Language",
"with",
"the",
"fields",
"of",
"another",
"Language",
"."
] | train | https://github.com/LuminosoInsight/langcodes/blob/0cedf9ca257ebf7250de5d3a63ec33a7d198db58/langcodes/__init__.py#L861-L873 |
LuminosoInsight/langcodes | langcodes/__init__.py | Language.update_dict | def update_dict(self, newdata: dict) -> 'Language':
"""
Update the attributes of this Language from a dictionary.
"""
return Language.make(
language=newdata.get('language', self.language),
extlangs=newdata.get('extlangs', self.extlangs),
script=newdata... | python | def update_dict(self, newdata: dict) -> 'Language':
"""
Update the attributes of this Language from a dictionary.
"""
return Language.make(
language=newdata.get('language', self.language),
extlangs=newdata.get('extlangs', self.extlangs),
script=newdata... | [
"def",
"update_dict",
"(",
"self",
",",
"newdata",
":",
"dict",
")",
"->",
"'Language'",
":",
"return",
"Language",
".",
"make",
"(",
"language",
"=",
"newdata",
".",
"get",
"(",
"'language'",
",",
"self",
".",
"language",
")",
",",
"extlangs",
"=",
"n... | Update the attributes of this Language from a dictionary. | [
"Update",
"the",
"attributes",
"of",
"this",
"Language",
"from",
"a",
"dictionary",
"."
] | train | https://github.com/LuminosoInsight/langcodes/blob/0cedf9ca257ebf7250de5d3a63ec33a7d198db58/langcodes/__init__.py#L875-L887 |
LuminosoInsight/langcodes | langcodes/__init__.py | Language._filter_keys | def _filter_keys(d: dict, keys: set) -> dict:
"""
Select a subset of keys from a dictionary.
"""
return {key: d[key] for key in keys if key in d} | python | def _filter_keys(d: dict, keys: set) -> dict:
"""
Select a subset of keys from a dictionary.
"""
return {key: d[key] for key in keys if key in d} | [
"def",
"_filter_keys",
"(",
"d",
":",
"dict",
",",
"keys",
":",
"set",
")",
"->",
"dict",
":",
"return",
"{",
"key",
":",
"d",
"[",
"key",
"]",
"for",
"key",
"in",
"keys",
"if",
"key",
"in",
"d",
"}"
] | Select a subset of keys from a dictionary. | [
"Select",
"a",
"subset",
"of",
"keys",
"from",
"a",
"dictionary",
"."
] | train | https://github.com/LuminosoInsight/langcodes/blob/0cedf9ca257ebf7250de5d3a63ec33a7d198db58/langcodes/__init__.py#L890-L894 |
LuminosoInsight/langcodes | langcodes/__init__.py | Language._filter_attributes | def _filter_attributes(self, keyset):
"""
Return a copy of this object with a subset of its attributes set.
"""
filtered = self._filter_keys(self.to_dict(), keyset)
return Language.make(**filtered) | python | def _filter_attributes(self, keyset):
"""
Return a copy of this object with a subset of its attributes set.
"""
filtered = self._filter_keys(self.to_dict(), keyset)
return Language.make(**filtered) | [
"def",
"_filter_attributes",
"(",
"self",
",",
"keyset",
")",
":",
"filtered",
"=",
"self",
".",
"_filter_keys",
"(",
"self",
".",
"to_dict",
"(",
")",
",",
"keyset",
")",
"return",
"Language",
".",
"make",
"(",
"*",
"*",
"filtered",
")"
] | Return a copy of this object with a subset of its attributes set. | [
"Return",
"a",
"copy",
"of",
"this",
"object",
"with",
"a",
"subset",
"of",
"its",
"attributes",
"set",
"."
] | train | https://github.com/LuminosoInsight/langcodes/blob/0cedf9ca257ebf7250de5d3a63ec33a7d198db58/langcodes/__init__.py#L896-L901 |
LuminosoInsight/langcodes | langcodes/__init__.py | Language._searchable_form | def _searchable_form(self) -> 'Language':
"""
Convert a parsed language tag so that the information it contains is in
the best form for looking up information in the CLDR.
"""
if self._searchable is not None:
return self._searchable
self._searchable = self._f... | python | def _searchable_form(self) -> 'Language':
"""
Convert a parsed language tag so that the information it contains is in
the best form for looking up information in the CLDR.
"""
if self._searchable is not None:
return self._searchable
self._searchable = self._f... | [
"def",
"_searchable_form",
"(",
"self",
")",
"->",
"'Language'",
":",
"if",
"self",
".",
"_searchable",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_searchable",
"self",
".",
"_searchable",
"=",
"self",
".",
"_filter_attributes",
"(",
"{",
"'language'"... | Convert a parsed language tag so that the information it contains is in
the best form for looking up information in the CLDR. | [
"Convert",
"a",
"parsed",
"language",
"tag",
"so",
"that",
"the",
"information",
"it",
"contains",
"is",
"in",
"the",
"best",
"form",
"for",
"looking",
"up",
"information",
"in",
"the",
"CLDR",
"."
] | train | https://github.com/LuminosoInsight/langcodes/blob/0cedf9ca257ebf7250de5d3a63ec33a7d198db58/langcodes/__init__.py#L903-L914 |
LuminosoInsight/langcodes | langcodes/build_data.py | resolve_name | def resolve_name(key, vals, debug=False):
"""
Given a name, and a number of possible values it could resolve to,
find the single value it should resolve to, in the following way:
- Apply the priority order
- If names with the highest priority all agree, use that name
- If there is disagreement ... | python | def resolve_name(key, vals, debug=False):
"""
Given a name, and a number of possible values it could resolve to,
find the single value it should resolve to, in the following way:
- Apply the priority order
- If names with the highest priority all agree, use that name
- If there is disagreement ... | [
"def",
"resolve_name",
"(",
"key",
",",
"vals",
",",
"debug",
"=",
"False",
")",
":",
"max_priority",
"=",
"max",
"(",
"[",
"val",
"[",
"2",
"]",
"for",
"val",
"in",
"vals",
"]",
")",
"val_count",
"=",
"Counter",
"(",
"[",
"val",
"[",
"1",
"]",
... | Given a name, and a number of possible values it could resolve to,
find the single value it should resolve to, in the following way:
- Apply the priority order
- If names with the highest priority all agree, use that name
- If there is disagreement that can be resolved by AMBIGUOUS_PREFERENCES,
u... | [
"Given",
"a",
"name",
"and",
"a",
"number",
"of",
"possible",
"values",
"it",
"could",
"resolve",
"to",
"find",
"the",
"single",
"value",
"it",
"should",
"resolve",
"to",
"in",
"the",
"following",
"way",
":"
] | train | https://github.com/LuminosoInsight/langcodes/blob/0cedf9ca257ebf7250de5d3a63ec33a7d198db58/langcodes/build_data.py#L141-L180 |
LuminosoInsight/langcodes | langcodes/build_data.py | read_cldr_names | def read_cldr_names(path, language, category):
"""
Read CLDR's names for things in a particular language.
"""
filename = data_filename('{}/{}/{}.json'.format(path, language, category))
fulldata = json.load(open(filename, encoding='utf-8'))
data = fulldata['main'][language]['localeDisplayNames'][... | python | def read_cldr_names(path, language, category):
"""
Read CLDR's names for things in a particular language.
"""
filename = data_filename('{}/{}/{}.json'.format(path, language, category))
fulldata = json.load(open(filename, encoding='utf-8'))
data = fulldata['main'][language]['localeDisplayNames'][... | [
"def",
"read_cldr_names",
"(",
"path",
",",
"language",
",",
"category",
")",
":",
"filename",
"=",
"data_filename",
"(",
"'{}/{}/{}.json'",
".",
"format",
"(",
"path",
",",
"language",
",",
"category",
")",
")",
"fulldata",
"=",
"json",
".",
"load",
"(",
... | Read CLDR's names for things in a particular language. | [
"Read",
"CLDR",
"s",
"names",
"for",
"things",
"in",
"a",
"particular",
"language",
"."
] | train | https://github.com/LuminosoInsight/langcodes/blob/0cedf9ca257ebf7250de5d3a63ec33a7d198db58/langcodes/build_data.py#L192-L199 |
LuminosoInsight/langcodes | langcodes/registry_parser.py | parse_file | def parse_file(file):
"""
Take an open file containing the IANA subtag registry, and yield a
dictionary of information for each subtag it describes.
"""
lines = []
for line in file:
line = line.rstrip('\n')
if line == '%%':
# This is a separator between items. Parse t... | python | def parse_file(file):
"""
Take an open file containing the IANA subtag registry, and yield a
dictionary of information for each subtag it describes.
"""
lines = []
for line in file:
line = line.rstrip('\n')
if line == '%%':
# This is a separator between items. Parse t... | [
"def",
"parse_file",
"(",
"file",
")",
":",
"lines",
"=",
"[",
"]",
"for",
"line",
"in",
"file",
":",
"line",
"=",
"line",
".",
"rstrip",
"(",
"'\\n'",
")",
"if",
"line",
"==",
"'%%'",
":",
"# This is a separator between items. Parse the data we've",
"# coll... | Take an open file containing the IANA subtag registry, and yield a
dictionary of information for each subtag it describes. | [
"Take",
"an",
"open",
"file",
"containing",
"the",
"IANA",
"subtag",
"registry",
"and",
"yield",
"a",
"dictionary",
"of",
"information",
"for",
"each",
"subtag",
"it",
"describes",
"."
] | train | https://github.com/LuminosoInsight/langcodes/blob/0cedf9ca257ebf7250de5d3a63ec33a7d198db58/langcodes/registry_parser.py#L6-L25 |
LuminosoInsight/langcodes | langcodes/registry_parser.py | parse_item | def parse_item(lines):
"""
Given the lines that form a subtag entry (after joining wrapped lines
back together), parse the data they contain.
Returns a generator that yields once if there was any data there
(and an empty generator if this was just the header).
"""
info = {}
for line... | python | def parse_item(lines):
"""
Given the lines that form a subtag entry (after joining wrapped lines
back together), parse the data they contain.
Returns a generator that yields once if there was any data there
(and an empty generator if this was just the header).
"""
info = {}
for line... | [
"def",
"parse_item",
"(",
"lines",
")",
":",
"info",
"=",
"{",
"}",
"for",
"line",
"in",
"lines",
":",
"key",
",",
"value",
"=",
"line",
".",
"split",
"(",
"': '",
",",
"1",
")",
"if",
"key",
"in",
"LIST_KEYS",
":",
"info",
".",
"setdefault",
"("... | Given the lines that form a subtag entry (after joining wrapped lines
back together), parse the data they contain.
Returns a generator that yields once if there was any data there
(and an empty generator if this was just the header). | [
"Given",
"the",
"lines",
"that",
"form",
"a",
"subtag",
"entry",
"(",
"after",
"joining",
"wrapped",
"lines",
"back",
"together",
")",
"parse",
"the",
"data",
"they",
"contain",
".",
"Returns",
"a",
"generator",
"that",
"yields",
"once",
"if",
"there",
"wa... | train | https://github.com/LuminosoInsight/langcodes/blob/0cedf9ca257ebf7250de5d3a63ec33a7d198db58/langcodes/registry_parser.py#L28-L46 |
LuminosoInsight/langcodes | langcodes/distance.py | _make_simple_distances | def _make_simple_distances():
"""
This is a translation of the non-wildcard rules in
http://www.unicode.org/cldr/charts/29/supplemental/language_matching.html.
It defines a few functions to make the chart easy to mindlessly transcribe,
instead of having to parse it out of idiosyncratic XML or HTML,... | python | def _make_simple_distances():
"""
This is a translation of the non-wildcard rules in
http://www.unicode.org/cldr/charts/29/supplemental/language_matching.html.
It defines a few functions to make the chart easy to mindlessly transcribe,
instead of having to parse it out of idiosyncratic XML or HTML,... | [
"def",
"_make_simple_distances",
"(",
")",
":",
"distances",
"=",
"{",
"}",
"def",
"sym",
"(",
"desired",
",",
"supported",
",",
"strength",
")",
":",
"\"Define a symmetric distance between languages.\"",
"desired_t",
"=",
"tuple",
"(",
"desired",
".",
"split",
... | This is a translation of the non-wildcard rules in
http://www.unicode.org/cldr/charts/29/supplemental/language_matching.html.
It defines a few functions to make the chart easy to mindlessly transcribe,
instead of having to parse it out of idiosyncratic XML or HTML, which
actually seems harder. | [
"This",
"is",
"a",
"translation",
"of",
"the",
"non",
"-",
"wildcard",
"rules",
"in",
"http",
":",
"//",
"www",
".",
"unicode",
".",
"org",
"/",
"cldr",
"/",
"charts",
"/",
"29",
"/",
"supplemental",
"/",
"language_matching",
".",
"html",
"."
] | train | https://github.com/LuminosoInsight/langcodes/blob/0cedf9ca257ebf7250de5d3a63ec33a7d198db58/langcodes/distance.py#L12-L182 |
LuminosoInsight/langcodes | langcodes/names.py | normalize_name | def normalize_name(name):
"""
When looking up a language-code component by name, we would rather ignore
distinctions of case and certain punctuation. "Chinese (Traditional)"
should be matched by "Chinese Traditional" and "chinese traditional".
"""
name = name.casefold()
name = name.replace("... | python | def normalize_name(name):
"""
When looking up a language-code component by name, we would rather ignore
distinctions of case and certain punctuation. "Chinese (Traditional)"
should be matched by "Chinese Traditional" and "chinese traditional".
"""
name = name.casefold()
name = name.replace("... | [
"def",
"normalize_name",
"(",
"name",
")",
":",
"name",
"=",
"name",
".",
"casefold",
"(",
")",
"name",
"=",
"name",
".",
"replace",
"(",
"\"’\", ",
"\"",
"\")",
"",
"name",
"=",
"name",
".",
"replace",
"(",
"\"-\"",
",",
"\" \"",
")",
"name",
"=",... | When looking up a language-code component by name, we would rather ignore
distinctions of case and certain punctuation. "Chinese (Traditional)"
should be matched by "Chinese Traditional" and "chinese traditional". | [
"When",
"looking",
"up",
"a",
"language",
"-",
"code",
"component",
"by",
"name",
"we",
"would",
"rather",
"ignore",
"distinctions",
"of",
"case",
"and",
"certain",
"punctuation",
".",
"Chinese",
"(",
"Traditional",
")",
"should",
"be",
"matched",
"by",
"Chi... | train | https://github.com/LuminosoInsight/langcodes/blob/0cedf9ca257ebf7250de5d3a63ec33a7d198db58/langcodes/names.py#L12-L24 |
LuminosoInsight/langcodes | langcodes/names.py | load_trie | def load_trie(filename):
"""
Load a BytesTrie from the marisa_trie on-disk format.
"""
trie = marisa_trie.BytesTrie()
# marisa_trie raises warnings that make no sense. Ignore them.
with warnings.catch_warnings():
warnings.simplefilter("ignore")
trie.load(filename)
return trie | python | def load_trie(filename):
"""
Load a BytesTrie from the marisa_trie on-disk format.
"""
trie = marisa_trie.BytesTrie()
# marisa_trie raises warnings that make no sense. Ignore them.
with warnings.catch_warnings():
warnings.simplefilter("ignore")
trie.load(filename)
return trie | [
"def",
"load_trie",
"(",
"filename",
")",
":",
"trie",
"=",
"marisa_trie",
".",
"BytesTrie",
"(",
")",
"# marisa_trie raises warnings that make no sense. Ignore them.",
"with",
"warnings",
".",
"catch_warnings",
"(",
")",
":",
"warnings",
".",
"simplefilter",
"(",
"... | Load a BytesTrie from the marisa_trie on-disk format. | [
"Load",
"a",
"BytesTrie",
"from",
"the",
"marisa_trie",
"on",
"-",
"disk",
"format",
"."
] | train | https://github.com/LuminosoInsight/langcodes/blob/0cedf9ca257ebf7250de5d3a63ec33a7d198db58/langcodes/names.py#L27-L36 |
LuminosoInsight/langcodes | langcodes/names.py | name_to_code | def name_to_code(category, name, language: str='und'):
"""
Get a language, script, or region by its name in some language.
The language here must be a string representing a language subtag only.
The `Language.find` method can handle other representations of a language
and normalize them to this for... | python | def name_to_code(category, name, language: str='und'):
"""
Get a language, script, or region by its name in some language.
The language here must be a string representing a language subtag only.
The `Language.find` method can handle other representations of a language
and normalize them to this for... | [
"def",
"name_to_code",
"(",
"category",
",",
"name",
",",
"language",
":",
"str",
"=",
"'und'",
")",
":",
"assert",
"'/'",
"not",
"in",
"language",
",",
"\"Language codes cannot contain slashes\"",
"assert",
"'-'",
"not",
"in",
"language",
",",
"\"This code shou... | Get a language, script, or region by its name in some language.
The language here must be a string representing a language subtag only.
The `Language.find` method can handle other representations of a language
and normalize them to this form.
The default language, "und", will allow matching names in a... | [
"Get",
"a",
"language",
"script",
"or",
"region",
"by",
"its",
"name",
"in",
"some",
"language",
"."
] | train | https://github.com/LuminosoInsight/langcodes/blob/0cedf9ca257ebf7250de5d3a63ec33a7d198db58/langcodes/names.py#L47-L86 |
LuminosoInsight/langcodes | langcodes/names.py | code_to_names | def code_to_names(category, code):
"""
Given the code for a language, script, or region, get a dictionary of its
names in various languages.
"""
trie_name = '{}_to_name'.format(category)
if trie_name not in TRIES:
TRIES[trie_name] = load_trie(data_filename('trie/{}.marisa'.format(trie_na... | python | def code_to_names(category, code):
"""
Given the code for a language, script, or region, get a dictionary of its
names in various languages.
"""
trie_name = '{}_to_name'.format(category)
if trie_name not in TRIES:
TRIES[trie_name] = load_trie(data_filename('trie/{}.marisa'.format(trie_na... | [
"def",
"code_to_names",
"(",
"category",
",",
"code",
")",
":",
"trie_name",
"=",
"'{}_to_name'",
".",
"format",
"(",
"category",
")",
"if",
"trie_name",
"not",
"in",
"TRIES",
":",
"TRIES",
"[",
"trie_name",
"]",
"=",
"load_trie",
"(",
"data_filename",
"("... | Given the code for a language, script, or region, get a dictionary of its
names in various languages. | [
"Given",
"the",
"code",
"for",
"a",
"language",
"script",
"or",
"region",
"get",
"a",
"dictionary",
"of",
"its",
"names",
"in",
"various",
"languages",
"."
] | train | https://github.com/LuminosoInsight/langcodes/blob/0cedf9ca257ebf7250de5d3a63ec33a7d198db58/langcodes/names.py#L89-L105 |
Ezhil-Language-Foundation/open-tamil | tamil/txt2unicode/unicode2encode.py | unicode2encode | def unicode2encode(text, charmap):
'''
charmap : dictionary which has both encode as key, unicode as value
'''
if isinstance(text, (list, tuple)):
unitxt = ''
for line in text:
for val,key in charmap.items():
if key in line:
line =... | python | def unicode2encode(text, charmap):
'''
charmap : dictionary which has both encode as key, unicode as value
'''
if isinstance(text, (list, tuple)):
unitxt = ''
for line in text:
for val,key in charmap.items():
if key in line:
line =... | [
"def",
"unicode2encode",
"(",
"text",
",",
"charmap",
")",
":",
"if",
"isinstance",
"(",
"text",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"unitxt",
"=",
"''",
"for",
"line",
"in",
"text",
":",
"for",
"val",
",",
"key",
"in",
"charmap",
".",
... | charmap : dictionary which has both encode as key, unicode as value | [
"charmap",
":",
"dictionary",
"which",
"has",
"both",
"encode",
"as",
"key",
"unicode",
"as",
"value"
] | train | https://github.com/Ezhil-Language-Foundation/open-tamil/blob/b7556e88878d29bbc6c944ee17cdd3f75b8ea9f0/tamil/txt2unicode/unicode2encode.py#L47-L65 |
Ezhil-Language-Foundation/open-tamil | tamil/txt2unicode/unicode2encode.py | unicode2auto | def unicode2auto(unicode_text, encode_text):
"""
This function will convert unicode (first argument) text into other
encodes by auto find the encode (from available encodes) by using sample
encode text in second argument of this function.
unicode_text : Pass unicode string which has to conver... | python | def unicode2auto(unicode_text, encode_text):
"""
This function will convert unicode (first argument) text into other
encodes by auto find the encode (from available encodes) by using sample
encode text in second argument of this function.
unicode_text : Pass unicode string which has to conver... | [
"def",
"unicode2auto",
"(",
"unicode_text",
",",
"encode_text",
")",
":",
"_all_unique_encodes_",
",",
"_all_common_encodes_",
"=",
"_get_unique_common_encodes",
"(",
")",
"# get unique word which falls under any one of available encodes from\r",
"# user passed text lines\r",
"uniq... | This function will convert unicode (first argument) text into other
encodes by auto find the encode (from available encodes) by using sample
encode text in second argument of this function.
unicode_text : Pass unicode string which has to convert into other encode.
encode_text : Pass sample encode ... | [
"This",
"function",
"will",
"convert",
"unicode",
"(",
"first",
"argument",
")",
"text",
"into",
"other",
"encodes",
"by",
"auto",
"find",
"the",
"encode",
"(",
"from",
"available",
"encodes",
")",
"by",
"using",
"sample",
"encode",
"text",
"in",
"second",
... | train | https://github.com/Ezhil-Language-Foundation/open-tamil/blob/b7556e88878d29bbc6c944ee17cdd3f75b8ea9f0/tamil/txt2unicode/unicode2encode.py#L151-L196 |
Ezhil-Language-Foundation/open-tamil | examples/tamilmorse/huffman.py | print_huffman_code_cwl | def print_huffman_code_cwl(code,p,v):
""" code - code dictionary with symbol -> code map, p, v is probability map """
cwl = 0.0
for k,_v in code.items():
print(u"%s -> %s"%(k,_v))
cwl += p[v.index(k)]*len(_v)
print(u"cwl = %g"%cwl)
return cwl,code.values() | python | def print_huffman_code_cwl(code,p,v):
""" code - code dictionary with symbol -> code map, p, v is probability map """
cwl = 0.0
for k,_v in code.items():
print(u"%s -> %s"%(k,_v))
cwl += p[v.index(k)]*len(_v)
print(u"cwl = %g"%cwl)
return cwl,code.values() | [
"def",
"print_huffman_code_cwl",
"(",
"code",
",",
"p",
",",
"v",
")",
":",
"cwl",
"=",
"0.0",
"for",
"k",
",",
"_v",
"in",
"code",
".",
"items",
"(",
")",
":",
"print",
"(",
"u\"%s -> %s\"",
"%",
"(",
"k",
",",
"_v",
")",
")",
"cwl",
"+=",
"p"... | code - code dictionary with symbol -> code map, p, v is probability map | [
"code",
"-",
"code",
"dictionary",
"with",
"symbol",
"-",
">",
"code",
"map",
"p",
"v",
"is",
"probability",
"map"
] | train | https://github.com/Ezhil-Language-Foundation/open-tamil/blob/b7556e88878d29bbc6c944ee17cdd3f75b8ea9f0/examples/tamilmorse/huffman.py#L77-L84 |
Ezhil-Language-Foundation/open-tamil | ngram/Distance.py | edit_distance | def edit_distance(wordA,wordB):
"""" Implements Daegmar-Levenshtein edit distance algorithm:
Ref: https://en.wikipedia.org/wiki/Edit_distance
Ref: https://en.wikipedia.org/wiki/Levenshtein_distance"""
if not type(wordA) is list:
lettersA = tamil.utf8.get_letters(wordA)
else:
... | python | def edit_distance(wordA,wordB):
"""" Implements Daegmar-Levenshtein edit distance algorithm:
Ref: https://en.wikipedia.org/wiki/Edit_distance
Ref: https://en.wikipedia.org/wiki/Levenshtein_distance"""
if not type(wordA) is list:
lettersA = tamil.utf8.get_letters(wordA)
else:
... | [
"def",
"edit_distance",
"(",
"wordA",
",",
"wordB",
")",
":",
"if",
"not",
"type",
"(",
"wordA",
")",
"is",
"list",
":",
"lettersA",
"=",
"tamil",
".",
"utf8",
".",
"get_letters",
"(",
"wordA",
")",
"else",
":",
"lettersA",
"=",
"wordA",
"if",
"not",... | Implements Daegmar-Levenshtein edit distance algorithm:
Ref: https://en.wikipedia.org/wiki/Edit_distance
Ref: https://en.wikipedia.org/wiki/Levenshtein_distance | [
"Implements",
"Daegmar",
"-",
"Levenshtein",
"edit",
"distance",
"algorithm",
":",
"Ref",
":",
"https",
":",
"//",
"en",
".",
"wikipedia",
".",
"org",
"/",
"wiki",
"/",
"Edit_distance",
"Ref",
":",
"https",
":",
"//",
"en",
".",
"wikipedia",
".",
"org",
... | train | https://github.com/Ezhil-Language-Foundation/open-tamil/blob/b7556e88878d29bbc6c944ee17cdd3f75b8ea9f0/ngram/Distance.py#L10-L38 |
Ezhil-Language-Foundation/open-tamil | ngram/Distance.py | Dice_coeff | def Dice_coeff(wordA,wordB):
"""
# Calculate edit-distance - Implements the Dice coefficent
# Ref: https://en.wikipedia.org/wiki/S%C3%B8rensen%E2%80%93Dice_coefficient
# distance should be between 0 - 1.0. can be used as a similarity match
"""
if not type(wordA) is list:
lett... | python | def Dice_coeff(wordA,wordB):
"""
# Calculate edit-distance - Implements the Dice coefficent
# Ref: https://en.wikipedia.org/wiki/S%C3%B8rensen%E2%80%93Dice_coefficient
# distance should be between 0 - 1.0. can be used as a similarity match
"""
if not type(wordA) is list:
lett... | [
"def",
"Dice_coeff",
"(",
"wordA",
",",
"wordB",
")",
":",
"if",
"not",
"type",
"(",
"wordA",
")",
"is",
"list",
":",
"lettersA",
"=",
"tamil",
".",
"utf8",
".",
"get_letters",
"(",
"wordA",
")",
"else",
":",
"lettersA",
"=",
"wordA",
"if",
"not",
... | # Calculate edit-distance - Implements the Dice coefficent
# Ref: https://en.wikipedia.org/wiki/S%C3%B8rensen%E2%80%93Dice_coefficient
# distance should be between 0 - 1.0. can be used as a similarity match | [
"#",
"Calculate",
"edit",
"-",
"distance",
"-",
"Implements",
"the",
"Dice",
"coefficent",
"#",
"Ref",
":",
"https",
":",
"//",
"en",
".",
"wikipedia",
".",
"org",
"/",
"wiki",
"/",
"S%C3%B8rensen%E2%80%93Dice_coefficient",
"#",
"distance",
"should",
"be",
"... | train | https://github.com/Ezhil-Language-Foundation/open-tamil/blob/b7556e88878d29bbc6c944ee17cdd3f75b8ea9f0/ngram/Distance.py#L43-L62 |
Ezhil-Language-Foundation/open-tamil | spell/spell.py | OttruSplit.generate_splits | def generate_splits(self):
"""
யாரிகழ்ந்து =
[['ய்', 'ஆரிகழ்ந்து'],
['யார்', 'இகழ்ந்து'],
['யாரிக்', 'அழ்ந்து'],
['யாரிகழ்ந்த்', 'உ']]
"""
L = len(self.letters)-1
for idx,letter in enumerate(self.letters):
... | python | def generate_splits(self):
"""
யாரிகழ்ந்து =
[['ய்', 'ஆரிகழ்ந்து'],
['யார்', 'இகழ்ந்து'],
['யாரிக்', 'அழ்ந்து'],
['யாரிகழ்ந்த்', 'உ']]
"""
L = len(self.letters)-1
for idx,letter in enumerate(self.letters):
... | [
"def",
"generate_splits",
"(",
"self",
")",
":",
"L",
"=",
"len",
"(",
"self",
".",
"letters",
")",
"-",
"1",
"for",
"idx",
",",
"letter",
"in",
"enumerate",
"(",
"self",
".",
"letters",
")",
":",
"if",
"not",
"(",
"letter",
"in",
"tamil",
".",
"... | யாரிகழ்ந்து =
[['ய்', 'ஆரிகழ்ந்து'],
['யார்', 'இகழ்ந்து'],
['யாரிக்', 'அழ்ந்து'],
['யாரிகழ்ந்த்', 'உ']] | [
"யாரிகழ்ந்து",
"=",
"[[",
"ய்",
"ஆரிகழ்ந்து",
"]",
"[",
"யார்",
"இகழ்ந்து",
"]",
"[",
"யாரிக்",
"அழ்ந்து",
"]",
"[",
"யாரிகழ்ந்த்",
"உ",
"]]"
] | train | https://github.com/Ezhil-Language-Foundation/open-tamil/blob/b7556e88878d29bbc6c944ee17cdd3f75b8ea9f0/spell/spell.py#L78-L96 |
Ezhil-Language-Foundation/open-tamil | solthiruthi/typographical.py | oridam_generate_patterns | def oridam_generate_patterns(word_in,cm,ed=1,level=0,pos=0,candidates=None):
""" ed = 1 by default, pos - internal variable for algorithm """
alternates = cm.get(word_in[pos],[])
if not candidates:
candidates = []
assert ed <= len(word_in), 'edit distance has to be comparable to word size [ins/d... | python | def oridam_generate_patterns(word_in,cm,ed=1,level=0,pos=0,candidates=None):
""" ed = 1 by default, pos - internal variable for algorithm """
alternates = cm.get(word_in[pos],[])
if not candidates:
candidates = []
assert ed <= len(word_in), 'edit distance has to be comparable to word size [ins/d... | [
"def",
"oridam_generate_patterns",
"(",
"word_in",
",",
"cm",
",",
"ed",
"=",
"1",
",",
"level",
"=",
"0",
",",
"pos",
"=",
"0",
",",
"candidates",
"=",
"None",
")",
":",
"alternates",
"=",
"cm",
".",
"get",
"(",
"word_in",
"[",
"pos",
"]",
",",
... | ed = 1 by default, pos - internal variable for algorithm | [
"ed",
"=",
"1",
"by",
"default",
"pos",
"-",
"internal",
"variable",
"for",
"algorithm"
] | train | https://github.com/Ezhil-Language-Foundation/open-tamil/blob/b7556e88878d29bbc6c944ee17cdd3f75b8ea9f0/solthiruthi/typographical.py#L20-L48 |
Ezhil-Language-Foundation/open-tamil | tamil/utf8.py | to_unicode_repr | def to_unicode_repr( _letter ):
""" helpful in situations where browser/app may recognize Unicode encoding
in the \u0b8e type syntax but not actual unicode glyph/code-point"""
# Python 2-3 compatible
return u"u'"+ u"".join( [ u"\\u%04x"%ord(l) for l in _letter ] ) + u"'" | python | def to_unicode_repr( _letter ):
""" helpful in situations where browser/app may recognize Unicode encoding
in the \u0b8e type syntax but not actual unicode glyph/code-point"""
# Python 2-3 compatible
return u"u'"+ u"".join( [ u"\\u%04x"%ord(l) for l in _letter ] ) + u"'" | [
"def",
"to_unicode_repr",
"(",
"_letter",
")",
":",
"# Python 2-3 compatible",
"return",
"u\"u'\"",
"+",
"u\"\"",
".",
"join",
"(",
"[",
"u\"\\\\u%04x\"",
"%",
"ord",
"(",
"l",
")",
"for",
"l",
"in",
"_letter",
"]",
")",
"+",
"u\"'\""
] | helpful in situations where browser/app may recognize Unicode encoding
in the \u0b8e type syntax but not actual unicode glyph/code-point | [
"helpful",
"in",
"situations",
"where",
"browser",
"/",
"app",
"may",
"recognize",
"Unicode",
"encoding",
"in",
"the",
"\\",
"u0b8e",
"type",
"syntax",
"but",
"not",
"actual",
"unicode",
"glyph",
"/",
"code",
"-",
"point"
] | train | https://github.com/Ezhil-Language-Foundation/open-tamil/blob/b7556e88878d29bbc6c944ee17cdd3f75b8ea9f0/tamil/utf8.py#L33-L37 |
Ezhil-Language-Foundation/open-tamil | tamil/utf8.py | uyirmei_constructed | def uyirmei_constructed( mei_idx, uyir_idx):
""" construct uyirmei letter give mei index and uyir index """
idx,idy = mei_idx,uyir_idx
assert ( idy >= 0 and idy < uyir_len() )
assert ( idx >= 0 and idx < 6+mei_len() )
return grantha_agaram_letters[mei_idx]+accent_symbols[uyir_idx] | python | def uyirmei_constructed( mei_idx, uyir_idx):
""" construct uyirmei letter give mei index and uyir index """
idx,idy = mei_idx,uyir_idx
assert ( idy >= 0 and idy < uyir_len() )
assert ( idx >= 0 and idx < 6+mei_len() )
return grantha_agaram_letters[mei_idx]+accent_symbols[uyir_idx] | [
"def",
"uyirmei_constructed",
"(",
"mei_idx",
",",
"uyir_idx",
")",
":",
"idx",
",",
"idy",
"=",
"mei_idx",
",",
"uyir_idx",
"assert",
"(",
"idy",
">=",
"0",
"and",
"idy",
"<",
"uyir_len",
"(",
")",
")",
"assert",
"(",
"idx",
">=",
"0",
"and",
"idx",... | construct uyirmei letter give mei index and uyir index | [
"construct",
"uyirmei",
"letter",
"give",
"mei",
"index",
"and",
"uyir",
"index"
] | train | https://github.com/Ezhil-Language-Foundation/open-tamil/blob/b7556e88878d29bbc6c944ee17cdd3f75b8ea9f0/tamil/utf8.py#L265-L270 |
Ezhil-Language-Foundation/open-tamil | tamil/utf8.py | has_english | def has_english( word_in ):
""" return True if word_in has any English letters in the string"""
return not all_tamil(word_in) and len(word_in) > 0 and any([l in word_in for l in string.ascii_letters]) | python | def has_english( word_in ):
""" return True if word_in has any English letters in the string"""
return not all_tamil(word_in) and len(word_in) > 0 and any([l in word_in for l in string.ascii_letters]) | [
"def",
"has_english",
"(",
"word_in",
")",
":",
"return",
"not",
"all_tamil",
"(",
"word_in",
")",
"and",
"len",
"(",
"word_in",
")",
">",
"0",
"and",
"any",
"(",
"[",
"l",
"in",
"word_in",
"for",
"l",
"in",
"string",
".",
"ascii_letters",
"]",
")"
] | return True if word_in has any English letters in the string | [
"return",
"True",
"if",
"word_in",
"has",
"any",
"English",
"letters",
"in",
"the",
"string"
] | train | https://github.com/Ezhil-Language-Foundation/open-tamil/blob/b7556e88878d29bbc6c944ee17cdd3f75b8ea9f0/tamil/utf8.py#L305-L307 |
Ezhil-Language-Foundation/open-tamil | tamil/utf8.py | all_tamil | def all_tamil( word_in ):
""" predicate checks if all letters of the input word are Tamil letters """
if isinstance(word_in,list):
word = word_in
else:
word = get_letters( word_in )
return all( [(letter in tamil_letters) for letter in word] ) | python | def all_tamil( word_in ):
""" predicate checks if all letters of the input word are Tamil letters """
if isinstance(word_in,list):
word = word_in
else:
word = get_letters( word_in )
return all( [(letter in tamil_letters) for letter in word] ) | [
"def",
"all_tamil",
"(",
"word_in",
")",
":",
"if",
"isinstance",
"(",
"word_in",
",",
"list",
")",
":",
"word",
"=",
"word_in",
"else",
":",
"word",
"=",
"get_letters",
"(",
"word_in",
")",
"return",
"all",
"(",
"[",
"(",
"letter",
"in",
"tamil_letter... | predicate checks if all letters of the input word are Tamil letters | [
"predicate",
"checks",
"if",
"all",
"letters",
"of",
"the",
"input",
"word",
"are",
"Tamil",
"letters"
] | train | https://github.com/Ezhil-Language-Foundation/open-tamil/blob/b7556e88878d29bbc6c944ee17cdd3f75b8ea9f0/tamil/utf8.py#L309-L315 |
Ezhil-Language-Foundation/open-tamil | tamil/utf8.py | reverse_word | def reverse_word( word ):
""" reverse a Tamil word according to letters not unicode-points """
op = get_letters( word )
op.reverse()
return u"".join(op) | python | def reverse_word( word ):
""" reverse a Tamil word according to letters not unicode-points """
op = get_letters( word )
op.reverse()
return u"".join(op) | [
"def",
"reverse_word",
"(",
"word",
")",
":",
"op",
"=",
"get_letters",
"(",
"word",
")",
"op",
".",
"reverse",
"(",
")",
"return",
"u\"\"",
".",
"join",
"(",
"op",
")"
] | reverse a Tamil word according to letters not unicode-points | [
"reverse",
"a",
"Tamil",
"word",
"according",
"to",
"letters",
"not",
"unicode",
"-",
"points"
] | train | https://github.com/Ezhil-Language-Foundation/open-tamil/blob/b7556e88878d29bbc6c944ee17cdd3f75b8ea9f0/tamil/utf8.py#L337-L341 |
Ezhil-Language-Foundation/open-tamil | tamil/utf8.py | get_letters | def get_letters( word ):
""" splits the word into a character-list of tamil/english
characters present in the stream """
ta_letters = list()
not_empty = False
WLEN,idx = len(word),0
while (idx < WLEN):
c = word[idx]
#print(idx,hex(ord(c)),len(ta_letters))
if c in uyir_let... | python | def get_letters( word ):
""" splits the word into a character-list of tamil/english
characters present in the stream """
ta_letters = list()
not_empty = False
WLEN,idx = len(word),0
while (idx < WLEN):
c = word[idx]
#print(idx,hex(ord(c)),len(ta_letters))
if c in uyir_let... | [
"def",
"get_letters",
"(",
"word",
")",
":",
"ta_letters",
"=",
"list",
"(",
")",
"not_empty",
"=",
"False",
"WLEN",
",",
"idx",
"=",
"len",
"(",
"word",
")",
",",
"0",
"while",
"(",
"idx",
"<",
"WLEN",
")",
":",
"c",
"=",
"word",
"[",
"idx",
"... | splits the word into a character-list of tamil/english
characters present in the stream | [
"splits",
"the",
"word",
"into",
"a",
"character",
"-",
"list",
"of",
"tamil",
"/",
"english",
"characters",
"present",
"in",
"the",
"stream"
] | train | https://github.com/Ezhil-Language-Foundation/open-tamil/blob/b7556e88878d29bbc6c944ee17cdd3f75b8ea9f0/tamil/utf8.py#L389-L423 |
Ezhil-Language-Foundation/open-tamil | tamil/utf8.py | get_letters_iterable | def get_letters_iterable( word ):
""" splits the word into a character-list of tamil/english
characters present in the stream """
WLEN,idx = len(word),0
while (idx < WLEN):
c = word[idx]
#print(idx,hex(ord(c)),len(ta_letters))
if c in uyir_letter_set or c == ayudha_letter:
... | python | def get_letters_iterable( word ):
""" splits the word into a character-list of tamil/english
characters present in the stream """
WLEN,idx = len(word),0
while (idx < WLEN):
c = word[idx]
#print(idx,hex(ord(c)),len(ta_letters))
if c in uyir_letter_set or c == ayudha_letter:
... | [
"def",
"get_letters_iterable",
"(",
"word",
")",
":",
"WLEN",
",",
"idx",
"=",
"len",
"(",
"word",
")",
",",
"0",
"while",
"(",
"idx",
"<",
"WLEN",
")",
":",
"c",
"=",
"word",
"[",
"idx",
"]",
"#print(idx,hex(ord(c)),len(ta_letters))",
"if",
"c",
"in",... | splits the word into a character-list of tamil/english
characters present in the stream | [
"splits",
"the",
"word",
"into",
"a",
"character",
"-",
"list",
"of",
"tamil",
"/",
"english",
"characters",
"present",
"in",
"the",
"stream"
] | train | https://github.com/Ezhil-Language-Foundation/open-tamil/blob/b7556e88878d29bbc6c944ee17cdd3f75b8ea9f0/tamil/utf8.py#L431-L453 |
Ezhil-Language-Foundation/open-tamil | tamil/utf8.py | get_words_iterable | def get_words_iterable( letters, tamil_only=False ):
""" given a list of UTF-8 letters section them into words, grouping them at spaces """
# correct algorithm for get-tamil-words
buf = []
for idx,let in enumerate(letters):
if not let.isspace():
if istamil(let) or (not tamil_only):
... | python | def get_words_iterable( letters, tamil_only=False ):
""" given a list of UTF-8 letters section them into words, grouping them at spaces """
# correct algorithm for get-tamil-words
buf = []
for idx,let in enumerate(letters):
if not let.isspace():
if istamil(let) or (not tamil_only):
... | [
"def",
"get_words_iterable",
"(",
"letters",
",",
"tamil_only",
"=",
"False",
")",
":",
"# correct algorithm for get-tamil-words",
"buf",
"=",
"[",
"]",
"for",
"idx",
",",
"let",
"in",
"enumerate",
"(",
"letters",
")",
":",
"if",
"not",
"let",
".",
"isspace"... | given a list of UTF-8 letters section them into words, grouping them at spaces | [
"given",
"a",
"list",
"of",
"UTF",
"-",
"8",
"letters",
"section",
"them",
"into",
"words",
"grouping",
"them",
"at",
"spaces"
] | train | https://github.com/Ezhil-Language-Foundation/open-tamil/blob/b7556e88878d29bbc6c944ee17cdd3f75b8ea9f0/tamil/utf8.py#L499-L513 |
Ezhil-Language-Foundation/open-tamil | tamil/utf8.py | get_tamil_words | def get_tamil_words( letters ):
""" reverse a Tamil word according to letters, not unicode-points """
if not isinstance(letters,list):
raise Exception("metehod needs to be used with list generated from 'tamil.utf8.get_letters(...)'")
return [word for word in get_words_iterable( letters, tamil_only =... | python | def get_tamil_words( letters ):
""" reverse a Tamil word according to letters, not unicode-points """
if not isinstance(letters,list):
raise Exception("metehod needs to be used with list generated from 'tamil.utf8.get_letters(...)'")
return [word for word in get_words_iterable( letters, tamil_only =... | [
"def",
"get_tamil_words",
"(",
"letters",
")",
":",
"if",
"not",
"isinstance",
"(",
"letters",
",",
"list",
")",
":",
"raise",
"Exception",
"(",
"\"metehod needs to be used with list generated from 'tamil.utf8.get_letters(...)'\"",
")",
"return",
"[",
"word",
"for",
"... | reverse a Tamil word according to letters, not unicode-points | [
"reverse",
"a",
"Tamil",
"word",
"according",
"to",
"letters",
"not",
"unicode",
"-",
"points"
] | train | https://github.com/Ezhil-Language-Foundation/open-tamil/blob/b7556e88878d29bbc6c944ee17cdd3f75b8ea9f0/tamil/utf8.py#L515-L519 |
Ezhil-Language-Foundation/open-tamil | tamil/utf8.py | compare_words_lexicographic | def compare_words_lexicographic( word_a, word_b ):
""" compare words in Tamil lexicographic order """
# sanity check for words to be all Tamil
if ( not all_tamil(word_a) ) or (not all_tamil(word_b)) :
#print("## ")
#print(word_a)
#print(word_b)
#print("Both operands need to b... | python | def compare_words_lexicographic( word_a, word_b ):
""" compare words in Tamil lexicographic order """
# sanity check for words to be all Tamil
if ( not all_tamil(word_a) ) or (not all_tamil(word_b)) :
#print("## ")
#print(word_a)
#print(word_b)
#print("Both operands need to b... | [
"def",
"compare_words_lexicographic",
"(",
"word_a",
",",
"word_b",
")",
":",
"# sanity check for words to be all Tamil",
"if",
"(",
"not",
"all_tamil",
"(",
"word_a",
")",
")",
"or",
"(",
"not",
"all_tamil",
"(",
"word_b",
")",
")",
":",
"#print(\"## \")",
"#pr... | compare words in Tamil lexicographic order | [
"compare",
"words",
"in",
"Tamil",
"lexicographic",
"order"
] | train | https://github.com/Ezhil-Language-Foundation/open-tamil/blob/b7556e88878d29bbc6c944ee17cdd3f75b8ea9f0/tamil/utf8.py#L531-L552 |
Ezhil-Language-Foundation/open-tamil | tamil/utf8.py | word_intersection | def word_intersection( word_a, word_b ):
""" return a list of tuples where word_a, word_b intersect """
positions = []
word_a_letters = get_letters( word_a )
word_b_letters = get_letters( word_b )
for idx,wa in enumerate(word_a_letters):
for idy,wb in enumerate(word_b_letters):
i... | python | def word_intersection( word_a, word_b ):
""" return a list of tuples where word_a, word_b intersect """
positions = []
word_a_letters = get_letters( word_a )
word_b_letters = get_letters( word_b )
for idx,wa in enumerate(word_a_letters):
for idy,wb in enumerate(word_b_letters):
i... | [
"def",
"word_intersection",
"(",
"word_a",
",",
"word_b",
")",
":",
"positions",
"=",
"[",
"]",
"word_a_letters",
"=",
"get_letters",
"(",
"word_a",
")",
"word_b_letters",
"=",
"get_letters",
"(",
"word_b",
")",
"for",
"idx",
",",
"wa",
"in",
"enumerate",
... | return a list of tuples where word_a, word_b intersect | [
"return",
"a",
"list",
"of",
"tuples",
"where",
"word_a",
"word_b",
"intersect"
] | train | https://github.com/Ezhil-Language-Foundation/open-tamil/blob/b7556e88878d29bbc6c944ee17cdd3f75b8ea9f0/tamil/utf8.py#L558-L567 |
Ezhil-Language-Foundation/open-tamil | tamil/utf8.py | splitMeiUyir | def splitMeiUyir(uyirmei_char):
"""
This function split uyirmei compound character into mei + uyir characters
and returns in tuple.
Input : It must be unicode tamil char.
Written By : Arulalan.T
Date : 22.09.2014
"""
if not isinstance(uyirmei_char, PYTHON3 and str or unicode):
... | python | def splitMeiUyir(uyirmei_char):
"""
This function split uyirmei compound character into mei + uyir characters
and returns in tuple.
Input : It must be unicode tamil char.
Written By : Arulalan.T
Date : 22.09.2014
"""
if not isinstance(uyirmei_char, PYTHON3 and str or unicode):
... | [
"def",
"splitMeiUyir",
"(",
"uyirmei_char",
")",
":",
"if",
"not",
"isinstance",
"(",
"uyirmei_char",
",",
"PYTHON3",
"and",
"str",
"or",
"unicode",
")",
":",
"raise",
"ValueError",
"(",
"\"Passed input letter '%s' must be unicode, \\\n not ... | This function split uyirmei compound character into mei + uyir characters
and returns in tuple.
Input : It must be unicode tamil char.
Written By : Arulalan.T
Date : 22.09.2014 | [
"This",
"function",
"split",
"uyirmei",
"compound",
"character",
"into",
"mei",
"+",
"uyir",
"characters",
"and",
"returns",
"in",
"tuple",
"."
] | train | https://github.com/Ezhil-Language-Foundation/open-tamil/blob/b7556e88878d29bbc6c944ee17cdd3f75b8ea9f0/tamil/utf8.py#L590-L619 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.