id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
20,700 | OCA/odoorpc | odoorpc/rpc/__init__.py | ConnectorJSONRPC.timeout | def timeout(self, timeout):
"""Set the timeout."""
self._proxy_json._timeout = timeout
self._proxy_http._timeout = timeout | python | def timeout(self, timeout):
self._proxy_json._timeout = timeout
self._proxy_http._timeout = timeout | [
"def",
"timeout",
"(",
"self",
",",
"timeout",
")",
":",
"self",
".",
"_proxy_json",
".",
"_timeout",
"=",
"timeout",
"self",
".",
"_proxy_http",
".",
"_timeout",
"=",
"timeout"
] | Set the timeout. | [
"Set",
"the",
"timeout",
"."
] | d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0 | https://github.com/OCA/odoorpc/blob/d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0/odoorpc/rpc/__init__.py#L245-L248 |
20,701 | OCA/odoorpc | odoorpc/fields.py | is_int | def is_int(value):
"""Return `True` if ``value`` is an integer."""
if isinstance(value, bool):
return False
try:
int(value)
return True
except (ValueError, TypeError):
return False | python | def is_int(value):
if isinstance(value, bool):
return False
try:
int(value)
return True
except (ValueError, TypeError):
return False | [
"def",
"is_int",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"bool",
")",
":",
"return",
"False",
"try",
":",
"int",
"(",
"value",
")",
"return",
"True",
"except",
"(",
"ValueError",
",",
"TypeError",
")",
":",
"return",
"False"
] | Return `True` if ``value`` is an integer. | [
"Return",
"True",
"if",
"value",
"is",
"an",
"integer",
"."
] | d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0 | https://github.com/OCA/odoorpc/blob/d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0/odoorpc/fields.py#L32-L40 |
20,702 | OCA/odoorpc | odoorpc/fields.py | BaseField.check_value | def check_value(self, value):
"""Check the validity of a value for the field."""
#if self.readonly:
# raise error.Error(
# "'{field_name}' field is readonly".format(
# field_name=self.name))
if value and self.size:
if not is_string(value):
raise ValueError("Value supplied has to be a string")
if len(value) > self.size:
raise ValueError(
"Lenght of the '{0}' is limited to {1}".format(
self.name, self.size))
if not value and self.required:
raise ValueError("'{0}' field is required".format(self.name))
return value | python | def check_value(self, value):
#if self.readonly:
# raise error.Error(
# "'{field_name}' field is readonly".format(
# field_name=self.name))
if value and self.size:
if not is_string(value):
raise ValueError("Value supplied has to be a string")
if len(value) > self.size:
raise ValueError(
"Lenght of the '{0}' is limited to {1}".format(
self.name, self.size))
if not value and self.required:
raise ValueError("'{0}' field is required".format(self.name))
return value | [
"def",
"check_value",
"(",
"self",
",",
"value",
")",
":",
"#if self.readonly:",
"# raise error.Error(",
"# \"'{field_name}' field is readonly\".format(",
"# field_name=self.name))",
"if",
"value",
"and",
"self",
".",
"size",
":",
"if",
"not",
"is_strin... | Check the validity of a value for the field. | [
"Check",
"the",
"validity",
"of",
"a",
"value",
"for",
"the",
"field",
"."
] | d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0 | https://github.com/OCA/odoorpc/blob/d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0/odoorpc/fields.py#L147-L162 |
20,703 | OCA/odoorpc | odoorpc/fields.py | Reference._check_relation | def _check_relation(self, relation):
"""Raise a `ValueError` if `relation` is not allowed among
the possible values.
"""
selection = [val[0] for val in self.selection]
if relation not in selection:
raise ValueError(
("The value '{value}' supplied doesn't match with the possible"
" values '{selection}' for the '{field_name}' field").format(
value=relation,
selection=selection,
field_name=self.name,
))
return relation | python | def _check_relation(self, relation):
selection = [val[0] for val in self.selection]
if relation not in selection:
raise ValueError(
("The value '{value}' supplied doesn't match with the possible"
" values '{selection}' for the '{field_name}' field").format(
value=relation,
selection=selection,
field_name=self.name,
))
return relation | [
"def",
"_check_relation",
"(",
"self",
",",
"relation",
")",
":",
"selection",
"=",
"[",
"val",
"[",
"0",
"]",
"for",
"val",
"in",
"self",
".",
"selection",
"]",
"if",
"relation",
"not",
"in",
"selection",
":",
"raise",
"ValueError",
"(",
"(",
"\"The v... | Raise a `ValueError` if `relation` is not allowed among
the possible values. | [
"Raise",
"a",
"ValueError",
"if",
"relation",
"is",
"not",
"allowed",
"among",
"the",
"possible",
"values",
"."
] | d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0 | https://github.com/OCA/odoorpc/blob/d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0/odoorpc/fields.py#L612-L625 |
20,704 | OCA/odoorpc | odoorpc/models.py | Model._with_context | def _with_context(self, *args, **kwargs):
"""As the `with_context` class method but for recordset."""
context = dict(args[0] if args else self.env.context, **kwargs)
return self.with_env(self.env(context=context)) | python | def _with_context(self, *args, **kwargs):
context = dict(args[0] if args else self.env.context, **kwargs)
return self.with_env(self.env(context=context)) | [
"def",
"_with_context",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"context",
"=",
"dict",
"(",
"args",
"[",
"0",
"]",
"if",
"args",
"else",
"self",
".",
"env",
".",
"context",
",",
"*",
"*",
"kwargs",
")",
"return",
"self"... | As the `with_context` class method but for recordset. | [
"As",
"the",
"with_context",
"class",
"method",
"but",
"for",
"recordset",
"."
] | d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0 | https://github.com/OCA/odoorpc/blob/d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0/odoorpc/models.py#L326-L329 |
20,705 | OCA/odoorpc | odoorpc/models.py | Model._with_env | def _with_env(self, env):
"""As the `with_env` class method but for recordset."""
res = self._browse(env, self._ids)
return res | python | def _with_env(self, env):
res = self._browse(env, self._ids)
return res | [
"def",
"_with_env",
"(",
"self",
",",
"env",
")",
":",
"res",
"=",
"self",
".",
"_browse",
"(",
"env",
",",
"self",
".",
"_ids",
")",
"return",
"res"
] | As the `with_env` class method but for recordset. | [
"As",
"the",
"with_env",
"class",
"method",
"but",
"for",
"recordset",
"."
] | d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0 | https://github.com/OCA/odoorpc/blob/d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0/odoorpc/models.py#L340-L343 |
20,706 | OCA/odoorpc | odoorpc/models.py | Model._init_values | def _init_values(self, context=None):
"""Retrieve field values from the server.
May be used to restore the original values in the purpose to cancel
all changes made.
"""
if context is None:
context = self.env.context
# Get basic fields (no relational ones)
basic_fields = []
for field_name in self._columns:
field = self._columns[field_name]
if not getattr(field, 'relation', False):
basic_fields.append(field_name)
# Fetch values from the server
if self.ids:
rows = self.__class__.read(
self.ids, basic_fields, context=context, load='_classic_write')
ids_fetched = set()
for row in rows:
ids_fetched.add(row['id'])
for field_name in row:
if field_name == 'id':
continue
self._values[field_name][row['id']] = row[field_name]
ids_in_error = set(self.ids) - ids_fetched
if ids_in_error:
raise ValueError(
"There is no '{model}' record with IDs {ids}.".format(
model=self._name, ids=list(ids_in_error)))
# No ID: fields filled with default values
else:
default_get = self.__class__.default_get(
list(self._columns), context=context)
for field_name in self._columns:
self._values[field_name][None] = default_get.get(
field_name, False) | python | def _init_values(self, context=None):
if context is None:
context = self.env.context
# Get basic fields (no relational ones)
basic_fields = []
for field_name in self._columns:
field = self._columns[field_name]
if not getattr(field, 'relation', False):
basic_fields.append(field_name)
# Fetch values from the server
if self.ids:
rows = self.__class__.read(
self.ids, basic_fields, context=context, load='_classic_write')
ids_fetched = set()
for row in rows:
ids_fetched.add(row['id'])
for field_name in row:
if field_name == 'id':
continue
self._values[field_name][row['id']] = row[field_name]
ids_in_error = set(self.ids) - ids_fetched
if ids_in_error:
raise ValueError(
"There is no '{model}' record with IDs {ids}.".format(
model=self._name, ids=list(ids_in_error)))
# No ID: fields filled with default values
else:
default_get = self.__class__.default_get(
list(self._columns), context=context)
for field_name in self._columns:
self._values[field_name][None] = default_get.get(
field_name, False) | [
"def",
"_init_values",
"(",
"self",
",",
"context",
"=",
"None",
")",
":",
"if",
"context",
"is",
"None",
":",
"context",
"=",
"self",
".",
"env",
".",
"context",
"# Get basic fields (no relational ones)",
"basic_fields",
"=",
"[",
"]",
"for",
"field_name",
... | Retrieve field values from the server.
May be used to restore the original values in the purpose to cancel
all changes made. | [
"Retrieve",
"field",
"values",
"from",
"the",
"server",
".",
"May",
"be",
"used",
"to",
"restore",
"the",
"original",
"values",
"in",
"the",
"purpose",
"to",
"cancel",
"all",
"changes",
"made",
"."
] | d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0 | https://github.com/OCA/odoorpc/blob/d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0/odoorpc/models.py#L345-L380 |
20,707 | ethereum/eth-utils | eth_utils/currency.py | from_wei | def from_wei(number: int, unit: str) -> Union[int, decimal.Decimal]:
"""
Takes a number of wei and converts it to any other ether unit.
"""
if unit.lower() not in units:
raise ValueError(
"Unknown unit. Must be one of {0}".format("/".join(units.keys()))
)
if number == 0:
return 0
if number < MIN_WEI or number > MAX_WEI:
raise ValueError("value must be between 1 and 2**256 - 1")
unit_value = units[unit.lower()]
with localcontext() as ctx:
ctx.prec = 999
d_number = decimal.Decimal(value=number, context=ctx)
result_value = d_number / unit_value
return result_value | python | def from_wei(number: int, unit: str) -> Union[int, decimal.Decimal]:
if unit.lower() not in units:
raise ValueError(
"Unknown unit. Must be one of {0}".format("/".join(units.keys()))
)
if number == 0:
return 0
if number < MIN_WEI or number > MAX_WEI:
raise ValueError("value must be between 1 and 2**256 - 1")
unit_value = units[unit.lower()]
with localcontext() as ctx:
ctx.prec = 999
d_number = decimal.Decimal(value=number, context=ctx)
result_value = d_number / unit_value
return result_value | [
"def",
"from_wei",
"(",
"number",
":",
"int",
",",
"unit",
":",
"str",
")",
"->",
"Union",
"[",
"int",
",",
"decimal",
".",
"Decimal",
"]",
":",
"if",
"unit",
".",
"lower",
"(",
")",
"not",
"in",
"units",
":",
"raise",
"ValueError",
"(",
"\"Unknown... | Takes a number of wei and converts it to any other ether unit. | [
"Takes",
"a",
"number",
"of",
"wei",
"and",
"converts",
"it",
"to",
"any",
"other",
"ether",
"unit",
"."
] | d9889753a8e016d2fcd64ade0e2db3844486551d | https://github.com/ethereum/eth-utils/blob/d9889753a8e016d2fcd64ade0e2db3844486551d/eth_utils/currency.py#L40-L62 |
20,708 | ethereum/eth-utils | eth_utils/currency.py | to_wei | def to_wei(number: int, unit: str) -> int:
"""
Takes a number of a unit and converts it to wei.
"""
if unit.lower() not in units:
raise ValueError(
"Unknown unit. Must be one of {0}".format("/".join(units.keys()))
)
if is_integer(number) or is_string(number):
d_number = decimal.Decimal(value=number)
elif isinstance(number, float):
d_number = decimal.Decimal(value=str(number))
elif isinstance(number, decimal.Decimal):
d_number = number
else:
raise TypeError("Unsupported type. Must be one of integer, float, or string")
s_number = str(number)
unit_value = units[unit.lower()]
if d_number == 0:
return 0
if d_number < 1 and "." in s_number:
with localcontext() as ctx:
multiplier = len(s_number) - s_number.index(".") - 1
ctx.prec = multiplier
d_number = decimal.Decimal(value=number, context=ctx) * 10 ** multiplier
unit_value /= 10 ** multiplier
with localcontext() as ctx:
ctx.prec = 999
result_value = decimal.Decimal(value=d_number, context=ctx) * unit_value
if result_value < MIN_WEI or result_value > MAX_WEI:
raise ValueError("Resulting wei value must be between 1 and 2**256 - 1")
return int(result_value) | python | def to_wei(number: int, unit: str) -> int:
if unit.lower() not in units:
raise ValueError(
"Unknown unit. Must be one of {0}".format("/".join(units.keys()))
)
if is_integer(number) or is_string(number):
d_number = decimal.Decimal(value=number)
elif isinstance(number, float):
d_number = decimal.Decimal(value=str(number))
elif isinstance(number, decimal.Decimal):
d_number = number
else:
raise TypeError("Unsupported type. Must be one of integer, float, or string")
s_number = str(number)
unit_value = units[unit.lower()]
if d_number == 0:
return 0
if d_number < 1 and "." in s_number:
with localcontext() as ctx:
multiplier = len(s_number) - s_number.index(".") - 1
ctx.prec = multiplier
d_number = decimal.Decimal(value=number, context=ctx) * 10 ** multiplier
unit_value /= 10 ** multiplier
with localcontext() as ctx:
ctx.prec = 999
result_value = decimal.Decimal(value=d_number, context=ctx) * unit_value
if result_value < MIN_WEI or result_value > MAX_WEI:
raise ValueError("Resulting wei value must be between 1 and 2**256 - 1")
return int(result_value) | [
"def",
"to_wei",
"(",
"number",
":",
"int",
",",
"unit",
":",
"str",
")",
"->",
"int",
":",
"if",
"unit",
".",
"lower",
"(",
")",
"not",
"in",
"units",
":",
"raise",
"ValueError",
"(",
"\"Unknown unit. Must be one of {0}\"",
".",
"format",
"(",
"\"/\"",... | Takes a number of a unit and converts it to wei. | [
"Takes",
"a",
"number",
"of",
"a",
"unit",
"and",
"converts",
"it",
"to",
"wei",
"."
] | d9889753a8e016d2fcd64ade0e2db3844486551d | https://github.com/ethereum/eth-utils/blob/d9889753a8e016d2fcd64ade0e2db3844486551d/eth_utils/currency.py#L65-L103 |
20,709 | ethereum/eth-utils | eth_utils/decorators.py | validate_conversion_arguments | def validate_conversion_arguments(to_wrap):
"""
Validates arguments for conversion functions.
- Only a single argument is present
- Kwarg must be 'primitive' 'hexstr' or 'text'
- If it is 'hexstr' or 'text' that it is a text type
"""
@functools.wraps(to_wrap)
def wrapper(*args, **kwargs):
_assert_one_val(*args, **kwargs)
if kwargs:
_validate_supported_kwarg(kwargs)
if len(args) == 0 and "primitive" not in kwargs:
_assert_hexstr_or_text_kwarg_is_text_type(**kwargs)
return to_wrap(*args, **kwargs)
return wrapper | python | def validate_conversion_arguments(to_wrap):
@functools.wraps(to_wrap)
def wrapper(*args, **kwargs):
_assert_one_val(*args, **kwargs)
if kwargs:
_validate_supported_kwarg(kwargs)
if len(args) == 0 and "primitive" not in kwargs:
_assert_hexstr_or_text_kwarg_is_text_type(**kwargs)
return to_wrap(*args, **kwargs)
return wrapper | [
"def",
"validate_conversion_arguments",
"(",
"to_wrap",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"to_wrap",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_assert_one_val",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
... | Validates arguments for conversion functions.
- Only a single argument is present
- Kwarg must be 'primitive' 'hexstr' or 'text'
- If it is 'hexstr' or 'text' that it is a text type | [
"Validates",
"arguments",
"for",
"conversion",
"functions",
".",
"-",
"Only",
"a",
"single",
"argument",
"is",
"present",
"-",
"Kwarg",
"must",
"be",
"primitive",
"hexstr",
"or",
"text",
"-",
"If",
"it",
"is",
"hexstr",
"or",
"text",
"that",
"it",
"is",
... | d9889753a8e016d2fcd64ade0e2db3844486551d | https://github.com/ethereum/eth-utils/blob/d9889753a8e016d2fcd64ade0e2db3844486551d/eth_utils/decorators.py#L59-L77 |
20,710 | ethereum/eth-utils | eth_utils/decorators.py | replace_exceptions | def replace_exceptions(
old_to_new_exceptions: Dict[Type[BaseException], Type[BaseException]]
) -> Callable[..., Any]:
"""
Replaces old exceptions with new exceptions to be raised in their place.
"""
old_exceptions = tuple(old_to_new_exceptions.keys())
def decorator(to_wrap: Callable[..., Any]) -> Callable[..., Any]:
@functools.wraps(to_wrap)
# String type b/c pypy3 throws SegmentationFault with Iterable as arg on nested fn
# Ignore so we don't have to import `Iterable`
def wrapper(
*args: Iterable[Any], **kwargs: Dict[str, Any]
) -> Callable[..., Any]:
try:
return to_wrap(*args, **kwargs)
except old_exceptions as err:
try:
raise old_to_new_exceptions[type(err)] from err
except KeyError:
raise TypeError(
"could not look up new exception to use for %r" % err
) from err
return wrapper
return decorator | python | def replace_exceptions(
old_to_new_exceptions: Dict[Type[BaseException], Type[BaseException]]
) -> Callable[..., Any]:
old_exceptions = tuple(old_to_new_exceptions.keys())
def decorator(to_wrap: Callable[..., Any]) -> Callable[..., Any]:
@functools.wraps(to_wrap)
# String type b/c pypy3 throws SegmentationFault with Iterable as arg on nested fn
# Ignore so we don't have to import `Iterable`
def wrapper(
*args: Iterable[Any], **kwargs: Dict[str, Any]
) -> Callable[..., Any]:
try:
return to_wrap(*args, **kwargs)
except old_exceptions as err:
try:
raise old_to_new_exceptions[type(err)] from err
except KeyError:
raise TypeError(
"could not look up new exception to use for %r" % err
) from err
return wrapper
return decorator | [
"def",
"replace_exceptions",
"(",
"old_to_new_exceptions",
":",
"Dict",
"[",
"Type",
"[",
"BaseException",
"]",
",",
"Type",
"[",
"BaseException",
"]",
"]",
")",
"->",
"Callable",
"[",
"...",
",",
"Any",
"]",
":",
"old_exceptions",
"=",
"tuple",
"(",
"old_... | Replaces old exceptions with new exceptions to be raised in their place. | [
"Replaces",
"old",
"exceptions",
"with",
"new",
"exceptions",
"to",
"be",
"raised",
"in",
"their",
"place",
"."
] | d9889753a8e016d2fcd64ade0e2db3844486551d | https://github.com/ethereum/eth-utils/blob/d9889753a8e016d2fcd64ade0e2db3844486551d/eth_utils/decorators.py#L97-L124 |
20,711 | ethereum/eth-utils | eth_utils/abi.py | collapse_if_tuple | def collapse_if_tuple(abi):
"""Converts a tuple from a dict to a parenthesized list of its types.
>>> from eth_utils.abi import collapse_if_tuple
>>> collapse_if_tuple(
... {
... 'components': [
... {'name': 'anAddress', 'type': 'address'},
... {'name': 'anInt', 'type': 'uint256'},
... {'name': 'someBytes', 'type': 'bytes'},
... ],
... 'type': 'tuple',
... }
... )
'(address,uint256,bytes)'
"""
typ = abi["type"]
if not typ.startswith("tuple"):
return typ
delimited = ",".join(collapse_if_tuple(c) for c in abi["components"])
# Whatever comes after "tuple" is the array dims. The ABI spec states that
# this will have the form "", "[]", or "[k]".
array_dim = typ[5:]
collapsed = "({}){}".format(delimited, array_dim)
return collapsed | python | def collapse_if_tuple(abi):
typ = abi["type"]
if not typ.startswith("tuple"):
return typ
delimited = ",".join(collapse_if_tuple(c) for c in abi["components"])
# Whatever comes after "tuple" is the array dims. The ABI spec states that
# this will have the form "", "[]", or "[k]".
array_dim = typ[5:]
collapsed = "({}){}".format(delimited, array_dim)
return collapsed | [
"def",
"collapse_if_tuple",
"(",
"abi",
")",
":",
"typ",
"=",
"abi",
"[",
"\"type\"",
"]",
"if",
"not",
"typ",
".",
"startswith",
"(",
"\"tuple\"",
")",
":",
"return",
"typ",
"delimited",
"=",
"\",\"",
".",
"join",
"(",
"collapse_if_tuple",
"(",
"c",
"... | Converts a tuple from a dict to a parenthesized list of its types.
>>> from eth_utils.abi import collapse_if_tuple
>>> collapse_if_tuple(
... {
... 'components': [
... {'name': 'anAddress', 'type': 'address'},
... {'name': 'anInt', 'type': 'uint256'},
... {'name': 'someBytes', 'type': 'bytes'},
... ],
... 'type': 'tuple',
... }
... )
'(address,uint256,bytes)' | [
"Converts",
"a",
"tuple",
"from",
"a",
"dict",
"to",
"a",
"parenthesized",
"list",
"of",
"its",
"types",
"."
] | d9889753a8e016d2fcd64ade0e2db3844486551d | https://github.com/ethereum/eth-utils/blob/d9889753a8e016d2fcd64ade0e2db3844486551d/eth_utils/abi.py#L6-L32 |
20,712 | ethereum/eth-utils | eth_utils/address.py | is_hex_address | def is_hex_address(value: Any) -> bool:
"""
Checks if the given string of text type is an address in hexadecimal encoded form.
"""
if not is_text(value):
return False
elif not is_hex(value):
return False
else:
unprefixed = remove_0x_prefix(value)
return len(unprefixed) == 40 | python | def is_hex_address(value: Any) -> bool:
if not is_text(value):
return False
elif not is_hex(value):
return False
else:
unprefixed = remove_0x_prefix(value)
return len(unprefixed) == 40 | [
"def",
"is_hex_address",
"(",
"value",
":",
"Any",
")",
"->",
"bool",
":",
"if",
"not",
"is_text",
"(",
"value",
")",
":",
"return",
"False",
"elif",
"not",
"is_hex",
"(",
"value",
")",
":",
"return",
"False",
"else",
":",
"unprefixed",
"=",
"remove_0x... | Checks if the given string of text type is an address in hexadecimal encoded form. | [
"Checks",
"if",
"the",
"given",
"string",
"of",
"text",
"type",
"is",
"an",
"address",
"in",
"hexadecimal",
"encoded",
"form",
"."
] | d9889753a8e016d2fcd64ade0e2db3844486551d | https://github.com/ethereum/eth-utils/blob/d9889753a8e016d2fcd64ade0e2db3844486551d/eth_utils/address.py#L10-L20 |
20,713 | ethereum/eth-utils | eth_utils/address.py | is_binary_address | def is_binary_address(value: Any) -> bool:
"""
Checks if the given string is an address in raw bytes form.
"""
if not is_bytes(value):
return False
elif len(value) != 20:
return False
else:
return True | python | def is_binary_address(value: Any) -> bool:
if not is_bytes(value):
return False
elif len(value) != 20:
return False
else:
return True | [
"def",
"is_binary_address",
"(",
"value",
":",
"Any",
")",
"->",
"bool",
":",
"if",
"not",
"is_bytes",
"(",
"value",
")",
":",
"return",
"False",
"elif",
"len",
"(",
"value",
")",
"!=",
"20",
":",
"return",
"False",
"else",
":",
"return",
"True"
] | Checks if the given string is an address in raw bytes form. | [
"Checks",
"if",
"the",
"given",
"string",
"is",
"an",
"address",
"in",
"raw",
"bytes",
"form",
"."
] | d9889753a8e016d2fcd64ade0e2db3844486551d | https://github.com/ethereum/eth-utils/blob/d9889753a8e016d2fcd64ade0e2db3844486551d/eth_utils/address.py#L23-L32 |
20,714 | ethereum/eth-utils | eth_utils/address.py | is_address | def is_address(value: Any) -> bool:
"""
Checks if the given string in a supported value
is an address in any of the known formats.
"""
if is_checksum_formatted_address(value):
return is_checksum_address(value)
elif is_hex_address(value):
return True
elif is_binary_address(value):
return True
else:
return False | python | def is_address(value: Any) -> bool:
if is_checksum_formatted_address(value):
return is_checksum_address(value)
elif is_hex_address(value):
return True
elif is_binary_address(value):
return True
else:
return False | [
"def",
"is_address",
"(",
"value",
":",
"Any",
")",
"->",
"bool",
":",
"if",
"is_checksum_formatted_address",
"(",
"value",
")",
":",
"return",
"is_checksum_address",
"(",
"value",
")",
"elif",
"is_hex_address",
"(",
"value",
")",
":",
"return",
"True",
"eli... | Checks if the given string in a supported value
is an address in any of the known formats. | [
"Checks",
"if",
"the",
"given",
"string",
"in",
"a",
"supported",
"value",
"is",
"an",
"address",
"in",
"any",
"of",
"the",
"known",
"formats",
"."
] | d9889753a8e016d2fcd64ade0e2db3844486551d | https://github.com/ethereum/eth-utils/blob/d9889753a8e016d2fcd64ade0e2db3844486551d/eth_utils/address.py#L35-L47 |
20,715 | ethereum/eth-utils | eth_utils/address.py | to_normalized_address | def to_normalized_address(value: AnyStr) -> HexAddress:
"""
Converts an address to its normalized hexadecimal representation.
"""
try:
hex_address = hexstr_if_str(to_hex, value).lower()
except AttributeError:
raise TypeError(
"Value must be any string, instead got type {}".format(type(value))
)
if is_address(hex_address):
return HexAddress(hex_address)
else:
raise ValueError(
"Unknown format {}, attempted to normalize to {}".format(value, hex_address)
) | python | def to_normalized_address(value: AnyStr) -> HexAddress:
try:
hex_address = hexstr_if_str(to_hex, value).lower()
except AttributeError:
raise TypeError(
"Value must be any string, instead got type {}".format(type(value))
)
if is_address(hex_address):
return HexAddress(hex_address)
else:
raise ValueError(
"Unknown format {}, attempted to normalize to {}".format(value, hex_address)
) | [
"def",
"to_normalized_address",
"(",
"value",
":",
"AnyStr",
")",
"->",
"HexAddress",
":",
"try",
":",
"hex_address",
"=",
"hexstr_if_str",
"(",
"to_hex",
",",
"value",
")",
".",
"lower",
"(",
")",
"except",
"AttributeError",
":",
"raise",
"TypeError",
"(",
... | Converts an address to its normalized hexadecimal representation. | [
"Converts",
"an",
"address",
"to",
"its",
"normalized",
"hexadecimal",
"representation",
"."
] | d9889753a8e016d2fcd64ade0e2db3844486551d | https://github.com/ethereum/eth-utils/blob/d9889753a8e016d2fcd64ade0e2db3844486551d/eth_utils/address.py#L50-L65 |
20,716 | ethereum/eth-utils | eth_utils/address.py | is_normalized_address | def is_normalized_address(value: Any) -> bool:
"""
Returns whether the provided value is an address in its normalized form.
"""
if not is_address(value):
return False
else:
return value == to_normalized_address(value) | python | def is_normalized_address(value: Any) -> bool:
if not is_address(value):
return False
else:
return value == to_normalized_address(value) | [
"def",
"is_normalized_address",
"(",
"value",
":",
"Any",
")",
"->",
"bool",
":",
"if",
"not",
"is_address",
"(",
"value",
")",
":",
"return",
"False",
"else",
":",
"return",
"value",
"==",
"to_normalized_address",
"(",
"value",
")"
] | Returns whether the provided value is an address in its normalized form. | [
"Returns",
"whether",
"the",
"provided",
"value",
"is",
"an",
"address",
"in",
"its",
"normalized",
"form",
"."
] | d9889753a8e016d2fcd64ade0e2db3844486551d | https://github.com/ethereum/eth-utils/blob/d9889753a8e016d2fcd64ade0e2db3844486551d/eth_utils/address.py#L68-L75 |
20,717 | ethereum/eth-utils | eth_utils/address.py | is_canonical_address | def is_canonical_address(address: Any) -> bool:
"""
Returns `True` if the `value` is an address in its canonical form.
"""
if not is_bytes(address) or len(address) != 20:
return False
return address == to_canonical_address(address) | python | def is_canonical_address(address: Any) -> bool:
if not is_bytes(address) or len(address) != 20:
return False
return address == to_canonical_address(address) | [
"def",
"is_canonical_address",
"(",
"address",
":",
"Any",
")",
"->",
"bool",
":",
"if",
"not",
"is_bytes",
"(",
"address",
")",
"or",
"len",
"(",
"address",
")",
"!=",
"20",
":",
"return",
"False",
"return",
"address",
"==",
"to_canonical_address",
"(",
... | Returns `True` if the `value` is an address in its canonical form. | [
"Returns",
"True",
"if",
"the",
"value",
"is",
"an",
"address",
"in",
"its",
"canonical",
"form",
"."
] | d9889753a8e016d2fcd64ade0e2db3844486551d | https://github.com/ethereum/eth-utils/blob/d9889753a8e016d2fcd64ade0e2db3844486551d/eth_utils/address.py#L86-L92 |
20,718 | ethereum/eth-utils | eth_utils/address.py | is_same_address | def is_same_address(left: AnyAddress, right: AnyAddress) -> bool:
"""
Checks if both addresses are same or not.
"""
if not is_address(left) or not is_address(right):
raise ValueError("Both values must be valid addresses")
else:
return to_normalized_address(left) == to_normalized_address(right) | python | def is_same_address(left: AnyAddress, right: AnyAddress) -> bool:
if not is_address(left) or not is_address(right):
raise ValueError("Both values must be valid addresses")
else:
return to_normalized_address(left) == to_normalized_address(right) | [
"def",
"is_same_address",
"(",
"left",
":",
"AnyAddress",
",",
"right",
":",
"AnyAddress",
")",
"->",
"bool",
":",
"if",
"not",
"is_address",
"(",
"left",
")",
"or",
"not",
"is_address",
"(",
"right",
")",
":",
"raise",
"ValueError",
"(",
"\"Both values mu... | Checks if both addresses are same or not. | [
"Checks",
"if",
"both",
"addresses",
"are",
"same",
"or",
"not",
"."
] | d9889753a8e016d2fcd64ade0e2db3844486551d | https://github.com/ethereum/eth-utils/blob/d9889753a8e016d2fcd64ade0e2db3844486551d/eth_utils/address.py#L95-L102 |
20,719 | ethereum/eth-utils | eth_utils/address.py | to_checksum_address | def to_checksum_address(value: AnyStr) -> ChecksumAddress:
"""
Makes a checksum address given a supported format.
"""
norm_address = to_normalized_address(value)
address_hash = encode_hex(keccak(text=remove_0x_prefix(norm_address)))
checksum_address = add_0x_prefix(
"".join(
(
norm_address[i].upper()
if int(address_hash[i], 16) > 7
else norm_address[i]
)
for i in range(2, 42)
)
)
return ChecksumAddress(HexAddress(checksum_address)) | python | def to_checksum_address(value: AnyStr) -> ChecksumAddress:
norm_address = to_normalized_address(value)
address_hash = encode_hex(keccak(text=remove_0x_prefix(norm_address)))
checksum_address = add_0x_prefix(
"".join(
(
norm_address[i].upper()
if int(address_hash[i], 16) > 7
else norm_address[i]
)
for i in range(2, 42)
)
)
return ChecksumAddress(HexAddress(checksum_address)) | [
"def",
"to_checksum_address",
"(",
"value",
":",
"AnyStr",
")",
"->",
"ChecksumAddress",
":",
"norm_address",
"=",
"to_normalized_address",
"(",
"value",
")",
"address_hash",
"=",
"encode_hex",
"(",
"keccak",
"(",
"text",
"=",
"remove_0x_prefix",
"(",
"norm_addres... | Makes a checksum address given a supported format. | [
"Makes",
"a",
"checksum",
"address",
"given",
"a",
"supported",
"format",
"."
] | d9889753a8e016d2fcd64ade0e2db3844486551d | https://github.com/ethereum/eth-utils/blob/d9889753a8e016d2fcd64ade0e2db3844486551d/eth_utils/address.py#L105-L122 |
20,720 | Azure/msrestazure-for-python | msrestazure/azure_active_directory.py | get_msi_token | def get_msi_token(resource, port=50342, msi_conf=None):
"""Get MSI token if MSI_ENDPOINT is set.
IF MSI_ENDPOINT is not set, will try legacy access through 'http://localhost:{}/oauth2/token'.format(port).
If msi_conf is used, must be a dict of one key in ["client_id", "object_id", "msi_res_id"]
:param str resource: The resource where the token would be use.
:param int port: The port if not the default 50342 is used. Ignored if MSI_ENDPOINT is set.
:param dict[str,str] msi_conf: msi_conf if to request a token through a User Assigned Identity (if not specified, assume System Assigned)
"""
request_uri = os.environ.get("MSI_ENDPOINT", 'http://localhost:{}/oauth2/token'.format(port))
payload = {
'resource': resource
}
if msi_conf:
if len(msi_conf) > 1:
raise ValueError("{} are mutually exclusive".format(list(msi_conf.keys())))
payload.update(msi_conf)
try:
result = requests.post(request_uri, data=payload, headers={'Metadata': 'true'})
_LOGGER.debug("MSI: Retrieving a token from %s, with payload %s", request_uri, payload)
result.raise_for_status()
except Exception as ex: # pylint: disable=broad-except
_LOGGER.warning("MSI: Failed to retrieve a token from '%s' with an error of '%s'. This could be caused "
"by the MSI extension not yet fully provisioned.",
request_uri, ex)
raise
token_entry = result.json()
return token_entry['token_type'], token_entry['access_token'], token_entry | python | def get_msi_token(resource, port=50342, msi_conf=None):
request_uri = os.environ.get("MSI_ENDPOINT", 'http://localhost:{}/oauth2/token'.format(port))
payload = {
'resource': resource
}
if msi_conf:
if len(msi_conf) > 1:
raise ValueError("{} are mutually exclusive".format(list(msi_conf.keys())))
payload.update(msi_conf)
try:
result = requests.post(request_uri, data=payload, headers={'Metadata': 'true'})
_LOGGER.debug("MSI: Retrieving a token from %s, with payload %s", request_uri, payload)
result.raise_for_status()
except Exception as ex: # pylint: disable=broad-except
_LOGGER.warning("MSI: Failed to retrieve a token from '%s' with an error of '%s'. This could be caused "
"by the MSI extension not yet fully provisioned.",
request_uri, ex)
raise
token_entry = result.json()
return token_entry['token_type'], token_entry['access_token'], token_entry | [
"def",
"get_msi_token",
"(",
"resource",
",",
"port",
"=",
"50342",
",",
"msi_conf",
"=",
"None",
")",
":",
"request_uri",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"\"MSI_ENDPOINT\"",
",",
"'http://localhost:{}/oauth2/token'",
".",
"format",
"(",
"port",
... | Get MSI token if MSI_ENDPOINT is set.
IF MSI_ENDPOINT is not set, will try legacy access through 'http://localhost:{}/oauth2/token'.format(port).
If msi_conf is used, must be a dict of one key in ["client_id", "object_id", "msi_res_id"]
:param str resource: The resource where the token would be use.
:param int port: The port if not the default 50342 is used. Ignored if MSI_ENDPOINT is set.
:param dict[str,str] msi_conf: msi_conf if to request a token through a User Assigned Identity (if not specified, assume System Assigned) | [
"Get",
"MSI",
"token",
"if",
"MSI_ENDPOINT",
"is",
"set",
"."
] | 5f99262305692525d03ca87d2c5356b05c5aa874 | https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/azure_active_directory.py#L462-L492 |
20,721 | Azure/msrestazure-for-python | msrestazure/azure_active_directory.py | get_msi_token_webapp | def get_msi_token_webapp(resource):
"""Get a MSI token from inside a webapp or functions.
Env variable will look like:
- MSI_ENDPOINT = http://127.0.0.1:41741/MSI/token/
- MSI_SECRET = 69418689F1E342DD946CB82994CDA3CB
"""
try:
msi_endpoint = os.environ['MSI_ENDPOINT']
msi_secret = os.environ['MSI_SECRET']
except KeyError as err:
err_msg = "{} required env variable was not found. You might need to restart your app/function.".format(err)
_LOGGER.critical(err_msg)
raise RuntimeError(err_msg)
request_uri = '{}/?resource={}&api-version=2017-09-01'.format(msi_endpoint, resource)
headers = {
'secret': msi_secret
}
err = None
try:
result = requests.get(request_uri, headers=headers)
_LOGGER.debug("MSI: Retrieving a token from %s", request_uri)
if result.status_code != 200:
err = result.text
# Workaround since not all failures are != 200
if 'ExceptionMessage' in result.text:
err = result.text
except Exception as ex: # pylint: disable=broad-except
err = str(ex)
if err:
err_msg = "MSI: Failed to retrieve a token from '{}' with an error of '{}'.".format(
request_uri, err
)
_LOGGER.critical(err_msg)
raise RuntimeError(err_msg)
_LOGGER.debug('MSI: token retrieved')
token_entry = result.json()
return token_entry['token_type'], token_entry['access_token'], token_entry | python | def get_msi_token_webapp(resource):
try:
msi_endpoint = os.environ['MSI_ENDPOINT']
msi_secret = os.environ['MSI_SECRET']
except KeyError as err:
err_msg = "{} required env variable was not found. You might need to restart your app/function.".format(err)
_LOGGER.critical(err_msg)
raise RuntimeError(err_msg)
request_uri = '{}/?resource={}&api-version=2017-09-01'.format(msi_endpoint, resource)
headers = {
'secret': msi_secret
}
err = None
try:
result = requests.get(request_uri, headers=headers)
_LOGGER.debug("MSI: Retrieving a token from %s", request_uri)
if result.status_code != 200:
err = result.text
# Workaround since not all failures are != 200
if 'ExceptionMessage' in result.text:
err = result.text
except Exception as ex: # pylint: disable=broad-except
err = str(ex)
if err:
err_msg = "MSI: Failed to retrieve a token from '{}' with an error of '{}'.".format(
request_uri, err
)
_LOGGER.critical(err_msg)
raise RuntimeError(err_msg)
_LOGGER.debug('MSI: token retrieved')
token_entry = result.json()
return token_entry['token_type'], token_entry['access_token'], token_entry | [
"def",
"get_msi_token_webapp",
"(",
"resource",
")",
":",
"try",
":",
"msi_endpoint",
"=",
"os",
".",
"environ",
"[",
"'MSI_ENDPOINT'",
"]",
"msi_secret",
"=",
"os",
".",
"environ",
"[",
"'MSI_SECRET'",
"]",
"except",
"KeyError",
"as",
"err",
":",
"err_msg",... | Get a MSI token from inside a webapp or functions.
Env variable will look like:
- MSI_ENDPOINT = http://127.0.0.1:41741/MSI/token/
- MSI_SECRET = 69418689F1E342DD946CB82994CDA3CB | [
"Get",
"a",
"MSI",
"token",
"from",
"inside",
"a",
"webapp",
"or",
"functions",
"."
] | 5f99262305692525d03ca87d2c5356b05c5aa874 | https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/azure_active_directory.py#L494-L534 |
20,722 | Azure/msrestazure-for-python | msrestazure/azure_active_directory.py | AADMixin._configure | def _configure(self, **kwargs):
"""Configure authentication endpoint.
Optional kwargs may include:
- cloud_environment (msrestazure.azure_cloud.Cloud): A targeted cloud environment
- china (bool): Configure auth for China-based service,
default is 'False'.
- tenant (str): Alternative tenant, default is 'common'.
- resource (str): Alternative authentication resource, default
is 'https://management.core.windows.net/'.
- verify (bool): Verify secure connection, default is 'True'.
- timeout (int): Timeout of the request in seconds.
- proxies (dict): Dictionary mapping protocol or protocol and
hostname to the URL of the proxy.
- cache (adal.TokenCache): A adal.TokenCache, see ADAL configuration
for details. This parameter is not used here and directly passed to ADAL.
"""
if kwargs.get('china'):
err_msg = ("china parameter is deprecated, "
"please use "
"cloud_environment=msrestazure.azure_cloud.AZURE_CHINA_CLOUD")
warnings.warn(err_msg, DeprecationWarning)
self._cloud_environment = AZURE_CHINA_CLOUD
else:
self._cloud_environment = AZURE_PUBLIC_CLOUD
self._cloud_environment = kwargs.get('cloud_environment', self._cloud_environment)
auth_endpoint = self._cloud_environment.endpoints.active_directory
resource = self._cloud_environment.endpoints.active_directory_resource_id
self._tenant = kwargs.get('tenant', "common")
self._verify = kwargs.get('verify') # 'None' will honor ADAL_PYTHON_SSL_NO_VERIFY
self.resource = kwargs.get('resource', resource)
self._proxies = kwargs.get('proxies')
self._timeout = kwargs.get('timeout')
self._cache = kwargs.get('cache')
self.store_key = "{}_{}".format(
auth_endpoint.strip('/'), self.store_key)
self.secret = None
self._context = None | python | def _configure(self, **kwargs):
if kwargs.get('china'):
err_msg = ("china parameter is deprecated, "
"please use "
"cloud_environment=msrestazure.azure_cloud.AZURE_CHINA_CLOUD")
warnings.warn(err_msg, DeprecationWarning)
self._cloud_environment = AZURE_CHINA_CLOUD
else:
self._cloud_environment = AZURE_PUBLIC_CLOUD
self._cloud_environment = kwargs.get('cloud_environment', self._cloud_environment)
auth_endpoint = self._cloud_environment.endpoints.active_directory
resource = self._cloud_environment.endpoints.active_directory_resource_id
self._tenant = kwargs.get('tenant', "common")
self._verify = kwargs.get('verify') # 'None' will honor ADAL_PYTHON_SSL_NO_VERIFY
self.resource = kwargs.get('resource', resource)
self._proxies = kwargs.get('proxies')
self._timeout = kwargs.get('timeout')
self._cache = kwargs.get('cache')
self.store_key = "{}_{}".format(
auth_endpoint.strip('/'), self.store_key)
self.secret = None
self._context = None | [
"def",
"_configure",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"kwargs",
".",
"get",
"(",
"'china'",
")",
":",
"err_msg",
"=",
"(",
"\"china parameter is deprecated, \"",
"\"please use \"",
"\"cloud_environment=msrestazure.azure_cloud.AZURE_CHINA_CLOUD\"",
... | Configure authentication endpoint.
Optional kwargs may include:
- cloud_environment (msrestazure.azure_cloud.Cloud): A targeted cloud environment
- china (bool): Configure auth for China-based service,
default is 'False'.
- tenant (str): Alternative tenant, default is 'common'.
- resource (str): Alternative authentication resource, default
is 'https://management.core.windows.net/'.
- verify (bool): Verify secure connection, default is 'True'.
- timeout (int): Timeout of the request in seconds.
- proxies (dict): Dictionary mapping protocol or protocol and
hostname to the URL of the proxy.
- cache (adal.TokenCache): A adal.TokenCache, see ADAL configuration
for details. This parameter is not used here and directly passed to ADAL. | [
"Configure",
"authentication",
"endpoint",
"."
] | 5f99262305692525d03ca87d2c5356b05c5aa874 | https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/azure_active_directory.py#L60-L100 |
20,723 | Azure/msrestazure-for-python | msrestazure/azure_active_directory.py | AADMixin._convert_token | def _convert_token(self, token):
"""Convert token fields from camel case.
:param dict token: An authentication token.
:rtype: dict
"""
# Beware that ADAL returns a pointer to its own dict, do
# NOT change it in place
token = token.copy()
# If it's from ADAL, expiresOn will be in ISO form.
# Bring it back to float, using expiresIn
if "expiresOn" in token and "expiresIn" in token:
token["expiresOn"] = token['expiresIn'] + time.time()
return {self._case.sub(r'\1_\2', k).lower(): v
for k, v in token.items()} | python | def _convert_token(self, token):
# Beware that ADAL returns a pointer to its own dict, do
# NOT change it in place
token = token.copy()
# If it's from ADAL, expiresOn will be in ISO form.
# Bring it back to float, using expiresIn
if "expiresOn" in token and "expiresIn" in token:
token["expiresOn"] = token['expiresIn'] + time.time()
return {self._case.sub(r'\1_\2', k).lower(): v
for k, v in token.items()} | [
"def",
"_convert_token",
"(",
"self",
",",
"token",
")",
":",
"# Beware that ADAL returns a pointer to its own dict, do",
"# NOT change it in place",
"token",
"=",
"token",
".",
"copy",
"(",
")",
"# If it's from ADAL, expiresOn will be in ISO form.",
"# Bring it back to float, us... | Convert token fields from camel case.
:param dict token: An authentication token.
:rtype: dict | [
"Convert",
"token",
"fields",
"from",
"camel",
"case",
"."
] | 5f99262305692525d03ca87d2c5356b05c5aa874 | https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/azure_active_directory.py#L159-L174 |
20,724 | Azure/msrestazure-for-python | msrestazure/azure_active_directory.py | AADMixin.signed_session | def signed_session(self, session=None):
"""Create token-friendly Requests session, using auto-refresh.
Used internally when a request is made.
If a session object is provided, configure it directly. Otherwise,
create a new session and return it.
:param session: The session to configure for authentication
:type session: requests.Session
"""
self.set_token() # Adal does the caching.
self._parse_token()
return super(AADMixin, self).signed_session(session) | python | def signed_session(self, session=None):
self.set_token() # Adal does the caching.
self._parse_token()
return super(AADMixin, self).signed_session(session) | [
"def",
"signed_session",
"(",
"self",
",",
"session",
"=",
"None",
")",
":",
"self",
".",
"set_token",
"(",
")",
"# Adal does the caching.",
"self",
".",
"_parse_token",
"(",
")",
"return",
"super",
"(",
"AADMixin",
",",
"self",
")",
".",
"signed_session",
... | Create token-friendly Requests session, using auto-refresh.
Used internally when a request is made.
If a session object is provided, configure it directly. Otherwise,
create a new session and return it.
:param session: The session to configure for authentication
:type session: requests.Session | [
"Create",
"token",
"-",
"friendly",
"Requests",
"session",
"using",
"auto",
"-",
"refresh",
".",
"Used",
"internally",
"when",
"a",
"request",
"is",
"made",
"."
] | 5f99262305692525d03ca87d2c5356b05c5aa874 | https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/azure_active_directory.py#L189-L201 |
20,725 | Azure/msrestazure-for-python | msrestazure/azure_active_directory.py | AADMixin.refresh_session | def refresh_session(self, session=None):
"""Return updated session if token has expired, attempts to
refresh using newly acquired token.
If a session object is provided, configure it directly. Otherwise,
create a new session and return it.
:param session: The session to configure for authentication
:type session: requests.Session
:rtype: requests.Session.
"""
if 'refresh_token' in self.token:
try:
token = self._context.acquire_token_with_refresh_token(
self.token['refresh_token'],
self.id,
self.resource,
self.secret # This is needed when using Confidential Client
)
self.token = self._convert_token(token)
except adal.AdalError as err:
raise_with_traceback(AuthenticationError, "", err)
return self.signed_session(session) | python | def refresh_session(self, session=None):
if 'refresh_token' in self.token:
try:
token = self._context.acquire_token_with_refresh_token(
self.token['refresh_token'],
self.id,
self.resource,
self.secret # This is needed when using Confidential Client
)
self.token = self._convert_token(token)
except adal.AdalError as err:
raise_with_traceback(AuthenticationError, "", err)
return self.signed_session(session) | [
"def",
"refresh_session",
"(",
"self",
",",
"session",
"=",
"None",
")",
":",
"if",
"'refresh_token'",
"in",
"self",
".",
"token",
":",
"try",
":",
"token",
"=",
"self",
".",
"_context",
".",
"acquire_token_with_refresh_token",
"(",
"self",
".",
"token",
"... | Return updated session if token has expired, attempts to
refresh using newly acquired token.
If a session object is provided, configure it directly. Otherwise,
create a new session and return it.
:param session: The session to configure for authentication
:type session: requests.Session
:rtype: requests.Session. | [
"Return",
"updated",
"session",
"if",
"token",
"has",
"expired",
"attempts",
"to",
"refresh",
"using",
"newly",
"acquired",
"token",
"."
] | 5f99262305692525d03ca87d2c5356b05c5aa874 | https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/azure_active_directory.py#L203-L225 |
20,726 | Azure/msrestazure-for-python | msrestazure/azure_operation.py | _validate | def _validate(url):
"""Validate a url.
:param str url: Polling URL extracted from response header.
:raises: ValueError if URL has no scheme or host.
"""
if url is None:
return
parsed = urlparse(url)
if not parsed.scheme or not parsed.netloc:
raise ValueError("Invalid URL header") | python | def _validate(url):
if url is None:
return
parsed = urlparse(url)
if not parsed.scheme or not parsed.netloc:
raise ValueError("Invalid URL header") | [
"def",
"_validate",
"(",
"url",
")",
":",
"if",
"url",
"is",
"None",
":",
"return",
"parsed",
"=",
"urlparse",
"(",
"url",
")",
"if",
"not",
"parsed",
".",
"scheme",
"or",
"not",
"parsed",
".",
"netloc",
":",
"raise",
"ValueError",
"(",
"\"Invalid URL ... | Validate a url.
:param str url: Polling URL extracted from response header.
:raises: ValueError if URL has no scheme or host. | [
"Validate",
"a",
"url",
"."
] | 5f99262305692525d03ca87d2c5356b05c5aa874 | https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/azure_operation.py#L63-L73 |
20,727 | Azure/msrestazure-for-python | msrestazure/azure_operation.py | LongRunningOperation._raise_if_bad_http_status_and_method | def _raise_if_bad_http_status_and_method(self, response):
"""Check response status code is valid for a Put or Patch
request. Must be 200, 201, 202, or 204.
:raises: BadStatus if invalid status.
"""
code = response.status_code
if code in {200, 202} or \
(code == 201 and self.method in {'PUT', 'PATCH'}) or \
(code == 204 and self.method in {'DELETE', 'POST'}):
return
raise BadStatus(
"Invalid return status for {!r} operation".format(self.method)) | python | def _raise_if_bad_http_status_and_method(self, response):
code = response.status_code
if code in {200, 202} or \
(code == 201 and self.method in {'PUT', 'PATCH'}) or \
(code == 204 and self.method in {'DELETE', 'POST'}):
return
raise BadStatus(
"Invalid return status for {!r} operation".format(self.method)) | [
"def",
"_raise_if_bad_http_status_and_method",
"(",
"self",
",",
"response",
")",
":",
"code",
"=",
"response",
".",
"status_code",
"if",
"code",
"in",
"{",
"200",
",",
"202",
"}",
"or",
"(",
"code",
"==",
"201",
"and",
"self",
".",
"method",
"in",
"{",
... | Check response status code is valid for a Put or Patch
request. Must be 200, 201, 202, or 204.
:raises: BadStatus if invalid status. | [
"Check",
"response",
"status",
"code",
"is",
"valid",
"for",
"a",
"Put",
"or",
"Patch",
"request",
".",
"Must",
"be",
"200",
"201",
"202",
"or",
"204",
"."
] | 5f99262305692525d03ca87d2c5356b05c5aa874 | https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/azure_operation.py#L136-L148 |
20,728 | Azure/msrestazure-for-python | msrestazure/azure_operation.py | LongRunningOperation._deserialize | def _deserialize(self, response):
"""Attempt to deserialize resource from response.
:param requests.Response response: latest REST call response.
"""
# Hacking response with initial status_code
previous_status = response.status_code
response.status_code = self.initial_status_code
resource = self.get_outputs(response)
response.status_code = previous_status
# Hack for Storage or SQL, to workaround the bug in the Python generator
if resource is None:
previous_status = response.status_code
for status_code_to_test in [200, 201]:
try:
response.status_code = status_code_to_test
resource = self.get_outputs(response)
except ClientException:
pass
else:
return resource
finally:
response.status_code = previous_status
return resource | python | def _deserialize(self, response):
# Hacking response with initial status_code
previous_status = response.status_code
response.status_code = self.initial_status_code
resource = self.get_outputs(response)
response.status_code = previous_status
# Hack for Storage or SQL, to workaround the bug in the Python generator
if resource is None:
previous_status = response.status_code
for status_code_to_test in [200, 201]:
try:
response.status_code = status_code_to_test
resource = self.get_outputs(response)
except ClientException:
pass
else:
return resource
finally:
response.status_code = previous_status
return resource | [
"def",
"_deserialize",
"(",
"self",
",",
"response",
")",
":",
"# Hacking response with initial status_code",
"previous_status",
"=",
"response",
".",
"status_code",
"response",
".",
"status_code",
"=",
"self",
".",
"initial_status_code",
"resource",
"=",
"self",
".",... | Attempt to deserialize resource from response.
:param requests.Response response: latest REST call response. | [
"Attempt",
"to",
"deserialize",
"resource",
"from",
"response",
"."
] | 5f99262305692525d03ca87d2c5356b05c5aa874 | https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/azure_operation.py#L166-L190 |
20,729 | Azure/msrestazure-for-python | msrestazure/azure_operation.py | LongRunningOperation.get_status_from_location | def get_status_from_location(self, response):
"""Process the latest status update retrieved from a 'location'
header.
:param requests.Response response: latest REST call response.
:raises: BadResponse if response has no body and not status 202.
"""
self._raise_if_bad_http_status_and_method(response)
code = response.status_code
if code == 202:
self.status = "InProgress"
else:
self.status = 'Succeeded'
if self._is_empty(response):
self.resource = None
else:
self.resource = self._deserialize(response) | python | def get_status_from_location(self, response):
self._raise_if_bad_http_status_and_method(response)
code = response.status_code
if code == 202:
self.status = "InProgress"
else:
self.status = 'Succeeded'
if self._is_empty(response):
self.resource = None
else:
self.resource = self._deserialize(response) | [
"def",
"get_status_from_location",
"(",
"self",
",",
"response",
")",
":",
"self",
".",
"_raise_if_bad_http_status_and_method",
"(",
"response",
")",
"code",
"=",
"response",
".",
"status_code",
"if",
"code",
"==",
"202",
":",
"self",
".",
"status",
"=",
"\"In... | Process the latest status update retrieved from a 'location'
header.
:param requests.Response response: latest REST call response.
:raises: BadResponse if response has no body and not status 202. | [
"Process",
"the",
"latest",
"status",
"update",
"retrieved",
"from",
"a",
"location",
"header",
"."
] | 5f99262305692525d03ca87d2c5356b05c5aa874 | https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/azure_operation.py#L260-L276 |
20,730 | Azure/msrestazure-for-python | msrestazure/azure_operation.py | AzureOperationPoller._polling_cookie | def _polling_cookie(self):
"""Collect retry cookie - we only want to do this for the test server
at this point, unless we implement a proper cookie policy.
:returns: Dictionary containing a cookie header if required,
otherwise an empty dictionary.
"""
parsed_url = urlparse(self._response.request.url)
host = parsed_url.hostname.strip('.')
if host == 'localhost':
return {'cookie': self._response.headers.get('set-cookie', '')}
return {} | python | def _polling_cookie(self):
parsed_url = urlparse(self._response.request.url)
host = parsed_url.hostname.strip('.')
if host == 'localhost':
return {'cookie': self._response.headers.get('set-cookie', '')}
return {} | [
"def",
"_polling_cookie",
"(",
"self",
")",
":",
"parsed_url",
"=",
"urlparse",
"(",
"self",
".",
"_response",
".",
"request",
".",
"url",
")",
"host",
"=",
"parsed_url",
".",
"hostname",
".",
"strip",
"(",
"'.'",
")",
"if",
"host",
"==",
"'localhost'",
... | Collect retry cookie - we only want to do this for the test server
at this point, unless we implement a proper cookie policy.
:returns: Dictionary containing a cookie header if required,
otherwise an empty dictionary. | [
"Collect",
"retry",
"cookie",
"-",
"we",
"only",
"want",
"to",
"do",
"this",
"for",
"the",
"test",
"server",
"at",
"this",
"point",
"unless",
"we",
"implement",
"a",
"proper",
"cookie",
"policy",
"."
] | 5f99262305692525d03ca87d2c5356b05c5aa874 | https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/azure_operation.py#L420-L431 |
20,731 | Azure/msrestazure-for-python | msrestazure/azure_operation.py | AzureOperationPoller.remove_done_callback | def remove_done_callback(self, func):
"""Remove a callback from the long running operation.
:param callable func: The function to be removed from the callbacks.
:raises: ValueError if the long running operation has already
completed.
"""
if self._done is None or self._done.is_set():
raise ValueError("Process is complete.")
self._callbacks = [c for c in self._callbacks if c != func] | python | def remove_done_callback(self, func):
if self._done is None or self._done.is_set():
raise ValueError("Process is complete.")
self._callbacks = [c for c in self._callbacks if c != func] | [
"def",
"remove_done_callback",
"(",
"self",
",",
"func",
")",
":",
"if",
"self",
".",
"_done",
"is",
"None",
"or",
"self",
".",
"_done",
".",
"is_set",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Process is complete.\"",
")",
"self",
".",
"_callbacks",
... | Remove a callback from the long running operation.
:param callable func: The function to be removed from the callbacks.
:raises: ValueError if the long running operation has already
completed. | [
"Remove",
"a",
"callback",
"from",
"the",
"long",
"running",
"operation",
"."
] | 5f99262305692525d03ca87d2c5356b05c5aa874 | https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/azure_operation.py#L532-L541 |
20,732 | Azure/msrestazure-for-python | msrestazure/tools.py | register_rp_hook | def register_rp_hook(r, *args, **kwargs):
"""This is a requests hook to register RP automatically.
You should not use this command manually, this is added automatically
by the SDK.
See requests documentation for details of the signature of this function.
http://docs.python-requests.org/en/master/user/advanced/#event-hooks
"""
if r.status_code == 409 and 'msrest' in kwargs:
rp_name = _check_rp_not_registered_err(r)
if rp_name:
session = kwargs['msrest']['session']
url_prefix = _extract_subscription_url(r.request.url)
if not _register_rp(session, url_prefix, rp_name):
return
req = r.request
# Change the 'x-ms-client-request-id' otherwise the Azure endpoint
# just returns the same 409 payload without looking at the actual query
if 'x-ms-client-request-id' in req.headers:
req.headers['x-ms-client-request-id'] = str(uuid.uuid1())
return session.send(req) | python | def register_rp_hook(r, *args, **kwargs):
if r.status_code == 409 and 'msrest' in kwargs:
rp_name = _check_rp_not_registered_err(r)
if rp_name:
session = kwargs['msrest']['session']
url_prefix = _extract_subscription_url(r.request.url)
if not _register_rp(session, url_prefix, rp_name):
return
req = r.request
# Change the 'x-ms-client-request-id' otherwise the Azure endpoint
# just returns the same 409 payload without looking at the actual query
if 'x-ms-client-request-id' in req.headers:
req.headers['x-ms-client-request-id'] = str(uuid.uuid1())
return session.send(req) | [
"def",
"register_rp_hook",
"(",
"r",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"r",
".",
"status_code",
"==",
"409",
"and",
"'msrest'",
"in",
"kwargs",
":",
"rp_name",
"=",
"_check_rp_not_registered_err",
"(",
"r",
")",
"if",
"rp_name",
... | This is a requests hook to register RP automatically.
You should not use this command manually, this is added automatically
by the SDK.
See requests documentation for details of the signature of this function.
http://docs.python-requests.org/en/master/user/advanced/#event-hooks | [
"This",
"is",
"a",
"requests",
"hook",
"to",
"register",
"RP",
"automatically",
"."
] | 5f99262305692525d03ca87d2c5356b05c5aa874 | https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/tools.py#L43-L64 |
20,733 | Azure/msrestazure-for-python | msrestazure/tools.py | _register_rp | def _register_rp(session, url_prefix, rp_name):
"""Synchronously register the RP is paremeter.
Return False if we have a reason to believe this didn't work
"""
post_url = "{}providers/{}/register?api-version=2016-02-01".format(url_prefix, rp_name)
get_url = "{}providers/{}?api-version=2016-02-01".format(url_prefix, rp_name)
_LOGGER.warning("Resource provider '%s' used by this operation is not "
"registered. We are registering for you.", rp_name)
post_response = session.post(post_url)
if post_response.status_code != 200:
_LOGGER.warning("Registration failed. Please register manually.")
return False
while True:
time.sleep(10)
rp_info = session.get(get_url).json()
if rp_info['registrationState'] == 'Registered':
_LOGGER.warning("Registration succeeded.")
return True | python | def _register_rp(session, url_prefix, rp_name):
post_url = "{}providers/{}/register?api-version=2016-02-01".format(url_prefix, rp_name)
get_url = "{}providers/{}?api-version=2016-02-01".format(url_prefix, rp_name)
_LOGGER.warning("Resource provider '%s' used by this operation is not "
"registered. We are registering for you.", rp_name)
post_response = session.post(post_url)
if post_response.status_code != 200:
_LOGGER.warning("Registration failed. Please register manually.")
return False
while True:
time.sleep(10)
rp_info = session.get(get_url).json()
if rp_info['registrationState'] == 'Registered':
_LOGGER.warning("Registration succeeded.")
return True | [
"def",
"_register_rp",
"(",
"session",
",",
"url_prefix",
",",
"rp_name",
")",
":",
"post_url",
"=",
"\"{}providers/{}/register?api-version=2016-02-01\"",
".",
"format",
"(",
"url_prefix",
",",
"rp_name",
")",
"get_url",
"=",
"\"{}providers/{}?api-version=2016-02-01\"",
... | Synchronously register the RP is paremeter.
Return False if we have a reason to believe this didn't work | [
"Synchronously",
"register",
"the",
"RP",
"is",
"paremeter",
".",
"Return",
"False",
"if",
"we",
"have",
"a",
"reason",
"to",
"believe",
"this",
"didn",
"t",
"work"
] | 5f99262305692525d03ca87d2c5356b05c5aa874 | https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/tools.py#L85-L104 |
20,734 | Azure/msrestazure-for-python | msrestazure/tools.py | parse_resource_id | def parse_resource_id(rid):
"""Parses a resource_id into its various parts.
Returns a dictionary with a single key-value pair, 'name': rid, if invalid resource id.
:param rid: The resource id being parsed
:type rid: str
:returns: A dictionary with with following key/value pairs (if found):
- subscription: Subscription id
- resource_group: Name of resource group
- namespace: Namespace for the resource provider (i.e. Microsoft.Compute)
- type: Type of the root resource (i.e. virtualMachines)
- name: Name of the root resource
- child_namespace_{level}: Namespace for the child resoure of that level
- child_type_{level}: Type of the child resource of that level
- child_name_{level}: Name of the child resource of that level
- last_child_num: Level of the last child
- resource_parent: Computed parent in the following pattern: providers/{namespace}\
/{parent}/{type}/{name}
- resource_namespace: Same as namespace. Note that this may be different than the \
target resource's namespace.
- resource_type: Type of the target resource (not the parent)
- resource_name: Name of the target resource (not the parent)
:rtype: dict[str,str]
"""
if not rid:
return {}
match = _ARMID_RE.match(rid)
if match:
result = match.groupdict()
children = _CHILDREN_RE.finditer(result['children'] or '')
count = None
for count, child in enumerate(children):
result.update({
key + '_%d' % (count + 1): group for key, group in child.groupdict().items()})
result['last_child_num'] = count + 1 if isinstance(count, int) else None
result = _populate_alternate_kwargs(result)
else:
result = dict(name=rid)
return {key: value for key, value in result.items() if value is not None} | python | def parse_resource_id(rid):
if not rid:
return {}
match = _ARMID_RE.match(rid)
if match:
result = match.groupdict()
children = _CHILDREN_RE.finditer(result['children'] or '')
count = None
for count, child in enumerate(children):
result.update({
key + '_%d' % (count + 1): group for key, group in child.groupdict().items()})
result['last_child_num'] = count + 1 if isinstance(count, int) else None
result = _populate_alternate_kwargs(result)
else:
result = dict(name=rid)
return {key: value for key, value in result.items() if value is not None} | [
"def",
"parse_resource_id",
"(",
"rid",
")",
":",
"if",
"not",
"rid",
":",
"return",
"{",
"}",
"match",
"=",
"_ARMID_RE",
".",
"match",
"(",
"rid",
")",
"if",
"match",
":",
"result",
"=",
"match",
".",
"groupdict",
"(",
")",
"children",
"=",
"_CHILDR... | Parses a resource_id into its various parts.
Returns a dictionary with a single key-value pair, 'name': rid, if invalid resource id.
:param rid: The resource id being parsed
:type rid: str
:returns: A dictionary with with following key/value pairs (if found):
- subscription: Subscription id
- resource_group: Name of resource group
- namespace: Namespace for the resource provider (i.e. Microsoft.Compute)
- type: Type of the root resource (i.e. virtualMachines)
- name: Name of the root resource
- child_namespace_{level}: Namespace for the child resoure of that level
- child_type_{level}: Type of the child resource of that level
- child_name_{level}: Name of the child resource of that level
- last_child_num: Level of the last child
- resource_parent: Computed parent in the following pattern: providers/{namespace}\
/{parent}/{type}/{name}
- resource_namespace: Same as namespace. Note that this may be different than the \
target resource's namespace.
- resource_type: Type of the target resource (not the parent)
- resource_name: Name of the target resource (not the parent)
:rtype: dict[str,str] | [
"Parses",
"a",
"resource_id",
"into",
"its",
"various",
"parts",
"."
] | 5f99262305692525d03ca87d2c5356b05c5aa874 | https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/tools.py#L106-L147 |
20,735 | Azure/msrestazure-for-python | msrestazure/tools.py | _populate_alternate_kwargs | def _populate_alternate_kwargs(kwargs):
""" Translates the parsed arguments into a format used by generic ARM commands
such as the resource and lock commands.
"""
resource_namespace = kwargs['namespace']
resource_type = kwargs.get('child_type_{}'.format(kwargs['last_child_num'])) or kwargs['type']
resource_name = kwargs.get('child_name_{}'.format(kwargs['last_child_num'])) or kwargs['name']
_get_parents_from_parts(kwargs)
kwargs['resource_namespace'] = resource_namespace
kwargs['resource_type'] = resource_type
kwargs['resource_name'] = resource_name
return kwargs | python | def _populate_alternate_kwargs(kwargs):
resource_namespace = kwargs['namespace']
resource_type = kwargs.get('child_type_{}'.format(kwargs['last_child_num'])) or kwargs['type']
resource_name = kwargs.get('child_name_{}'.format(kwargs['last_child_num'])) or kwargs['name']
_get_parents_from_parts(kwargs)
kwargs['resource_namespace'] = resource_namespace
kwargs['resource_type'] = resource_type
kwargs['resource_name'] = resource_name
return kwargs | [
"def",
"_populate_alternate_kwargs",
"(",
"kwargs",
")",
":",
"resource_namespace",
"=",
"kwargs",
"[",
"'namespace'",
"]",
"resource_type",
"=",
"kwargs",
".",
"get",
"(",
"'child_type_{}'",
".",
"format",
"(",
"kwargs",
"[",
"'last_child_num'",
"]",
")",
")",
... | Translates the parsed arguments into a format used by generic ARM commands
such as the resource and lock commands. | [
"Translates",
"the",
"parsed",
"arguments",
"into",
"a",
"format",
"used",
"by",
"generic",
"ARM",
"commands",
"such",
"as",
"the",
"resource",
"and",
"lock",
"commands",
"."
] | 5f99262305692525d03ca87d2c5356b05c5aa874 | https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/tools.py#L149-L162 |
20,736 | Azure/msrestazure-for-python | msrestazure/tools.py | _get_parents_from_parts | def _get_parents_from_parts(kwargs):
""" Get the parents given all the children parameters.
"""
parent_builder = []
if kwargs['last_child_num'] is not None:
parent_builder.append('{type}/{name}/'.format(**kwargs))
for index in range(1, kwargs['last_child_num']):
child_namespace = kwargs.get('child_namespace_{}'.format(index))
if child_namespace is not None:
parent_builder.append('providers/{}/'.format(child_namespace))
kwargs['child_parent_{}'.format(index)] = ''.join(parent_builder)
parent_builder.append(
'{{child_type_{0}}}/{{child_name_{0}}}/'
.format(index).format(**kwargs))
child_namespace = kwargs.get('child_namespace_{}'.format(kwargs['last_child_num']))
if child_namespace is not None:
parent_builder.append('providers/{}/'.format(child_namespace))
kwargs['child_parent_{}'.format(kwargs['last_child_num'])] = ''.join(parent_builder)
kwargs['resource_parent'] = ''.join(parent_builder) if kwargs['name'] else None
return kwargs | python | def _get_parents_from_parts(kwargs):
parent_builder = []
if kwargs['last_child_num'] is not None:
parent_builder.append('{type}/{name}/'.format(**kwargs))
for index in range(1, kwargs['last_child_num']):
child_namespace = kwargs.get('child_namespace_{}'.format(index))
if child_namespace is not None:
parent_builder.append('providers/{}/'.format(child_namespace))
kwargs['child_parent_{}'.format(index)] = ''.join(parent_builder)
parent_builder.append(
'{{child_type_{0}}}/{{child_name_{0}}}/'
.format(index).format(**kwargs))
child_namespace = kwargs.get('child_namespace_{}'.format(kwargs['last_child_num']))
if child_namespace is not None:
parent_builder.append('providers/{}/'.format(child_namespace))
kwargs['child_parent_{}'.format(kwargs['last_child_num'])] = ''.join(parent_builder)
kwargs['resource_parent'] = ''.join(parent_builder) if kwargs['name'] else None
return kwargs | [
"def",
"_get_parents_from_parts",
"(",
"kwargs",
")",
":",
"parent_builder",
"=",
"[",
"]",
"if",
"kwargs",
"[",
"'last_child_num'",
"]",
"is",
"not",
"None",
":",
"parent_builder",
".",
"append",
"(",
"'{type}/{name}/'",
".",
"format",
"(",
"*",
"*",
"kwarg... | Get the parents given all the children parameters. | [
"Get",
"the",
"parents",
"given",
"all",
"the",
"children",
"parameters",
"."
] | 5f99262305692525d03ca87d2c5356b05c5aa874 | https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/tools.py#L164-L183 |
20,737 | Azure/msrestazure-for-python | msrestazure/tools.py | resource_id | def resource_id(**kwargs):
"""Create a valid resource id string from the given parts.
This method builds the resource id from the left until the next required id parameter
to be appended is not found. It then returns the built up id.
:param dict kwargs: The keyword arguments that will make up the id.
The method accepts the following keyword arguments:
- subscription (required): Subscription id
- resource_group: Name of resource group
- namespace: Namespace for the resource provider (i.e. Microsoft.Compute)
- type: Type of the resource (i.e. virtualMachines)
- name: Name of the resource (or parent if child_name is also \
specified)
- child_namespace_{level}: Namespace for the child resoure of that level (optional)
- child_type_{level}: Type of the child resource of that level
- child_name_{level}: Name of the child resource of that level
:returns: A resource id built from the given arguments.
:rtype: str
"""
kwargs = {k: v for k, v in kwargs.items() if v is not None}
rid_builder = ['/subscriptions/{subscription}'.format(**kwargs)]
try:
try:
rid_builder.append('resourceGroups/{resource_group}'.format(**kwargs))
except KeyError:
pass
rid_builder.append('providers/{namespace}'.format(**kwargs))
rid_builder.append('{type}/{name}'.format(**kwargs))
count = 1
while True:
try:
rid_builder.append('providers/{{child_namespace_{}}}'
.format(count).format(**kwargs))
except KeyError:
pass
rid_builder.append('{{child_type_{0}}}/{{child_name_{0}}}'
.format(count).format(**kwargs))
count += 1
except KeyError:
pass
return '/'.join(rid_builder) | python | def resource_id(**kwargs):
kwargs = {k: v for k, v in kwargs.items() if v is not None}
rid_builder = ['/subscriptions/{subscription}'.format(**kwargs)]
try:
try:
rid_builder.append('resourceGroups/{resource_group}'.format(**kwargs))
except KeyError:
pass
rid_builder.append('providers/{namespace}'.format(**kwargs))
rid_builder.append('{type}/{name}'.format(**kwargs))
count = 1
while True:
try:
rid_builder.append('providers/{{child_namespace_{}}}'
.format(count).format(**kwargs))
except KeyError:
pass
rid_builder.append('{{child_type_{0}}}/{{child_name_{0}}}'
.format(count).format(**kwargs))
count += 1
except KeyError:
pass
return '/'.join(rid_builder) | [
"def",
"resource_id",
"(",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"=",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items",
"(",
")",
"if",
"v",
"is",
"not",
"None",
"}",
"rid_builder",
"=",
"[",
"'/subscriptions/{subscription}'",... | Create a valid resource id string from the given parts.
This method builds the resource id from the left until the next required id parameter
to be appended is not found. It then returns the built up id.
:param dict kwargs: The keyword arguments that will make up the id.
The method accepts the following keyword arguments:
- subscription (required): Subscription id
- resource_group: Name of resource group
- namespace: Namespace for the resource provider (i.e. Microsoft.Compute)
- type: Type of the resource (i.e. virtualMachines)
- name: Name of the resource (or parent if child_name is also \
specified)
- child_namespace_{level}: Namespace for the child resoure of that level (optional)
- child_type_{level}: Type of the child resource of that level
- child_name_{level}: Name of the child resource of that level
:returns: A resource id built from the given arguments.
:rtype: str | [
"Create",
"a",
"valid",
"resource",
"id",
"string",
"from",
"the",
"given",
"parts",
"."
] | 5f99262305692525d03ca87d2c5356b05c5aa874 | https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/tools.py#L185-L228 |
20,738 | Azure/msrestazure-for-python | msrestazure/tools.py | is_valid_resource_id | def is_valid_resource_id(rid, exception_type=None):
"""Validates the given resource id.
:param rid: The resource id being validated.
:type rid: str
:param exception_type: Raises this Exception if invalid.
:type exception_type: :class:`Exception`
:returns: A boolean describing whether the id is valid.
:rtype: bool
"""
is_valid = False
try:
is_valid = rid and resource_id(**parse_resource_id(rid)).lower() == rid.lower()
except KeyError:
pass
if not is_valid and exception_type:
raise exception_type()
return is_valid | python | def is_valid_resource_id(rid, exception_type=None):
is_valid = False
try:
is_valid = rid and resource_id(**parse_resource_id(rid)).lower() == rid.lower()
except KeyError:
pass
if not is_valid and exception_type:
raise exception_type()
return is_valid | [
"def",
"is_valid_resource_id",
"(",
"rid",
",",
"exception_type",
"=",
"None",
")",
":",
"is_valid",
"=",
"False",
"try",
":",
"is_valid",
"=",
"rid",
"and",
"resource_id",
"(",
"*",
"*",
"parse_resource_id",
"(",
"rid",
")",
")",
".",
"lower",
"(",
")",... | Validates the given resource id.
:param rid: The resource id being validated.
:type rid: str
:param exception_type: Raises this Exception if invalid.
:type exception_type: :class:`Exception`
:returns: A boolean describing whether the id is valid.
:rtype: bool | [
"Validates",
"the",
"given",
"resource",
"id",
"."
] | 5f99262305692525d03ca87d2c5356b05c5aa874 | https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/tools.py#L230-L247 |
20,739 | Azure/msrestazure-for-python | msrestazure/tools.py | is_valid_resource_name | def is_valid_resource_name(rname, exception_type=None):
"""Validates the given resource name to ARM guidelines, individual services may be more restrictive.
:param rname: The resource name being validated.
:type rname: str
:param exception_type: Raises this Exception if invalid.
:type exception_type: :class:`Exception`
:returns: A boolean describing whether the name is valid.
:rtype: bool
"""
match = _ARMNAME_RE.match(rname)
if match:
return True
if exception_type:
raise exception_type()
return False | python | def is_valid_resource_name(rname, exception_type=None):
match = _ARMNAME_RE.match(rname)
if match:
return True
if exception_type:
raise exception_type()
return False | [
"def",
"is_valid_resource_name",
"(",
"rname",
",",
"exception_type",
"=",
"None",
")",
":",
"match",
"=",
"_ARMNAME_RE",
".",
"match",
"(",
"rname",
")",
"if",
"match",
":",
"return",
"True",
"if",
"exception_type",
":",
"raise",
"exception_type",
"(",
")",... | Validates the given resource name to ARM guidelines, individual services may be more restrictive.
:param rname: The resource name being validated.
:type rname: str
:param exception_type: Raises this Exception if invalid.
:type exception_type: :class:`Exception`
:returns: A boolean describing whether the name is valid.
:rtype: bool | [
"Validates",
"the",
"given",
"resource",
"name",
"to",
"ARM",
"guidelines",
"individual",
"services",
"may",
"be",
"more",
"restrictive",
"."
] | 5f99262305692525d03ca87d2c5356b05c5aa874 | https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/tools.py#L250-L267 |
20,740 | Azure/msrestazure-for-python | msrestazure/polling/async_arm_polling.py | AsyncARMPolling._delay | async def _delay(self):
"""Check for a 'retry-after' header to set timeout,
otherwise use configured timeout.
"""
if self._response is None:
await asyncio.sleep(0)
if self._response.headers.get('retry-after'):
await asyncio.sleep(int(self._response.headers['retry-after']))
else:
await asyncio.sleep(self._timeout) | python | async def _delay(self):
if self._response is None:
await asyncio.sleep(0)
if self._response.headers.get('retry-after'):
await asyncio.sleep(int(self._response.headers['retry-after']))
else:
await asyncio.sleep(self._timeout) | [
"async",
"def",
"_delay",
"(",
"self",
")",
":",
"if",
"self",
".",
"_response",
"is",
"None",
":",
"await",
"asyncio",
".",
"sleep",
"(",
"0",
")",
"if",
"self",
".",
"_response",
".",
"headers",
".",
"get",
"(",
"'retry-after'",
")",
":",
"await",
... | Check for a 'retry-after' header to set timeout,
otherwise use configured timeout. | [
"Check",
"for",
"a",
"retry",
"-",
"after",
"header",
"to",
"set",
"timeout",
"otherwise",
"use",
"configured",
"timeout",
"."
] | 5f99262305692525d03ca87d2c5356b05c5aa874 | https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/polling/async_arm_polling.py#L83-L92 |
20,741 | Azure/msrestazure-for-python | msrestazure/polling/async_arm_polling.py | AsyncARMPolling.update_status | async def update_status(self):
"""Update the current status of the LRO.
"""
if self._operation.async_url:
self._response = await self.request_status(self._operation.async_url)
self._operation.set_async_url_if_present(self._response)
self._operation.get_status_from_async(self._response)
elif self._operation.location_url:
self._response = await self.request_status(self._operation.location_url)
self._operation.set_async_url_if_present(self._response)
self._operation.get_status_from_location(self._response)
elif self._operation.method == "PUT":
initial_url = self._operation.initial_response.request.url
self._response = await self.request_status(initial_url)
self._operation.set_async_url_if_present(self._response)
self._operation.get_status_from_resource(self._response)
else:
raise BadResponse("Unable to find status link for polling.") | python | async def update_status(self):
if self._operation.async_url:
self._response = await self.request_status(self._operation.async_url)
self._operation.set_async_url_if_present(self._response)
self._operation.get_status_from_async(self._response)
elif self._operation.location_url:
self._response = await self.request_status(self._operation.location_url)
self._operation.set_async_url_if_present(self._response)
self._operation.get_status_from_location(self._response)
elif self._operation.method == "PUT":
initial_url = self._operation.initial_response.request.url
self._response = await self.request_status(initial_url)
self._operation.set_async_url_if_present(self._response)
self._operation.get_status_from_resource(self._response)
else:
raise BadResponse("Unable to find status link for polling.") | [
"async",
"def",
"update_status",
"(",
"self",
")",
":",
"if",
"self",
".",
"_operation",
".",
"async_url",
":",
"self",
".",
"_response",
"=",
"await",
"self",
".",
"request_status",
"(",
"self",
".",
"_operation",
".",
"async_url",
")",
"self",
".",
"_o... | Update the current status of the LRO. | [
"Update",
"the",
"current",
"status",
"of",
"the",
"LRO",
"."
] | 5f99262305692525d03ca87d2c5356b05c5aa874 | https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/polling/async_arm_polling.py#L94-L111 |
20,742 | Azure/msrestazure-for-python | msrestazure/polling/async_arm_polling.py | AsyncARMPolling.request_status | async def request_status(self, status_link):
"""Do a simple GET to this status link.
This method re-inject 'x-ms-client-request-id'.
:rtype: requests.Response
"""
# ARM requires to re-inject 'x-ms-client-request-id' while polling
header_parameters = {
'x-ms-client-request-id': self._operation.initial_response.request.headers['x-ms-client-request-id']
}
request = self._client.get(status_link, headers=header_parameters)
return await self._client.async_send(request, stream=False, **self._operation_config) | python | async def request_status(self, status_link):
# ARM requires to re-inject 'x-ms-client-request-id' while polling
header_parameters = {
'x-ms-client-request-id': self._operation.initial_response.request.headers['x-ms-client-request-id']
}
request = self._client.get(status_link, headers=header_parameters)
return await self._client.async_send(request, stream=False, **self._operation_config) | [
"async",
"def",
"request_status",
"(",
"self",
",",
"status_link",
")",
":",
"# ARM requires to re-inject 'x-ms-client-request-id' while polling",
"header_parameters",
"=",
"{",
"'x-ms-client-request-id'",
":",
"self",
".",
"_operation",
".",
"initial_response",
".",
"reque... | Do a simple GET to this status link.
This method re-inject 'x-ms-client-request-id'.
:rtype: requests.Response | [
"Do",
"a",
"simple",
"GET",
"to",
"this",
"status",
"link",
"."
] | 5f99262305692525d03ca87d2c5356b05c5aa874 | https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/polling/async_arm_polling.py#L113-L125 |
20,743 | Azure/msrestazure-for-python | msrestazure/azure_exceptions.py | CloudErrorData.message | def message(self, value):
"""Attempt to deconstruct error message to retrieve further
error data.
"""
try:
import ast
value = ast.literal_eval(value)
except (SyntaxError, TypeError, ValueError):
pass
try:
value = value.get('value', value)
msg_data = value.split('\n')
self._message = msg_data[0]
except AttributeError:
self._message = value
return
try:
self.request_id = msg_data[1].partition(':')[2]
time_str = msg_data[2].partition(':')
self.error_time = Deserializer.deserialize_iso(
"".join(time_str[2:]))
except (IndexError, DeserializationError):
pass | python | def message(self, value):
try:
import ast
value = ast.literal_eval(value)
except (SyntaxError, TypeError, ValueError):
pass
try:
value = value.get('value', value)
msg_data = value.split('\n')
self._message = msg_data[0]
except AttributeError:
self._message = value
return
try:
self.request_id = msg_data[1].partition(':')[2]
time_str = msg_data[2].partition(':')
self.error_time = Deserializer.deserialize_iso(
"".join(time_str[2:]))
except (IndexError, DeserializationError):
pass | [
"def",
"message",
"(",
"self",
",",
"value",
")",
":",
"try",
":",
"import",
"ast",
"value",
"=",
"ast",
".",
"literal_eval",
"(",
"value",
")",
"except",
"(",
"SyntaxError",
",",
"TypeError",
",",
"ValueError",
")",
":",
"pass",
"try",
":",
"value",
... | Attempt to deconstruct error message to retrieve further
error data. | [
"Attempt",
"to",
"deconstruct",
"error",
"message",
"to",
"retrieve",
"further",
"error",
"data",
"."
] | 5f99262305692525d03ca87d2c5356b05c5aa874 | https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/azure_exceptions.py#L119-L141 |
20,744 | Azure/msrestazure-for-python | msrestazure/azure_cloud.py | get_cloud_from_metadata_endpoint | def get_cloud_from_metadata_endpoint(arm_endpoint, name=None, session=None):
"""Get a Cloud object from an ARM endpoint.
.. versionadded:: 0.4.11
:Example:
.. code:: python
get_cloud_from_metadata_endpoint(https://management.azure.com/, "Public Azure")
:param str arm_endpoint: The ARM management endpoint
:param str name: An optional name for the Cloud object. Otherwise it's the ARM endpoint
:params requests.Session session: A requests session object if you need to configure proxy, cert, etc.
:rtype Cloud:
:returns: a Cloud object
:raises: MetadataEndpointError if unable to build the Cloud object
"""
cloud = Cloud(name or arm_endpoint)
cloud.endpoints.management = arm_endpoint
cloud.endpoints.resource_manager = arm_endpoint
_populate_from_metadata_endpoint(cloud, arm_endpoint, session)
return cloud | python | def get_cloud_from_metadata_endpoint(arm_endpoint, name=None, session=None):
cloud = Cloud(name or arm_endpoint)
cloud.endpoints.management = arm_endpoint
cloud.endpoints.resource_manager = arm_endpoint
_populate_from_metadata_endpoint(cloud, arm_endpoint, session)
return cloud | [
"def",
"get_cloud_from_metadata_endpoint",
"(",
"arm_endpoint",
",",
"name",
"=",
"None",
",",
"session",
"=",
"None",
")",
":",
"cloud",
"=",
"Cloud",
"(",
"name",
"or",
"arm_endpoint",
")",
"cloud",
".",
"endpoints",
".",
"management",
"=",
"arm_endpoint",
... | Get a Cloud object from an ARM endpoint.
.. versionadded:: 0.4.11
:Example:
.. code:: python
get_cloud_from_metadata_endpoint(https://management.azure.com/, "Public Azure")
:param str arm_endpoint: The ARM management endpoint
:param str name: An optional name for the Cloud object. Otherwise it's the ARM endpoint
:params requests.Session session: A requests session object if you need to configure proxy, cert, etc.
:rtype Cloud:
:returns: a Cloud object
:raises: MetadataEndpointError if unable to build the Cloud object | [
"Get",
"a",
"Cloud",
"object",
"from",
"an",
"ARM",
"endpoint",
"."
] | 5f99262305692525d03ca87d2c5356b05c5aa874 | https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/azure_cloud.py#L229-L251 |
20,745 | Azure/msrestazure-for-python | msrestazure/polling/arm_polling.py | LongRunningOperation._as_json | def _as_json(self, response):
"""Assuming this is not empty, return the content as JSON.
Result/exceptions is not determined if you call this method without testing _is_empty.
:raises: DeserializationError if response body contains invalid json data.
"""
# Assume ClientResponse has "body", and otherwise it's a requests.Response
content = response.text() if hasattr(response, "body") else response.text
try:
return json.loads(content)
except ValueError:
raise DeserializationError(
"Error occurred in deserializing the response body.") | python | def _as_json(self, response):
# Assume ClientResponse has "body", and otherwise it's a requests.Response
content = response.text() if hasattr(response, "body") else response.text
try:
return json.loads(content)
except ValueError:
raise DeserializationError(
"Error occurred in deserializing the response body.") | [
"def",
"_as_json",
"(",
"self",
",",
"response",
")",
":",
"# Assume ClientResponse has \"body\", and otherwise it's a requests.Response",
"content",
"=",
"response",
".",
"text",
"(",
")",
"if",
"hasattr",
"(",
"response",
",",
"\"body\"",
")",
"else",
"response",
... | Assuming this is not empty, return the content as JSON.
Result/exceptions is not determined if you call this method without testing _is_empty.
:raises: DeserializationError if response body contains invalid json data. | [
"Assuming",
"this",
"is",
"not",
"empty",
"return",
"the",
"content",
"as",
"JSON",
"."
] | 5f99262305692525d03ca87d2c5356b05c5aa874 | https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/polling/arm_polling.py#L158-L171 |
20,746 | Azure/msrestazure-for-python | msrestazure/polling/arm_polling.py | LongRunningOperation.should_do_final_get | def should_do_final_get(self):
"""Check whether the polling should end doing a final GET.
:param requests.Response response: latest REST call response.
:rtype: bool
"""
return ((self.async_url or not self.resource) and self.method in {'PUT', 'PATCH'}) \
or (self.lro_options['final-state-via'] == _LOCATION_FINAL_STATE and self.location_url and self.async_url and self.method == 'POST') | python | def should_do_final_get(self):
return ((self.async_url or not self.resource) and self.method in {'PUT', 'PATCH'}) \
or (self.lro_options['final-state-via'] == _LOCATION_FINAL_STATE and self.location_url and self.async_url and self.method == 'POST') | [
"def",
"should_do_final_get",
"(",
"self",
")",
":",
"return",
"(",
"(",
"self",
".",
"async_url",
"or",
"not",
"self",
".",
"resource",
")",
"and",
"self",
".",
"method",
"in",
"{",
"'PUT'",
",",
"'PATCH'",
"}",
")",
"or",
"(",
"self",
".",
"lro_opt... | Check whether the polling should end doing a final GET.
:param requests.Response response: latest REST call response.
:rtype: bool | [
"Check",
"whether",
"the",
"polling",
"should",
"end",
"doing",
"a",
"final",
"GET",
"."
] | 5f99262305692525d03ca87d2c5356b05c5aa874 | https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/polling/arm_polling.py#L203-L210 |
20,747 | Azure/msrestazure-for-python | msrestazure/polling/arm_polling.py | LongRunningOperation.set_initial_status | def set_initial_status(self, response):
"""Process first response after initiating long running
operation and set self.status attribute.
:param requests.Response response: initial REST call response.
"""
self._raise_if_bad_http_status_and_method(response)
if self._is_empty(response):
self.resource = None
else:
try:
self.resource = self._deserialize(response)
except DeserializationError:
self.resource = None
self.set_async_url_if_present(response)
if response.status_code in {200, 201, 202, 204}:
if self.async_url or self.location_url or response.status_code == 202:
self.status = 'InProgress'
elif response.status_code == 201:
status = self._get_provisioning_state(response)
self.status = status or 'InProgress'
elif response.status_code == 200:
status = self._get_provisioning_state(response)
self.status = status or 'Succeeded'
elif response.status_code == 204:
self.status = 'Succeeded'
self.resource = None
else:
raise OperationFailed("Invalid status found")
return
raise OperationFailed("Operation failed or cancelled") | python | def set_initial_status(self, response):
self._raise_if_bad_http_status_and_method(response)
if self._is_empty(response):
self.resource = None
else:
try:
self.resource = self._deserialize(response)
except DeserializationError:
self.resource = None
self.set_async_url_if_present(response)
if response.status_code in {200, 201, 202, 204}:
if self.async_url or self.location_url or response.status_code == 202:
self.status = 'InProgress'
elif response.status_code == 201:
status = self._get_provisioning_state(response)
self.status = status or 'InProgress'
elif response.status_code == 200:
status = self._get_provisioning_state(response)
self.status = status or 'Succeeded'
elif response.status_code == 204:
self.status = 'Succeeded'
self.resource = None
else:
raise OperationFailed("Invalid status found")
return
raise OperationFailed("Operation failed or cancelled") | [
"def",
"set_initial_status",
"(",
"self",
",",
"response",
")",
":",
"self",
".",
"_raise_if_bad_http_status_and_method",
"(",
"response",
")",
"if",
"self",
".",
"_is_empty",
"(",
"response",
")",
":",
"self",
".",
"resource",
"=",
"None",
"else",
":",
"try... | Process first response after initiating long running
operation and set self.status attribute.
:param requests.Response response: initial REST call response. | [
"Process",
"first",
"response",
"after",
"initiating",
"long",
"running",
"operation",
"and",
"set",
"self",
".",
"status",
"attribute",
"."
] | 5f99262305692525d03ca87d2c5356b05c5aa874 | https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/polling/arm_polling.py#L212-L245 |
20,748 | Azure/msrestazure-for-python | msrestazure/polling/arm_polling.py | LongRunningOperation.parse_resource | def parse_resource(self, response):
"""Assuming this response is a resource, use the deserialization callback to parse it.
If body is empty, assuming no resource to return.
"""
self._raise_if_bad_http_status_and_method(response)
if not self._is_empty(response):
self.resource = self._deserialize(response)
else:
self.resource = None | python | def parse_resource(self, response):
self._raise_if_bad_http_status_and_method(response)
if not self._is_empty(response):
self.resource = self._deserialize(response)
else:
self.resource = None | [
"def",
"parse_resource",
"(",
"self",
",",
"response",
")",
":",
"self",
".",
"_raise_if_bad_http_status_and_method",
"(",
"response",
")",
"if",
"not",
"self",
".",
"_is_empty",
"(",
"response",
")",
":",
"self",
".",
"resource",
"=",
"self",
".",
"_deseria... | Assuming this response is a resource, use the deserialization callback to parse it.
If body is empty, assuming no resource to return. | [
"Assuming",
"this",
"response",
"is",
"a",
"resource",
"use",
"the",
"deserialization",
"callback",
"to",
"parse",
"it",
".",
"If",
"body",
"is",
"empty",
"assuming",
"no",
"resource",
"to",
"return",
"."
] | 5f99262305692525d03ca87d2c5356b05c5aa874 | https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/polling/arm_polling.py#L282-L290 |
20,749 | Azure/msrestazure-for-python | msrestazure/polling/arm_polling.py | LongRunningOperation.get_status_from_async | def get_status_from_async(self, response):
"""Process the latest status update retrieved from a
'azure-asyncoperation' header.
:param requests.Response response: latest REST call response.
:raises: BadResponse if response has no body, or body does not
contain status.
"""
self._raise_if_bad_http_status_and_method(response)
if self._is_empty(response):
raise BadResponse('The response from long running operation '
'does not contain a body.')
self.status = self._get_async_status(response)
if not self.status:
raise BadResponse("No status found in body")
# Status can contains information, see ARM spec:
# https://github.com/Azure/azure-resource-manager-rpc/blob/master/v1.0/Addendum.md#operation-resource-format
# "properties": {
# /\* The resource provider can choose the values here, but it should only be
# returned on a successful operation (status being "Succeeded"). \*/
#},
# So try to parse it
try:
self.resource = self._deserialize(response)
except Exception:
self.resource = None | python | def get_status_from_async(self, response):
self._raise_if_bad_http_status_and_method(response)
if self._is_empty(response):
raise BadResponse('The response from long running operation '
'does not contain a body.')
self.status = self._get_async_status(response)
if not self.status:
raise BadResponse("No status found in body")
# Status can contains information, see ARM spec:
# https://github.com/Azure/azure-resource-manager-rpc/blob/master/v1.0/Addendum.md#operation-resource-format
# "properties": {
# /\* The resource provider can choose the values here, but it should only be
# returned on a successful operation (status being "Succeeded"). \*/
#},
# So try to parse it
try:
self.resource = self._deserialize(response)
except Exception:
self.resource = None | [
"def",
"get_status_from_async",
"(",
"self",
",",
"response",
")",
":",
"self",
".",
"_raise_if_bad_http_status_and_method",
"(",
"response",
")",
"if",
"self",
".",
"_is_empty",
"(",
"response",
")",
":",
"raise",
"BadResponse",
"(",
"'The response from long runnin... | Process the latest status update retrieved from a
'azure-asyncoperation' header.
:param requests.Response response: latest REST call response.
:raises: BadResponse if response has no body, or body does not
contain status. | [
"Process",
"the",
"latest",
"status",
"update",
"retrieved",
"from",
"a",
"azure",
"-",
"asyncoperation",
"header",
"."
] | 5f99262305692525d03ca87d2c5356b05c5aa874 | https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/polling/arm_polling.py#L292-L319 |
20,750 | Azure/msrestazure-for-python | msrestazure/polling/arm_polling.py | ARMPolling.initialize | def initialize(self, client, initial_response, deserialization_callback):
"""Set the initial status of this LRO.
:param initial_response: The initial response of the poller
:raises: CloudError if initial status is incorrect LRO state
"""
self._client = client
self._response = initial_response
self._operation = LongRunningOperation(initial_response, deserialization_callback, self._lro_options)
try:
self._operation.set_initial_status(initial_response)
except BadStatus:
self._operation.status = 'Failed'
raise CloudError(initial_response)
except BadResponse as err:
self._operation.status = 'Failed'
raise CloudError(initial_response, str(err))
except OperationFailed:
raise CloudError(initial_response) | python | def initialize(self, client, initial_response, deserialization_callback):
self._client = client
self._response = initial_response
self._operation = LongRunningOperation(initial_response, deserialization_callback, self._lro_options)
try:
self._operation.set_initial_status(initial_response)
except BadStatus:
self._operation.status = 'Failed'
raise CloudError(initial_response)
except BadResponse as err:
self._operation.status = 'Failed'
raise CloudError(initial_response, str(err))
except OperationFailed:
raise CloudError(initial_response) | [
"def",
"initialize",
"(",
"self",
",",
"client",
",",
"initial_response",
",",
"deserialization_callback",
")",
":",
"self",
".",
"_client",
"=",
"client",
"self",
".",
"_response",
"=",
"initial_response",
"self",
".",
"_operation",
"=",
"LongRunningOperation",
... | Set the initial status of this LRO.
:param initial_response: The initial response of the poller
:raises: CloudError if initial status is incorrect LRO state | [
"Set",
"the",
"initial",
"status",
"of",
"this",
"LRO",
"."
] | 5f99262305692525d03ca87d2c5356b05c5aa874 | https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/polling/arm_polling.py#L368-L386 |
20,751 | diux-dev/ncluster | benchmarks/pytorch_two_machines.py | worker | def worker():
""" Initialize the distributed environment. """
import torch
import torch.distributed as dist
from torch.multiprocessing import Process
import numpy as np
print("Initializing distributed pytorch")
os.environ['MASTER_ADDR'] = str(args.master_addr)
os.environ['MASTER_PORT'] = str(args.master_port)
# Use TCP backend. Gloo needs nightly, where it currently fails with
# dist.init_process_group('gloo', rank=args.rank,
# AttributeError: module 'torch.distributed' has no attribute 'init_process_group'
dist.init_process_group('tcp', rank=args.rank,
world_size=args.size)
tensor = torch.ones(args.size_mb*250*1000)*(args.rank+1)
time_list = []
outfile = 'out' if args.rank == 0 else '/dev/null'
log = util.FileLogger(outfile)
for i in range(args.iters):
# print('before: rank ', args.rank, ' has data ', tensor[0])
start_time = time.perf_counter()
if args.rank == 0:
dist.send(tensor=tensor, dst=1)
else:
dist.recv(tensor=tensor, src=0)
elapsed_time_ms = (time.perf_counter() - start_time)*1000
time_list.append(elapsed_time_ms)
# print('after: rank ', args.rank, ' has data ', tensor[0])
rate = args.size_mb/(elapsed_time_ms/1000)
log('%03d/%d added %d MBs in %.1f ms: %.2f MB/second' % (i, args.iters, args.size_mb, elapsed_time_ms, rate))
min = np.min(time_list)
median = np.median(time_list)
log(f"min: {min:8.2f}, median: {median:8.2f}, mean: {np.mean(time_list):8.2f}") | python | def worker():
import torch
import torch.distributed as dist
from torch.multiprocessing import Process
import numpy as np
print("Initializing distributed pytorch")
os.environ['MASTER_ADDR'] = str(args.master_addr)
os.environ['MASTER_PORT'] = str(args.master_port)
# Use TCP backend. Gloo needs nightly, where it currently fails with
# dist.init_process_group('gloo', rank=args.rank,
# AttributeError: module 'torch.distributed' has no attribute 'init_process_group'
dist.init_process_group('tcp', rank=args.rank,
world_size=args.size)
tensor = torch.ones(args.size_mb*250*1000)*(args.rank+1)
time_list = []
outfile = 'out' if args.rank == 0 else '/dev/null'
log = util.FileLogger(outfile)
for i in range(args.iters):
# print('before: rank ', args.rank, ' has data ', tensor[0])
start_time = time.perf_counter()
if args.rank == 0:
dist.send(tensor=tensor, dst=1)
else:
dist.recv(tensor=tensor, src=0)
elapsed_time_ms = (time.perf_counter() - start_time)*1000
time_list.append(elapsed_time_ms)
# print('after: rank ', args.rank, ' has data ', tensor[0])
rate = args.size_mb/(elapsed_time_ms/1000)
log('%03d/%d added %d MBs in %.1f ms: %.2f MB/second' % (i, args.iters, args.size_mb, elapsed_time_ms, rate))
min = np.min(time_list)
median = np.median(time_list)
log(f"min: {min:8.2f}, median: {median:8.2f}, mean: {np.mean(time_list):8.2f}") | [
"def",
"worker",
"(",
")",
":",
"import",
"torch",
"import",
"torch",
".",
"distributed",
"as",
"dist",
"from",
"torch",
".",
"multiprocessing",
"import",
"Process",
"import",
"numpy",
"as",
"np",
"print",
"(",
"\"Initializing distributed pytorch\"",
")",
"os",
... | Initialize the distributed environment. | [
"Initialize",
"the",
"distributed",
"environment",
"."
] | 2fd359621896717197b479c7174d06d80df1529b | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/benchmarks/pytorch_two_machines.py#L61-L100 |
20,752 | diux-dev/ncluster | ncluster/ncluster.py | make_job | def make_job(name: str = '',
run_name: str = '',
num_tasks: int = 0,
install_script: str = '',
**kwargs
) -> backend.Job:
"""
Create a job using current backend. Blocks until all tasks are up and initialized.
Args:
name: name of the job
run_name: name of the run (auto-assigned if empty)
num_tasks: number of tasks
install_script: bash-runnable script
**kwargs:
Returns:
backend.Job
"""
return _backend.make_job(name=name, run_name=run_name, num_tasks=num_tasks,
install_script=install_script, **kwargs) | python | def make_job(name: str = '',
run_name: str = '',
num_tasks: int = 0,
install_script: str = '',
**kwargs
) -> backend.Job:
return _backend.make_job(name=name, run_name=run_name, num_tasks=num_tasks,
install_script=install_script, **kwargs) | [
"def",
"make_job",
"(",
"name",
":",
"str",
"=",
"''",
",",
"run_name",
":",
"str",
"=",
"''",
",",
"num_tasks",
":",
"int",
"=",
"0",
",",
"install_script",
":",
"str",
"=",
"''",
",",
"*",
"*",
"kwargs",
")",
"->",
"backend",
".",
"Job",
":",
... | Create a job using current backend. Blocks until all tasks are up and initialized.
Args:
name: name of the job
run_name: name of the run (auto-assigned if empty)
num_tasks: number of tasks
install_script: bash-runnable script
**kwargs:
Returns:
backend.Job | [
"Create",
"a",
"job",
"using",
"current",
"backend",
".",
"Blocks",
"until",
"all",
"tasks",
"are",
"up",
"and",
"initialized",
"."
] | 2fd359621896717197b479c7174d06d80df1529b | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/ncluster.py#L86-L106 |
20,753 | diux-dev/ncluster | ncluster/local_backend.py | make_task | def make_task(name='',
run_name='',
**kwargs) -> Task:
"""Create task, also create dummy run if not specified."""
ncluster_globals.task_launched = True
name = ncluster_globals.auto_assign_task_name_if_needed(name)
# tmux can't use . for session names
tmux_session = name.replace('.', '=')
tmux_window_id = 0
util.log(f'killing session {tmux_session}')
if not util.is_set("NCLUSTER_NOKILL_TMUX"):
os.system(f'tmux kill-session -t {tmux_session}')
os.system(f'tmux new-session -s {tmux_session} -n {tmux_window_id} -d')
task = Task(name,
tmux_session=tmux_session, # propagate optional args
run_name=run_name,
**kwargs)
ncluster_globals.register_task(task, run_name)
return task | python | def make_task(name='',
run_name='',
**kwargs) -> Task:
ncluster_globals.task_launched = True
name = ncluster_globals.auto_assign_task_name_if_needed(name)
# tmux can't use . for session names
tmux_session = name.replace('.', '=')
tmux_window_id = 0
util.log(f'killing session {tmux_session}')
if not util.is_set("NCLUSTER_NOKILL_TMUX"):
os.system(f'tmux kill-session -t {tmux_session}')
os.system(f'tmux new-session -s {tmux_session} -n {tmux_window_id} -d')
task = Task(name,
tmux_session=tmux_session, # propagate optional args
run_name=run_name,
**kwargs)
ncluster_globals.register_task(task, run_name)
return task | [
"def",
"make_task",
"(",
"name",
"=",
"''",
",",
"run_name",
"=",
"''",
",",
"*",
"*",
"kwargs",
")",
"->",
"Task",
":",
"ncluster_globals",
".",
"task_launched",
"=",
"True",
"name",
"=",
"ncluster_globals",
".",
"auto_assign_task_name_if_needed",
"(",
"nam... | Create task, also create dummy run if not specified. | [
"Create",
"task",
"also",
"create",
"dummy",
"run",
"if",
"not",
"specified",
"."
] | 2fd359621896717197b479c7174d06d80df1529b | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/local_backend.py#L447-L469 |
20,754 | diux-dev/ncluster | ncluster/local_backend.py | Task._run_raw | def _run_raw(self, cmd, ignore_errors=False):
"""Runs command directly, skipping tmux interface"""
# TODO: capture stdout/stderr for feature parity with aws_backend
result = os.system(cmd)
if result != 0:
if ignore_errors:
self.log(f"command ({cmd}) failed.")
assert False, "_run_raw failed" | python | def _run_raw(self, cmd, ignore_errors=False):
# TODO: capture stdout/stderr for feature parity with aws_backend
result = os.system(cmd)
if result != 0:
if ignore_errors:
self.log(f"command ({cmd}) failed.")
assert False, "_run_raw failed" | [
"def",
"_run_raw",
"(",
"self",
",",
"cmd",
",",
"ignore_errors",
"=",
"False",
")",
":",
"# TODO: capture stdout/stderr for feature parity with aws_backend",
"result",
"=",
"os",
".",
"system",
"(",
"cmd",
")",
"if",
"result",
"!=",
"0",
":",
"if",
"ignore_erro... | Runs command directly, skipping tmux interface | [
"Runs",
"command",
"directly",
"skipping",
"tmux",
"interface"
] | 2fd359621896717197b479c7174d06d80df1529b | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/local_backend.py#L270-L277 |
20,755 | diux-dev/ncluster | ncluster/local_backend.py | Task.upload | def upload(self, local_fn, remote_fn=None, dont_overwrite=False):
"""Uploads file to remote instance. If location not specified, dumps it
into default directory. Creates missing directories in path name."""
# support wildcard through glob
if '*' in local_fn:
for local_subfn in glob.glob(local_fn):
self.upload(local_subfn)
return
if remote_fn is None:
remote_fn = os.path.basename(local_fn)
if dont_overwrite and self.exists(remote_fn):
self.log("Remote file %s exists, skipping" % (remote_fn,))
return
if not remote_fn.startswith('/'):
remote_fn = self.taskdir + '/' + remote_fn
remote_fn = remote_fn.replace('~', self.homedir)
self.log('uploading ' + local_fn + ' to ' + remote_fn)
local_fn = os.path.abspath(local_fn)
self._run_raw("cp -R %s %s" % (local_fn, remote_fn)) | python | def upload(self, local_fn, remote_fn=None, dont_overwrite=False):
# support wildcard through glob
if '*' in local_fn:
for local_subfn in glob.glob(local_fn):
self.upload(local_subfn)
return
if remote_fn is None:
remote_fn = os.path.basename(local_fn)
if dont_overwrite and self.exists(remote_fn):
self.log("Remote file %s exists, skipping" % (remote_fn,))
return
if not remote_fn.startswith('/'):
remote_fn = self.taskdir + '/' + remote_fn
remote_fn = remote_fn.replace('~', self.homedir)
self.log('uploading ' + local_fn + ' to ' + remote_fn)
local_fn = os.path.abspath(local_fn)
self._run_raw("cp -R %s %s" % (local_fn, remote_fn)) | [
"def",
"upload",
"(",
"self",
",",
"local_fn",
",",
"remote_fn",
"=",
"None",
",",
"dont_overwrite",
"=",
"False",
")",
":",
"# support wildcard through glob",
"if",
"'*'",
"in",
"local_fn",
":",
"for",
"local_subfn",
"in",
"glob",
".",
"glob",
"(",
"local_f... | Uploads file to remote instance. If location not specified, dumps it
into default directory. Creates missing directories in path name. | [
"Uploads",
"file",
"to",
"remote",
"instance",
".",
"If",
"location",
"not",
"specified",
"dumps",
"it",
"into",
"default",
"directory",
".",
"Creates",
"missing",
"directories",
"in",
"path",
"name",
"."
] | 2fd359621896717197b479c7174d06d80df1529b | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/local_backend.py#L279-L303 |
20,756 | diux-dev/ncluster | ncluster/local_backend.py | Task.logdir | def logdir(self):
"""Returns logging directory, creating one if necessary. See "Logdir" section of design doc on naming convention."""
run_name = ncluster_globals.get_run_for_task(self)
logdir = ncluster_globals.get_logdir(run_name)
if logdir:
return logdir
# create logdir. Only single task in a group creates the logdir
if ncluster_globals.is_chief(self, run_name):
chief = self
else:
chief = ncluster_globals.get_chief(run_name)
chief.setup_logdir()
return ncluster_globals.get_logdir(run_name) | python | def logdir(self):
run_name = ncluster_globals.get_run_for_task(self)
logdir = ncluster_globals.get_logdir(run_name)
if logdir:
return logdir
# create logdir. Only single task in a group creates the logdir
if ncluster_globals.is_chief(self, run_name):
chief = self
else:
chief = ncluster_globals.get_chief(run_name)
chief.setup_logdir()
return ncluster_globals.get_logdir(run_name) | [
"def",
"logdir",
"(",
"self",
")",
":",
"run_name",
"=",
"ncluster_globals",
".",
"get_run_for_task",
"(",
"self",
")",
"logdir",
"=",
"ncluster_globals",
".",
"get_logdir",
"(",
"run_name",
")",
"if",
"logdir",
":",
"return",
"logdir",
"# create logdir. Only si... | Returns logging directory, creating one if necessary. See "Logdir" section of design doc on naming convention. | [
"Returns",
"logging",
"directory",
"creating",
"one",
"if",
"necessary",
".",
"See",
"Logdir",
"section",
"of",
"design",
"doc",
"on",
"naming",
"convention",
"."
] | 2fd359621896717197b479c7174d06d80df1529b | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/local_backend.py#L351-L366 |
20,757 | diux-dev/ncluster | ncluster/local_backend.py | Run.run_with_output | def run_with_output(self, *args, **kwargs):
"""Runs command on every first job in the run, returns stdout."""
for job in self.jobs:
job.run_with_output(*args, **kwargs) | python | def run_with_output(self, *args, **kwargs):
for job in self.jobs:
job.run_with_output(*args, **kwargs) | [
"def",
"run_with_output",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"job",
"in",
"self",
".",
"jobs",
":",
"job",
".",
"run_with_output",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Runs command on every first job in the run, returns stdout. | [
"Runs",
"command",
"on",
"every",
"first",
"job",
"in",
"the",
"run",
"returns",
"stdout",
"."
] | 2fd359621896717197b479c7174d06d80df1529b | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/local_backend.py#L428-L431 |
20,758 | diux-dev/ncluster | ncluster/local_backend.py | Run._run_raw | def _run_raw(self, *args, **kwargs):
"""_run_raw on every job in the run."""
for job in self.jobs:
job._run_raw(*args, **kwargs) | python | def _run_raw(self, *args, **kwargs):
for job in self.jobs:
job._run_raw(*args, **kwargs) | [
"def",
"_run_raw",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"job",
"in",
"self",
".",
"jobs",
":",
"job",
".",
"_run_raw",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | _run_raw on every job in the run. | [
"_run_raw",
"on",
"every",
"job",
"in",
"the",
"run",
"."
] | 2fd359621896717197b479c7174d06d80df1529b | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/local_backend.py#L433-L436 |
20,759 | diux-dev/ncluster | ncluster/aws_create_resources.py | keypair_setup | def keypair_setup():
"""Creates keypair if necessary, saves private key locally, returns contents
of private key file."""
os.system('mkdir -p ' + u.PRIVATE_KEY_LOCATION)
keypair_name = u.get_keypair_name()
keypair = u.get_keypair_dict().get(keypair_name, None)
keypair_fn = u.get_keypair_fn()
if keypair:
print("Reusing keypair " + keypair_name)
# check that local pem file exists and is readable
assert os.path.exists(
keypair_fn), "Keypair %s exists, but corresponding .pem file %s is not found, delete keypair %s through console and run again to recreate keypair/.pem together" % (
keypair_name, keypair_fn, keypair_name)
keypair_contents = open(keypair_fn).read()
assert len(keypair_contents) > 0
else:
print("Creating keypair " + keypair_name)
ec2 = u.get_ec2_resource()
assert not os.path.exists(
keypair_fn), "previous keypair exists, delete it with 'sudo rm %s' and also delete corresponding keypair through console" % (
keypair_fn)
keypair = ec2.create_key_pair(KeyName=keypair_name)
open(keypair_fn, 'w').write(keypair.key_material)
os.system('chmod 400 ' + keypair_fn)
return keypair | python | def keypair_setup():
os.system('mkdir -p ' + u.PRIVATE_KEY_LOCATION)
keypair_name = u.get_keypair_name()
keypair = u.get_keypair_dict().get(keypair_name, None)
keypair_fn = u.get_keypair_fn()
if keypair:
print("Reusing keypair " + keypair_name)
# check that local pem file exists and is readable
assert os.path.exists(
keypair_fn), "Keypair %s exists, but corresponding .pem file %s is not found, delete keypair %s through console and run again to recreate keypair/.pem together" % (
keypair_name, keypair_fn, keypair_name)
keypair_contents = open(keypair_fn).read()
assert len(keypair_contents) > 0
else:
print("Creating keypair " + keypair_name)
ec2 = u.get_ec2_resource()
assert not os.path.exists(
keypair_fn), "previous keypair exists, delete it with 'sudo rm %s' and also delete corresponding keypair through console" % (
keypair_fn)
keypair = ec2.create_key_pair(KeyName=keypair_name)
open(keypair_fn, 'w').write(keypair.key_material)
os.system('chmod 400 ' + keypair_fn)
return keypair | [
"def",
"keypair_setup",
"(",
")",
":",
"os",
".",
"system",
"(",
"'mkdir -p '",
"+",
"u",
".",
"PRIVATE_KEY_LOCATION",
")",
"keypair_name",
"=",
"u",
".",
"get_keypair_name",
"(",
")",
"keypair",
"=",
"u",
".",
"get_keypair_dict",
"(",
")",
".",
"get",
"... | Creates keypair if necessary, saves private key locally, returns contents
of private key file. | [
"Creates",
"keypair",
"if",
"necessary",
"saves",
"private",
"key",
"locally",
"returns",
"contents",
"of",
"private",
"key",
"file",
"."
] | 2fd359621896717197b479c7174d06d80df1529b | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/aws_create_resources.py#L226-L254 |
20,760 | diux-dev/ncluster | ncluster/aws_create_resources.py | placement_group_setup | def placement_group_setup(group_name):
"""Creates placement_group group if necessary. Returns True if new placement_group
group was created, False otherwise."""
existing_placement_groups = u.get_placement_group_dict()
group = existing_placement_groups.get(group_name, None)
if group:
assert group.state == 'available'
assert group.strategy == 'cluster'
print("Reusing group ", group.name)
return group
print("Creating group " + group_name)
ec2 = u.get_ec2_resource()
group = ec2.create_placement_group(GroupName=group_name, Strategy='cluster')
return group | python | def placement_group_setup(group_name):
existing_placement_groups = u.get_placement_group_dict()
group = existing_placement_groups.get(group_name, None)
if group:
assert group.state == 'available'
assert group.strategy == 'cluster'
print("Reusing group ", group.name)
return group
print("Creating group " + group_name)
ec2 = u.get_ec2_resource()
group = ec2.create_placement_group(GroupName=group_name, Strategy='cluster')
return group | [
"def",
"placement_group_setup",
"(",
"group_name",
")",
":",
"existing_placement_groups",
"=",
"u",
".",
"get_placement_group_dict",
"(",
")",
"group",
"=",
"existing_placement_groups",
".",
"get",
"(",
"group_name",
",",
"None",
")",
"if",
"group",
":",
"assert",... | Creates placement_group group if necessary. Returns True if new placement_group
group was created, False otherwise. | [
"Creates",
"placement_group",
"group",
"if",
"necessary",
".",
"Returns",
"True",
"if",
"new",
"placement_group",
"group",
"was",
"created",
"False",
"otherwise",
"."
] | 2fd359621896717197b479c7174d06d80df1529b | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/aws_create_resources.py#L257-L273 |
20,761 | diux-dev/ncluster | ncluster/backend.py | Task.upload | def upload(self, local_fn: str, remote_fn: str = '',
dont_overwrite: bool = False):
"""Uploads given file to the task. If remote_fn is not specified, dumps it
into task current directory with the same name.
Args:
local_fn: location of file locally
remote_fn: location of file on task
dont_overwrite: if True, will be no-op if target file exists
"""
raise NotImplementedError() | python | def upload(self, local_fn: str, remote_fn: str = '',
dont_overwrite: bool = False):
raise NotImplementedError() | [
"def",
"upload",
"(",
"self",
",",
"local_fn",
":",
"str",
",",
"remote_fn",
":",
"str",
"=",
"''",
",",
"dont_overwrite",
":",
"bool",
"=",
"False",
")",
":",
"raise",
"NotImplementedError",
"(",
")"
] | Uploads given file to the task. If remote_fn is not specified, dumps it
into task current directory with the same name.
Args:
local_fn: location of file locally
remote_fn: location of file on task
dont_overwrite: if True, will be no-op if target file exists | [
"Uploads",
"given",
"file",
"to",
"the",
"task",
".",
"If",
"remote_fn",
"is",
"not",
"specified",
"dumps",
"it",
"into",
"task",
"current",
"directory",
"with",
"the",
"same",
"name",
"."
] | 2fd359621896717197b479c7174d06d80df1529b | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/backend.py#L139-L149 |
20,762 | diux-dev/ncluster | ncluster/backend.py | Job._non_blocking_wrapper | def _non_blocking_wrapper(self, method, *args, **kwargs):
"""Runs given method on every task in the job. Blocks until all tasks finish. Propagates exception from first
failed task."""
exceptions = []
def task_run(task):
try:
getattr(task, method)(*args, **kwargs)
except Exception as e:
exceptions.append(e)
threads = [threading.Thread(name=f'task_{method}_{i}',
target=task_run, args=[t])
for i, t in enumerate(self.tasks)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
if exceptions:
raise exceptions[0] | python | def _non_blocking_wrapper(self, method, *args, **kwargs):
exceptions = []
def task_run(task):
try:
getattr(task, method)(*args, **kwargs)
except Exception as e:
exceptions.append(e)
threads = [threading.Thread(name=f'task_{method}_{i}',
target=task_run, args=[t])
for i, t in enumerate(self.tasks)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
if exceptions:
raise exceptions[0] | [
"def",
"_non_blocking_wrapper",
"(",
"self",
",",
"method",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"exceptions",
"=",
"[",
"]",
"def",
"task_run",
"(",
"task",
")",
":",
"try",
":",
"getattr",
"(",
"task",
",",
"method",
")",
"(",
"*"... | Runs given method on every task in the job. Blocks until all tasks finish. Propagates exception from first
failed task. | [
"Runs",
"given",
"method",
"on",
"every",
"task",
"in",
"the",
"job",
".",
"Blocks",
"until",
"all",
"tasks",
"finish",
".",
"Propagates",
"exception",
"from",
"first",
"failed",
"task",
"."
] | 2fd359621896717197b479c7174d06d80df1529b | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/backend.py#L202-L222 |
20,763 | diux-dev/ncluster | ncluster/aws_util.py | get_default_vpc | def get_default_vpc():
"""
Return default VPC or none if not present
"""
ec2 = get_ec2_resource()
for vpc in ec2.vpcs.all():
if vpc.is_default:
return vpc | python | def get_default_vpc():
ec2 = get_ec2_resource()
for vpc in ec2.vpcs.all():
if vpc.is_default:
return vpc | [
"def",
"get_default_vpc",
"(",
")",
":",
"ec2",
"=",
"get_ec2_resource",
"(",
")",
"for",
"vpc",
"in",
"ec2",
".",
"vpcs",
".",
"all",
"(",
")",
":",
"if",
"vpc",
".",
"is_default",
":",
"return",
"vpc"
] | Return default VPC or none if not present | [
"Return",
"default",
"VPC",
"or",
"none",
"if",
"not",
"present"
] | 2fd359621896717197b479c7174d06d80df1529b | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/aws_util.py#L75-L83 |
20,764 | diux-dev/ncluster | ncluster/aws_util.py | get_subnet_dict | def get_subnet_dict():
"""Returns dictionary of "availability zone" -> subnet for current VPC."""
subnet_dict = {}
vpc = get_vpc()
for subnet in vpc.subnets.all():
zone = subnet.availability_zone
assert zone not in subnet_dict, "More than one subnet in %s, why?" % (zone,)
subnet_dict[zone] = subnet
return subnet_dict | python | def get_subnet_dict():
subnet_dict = {}
vpc = get_vpc()
for subnet in vpc.subnets.all():
zone = subnet.availability_zone
assert zone not in subnet_dict, "More than one subnet in %s, why?" % (zone,)
subnet_dict[zone] = subnet
return subnet_dict | [
"def",
"get_subnet_dict",
"(",
")",
":",
"subnet_dict",
"=",
"{",
"}",
"vpc",
"=",
"get_vpc",
"(",
")",
"for",
"subnet",
"in",
"vpc",
".",
"subnets",
".",
"all",
"(",
")",
":",
"zone",
"=",
"subnet",
".",
"availability_zone",
"assert",
"zone",
"not",
... | Returns dictionary of "availability zone" -> subnet for current VPC. | [
"Returns",
"dictionary",
"of",
"availability",
"zone",
"-",
">",
"subnet",
"for",
"current",
"VPC",
"."
] | 2fd359621896717197b479c7174d06d80df1529b | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/aws_util.py#L86-L94 |
20,765 | diux-dev/ncluster | ncluster/aws_util.py | get_keypair_name | def get_keypair_name():
"""Returns current keypair name."""
username = get_username()
assert '-' not in username, "username must not contain -, change $USER"
validate_aws_name(username)
assert len(username) < 30 # to avoid exceeding AWS 127 char limit
return get_prefix() + '-' + username | python | def get_keypair_name():
username = get_username()
assert '-' not in username, "username must not contain -, change $USER"
validate_aws_name(username)
assert len(username) < 30 # to avoid exceeding AWS 127 char limit
return get_prefix() + '-' + username | [
"def",
"get_keypair_name",
"(",
")",
":",
"username",
"=",
"get_username",
"(",
")",
"assert",
"'-'",
"not",
"in",
"username",
",",
"\"username must not contain -, change $USER\"",
"validate_aws_name",
"(",
"username",
")",
"assert",
"len",
"(",
"username",
")",
"... | Returns current keypair name. | [
"Returns",
"current",
"keypair",
"name",
"."
] | 2fd359621896717197b479c7174d06d80df1529b | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/aws_util.py#L247-L254 |
20,766 | diux-dev/ncluster | ncluster/aws_util.py | get_keypair_fn | def get_keypair_fn():
"""Location of .pem file for current keypair"""
keypair_name = get_keypair_name()
account = get_account_number()
region = get_region()
fn = f'{PRIVATE_KEY_LOCATION}/{keypair_name}-{account}-{region}.pem'
return fn | python | def get_keypair_fn():
keypair_name = get_keypair_name()
account = get_account_number()
region = get_region()
fn = f'{PRIVATE_KEY_LOCATION}/{keypair_name}-{account}-{region}.pem'
return fn | [
"def",
"get_keypair_fn",
"(",
")",
":",
"keypair_name",
"=",
"get_keypair_name",
"(",
")",
"account",
"=",
"get_account_number",
"(",
")",
"region",
"=",
"get_region",
"(",
")",
"fn",
"=",
"f'{PRIVATE_KEY_LOCATION}/{keypair_name}-{account}-{region}.pem'",
"return",
"f... | Location of .pem file for current keypair | [
"Location",
"of",
".",
"pem",
"file",
"for",
"current",
"keypair"
] | 2fd359621896717197b479c7174d06d80df1529b | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/aws_util.py#L266-L273 |
20,767 | diux-dev/ncluster | ncluster/aws_util.py | lookup_instance | def lookup_instance(name: str, instance_type: str = '', image_name: str = '',
states: tuple = ('running', 'stopped', 'initializing')):
"""Looks up AWS instance for given instance name, like
simple.worker. If no instance found in current AWS environment, returns None. """
ec2 = get_ec2_resource()
instances = ec2.instances.filter(
Filters=[{'Name': 'instance-state-name', 'Values': states}])
prefix = get_prefix()
username = get_username()
# look for an existing instance matching job, ignore instances launched
# by different user or under different resource name
result = []
for i in instances.all():
instance_name = get_name(i)
if instance_name != name:
continue
seen_prefix, seen_username = parse_key_name(i.key_name)
if prefix != seen_prefix:
print(f"Found {name} launched under {seen_prefix}, ignoring")
continue
if username != seen_username:
print(f"Found {name} launched by {seen_username}, ignoring")
continue
if instance_type:
assert i.instance_type == instance_type, f"Found existing instance for job {name} but different instance type ({i.instance_type}) than requested ({instance_type}), terminate {name} first or use new task name."
if image_name:
assert i.image.name == image_name, f"Found existing instance for job {name} but launched with different image ({i.image.name}) than requested ({image_name}), terminate {name} first or use new task name."
result.append(i)
assert len(result) < 2, f"Found two instances with name {name}"
if not result:
return None
else:
return result[0] | python | def lookup_instance(name: str, instance_type: str = '', image_name: str = '',
states: tuple = ('running', 'stopped', 'initializing')):
ec2 = get_ec2_resource()
instances = ec2.instances.filter(
Filters=[{'Name': 'instance-state-name', 'Values': states}])
prefix = get_prefix()
username = get_username()
# look for an existing instance matching job, ignore instances launched
# by different user or under different resource name
result = []
for i in instances.all():
instance_name = get_name(i)
if instance_name != name:
continue
seen_prefix, seen_username = parse_key_name(i.key_name)
if prefix != seen_prefix:
print(f"Found {name} launched under {seen_prefix}, ignoring")
continue
if username != seen_username:
print(f"Found {name} launched by {seen_username}, ignoring")
continue
if instance_type:
assert i.instance_type == instance_type, f"Found existing instance for job {name} but different instance type ({i.instance_type}) than requested ({instance_type}), terminate {name} first or use new task name."
if image_name:
assert i.image.name == image_name, f"Found existing instance for job {name} but launched with different image ({i.image.name}) than requested ({image_name}), terminate {name} first or use new task name."
result.append(i)
assert len(result) < 2, f"Found two instances with name {name}"
if not result:
return None
else:
return result[0] | [
"def",
"lookup_instance",
"(",
"name",
":",
"str",
",",
"instance_type",
":",
"str",
"=",
"''",
",",
"image_name",
":",
"str",
"=",
"''",
",",
"states",
":",
"tuple",
"=",
"(",
"'running'",
",",
"'stopped'",
",",
"'initializing'",
")",
")",
":",
"ec2",... | Looks up AWS instance for given instance name, like
simple.worker. If no instance found in current AWS environment, returns None. | [
"Looks",
"up",
"AWS",
"instance",
"for",
"given",
"instance",
"name",
"like",
"simple",
".",
"worker",
".",
"If",
"no",
"instance",
"found",
"in",
"current",
"AWS",
"environment",
"returns",
"None",
"."
] | 2fd359621896717197b479c7174d06d80df1529b | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/aws_util.py#L326-L366 |
20,768 | diux-dev/ncluster | ncluster/aws_util.py | ssh_to_task | def ssh_to_task(task) -> paramiko.SSHClient:
"""Create ssh connection to task's machine
returns Paramiko SSH client connected to host.
"""
username = task.ssh_username
hostname = task.public_ip
ssh_key_fn = get_keypair_fn()
print(f"ssh -i {ssh_key_fn} {username}@{hostname}")
pkey = paramiko.RSAKey.from_private_key_file(ssh_key_fn)
ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
assert ssh_client
counter = 1
while True:
try:
ssh_client.connect(hostname=hostname, username=username, pkey=pkey)
if counter % 11 == 0: # occasionally re-obtain public ip, machine could've gotten restarted
hostname = task.public_ip
break
except Exception as e:
print(
f'{task.name}: Exception connecting to {hostname} via ssh (could be a timeout): {e}')
time.sleep(RETRY_INTERVAL_SEC)
return ssh_client | python | def ssh_to_task(task) -> paramiko.SSHClient:
username = task.ssh_username
hostname = task.public_ip
ssh_key_fn = get_keypair_fn()
print(f"ssh -i {ssh_key_fn} {username}@{hostname}")
pkey = paramiko.RSAKey.from_private_key_file(ssh_key_fn)
ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
assert ssh_client
counter = 1
while True:
try:
ssh_client.connect(hostname=hostname, username=username, pkey=pkey)
if counter % 11 == 0: # occasionally re-obtain public ip, machine could've gotten restarted
hostname = task.public_ip
break
except Exception as e:
print(
f'{task.name}: Exception connecting to {hostname} via ssh (could be a timeout): {e}')
time.sleep(RETRY_INTERVAL_SEC)
return ssh_client | [
"def",
"ssh_to_task",
"(",
"task",
")",
"->",
"paramiko",
".",
"SSHClient",
":",
"username",
"=",
"task",
".",
"ssh_username",
"hostname",
"=",
"task",
".",
"public_ip",
"ssh_key_fn",
"=",
"get_keypair_fn",
"(",
")",
"print",
"(",
"f\"ssh -i {ssh_key_fn} {userna... | Create ssh connection to task's machine
returns Paramiko SSH client connected to host. | [
"Create",
"ssh",
"connection",
"to",
"task",
"s",
"machine"
] | 2fd359621896717197b479c7174d06d80df1529b | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/aws_util.py#L369-L398 |
20,769 | diux-dev/ncluster | ncluster/aws_util.py | delete_efs_by_id | def delete_efs_by_id(efs_id):
"""Deletion sometimes fails, try several times."""
start_time = time.time()
efs_client = get_efs_client()
sys.stdout.write("deleting %s ... " % (efs_id,))
while True:
try:
response = efs_client.delete_file_system(FileSystemId=efs_id)
if is_good_response(response):
print("succeeded")
break
time.sleep(RETRY_INTERVAL_SEC)
except Exception as e:
print("Failed with %s" % (e,))
if time.time() - start_time - RETRY_INTERVAL_SEC < RETRY_TIMEOUT_SEC:
print("Retrying in %s sec" % (RETRY_INTERVAL_SEC,))
time.sleep(RETRY_INTERVAL_SEC)
else:
print("Giving up")
break | python | def delete_efs_by_id(efs_id):
start_time = time.time()
efs_client = get_efs_client()
sys.stdout.write("deleting %s ... " % (efs_id,))
while True:
try:
response = efs_client.delete_file_system(FileSystemId=efs_id)
if is_good_response(response):
print("succeeded")
break
time.sleep(RETRY_INTERVAL_SEC)
except Exception as e:
print("Failed with %s" % (e,))
if time.time() - start_time - RETRY_INTERVAL_SEC < RETRY_TIMEOUT_SEC:
print("Retrying in %s sec" % (RETRY_INTERVAL_SEC,))
time.sleep(RETRY_INTERVAL_SEC)
else:
print("Giving up")
break | [
"def",
"delete_efs_by_id",
"(",
"efs_id",
")",
":",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"efs_client",
"=",
"get_efs_client",
"(",
")",
"sys",
".",
"stdout",
".",
"write",
"(",
"\"deleting %s ... \"",
"%",
"(",
"efs_id",
",",
")",
")",
"whil... | Deletion sometimes fails, try several times. | [
"Deletion",
"sometimes",
"fails",
"try",
"several",
"times",
"."
] | 2fd359621896717197b479c7174d06d80df1529b | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/aws_util.py#L488-L507 |
20,770 | diux-dev/ncluster | ncluster/aws_util.py | extract_attr_for_match | def extract_attr_for_match(items, **kwargs):
"""Helper method to get attribute value for an item matching some criterion.
Specify target criteria value as dict, with target attribute having value -1
Example:
to extract state of vpc matching given vpc id
response = [{'State': 'available', 'VpcId': 'vpc-2bb1584c'}]
extract_attr_for_match(response, State=-1, VpcId='vpc-2bb1584c') #=> 'available'"""
# find the value of attribute to return
query_arg = None
for arg, value in kwargs.items():
if value == -1:
assert query_arg is None, "Only single query arg (-1 valued) is allowed"
query_arg = arg
result = []
filterset = set(kwargs.keys())
for item in items:
match = True
assert filterset.issubset(
item.keys()), "Filter set contained %s which was not in record %s" % (
filterset.difference(item.keys()),
item)
for arg in item:
if arg == query_arg:
continue
if arg in kwargs:
if item[arg] != kwargs[arg]:
match = False
break
if match:
result.append(item[query_arg])
assert len(result) <= 1, "%d values matched %s, only allow 1" % (
len(result), kwargs)
if result:
return result[0]
return None | python | def extract_attr_for_match(items, **kwargs):
"""Helper method to get attribute value for an item matching some criterion.
Specify target criteria value as dict, with target attribute having value -1
Example:
to extract state of vpc matching given vpc id
response = [{'State': 'available', 'VpcId': 'vpc-2bb1584c'}]
extract_attr_for_match(response, State=-1, VpcId='vpc-2bb1584c') #=> 'available'"""
# find the value of attribute to return
query_arg = None
for arg, value in kwargs.items():
if value == -1:
assert query_arg is None, "Only single query arg (-1 valued) is allowed"
query_arg = arg
result = []
filterset = set(kwargs.keys())
for item in items:
match = True
assert filterset.issubset(
item.keys()), "Filter set contained %s which was not in record %s" % (
filterset.difference(item.keys()),
item)
for arg in item:
if arg == query_arg:
continue
if arg in kwargs:
if item[arg] != kwargs[arg]:
match = False
break
if match:
result.append(item[query_arg])
assert len(result) <= 1, "%d values matched %s, only allow 1" % (
len(result), kwargs)
if result:
return result[0]
return None | [
"def",
"extract_attr_for_match",
"(",
"items",
",",
"*",
"*",
"kwargs",
")",
":",
"# find the value of attribute to return",
"query_arg",
"=",
"None",
"for",
"arg",
",",
"value",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"if",
"value",
"==",
"-",
"1",
"... | Helper method to get attribute value for an item matching some criterion.
Specify target criteria value as dict, with target attribute having value -1
Example:
to extract state of vpc matching given vpc id
response = [{'State': 'available', 'VpcId': 'vpc-2bb1584c'}]
extract_attr_for_match(response, State=-1, VpcId='vpc-2bb1584c') #=> 'available | [
"Helper",
"method",
"to",
"get",
"attribute",
"value",
"for",
"an",
"item",
"matching",
"some",
"criterion",
".",
"Specify",
"target",
"criteria",
"value",
"as",
"dict",
"with",
"target",
"attribute",
"having",
"value",
"-",
"1"
] | 2fd359621896717197b479c7174d06d80df1529b | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/aws_util.py#L510-L548 |
20,771 | diux-dev/ncluster | ncluster/aws_util.py | get_instance_property | def get_instance_property(instance, property_name):
"""Retrieves property of an instance, keeps retrying until getting a non-None"""
name = get_name(instance)
while True:
try:
value = getattr(instance, property_name)
if value is not None:
break
print(f"retrieving {property_name} on {name} produced None, retrying")
time.sleep(RETRY_INTERVAL_SEC)
instance.reload()
continue
except Exception as e:
print(f"retrieving {property_name} on {name} failed with {e}, retrying")
time.sleep(RETRY_INTERVAL_SEC)
try:
instance.reload()
except Exception:
pass
continue
return value | python | def get_instance_property(instance, property_name):
name = get_name(instance)
while True:
try:
value = getattr(instance, property_name)
if value is not None:
break
print(f"retrieving {property_name} on {name} produced None, retrying")
time.sleep(RETRY_INTERVAL_SEC)
instance.reload()
continue
except Exception as e:
print(f"retrieving {property_name} on {name} failed with {e}, retrying")
time.sleep(RETRY_INTERVAL_SEC)
try:
instance.reload()
except Exception:
pass
continue
return value | [
"def",
"get_instance_property",
"(",
"instance",
",",
"property_name",
")",
":",
"name",
"=",
"get_name",
"(",
"instance",
")",
"while",
"True",
":",
"try",
":",
"value",
"=",
"getattr",
"(",
"instance",
",",
"property_name",
")",
"if",
"value",
"is",
"not... | Retrieves property of an instance, keeps retrying until getting a non-None | [
"Retrieves",
"property",
"of",
"an",
"instance",
"keeps",
"retrying",
"until",
"getting",
"a",
"non",
"-",
"None"
] | 2fd359621896717197b479c7174d06d80df1529b | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/aws_util.py#L565-L587 |
20,772 | diux-dev/ncluster | ncluster/aws_util.py | wait_until_available | def wait_until_available(resource):
"""Waits until interval state becomes 'available'"""
while True:
resource.load()
if resource.state == 'available':
break
time.sleep(RETRY_INTERVAL_SEC) | python | def wait_until_available(resource):
"""Waits until interval state becomes 'available'"""
while True:
resource.load()
if resource.state == 'available':
break
time.sleep(RETRY_INTERVAL_SEC) | [
"def",
"wait_until_available",
"(",
"resource",
")",
":",
"while",
"True",
":",
"resource",
".",
"load",
"(",
")",
"if",
"resource",
".",
"state",
"==",
"'available'",
":",
"break",
"time",
".",
"sleep",
"(",
"RETRY_INTERVAL_SEC",
")"
] | Waits until interval state becomes 'available | [
"Waits",
"until",
"interval",
"state",
"becomes",
"available"
] | 2fd359621896717197b479c7174d06d80df1529b | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/aws_util.py#L675-L681 |
20,773 | diux-dev/ncluster | ncluster/aws_util.py | maybe_create_placement_group | def maybe_create_placement_group(name='', max_retries=10):
"""Creates placement_group group or reuses existing one. Crash if unable to create
placement_group group. If name is empty, ignores request."""
if not name:
return
client = get_ec2_client()
while True:
try:
client.describe_placement_groups(GroupNames=[name])
print("Reusing placement_group group: " + name)
break # no Exception means group name was found
except Exception:
print("Creating placement_group group: " + name)
try:
_response = client.create_placement_group(GroupName=name,
Strategy='cluster')
except Exception:
# because of race can get InvalidPlacementGroup.Duplicate
pass
counter = 0
while True:
try:
res = client.describe_placement_groups(GroupNames=[name])
res_entry = res['PlacementGroups'][0]
if res_entry['State'] == 'available':
assert res_entry['Strategy'] == 'cluster'
break
except Exception as e:
print("Got exception: %s" % (e,))
counter += 1
if counter >= max_retries:
assert False, f'Failed to create placement_group group {name} in {max_retries} attempts'
time.sleep(RETRY_INTERVAL_SEC) | python | def maybe_create_placement_group(name='', max_retries=10):
if not name:
return
client = get_ec2_client()
while True:
try:
client.describe_placement_groups(GroupNames=[name])
print("Reusing placement_group group: " + name)
break # no Exception means group name was found
except Exception:
print("Creating placement_group group: " + name)
try:
_response = client.create_placement_group(GroupName=name,
Strategy='cluster')
except Exception:
# because of race can get InvalidPlacementGroup.Duplicate
pass
counter = 0
while True:
try:
res = client.describe_placement_groups(GroupNames=[name])
res_entry = res['PlacementGroups'][0]
if res_entry['State'] == 'available':
assert res_entry['Strategy'] == 'cluster'
break
except Exception as e:
print("Got exception: %s" % (e,))
counter += 1
if counter >= max_retries:
assert False, f'Failed to create placement_group group {name} in {max_retries} attempts'
time.sleep(RETRY_INTERVAL_SEC) | [
"def",
"maybe_create_placement_group",
"(",
"name",
"=",
"''",
",",
"max_retries",
"=",
"10",
")",
":",
"if",
"not",
"name",
":",
"return",
"client",
"=",
"get_ec2_client",
"(",
")",
"while",
"True",
":",
"try",
":",
"client",
".",
"describe_placement_groups... | Creates placement_group group or reuses existing one. Crash if unable to create
placement_group group. If name is empty, ignores request. | [
"Creates",
"placement_group",
"group",
"or",
"reuses",
"existing",
"one",
".",
"Crash",
"if",
"unable",
"to",
"create",
"placement_group",
"group",
".",
"If",
"name",
"is",
"empty",
"ignores",
"request",
"."
] | 2fd359621896717197b479c7174d06d80df1529b | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/aws_util.py#L684-L719 |
20,774 | diux-dev/ncluster | ncluster/ncluster_globals.py | is_chief | def is_chief(task: backend.Task, run_name: str):
"""Returns True if task is chief task in the corresponding run"""
global run_task_dict
if run_name not in run_task_dict:
return True
task_list = run_task_dict[run_name]
assert task in task_list, f"Task {task.name} doesn't belong to run {run_name}"
return task_list[0] == task | python | def is_chief(task: backend.Task, run_name: str):
global run_task_dict
if run_name not in run_task_dict:
return True
task_list = run_task_dict[run_name]
assert task in task_list, f"Task {task.name} doesn't belong to run {run_name}"
return task_list[0] == task | [
"def",
"is_chief",
"(",
"task",
":",
"backend",
".",
"Task",
",",
"run_name",
":",
"str",
")",
":",
"global",
"run_task_dict",
"if",
"run_name",
"not",
"in",
"run_task_dict",
":",
"return",
"True",
"task_list",
"=",
"run_task_dict",
"[",
"run_name",
"]",
"... | Returns True if task is chief task in the corresponding run | [
"Returns",
"True",
"if",
"task",
"is",
"chief",
"task",
"in",
"the",
"corresponding",
"run"
] | 2fd359621896717197b479c7174d06d80df1529b | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/ncluster_globals.py#L88-L95 |
20,775 | diux-dev/ncluster | benchmarks/util.py | ossystem | def ossystem(cmd):
"""Like os.system, but returns output of command as string."""
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
(stdout, stderr) = p.communicate()
return stdout.decode('ascii') | python | def ossystem(cmd):
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
(stdout, stderr) = p.communicate()
return stdout.decode('ascii') | [
"def",
"ossystem",
"(",
"cmd",
")",
":",
"p",
"=",
"subprocess",
".",
"Popen",
"(",
"cmd",
",",
"shell",
"=",
"True",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"STDOUT",
")",
"(",
"stdout",
",",
"stderr",
... | Like os.system, but returns output of command as string. | [
"Like",
"os",
".",
"system",
"but",
"returns",
"output",
"of",
"command",
"as",
"string",
"."
] | 2fd359621896717197b479c7174d06d80df1529b | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/benchmarks/util.py#L40-L45 |
20,776 | diux-dev/ncluster | ncluster/aws_backend.py | _maybe_create_resources | def _maybe_create_resources(logging_task: Task = None):
"""Use heuristics to decide to possibly create resources"""
def log(*args):
if logging_task:
logging_task.log(*args)
else:
util.log(*args)
def should_create_resources():
"""Check if gateway, keypair, vpc exist."""
prefix = u.get_prefix()
if u.get_keypair_name() not in u.get_keypair_dict():
log(f"Missing {u.get_keypair_name()} keypair, creating resources")
return True
vpcs = u.get_vpc_dict()
if prefix not in vpcs:
log(f"Missing {prefix} vpc, creating resources")
return True
vpc = vpcs[prefix]
gateways = u.get_gateway_dict(vpc)
if prefix not in gateways:
log(f"Missing {prefix} gateway, creating resources")
return True
return False
try:
# this locking is approximate, still possible for threads to slip through
if os.path.exists(AWS_LOCK_FN):
pid, ts, lock_taskname = open(AWS_LOCK_FN).read().split('-')
ts = int(ts)
log(f"waiting for aws resource creation, another resource initiation was "
f"initiated {int(time.time()-ts)} seconds ago by "
f"{lock_taskname}, delete lock file "
f"{AWS_LOCK_FN} if this is an error")
while True:
if os.path.exists(AWS_LOCK_FN):
log(f"waiting for lock file {AWS_LOCK_FN} to get deleted "
f"initiated {int(time.time()-ts)} seconds ago by ")
time.sleep(2)
continue
else:
break
return
with open(AWS_LOCK_FN, 'w') as f:
f.write(
f'{os.getpid()}-{int(time.time())}-{logging_task.name if logging_task else ""}')
if not should_create_resources():
util.log("Resources already created, no-op")
os.remove(AWS_LOCK_FN)
return
create_lib.create_resources()
finally:
if os.path.exists(AWS_LOCK_FN):
os.remove(AWS_LOCK_FN) | python | def _maybe_create_resources(logging_task: Task = None):
def log(*args):
if logging_task:
logging_task.log(*args)
else:
util.log(*args)
def should_create_resources():
"""Check if gateway, keypair, vpc exist."""
prefix = u.get_prefix()
if u.get_keypair_name() not in u.get_keypair_dict():
log(f"Missing {u.get_keypair_name()} keypair, creating resources")
return True
vpcs = u.get_vpc_dict()
if prefix not in vpcs:
log(f"Missing {prefix} vpc, creating resources")
return True
vpc = vpcs[prefix]
gateways = u.get_gateway_dict(vpc)
if prefix not in gateways:
log(f"Missing {prefix} gateway, creating resources")
return True
return False
try:
# this locking is approximate, still possible for threads to slip through
if os.path.exists(AWS_LOCK_FN):
pid, ts, lock_taskname = open(AWS_LOCK_FN).read().split('-')
ts = int(ts)
log(f"waiting for aws resource creation, another resource initiation was "
f"initiated {int(time.time()-ts)} seconds ago by "
f"{lock_taskname}, delete lock file "
f"{AWS_LOCK_FN} if this is an error")
while True:
if os.path.exists(AWS_LOCK_FN):
log(f"waiting for lock file {AWS_LOCK_FN} to get deleted "
f"initiated {int(time.time()-ts)} seconds ago by ")
time.sleep(2)
continue
else:
break
return
with open(AWS_LOCK_FN, 'w') as f:
f.write(
f'{os.getpid()}-{int(time.time())}-{logging_task.name if logging_task else ""}')
if not should_create_resources():
util.log("Resources already created, no-op")
os.remove(AWS_LOCK_FN)
return
create_lib.create_resources()
finally:
if os.path.exists(AWS_LOCK_FN):
os.remove(AWS_LOCK_FN) | [
"def",
"_maybe_create_resources",
"(",
"logging_task",
":",
"Task",
"=",
"None",
")",
":",
"def",
"log",
"(",
"*",
"args",
")",
":",
"if",
"logging_task",
":",
"logging_task",
".",
"log",
"(",
"*",
"args",
")",
"else",
":",
"util",
".",
"log",
"(",
"... | Use heuristics to decide to possibly create resources | [
"Use",
"heuristics",
"to",
"decide",
"to",
"possibly",
"create",
"resources"
] | 2fd359621896717197b479c7174d06d80df1529b | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/aws_backend.py#L933-L990 |
20,777 | diux-dev/ncluster | ncluster/aws_backend.py | _set_aws_environment | def _set_aws_environment(task: Task = None):
"""Sets up AWS environment from NCLUSTER environment variables"""
current_zone = os.environ.get('NCLUSTER_ZONE', '')
current_region = os.environ.get('AWS_DEFAULT_REGION', '')
def log(*args):
if task:
task.log(*args)
else:
util.log(*args)
if current_region and current_zone:
assert current_zone.startswith(
current_region), f'Current zone "{current_zone}" ($NCLUSTER_ZONE) is not ' \
f'in current region "{current_region} ($AWS_DEFAULT_REGION)'
assert u.get_session().region_name == current_region # setting from ~/.aws
# zone is set, set region from zone
if current_zone and not current_region:
current_region = current_zone[:-1]
os.environ['AWS_DEFAULT_REGION'] = current_region
# neither zone nor region not set, use default setting for region
# if default is not set, use NCLUSTER_DEFAULT_REGION
if not current_region:
current_region = u.get_session().region_name
if not current_region:
log(f"No default region available, using {NCLUSTER_DEFAULT_REGION}")
current_region = NCLUSTER_DEFAULT_REGION
os.environ['AWS_DEFAULT_REGION'] = current_region
# zone not set, use first zone of the region
# if not current_zone:
# current_zone = current_region + 'a'
# os.environ['NCLUSTER_ZONE'] = current_zone
log(f"Using account {u.get_account_number()}, region {current_region}, "
f"zone {current_zone}") | python | def _set_aws_environment(task: Task = None):
current_zone = os.environ.get('NCLUSTER_ZONE', '')
current_region = os.environ.get('AWS_DEFAULT_REGION', '')
def log(*args):
if task:
task.log(*args)
else:
util.log(*args)
if current_region and current_zone:
assert current_zone.startswith(
current_region), f'Current zone "{current_zone}" ($NCLUSTER_ZONE) is not ' \
f'in current region "{current_region} ($AWS_DEFAULT_REGION)'
assert u.get_session().region_name == current_region # setting from ~/.aws
# zone is set, set region from zone
if current_zone and not current_region:
current_region = current_zone[:-1]
os.environ['AWS_DEFAULT_REGION'] = current_region
# neither zone nor region not set, use default setting for region
# if default is not set, use NCLUSTER_DEFAULT_REGION
if not current_region:
current_region = u.get_session().region_name
if not current_region:
log(f"No default region available, using {NCLUSTER_DEFAULT_REGION}")
current_region = NCLUSTER_DEFAULT_REGION
os.environ['AWS_DEFAULT_REGION'] = current_region
# zone not set, use first zone of the region
# if not current_zone:
# current_zone = current_region + 'a'
# os.environ['NCLUSTER_ZONE'] = current_zone
log(f"Using account {u.get_account_number()}, region {current_region}, "
f"zone {current_zone}") | [
"def",
"_set_aws_environment",
"(",
"task",
":",
"Task",
"=",
"None",
")",
":",
"current_zone",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'NCLUSTER_ZONE'",
",",
"''",
")",
"current_region",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'AWS_DEFAULT_REGIO... | Sets up AWS environment from NCLUSTER environment variables | [
"Sets",
"up",
"AWS",
"environment",
"from",
"NCLUSTER",
"environment",
"variables"
] | 2fd359621896717197b479c7174d06d80df1529b | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/aws_backend.py#L993-L1030 |
20,778 | diux-dev/ncluster | ncluster/aws_backend.py | Task.join | def join(self, ignore_errors=False):
"""Waits until last executed command completed."""
assert self._status_fn, "Asked to join a task which hasn't had any commands executed on it"
check_interval = 0.2
status_fn = self._status_fn
if not self.wait_for_file(status_fn, max_wait_sec=30):
self.log(f"Retrying waiting for {status_fn}")
while not self.exists(status_fn):
self.log(f"Still waiting for {self._cmd}")
self.wait_for_file(status_fn, max_wait_sec=30)
contents = self.read(status_fn)
# if empty wait a bit to allow for race condition
if len(contents) == 0:
time.sleep(check_interval)
contents = self.read(status_fn)
status = int(contents.strip())
self.last_status = status
if status != 0:
extra_msg = '(ignoring error)' if ignore_errors else '(failing)'
if util.is_set('NCLUSTER_RUN_WITH_OUTPUT_ON_FAILURE') or True:
self.log(
f"Start failing output {extra_msg}: \n{'*'*80}\n\n '{self.read(self._out_fn)}'")
self.log(f"\n{'*'*80}\nEnd failing output")
if not ignore_errors:
raise RuntimeError(f"Command {self._cmd} returned status {status}")
else:
self.log(f"Warning: command {self._cmd} returned status {status}")
return status | python | def join(self, ignore_errors=False):
assert self._status_fn, "Asked to join a task which hasn't had any commands executed on it"
check_interval = 0.2
status_fn = self._status_fn
if not self.wait_for_file(status_fn, max_wait_sec=30):
self.log(f"Retrying waiting for {status_fn}")
while not self.exists(status_fn):
self.log(f"Still waiting for {self._cmd}")
self.wait_for_file(status_fn, max_wait_sec=30)
contents = self.read(status_fn)
# if empty wait a bit to allow for race condition
if len(contents) == 0:
time.sleep(check_interval)
contents = self.read(status_fn)
status = int(contents.strip())
self.last_status = status
if status != 0:
extra_msg = '(ignoring error)' if ignore_errors else '(failing)'
if util.is_set('NCLUSTER_RUN_WITH_OUTPUT_ON_FAILURE') or True:
self.log(
f"Start failing output {extra_msg}: \n{'*'*80}\n\n '{self.read(self._out_fn)}'")
self.log(f"\n{'*'*80}\nEnd failing output")
if not ignore_errors:
raise RuntimeError(f"Command {self._cmd} returned status {status}")
else:
self.log(f"Warning: command {self._cmd} returned status {status}")
return status | [
"def",
"join",
"(",
"self",
",",
"ignore_errors",
"=",
"False",
")",
":",
"assert",
"self",
".",
"_status_fn",
",",
"\"Asked to join a task which hasn't had any commands executed on it\"",
"check_interval",
"=",
"0.2",
"status_fn",
"=",
"self",
".",
"_status_fn",
"if"... | Waits until last executed command completed. | [
"Waits",
"until",
"last",
"executed",
"command",
"completed",
"."
] | 2fd359621896717197b479c7174d06d80df1529b | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/aws_backend.py#L272-L302 |
20,779 | diux-dev/ncluster | ncluster/aws_backend.py | Task._run_with_output_on_failure | def _run_with_output_on_failure(self, cmd, non_blocking=False,
ignore_errors=False,
max_wait_sec=365 * 24 * 3600,
check_interval=0.2) -> str:
"""Experimental version of run propagates error messages to client. This command will be default "run" eventually"""
if not self._can_run:
assert False, "Using .run before initialization finished"
if '\n' in cmd:
assert False, "Don't support multi-line for run2"
cmd = cmd.strip()
if cmd.startswith('#'): # ignore empty/commented out lines
return ''
self.run_counter += 1
self.log("tmux> %s", cmd)
self._cmd = cmd
self._cmd_fn = f'{self.remote_scratch}/{self.run_counter}.cmd'
self._status_fn = f'{self.remote_scratch}/{self.run_counter}.status'
self._out_fn = f'{self.remote_scratch}/{self.run_counter}.out'
cmd = util.shell_strip_comment(cmd)
assert '&' not in cmd, f"cmd {cmd} contains &, that breaks things"
# modify command to dump shell success status into file
self.file_write(self._cmd_fn, cmd + '\n')
# modified_cmd = f'{cmd} > {out_fn} 2>&1; echo $? > {status_fn}'
# https://stackoverflow.com/a/692407/419116
# $cmd > >(tee -a fn) 2> >(tee -a fn >&2)
modified_cmd = f'{cmd} > >(tee -a {self._out_fn}) 2> >(tee -a {self._out_fn} >&2); echo $? > {self._status_fn}'
modified_cmd = shlex.quote(modified_cmd)
start_time = time.time()
tmux_window = self.tmux_session + ':' + str(self.tmux_window_id)
tmux_cmd = f"tmux send-keys -t {tmux_window} {modified_cmd} Enter"
self._run_raw(tmux_cmd, ignore_errors=ignore_errors)
if non_blocking:
return 0
if not self.wait_for_file(self._status_fn, max_wait_sec=60):
self.log(f"Retrying waiting for {self._status_fn}")
elapsed_time = time.time() - start_time
while not self.exists(self._status_fn) and elapsed_time < max_wait_sec:
self.log(f"Still waiting for {cmd}")
self.wait_for_file(self._status_fn, max_wait_sec=60)
elapsed_time = time.time() - start_time
contents = self.read(self._status_fn)
# if empty wait a bit to allow for race condition
if len(contents) == 0:
time.sleep(check_interval)
contents = self.read(self._status_fn)
status = int(contents.strip())
self.last_status = status
if status != 0:
extra_msg = '(ignoring error)' if ignore_errors else '(failing)'
self.log(
f"Start failing output {extra_msg}: \n{'*'*80}\n\n '{self.read(self._out_fn)}'")
self.log(f"\n{'*'*80}\nEnd failing output")
if not ignore_errors:
raise RuntimeError(f"Command {cmd} returned status {status}")
else:
self.log(f"Warning: command {cmd} returned status {status}")
return self.read(self._out_fn) | python | def _run_with_output_on_failure(self, cmd, non_blocking=False,
ignore_errors=False,
max_wait_sec=365 * 24 * 3600,
check_interval=0.2) -> str:
if not self._can_run:
assert False, "Using .run before initialization finished"
if '\n' in cmd:
assert False, "Don't support multi-line for run2"
cmd = cmd.strip()
if cmd.startswith('#'): # ignore empty/commented out lines
return ''
self.run_counter += 1
self.log("tmux> %s", cmd)
self._cmd = cmd
self._cmd_fn = f'{self.remote_scratch}/{self.run_counter}.cmd'
self._status_fn = f'{self.remote_scratch}/{self.run_counter}.status'
self._out_fn = f'{self.remote_scratch}/{self.run_counter}.out'
cmd = util.shell_strip_comment(cmd)
assert '&' not in cmd, f"cmd {cmd} contains &, that breaks things"
# modify command to dump shell success status into file
self.file_write(self._cmd_fn, cmd + '\n')
# modified_cmd = f'{cmd} > {out_fn} 2>&1; echo $? > {status_fn}'
# https://stackoverflow.com/a/692407/419116
# $cmd > >(tee -a fn) 2> >(tee -a fn >&2)
modified_cmd = f'{cmd} > >(tee -a {self._out_fn}) 2> >(tee -a {self._out_fn} >&2); echo $? > {self._status_fn}'
modified_cmd = shlex.quote(modified_cmd)
start_time = time.time()
tmux_window = self.tmux_session + ':' + str(self.tmux_window_id)
tmux_cmd = f"tmux send-keys -t {tmux_window} {modified_cmd} Enter"
self._run_raw(tmux_cmd, ignore_errors=ignore_errors)
if non_blocking:
return 0
if not self.wait_for_file(self._status_fn, max_wait_sec=60):
self.log(f"Retrying waiting for {self._status_fn}")
elapsed_time = time.time() - start_time
while not self.exists(self._status_fn) and elapsed_time < max_wait_sec:
self.log(f"Still waiting for {cmd}")
self.wait_for_file(self._status_fn, max_wait_sec=60)
elapsed_time = time.time() - start_time
contents = self.read(self._status_fn)
# if empty wait a bit to allow for race condition
if len(contents) == 0:
time.sleep(check_interval)
contents = self.read(self._status_fn)
status = int(contents.strip())
self.last_status = status
if status != 0:
extra_msg = '(ignoring error)' if ignore_errors else '(failing)'
self.log(
f"Start failing output {extra_msg}: \n{'*'*80}\n\n '{self.read(self._out_fn)}'")
self.log(f"\n{'*'*80}\nEnd failing output")
if not ignore_errors:
raise RuntimeError(f"Command {cmd} returned status {status}")
else:
self.log(f"Warning: command {cmd} returned status {status}")
return self.read(self._out_fn) | [
"def",
"_run_with_output_on_failure",
"(",
"self",
",",
"cmd",
",",
"non_blocking",
"=",
"False",
",",
"ignore_errors",
"=",
"False",
",",
"max_wait_sec",
"=",
"365",
"*",
"24",
"*",
"3600",
",",
"check_interval",
"=",
"0.2",
")",
"->",
"str",
":",
"if",
... | Experimental version of run propagates error messages to client. This command will be default "run" eventually | [
"Experimental",
"version",
"of",
"run",
"propagates",
"error",
"messages",
"to",
"client",
".",
"This",
"command",
"will",
"be",
"default",
"run",
"eventually"
] | 2fd359621896717197b479c7174d06d80df1529b | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/aws_backend.py#L304-L373 |
20,780 | diux-dev/ncluster | ncluster/aws_backend.py | Task.upload | def upload(self, local_fn: str, remote_fn: str = '',
dont_overwrite: bool = False) -> None:
"""Uploads file to remote instance. If location not specified, dumps it
into default directory. If remote location has files or directories with the
same name, behavior is undefined."""
# support wildcard through glob
if '*' in local_fn:
for local_subfn in glob.glob(local_fn):
self.upload(local_subfn)
return
if '#' in local_fn: # hashes also give problems from shell commands
self.log("skipping backup file {local_fn}")
return
if not self.sftp:
self.sftp = u.call_with_retries(self.ssh_client.open_sftp,
'self.ssh_client.open_sftp')
def maybe_fix_mode(local_fn_, remote_fn_):
"""Makes remote file execute for locally executable files"""
mode = oct(os.stat(local_fn_)[stat.ST_MODE])[-3:]
if '7' in mode:
self.log(f"Making {remote_fn_} executable with mode {mode}")
# use raw run, in case tmux is unavailable
self._run_raw(f"chmod {mode} {remote_fn_}")
# augmented SFTP client that can transfer directories, from
# https://stackoverflow.com/a/19974994/419116
def _put_dir(source, target):
""" Uploads the contents of the source directory to the target path."""
def _safe_mkdir(path, mode=511, ignore_existing=True):
""" Augments mkdir by adding an option to not fail if the folder exists asdf asdf asdf as"""
try:
self.sftp.mkdir(path, mode)
except IOError:
if ignore_existing:
pass
else:
raise
assert os.path.isdir(source)
_safe_mkdir(target)
for item in os.listdir(source):
if os.path.isfile(os.path.join(source, item)):
self.sftp.put(os.path.join(source, item), os.path.join(target, item))
maybe_fix_mode(os.path.join(source, item), os.path.join(target, item))
else:
_safe_mkdir(f'{target}/{item}')
_put_dir(f'{source}/{item}', f'{target}/{item}')
if not remote_fn:
remote_fn = os.path.basename(local_fn)
self.log('uploading ' + local_fn + ' to ' + remote_fn)
remote_fn = remote_fn.replace('~', self.homedir)
if '/' in remote_fn:
remote_dir = os.path.dirname(remote_fn)
assert self.exists(
remote_dir), f"Remote dir {remote_dir} doesn't exist"
if dont_overwrite and self.exists(remote_fn):
self.log("Remote file %s exists, skipping" % (remote_fn,))
return
assert os.path.exists(local_fn), f"{local_fn} not found"
if os.path.isdir(local_fn):
_put_dir(local_fn, remote_fn)
else:
assert os.path.isfile(local_fn), "%s is not a file" % (local_fn,)
# this crashes with IOError when upload failed
if self.exists(remote_fn) and self.isdir(remote_fn):
remote_fn = remote_fn + '/' + os.path.basename(local_fn)
self.sftp.put(localpath=local_fn, remotepath=remote_fn)
maybe_fix_mode(local_fn, remote_fn) | python | def upload(self, local_fn: str, remote_fn: str = '',
dont_overwrite: bool = False) -> None:
# support wildcard through glob
if '*' in local_fn:
for local_subfn in glob.glob(local_fn):
self.upload(local_subfn)
return
if '#' in local_fn: # hashes also give problems from shell commands
self.log("skipping backup file {local_fn}")
return
if not self.sftp:
self.sftp = u.call_with_retries(self.ssh_client.open_sftp,
'self.ssh_client.open_sftp')
def maybe_fix_mode(local_fn_, remote_fn_):
"""Makes remote file execute for locally executable files"""
mode = oct(os.stat(local_fn_)[stat.ST_MODE])[-3:]
if '7' in mode:
self.log(f"Making {remote_fn_} executable with mode {mode}")
# use raw run, in case tmux is unavailable
self._run_raw(f"chmod {mode} {remote_fn_}")
# augmented SFTP client that can transfer directories, from
# https://stackoverflow.com/a/19974994/419116
def _put_dir(source, target):
""" Uploads the contents of the source directory to the target path."""
def _safe_mkdir(path, mode=511, ignore_existing=True):
""" Augments mkdir by adding an option to not fail if the folder exists asdf asdf asdf as"""
try:
self.sftp.mkdir(path, mode)
except IOError:
if ignore_existing:
pass
else:
raise
assert os.path.isdir(source)
_safe_mkdir(target)
for item in os.listdir(source):
if os.path.isfile(os.path.join(source, item)):
self.sftp.put(os.path.join(source, item), os.path.join(target, item))
maybe_fix_mode(os.path.join(source, item), os.path.join(target, item))
else:
_safe_mkdir(f'{target}/{item}')
_put_dir(f'{source}/{item}', f'{target}/{item}')
if not remote_fn:
remote_fn = os.path.basename(local_fn)
self.log('uploading ' + local_fn + ' to ' + remote_fn)
remote_fn = remote_fn.replace('~', self.homedir)
if '/' in remote_fn:
remote_dir = os.path.dirname(remote_fn)
assert self.exists(
remote_dir), f"Remote dir {remote_dir} doesn't exist"
if dont_overwrite and self.exists(remote_fn):
self.log("Remote file %s exists, skipping" % (remote_fn,))
return
assert os.path.exists(local_fn), f"{local_fn} not found"
if os.path.isdir(local_fn):
_put_dir(local_fn, remote_fn)
else:
assert os.path.isfile(local_fn), "%s is not a file" % (local_fn,)
# this crashes with IOError when upload failed
if self.exists(remote_fn) and self.isdir(remote_fn):
remote_fn = remote_fn + '/' + os.path.basename(local_fn)
self.sftp.put(localpath=local_fn, remotepath=remote_fn)
maybe_fix_mode(local_fn, remote_fn) | [
"def",
"upload",
"(",
"self",
",",
"local_fn",
":",
"str",
",",
"remote_fn",
":",
"str",
"=",
"''",
",",
"dont_overwrite",
":",
"bool",
"=",
"False",
")",
"->",
"None",
":",
"# support wildcard through glob",
"if",
"'*'",
"in",
"local_fn",
":",
"for",
"l... | Uploads file to remote instance. If location not specified, dumps it
into default directory. If remote location has files or directories with the
same name, behavior is undefined. | [
"Uploads",
"file",
"to",
"remote",
"instance",
".",
"If",
"location",
"not",
"specified",
"dumps",
"it",
"into",
"default",
"directory",
".",
"If",
"remote",
"location",
"has",
"files",
"or",
"directories",
"with",
"the",
"same",
"name",
"behavior",
"is",
"u... | 2fd359621896717197b479c7174d06d80df1529b | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/aws_backend.py#L398-L475 |
20,781 | diux-dev/ncluster | examples/gpubox.py | _replace_lines | def _replace_lines(fn, startswith, new_line):
"""Replace lines starting with starts_with in fn with new_line."""
new_lines = []
for line in open(fn):
if line.startswith(startswith):
new_lines.append(new_line)
else:
new_lines.append(line)
with open(fn, 'w') as f:
f.write('\n'.join(new_lines)) | python | def _replace_lines(fn, startswith, new_line):
new_lines = []
for line in open(fn):
if line.startswith(startswith):
new_lines.append(new_line)
else:
new_lines.append(line)
with open(fn, 'w') as f:
f.write('\n'.join(new_lines)) | [
"def",
"_replace_lines",
"(",
"fn",
",",
"startswith",
",",
"new_line",
")",
":",
"new_lines",
"=",
"[",
"]",
"for",
"line",
"in",
"open",
"(",
"fn",
")",
":",
"if",
"line",
".",
"startswith",
"(",
"startswith",
")",
":",
"new_lines",
".",
"append",
... | Replace lines starting with starts_with in fn with new_line. | [
"Replace",
"lines",
"starting",
"with",
"starts_with",
"in",
"fn",
"with",
"new_line",
"."
] | 2fd359621896717197b479c7174d06d80df1529b | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/examples/gpubox.py#L59-L68 |
20,782 | diux-dev/ncluster | ncluster/util.py | now_micros | def now_micros(absolute=False) -> int:
"""Return current micros since epoch as integer."""
micros = int(time.time() * 1e6)
if absolute:
return micros
return micros - EPOCH_MICROS | python | def now_micros(absolute=False) -> int:
micros = int(time.time() * 1e6)
if absolute:
return micros
return micros - EPOCH_MICROS | [
"def",
"now_micros",
"(",
"absolute",
"=",
"False",
")",
"->",
"int",
":",
"micros",
"=",
"int",
"(",
"time",
".",
"time",
"(",
")",
"*",
"1e6",
")",
"if",
"absolute",
":",
"return",
"micros",
"return",
"micros",
"-",
"EPOCH_MICROS"
] | Return current micros since epoch as integer. | [
"Return",
"current",
"micros",
"since",
"epoch",
"as",
"integer",
"."
] | 2fd359621896717197b479c7174d06d80df1529b | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/util.py#L23-L28 |
20,783 | diux-dev/ncluster | ncluster/util.py | now_millis | def now_millis(absolute=False) -> int:
"""Return current millis since epoch as integer."""
millis = int(time.time() * 1e3)
if absolute:
return millis
return millis - EPOCH_MICROS // 1000 | python | def now_millis(absolute=False) -> int:
millis = int(time.time() * 1e3)
if absolute:
return millis
return millis - EPOCH_MICROS // 1000 | [
"def",
"now_millis",
"(",
"absolute",
"=",
"False",
")",
"->",
"int",
":",
"millis",
"=",
"int",
"(",
"time",
".",
"time",
"(",
")",
"*",
"1e3",
")",
"if",
"absolute",
":",
"return",
"millis",
"return",
"millis",
"-",
"EPOCH_MICROS",
"//",
"1000"
] | Return current millis since epoch as integer. | [
"Return",
"current",
"millis",
"since",
"epoch",
"as",
"integer",
"."
] | 2fd359621896717197b479c7174d06d80df1529b | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/util.py#L31-L36 |
20,784 | diux-dev/ncluster | ncluster/util.py | install_pdb_handler | def install_pdb_handler():
"""Make CTRL+\ break into gdb."""
import signal
import pdb
def handler(_signum, _frame):
pdb.set_trace()
signal.signal(signal.SIGQUIT, handler) | python | def install_pdb_handler():
import signal
import pdb
def handler(_signum, _frame):
pdb.set_trace()
signal.signal(signal.SIGQUIT, handler) | [
"def",
"install_pdb_handler",
"(",
")",
":",
"import",
"signal",
"import",
"pdb",
"def",
"handler",
"(",
"_signum",
",",
"_frame",
")",
":",
"pdb",
".",
"set_trace",
"(",
")",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGQUIT",
",",
"handler",
")"
] | Make CTRL+\ break into gdb. | [
"Make",
"CTRL",
"+",
"\\",
"break",
"into",
"gdb",
"."
] | 2fd359621896717197b479c7174d06d80df1529b | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/util.py#L56-L65 |
20,785 | diux-dev/ncluster | ncluster/util.py | shell_add_echo | def shell_add_echo(script):
"""Goes over each line script, adds "echo cmd" in front of each cmd.
ls a
becomes
echo * ls a
ls a
"""
new_script = ""
for cmd in script.split('\n'):
cmd = cmd.strip()
if not cmd:
continue
new_script += "echo \\* " + shlex.quote(cmd) + "\n"
new_script += cmd + "\n"
return new_script | python | def shell_add_echo(script):
new_script = ""
for cmd in script.split('\n'):
cmd = cmd.strip()
if not cmd:
continue
new_script += "echo \\* " + shlex.quote(cmd) + "\n"
new_script += cmd + "\n"
return new_script | [
"def",
"shell_add_echo",
"(",
"script",
")",
":",
"new_script",
"=",
"\"\"",
"for",
"cmd",
"in",
"script",
".",
"split",
"(",
"'\\n'",
")",
":",
"cmd",
"=",
"cmd",
".",
"strip",
"(",
")",
"if",
"not",
"cmd",
":",
"continue",
"new_script",
"+=",
"\"ec... | Goes over each line script, adds "echo cmd" in front of each cmd.
ls a
becomes
echo * ls a
ls a | [
"Goes",
"over",
"each",
"line",
"script",
"adds",
"echo",
"cmd",
"in",
"front",
"of",
"each",
"cmd",
"."
] | 2fd359621896717197b479c7174d06d80df1529b | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/util.py#L68-L85 |
20,786 | diux-dev/ncluster | ncluster/util.py | random_id | def random_id(k=5):
"""Random id to use for AWS identifiers."""
# https://stackoverflow.com/questions/2257441/random-string-generation-with-upper-case-letters-and-digits-in-python
return ''.join(random.choices(string.ascii_lowercase + string.digits, k=k)) | python | def random_id(k=5):
# https://stackoverflow.com/questions/2257441/random-string-generation-with-upper-case-letters-and-digits-in-python
return ''.join(random.choices(string.ascii_lowercase + string.digits, k=k)) | [
"def",
"random_id",
"(",
"k",
"=",
"5",
")",
":",
"# https://stackoverflow.com/questions/2257441/random-string-generation-with-upper-case-letters-and-digits-in-python",
"return",
"''",
".",
"join",
"(",
"random",
".",
"choices",
"(",
"string",
".",
"ascii_lowercase",
"+",
... | Random id to use for AWS identifiers. | [
"Random",
"id",
"to",
"use",
"for",
"AWS",
"identifiers",
"."
] | 2fd359621896717197b479c7174d06d80df1529b | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/util.py#L96-L99 |
20,787 | diux-dev/ncluster | ncluster/util.py | alphanumeric_hash | def alphanumeric_hash(s: str, size=5):
"""Short alphanumeric string derived from hash of given string"""
import hashlib
import base64
hash_object = hashlib.md5(s.encode('ascii'))
s = base64.b32encode(hash_object.digest())
result = s[:size].decode('ascii').lower()
return result | python | def alphanumeric_hash(s: str, size=5):
import hashlib
import base64
hash_object = hashlib.md5(s.encode('ascii'))
s = base64.b32encode(hash_object.digest())
result = s[:size].decode('ascii').lower()
return result | [
"def",
"alphanumeric_hash",
"(",
"s",
":",
"str",
",",
"size",
"=",
"5",
")",
":",
"import",
"hashlib",
"import",
"base64",
"hash_object",
"=",
"hashlib",
".",
"md5",
"(",
"s",
".",
"encode",
"(",
"'ascii'",
")",
")",
"s",
"=",
"base64",
".",
"b32enc... | Short alphanumeric string derived from hash of given string | [
"Short",
"alphanumeric",
"string",
"derived",
"from",
"hash",
"of",
"given",
"string"
] | 2fd359621896717197b479c7174d06d80df1529b | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/util.py#L102-L109 |
20,788 | diux-dev/ncluster | ncluster/util.py | is_bash_builtin | def is_bash_builtin(cmd):
"""Return true if command is invoking bash built-in
"""
# from compgen -b
bash_builtins = ['alias', 'bg', 'bind', 'alias', 'bg', 'bind', 'break',
'builtin', 'caller', 'cd', 'command', 'compgen', 'complete',
'compopt', 'continue', 'declare', 'dirs', 'disown', 'echo',
'enable', 'eval', 'exec', 'exit', 'export', 'false', 'fc',
'fg', 'getopts', 'hash', 'help', 'history', 'jobs', 'kill',
'let', 'local', 'logout', 'mapfile', 'popd', 'printf',
'pushd', 'pwd', 'read', 'readarray', 'readonly', 'return',
'set', 'shift', 'shopt', 'source', 'suspend', 'test',
'times', 'trap', 'true', 'type', 'typeset', 'ulimit',
'umask', 'unalias', 'unset', 'wait']
toks = cmd.split()
if toks and toks[0] in bash_builtins:
return True
return False | python | def is_bash_builtin(cmd):
# from compgen -b
bash_builtins = ['alias', 'bg', 'bind', 'alias', 'bg', 'bind', 'break',
'builtin', 'caller', 'cd', 'command', 'compgen', 'complete',
'compopt', 'continue', 'declare', 'dirs', 'disown', 'echo',
'enable', 'eval', 'exec', 'exit', 'export', 'false', 'fc',
'fg', 'getopts', 'hash', 'help', 'history', 'jobs', 'kill',
'let', 'local', 'logout', 'mapfile', 'popd', 'printf',
'pushd', 'pwd', 'read', 'readarray', 'readonly', 'return',
'set', 'shift', 'shopt', 'source', 'suspend', 'test',
'times', 'trap', 'true', 'type', 'typeset', 'ulimit',
'umask', 'unalias', 'unset', 'wait']
toks = cmd.split()
if toks and toks[0] in bash_builtins:
return True
return False | [
"def",
"is_bash_builtin",
"(",
"cmd",
")",
":",
"# from compgen -b",
"bash_builtins",
"=",
"[",
"'alias'",
",",
"'bg'",
",",
"'bind'",
",",
"'alias'",
",",
"'bg'",
",",
"'bind'",
",",
"'break'",
",",
"'builtin'",
",",
"'caller'",
",",
"'cd'",
",",
"'comman... | Return true if command is invoking bash built-in | [
"Return",
"true",
"if",
"command",
"is",
"invoking",
"bash",
"built",
"-",
"in"
] | 2fd359621896717197b479c7174d06d80df1529b | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/util.py#L130-L147 |
20,789 | diux-dev/ncluster | ncluster/util.py | is_set | def is_set(name):
"""Helper method to check if given property is set"""
val = os.environ.get(name, '0')
assert val == '0' or val == '1', f"env var {name} has value {val}, expected 0 or 1"
return val == '1' | python | def is_set(name):
val = os.environ.get(name, '0')
assert val == '0' or val == '1', f"env var {name} has value {val}, expected 0 or 1"
return val == '1' | [
"def",
"is_set",
"(",
"name",
")",
":",
"val",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"name",
",",
"'0'",
")",
"assert",
"val",
"==",
"'0'",
"or",
"val",
"==",
"'1'",
",",
"f\"env var {name} has value {val}, expected 0 or 1\"",
"return",
"val",
"==",
... | Helper method to check if given property is set | [
"Helper",
"method",
"to",
"check",
"if",
"given",
"property",
"is",
"set"
] | 2fd359621896717197b479c7174d06d80df1529b | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/util.py#L150-L154 |
20,790 | diux-dev/ncluster | ncluster/util.py | assert_script_in_current_directory | def assert_script_in_current_directory():
"""Assert fail if current directory is different from location of the script"""
script = sys.argv[0]
assert os.path.abspath(os.path.dirname(script)) == os.path.abspath(
'.'), f"Change into directory of script {script} and run again." | python | def assert_script_in_current_directory():
script = sys.argv[0]
assert os.path.abspath(os.path.dirname(script)) == os.path.abspath(
'.'), f"Change into directory of script {script} and run again." | [
"def",
"assert_script_in_current_directory",
"(",
")",
":",
"script",
"=",
"sys",
".",
"argv",
"[",
"0",
"]",
"assert",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"script",
")",
")",
"==",
"os",
".",
"path",
".",
... | Assert fail if current directory is different from location of the script | [
"Assert",
"fail",
"if",
"current",
"directory",
"is",
"different",
"from",
"location",
"of",
"the",
"script"
] | 2fd359621896717197b479c7174d06d80df1529b | https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/util.py#L157-L162 |
20,791 | croach/Flask-Fixtures | flask_fixtures/__init__.py | load_fixtures | def load_fixtures(db, fixtures):
"""Loads the given fixtures into the database.
"""
conn = db.engine.connect()
metadata = db.metadata
for fixture in fixtures:
if 'model' in fixture:
module_name, class_name = fixture['model'].rsplit('.', 1)
module = importlib.import_module(module_name)
model = getattr(module, class_name)
for fields in fixture['records']:
obj = model(**fields)
db.session.add(obj)
db.session.commit()
elif 'table' in fixture:
table = Table(fixture['table'], metadata)
conn.execute(table.insert(), fixture['records'])
else:
raise ValueError("Fixture missing a 'model' or 'table' field: {0}".format(json.dumps(fixture))) | python | def load_fixtures(db, fixtures):
conn = db.engine.connect()
metadata = db.metadata
for fixture in fixtures:
if 'model' in fixture:
module_name, class_name = fixture['model'].rsplit('.', 1)
module = importlib.import_module(module_name)
model = getattr(module, class_name)
for fields in fixture['records']:
obj = model(**fields)
db.session.add(obj)
db.session.commit()
elif 'table' in fixture:
table = Table(fixture['table'], metadata)
conn.execute(table.insert(), fixture['records'])
else:
raise ValueError("Fixture missing a 'model' or 'table' field: {0}".format(json.dumps(fixture))) | [
"def",
"load_fixtures",
"(",
"db",
",",
"fixtures",
")",
":",
"conn",
"=",
"db",
".",
"engine",
".",
"connect",
"(",
")",
"metadata",
"=",
"db",
".",
"metadata",
"for",
"fixture",
"in",
"fixtures",
":",
"if",
"'model'",
"in",
"fixture",
":",
"module_na... | Loads the given fixtures into the database. | [
"Loads",
"the",
"given",
"fixtures",
"into",
"the",
"database",
"."
] | b34597d165b33cc47cdd632ac0f3cf8a07428675 | https://github.com/croach/Flask-Fixtures/blob/b34597d165b33cc47cdd632ac0f3cf8a07428675/flask_fixtures/__init__.py#L130-L149 |
20,792 | croach/Flask-Fixtures | flask_fixtures/__init__.py | MetaFixturesMixin.setup_handler | def setup_handler(setup_fixtures_fn, setup_fn):
"""Returns a function that adds fixtures handling to the setup method.
Makes sure that fixtures are setup before calling the given setup method.
"""
def handler(obj):
setup_fixtures_fn(obj)
setup_fn(obj)
return handler | python | def setup_handler(setup_fixtures_fn, setup_fn):
def handler(obj):
setup_fixtures_fn(obj)
setup_fn(obj)
return handler | [
"def",
"setup_handler",
"(",
"setup_fixtures_fn",
",",
"setup_fn",
")",
":",
"def",
"handler",
"(",
"obj",
")",
":",
"setup_fixtures_fn",
"(",
"obj",
")",
"setup_fn",
"(",
"obj",
")",
"return",
"handler"
] | Returns a function that adds fixtures handling to the setup method.
Makes sure that fixtures are setup before calling the given setup method. | [
"Returns",
"a",
"function",
"that",
"adds",
"fixtures",
"handling",
"to",
"the",
"setup",
"method",
"."
] | b34597d165b33cc47cdd632ac0f3cf8a07428675 | https://github.com/croach/Flask-Fixtures/blob/b34597d165b33cc47cdd632ac0f3cf8a07428675/flask_fixtures/__init__.py#L180-L188 |
20,793 | croach/Flask-Fixtures | flask_fixtures/__init__.py | MetaFixturesMixin.teardown_handler | def teardown_handler(teardown_fixtures_fn, teardown_fn):
"""Returns a function that adds fixtures handling to the teardown method.
Calls the given teardown method first before calling the fixtures teardown.
"""
def handler(obj):
teardown_fn(obj)
teardown_fixtures_fn(obj)
return handler | python | def teardown_handler(teardown_fixtures_fn, teardown_fn):
def handler(obj):
teardown_fn(obj)
teardown_fixtures_fn(obj)
return handler | [
"def",
"teardown_handler",
"(",
"teardown_fixtures_fn",
",",
"teardown_fn",
")",
":",
"def",
"handler",
"(",
"obj",
")",
":",
"teardown_fn",
"(",
"obj",
")",
"teardown_fixtures_fn",
"(",
"obj",
")",
"return",
"handler"
] | Returns a function that adds fixtures handling to the teardown method.
Calls the given teardown method first before calling the fixtures teardown. | [
"Returns",
"a",
"function",
"that",
"adds",
"fixtures",
"handling",
"to",
"the",
"teardown",
"method",
"."
] | b34597d165b33cc47cdd632ac0f3cf8a07428675 | https://github.com/croach/Flask-Fixtures/blob/b34597d165b33cc47cdd632ac0f3cf8a07428675/flask_fixtures/__init__.py#L191-L199 |
20,794 | croach/Flask-Fixtures | flask_fixtures/__init__.py | MetaFixturesMixin.get_child_fn | def get_child_fn(attrs, names, bases):
"""Returns a function from the child class that matches one of the names.
Searches the child class's set of methods (i.e., the attrs dict) for all
the functions matching the given list of names. If more than one is found,
an exception is raised, if one is found, it is returned, and if none are
found, a function that calls the default method on each parent class is
returned.
"""
def call_method(obj, method):
"""Calls a method as either a class method or an instance method.
"""
# The __get__ method takes an instance and an owner which changes
# depending on the calling object. If the calling object is a class,
# the instance is None and the owner will be the object itself. If the
# calling object is an instance, the instance will be the calling object
# and the owner will be its class. For more info on the __get__ method,
# see http://docs.python.org/2/reference/datamodel.html#object.__get__.
if isinstance(obj, type):
instance = None
owner = obj
else:
instance = obj
owner = obj.__class__
method.__get__(instance, owner)()
# Create a default function that calls the default method on each parent
default_name = names[0]
def default_fn(obj):
for cls in bases:
if hasattr(cls, default_name):
call_method(obj, getattr(cls, default_name))
default_fn.__name__ = default_name
# Get all of the functions in the child class that match the list of names
fns = [(name, attrs[name]) for name in names if name in attrs]
# Raise an error if more than one setup/teardown method is found
if len(fns) > 1:
raise RuntimeError("Cannot have more than one setup or teardown method per context (class or test).")
# If one setup/teardown function was found, return it
elif len(fns) == 1:
name, fn = fns[0]
def child_fn(obj):
call_method(obj, fn)
child_fn.__name__ = name
return child_fn
# Otherwise, return the default function
else:
return default_fn | python | def get_child_fn(attrs, names, bases):
def call_method(obj, method):
"""Calls a method as either a class method or an instance method.
"""
# The __get__ method takes an instance and an owner which changes
# depending on the calling object. If the calling object is a class,
# the instance is None and the owner will be the object itself. If the
# calling object is an instance, the instance will be the calling object
# and the owner will be its class. For more info on the __get__ method,
# see http://docs.python.org/2/reference/datamodel.html#object.__get__.
if isinstance(obj, type):
instance = None
owner = obj
else:
instance = obj
owner = obj.__class__
method.__get__(instance, owner)()
# Create a default function that calls the default method on each parent
default_name = names[0]
def default_fn(obj):
for cls in bases:
if hasattr(cls, default_name):
call_method(obj, getattr(cls, default_name))
default_fn.__name__ = default_name
# Get all of the functions in the child class that match the list of names
fns = [(name, attrs[name]) for name in names if name in attrs]
# Raise an error if more than one setup/teardown method is found
if len(fns) > 1:
raise RuntimeError("Cannot have more than one setup or teardown method per context (class or test).")
# If one setup/teardown function was found, return it
elif len(fns) == 1:
name, fn = fns[0]
def child_fn(obj):
call_method(obj, fn)
child_fn.__name__ = name
return child_fn
# Otherwise, return the default function
else:
return default_fn | [
"def",
"get_child_fn",
"(",
"attrs",
",",
"names",
",",
"bases",
")",
":",
"def",
"call_method",
"(",
"obj",
",",
"method",
")",
":",
"\"\"\"Calls a method as either a class method or an instance method.\n \"\"\"",
"# The __get__ method takes an instance and an owner... | Returns a function from the child class that matches one of the names.
Searches the child class's set of methods (i.e., the attrs dict) for all
the functions matching the given list of names. If more than one is found,
an exception is raised, if one is found, it is returned, and if none are
found, a function that calls the default method on each parent class is
returned. | [
"Returns",
"a",
"function",
"from",
"the",
"child",
"class",
"that",
"matches",
"one",
"of",
"the",
"names",
"."
] | b34597d165b33cc47cdd632ac0f3cf8a07428675 | https://github.com/croach/Flask-Fixtures/blob/b34597d165b33cc47cdd632ac0f3cf8a07428675/flask_fixtures/__init__.py#L202-L252 |
20,795 | croach/Flask-Fixtures | flask_fixtures/utils.py | print_msg | def print_msg(msg, header, file=sys.stdout):
"""Prints a boardered message to the screen"""
DEFAULT_MSG_BLOCK_WIDTH = 60
# Calculate the length of the boarder on each side of the header and the
# total length of the bottom boarder
side_boarder_length = (DEFAULT_MSG_BLOCK_WIDTH - (len(header) + 2)) // 2
msg_block_width = side_boarder_length * 2 + (len(header) + 2)
# Create the top and bottom boarders
side_boarder = '#' * side_boarder_length
top_boarder = '{0} {1} {2}'.format(side_boarder, header, side_boarder)
bottom_boarder = '#' * msg_block_width
def pad(line, length):
"""Returns a string padded and centered by the given length"""
padding_length = length - len(line)
left_padding = ' ' * (padding_length//2)
right_padding = ' ' * (padding_length - len(left_padding))
return '{0} {1} {2}'.format(left_padding, line, right_padding)
words = msg.split(' ')
lines = []
line = ''
for word in words:
if len(line + ' ' + word) <= msg_block_width - 4:
line = (line + ' ' + word).strip()
else:
lines.append('#{0}#'.format(pad(line, msg_block_width - 4)))
line = word
lines.append('#{0}#'.format(pad(line, msg_block_width - 4)))
# Print the full message
print(file=file)
print(top_boarder, file=file)
print('#{0}#'.format(pad('', msg_block_width - 4)), file=file)
for line in lines:
print(line, file=file)
print('#{0}#'.format(pad('', msg_block_width - 4)), file=file)
print(bottom_boarder, file=file)
print(file=file) | python | def print_msg(msg, header, file=sys.stdout):
DEFAULT_MSG_BLOCK_WIDTH = 60
# Calculate the length of the boarder on each side of the header and the
# total length of the bottom boarder
side_boarder_length = (DEFAULT_MSG_BLOCK_WIDTH - (len(header) + 2)) // 2
msg_block_width = side_boarder_length * 2 + (len(header) + 2)
# Create the top and bottom boarders
side_boarder = '#' * side_boarder_length
top_boarder = '{0} {1} {2}'.format(side_boarder, header, side_boarder)
bottom_boarder = '#' * msg_block_width
def pad(line, length):
"""Returns a string padded and centered by the given length"""
padding_length = length - len(line)
left_padding = ' ' * (padding_length//2)
right_padding = ' ' * (padding_length - len(left_padding))
return '{0} {1} {2}'.format(left_padding, line, right_padding)
words = msg.split(' ')
lines = []
line = ''
for word in words:
if len(line + ' ' + word) <= msg_block_width - 4:
line = (line + ' ' + word).strip()
else:
lines.append('#{0}#'.format(pad(line, msg_block_width - 4)))
line = word
lines.append('#{0}#'.format(pad(line, msg_block_width - 4)))
# Print the full message
print(file=file)
print(top_boarder, file=file)
print('#{0}#'.format(pad('', msg_block_width - 4)), file=file)
for line in lines:
print(line, file=file)
print('#{0}#'.format(pad('', msg_block_width - 4)), file=file)
print(bottom_boarder, file=file)
print(file=file) | [
"def",
"print_msg",
"(",
"msg",
",",
"header",
",",
"file",
"=",
"sys",
".",
"stdout",
")",
":",
"DEFAULT_MSG_BLOCK_WIDTH",
"=",
"60",
"# Calculate the length of the boarder on each side of the header and the",
"# total length of the bottom boarder",
"side_boarder_length",
"=... | Prints a boardered message to the screen | [
"Prints",
"a",
"boardered",
"message",
"to",
"the",
"screen"
] | b34597d165b33cc47cdd632ac0f3cf8a07428675 | https://github.com/croach/Flask-Fixtures/blob/b34597d165b33cc47cdd632ac0f3cf8a07428675/flask_fixtures/utils.py#L20-L60 |
20,796 | croach/Flask-Fixtures | flask_fixtures/utils.py | can_persist_fixtures | def can_persist_fixtures():
"""Returns True if it's possible to persist fixtures across tests.
Flask-Fixtures uses the setUpClass and tearDownClass methods to persist
fixtures across tests. These methods were added to unittest.TestCase in
python 2.7. So, we can only persist fixtures when using python 2.7.
However, the nose and py.test libraries add support for these methods
regardless of what version of python we're running, so if we're running
with either of those libraries, return True to persist fixtures.
"""
# If we're running python 2.7 or greater, we're fine
if sys.hexversion >= 0x02070000:
return True
# Otherwise, nose and py.test support the setUpClass and tearDownClass
# methods, so if we're using either of those, go ahead and run the tests
filename = inspect.stack()[-1][1]
executable = os.path.split(filename)[1]
return executable in ('py.test', 'nosetests') | python | def can_persist_fixtures():
# If we're running python 2.7 or greater, we're fine
if sys.hexversion >= 0x02070000:
return True
# Otherwise, nose and py.test support the setUpClass and tearDownClass
# methods, so if we're using either of those, go ahead and run the tests
filename = inspect.stack()[-1][1]
executable = os.path.split(filename)[1]
return executable in ('py.test', 'nosetests') | [
"def",
"can_persist_fixtures",
"(",
")",
":",
"# If we're running python 2.7 or greater, we're fine",
"if",
"sys",
".",
"hexversion",
">=",
"0x02070000",
":",
"return",
"True",
"# Otherwise, nose and py.test support the setUpClass and tearDownClass",
"# methods, so if we're using eit... | Returns True if it's possible to persist fixtures across tests.
Flask-Fixtures uses the setUpClass and tearDownClass methods to persist
fixtures across tests. These methods were added to unittest.TestCase in
python 2.7. So, we can only persist fixtures when using python 2.7.
However, the nose and py.test libraries add support for these methods
regardless of what version of python we're running, so if we're running
with either of those libraries, return True to persist fixtures. | [
"Returns",
"True",
"if",
"it",
"s",
"possible",
"to",
"persist",
"fixtures",
"across",
"tests",
"."
] | b34597d165b33cc47cdd632ac0f3cf8a07428675 | https://github.com/croach/Flask-Fixtures/blob/b34597d165b33cc47cdd632ac0f3cf8a07428675/flask_fixtures/utils.py#L65-L84 |
20,797 | shichao-an/twitter-photos | twphotos/increment.py | read_since_ids | def read_since_ids(users):
"""
Read max ids of the last downloads
:param users: A list of users
Return a dictionary mapping users to ids
"""
since_ids = {}
for user in users:
if config.has_option(SECTIONS['INCREMENTS'], user):
since_ids[user] = config.getint(SECTIONS['INCREMENTS'], user) + 1
return since_ids | python | def read_since_ids(users):
since_ids = {}
for user in users:
if config.has_option(SECTIONS['INCREMENTS'], user):
since_ids[user] = config.getint(SECTIONS['INCREMENTS'], user) + 1
return since_ids | [
"def",
"read_since_ids",
"(",
"users",
")",
":",
"since_ids",
"=",
"{",
"}",
"for",
"user",
"in",
"users",
":",
"if",
"config",
".",
"has_option",
"(",
"SECTIONS",
"[",
"'INCREMENTS'",
"]",
",",
"user",
")",
":",
"since_ids",
"[",
"user",
"]",
"=",
"... | Read max ids of the last downloads
:param users: A list of users
Return a dictionary mapping users to ids | [
"Read",
"max",
"ids",
"of",
"the",
"last",
"downloads"
] | 32de6e8805edcbb431d08af861e9d2f0ab221106 | https://github.com/shichao-an/twitter-photos/blob/32de6e8805edcbb431d08af861e9d2f0ab221106/twphotos/increment.py#L19-L31 |
20,798 | shichao-an/twitter-photos | twphotos/increment.py | set_max_ids | def set_max_ids(max_ids):
"""
Set max ids of the current downloads
:param max_ids: A dictionary mapping users to ids
"""
config.read(CONFIG)
for user, max_id in max_ids.items():
config.set(SECTIONS['INCREMENTS'], user, str(max_id))
with open(CONFIG, 'w') as f:
config.write(f) | python | def set_max_ids(max_ids):
config.read(CONFIG)
for user, max_id in max_ids.items():
config.set(SECTIONS['INCREMENTS'], user, str(max_id))
with open(CONFIG, 'w') as f:
config.write(f) | [
"def",
"set_max_ids",
"(",
"max_ids",
")",
":",
"config",
".",
"read",
"(",
"CONFIG",
")",
"for",
"user",
",",
"max_id",
"in",
"max_ids",
".",
"items",
"(",
")",
":",
"config",
".",
"set",
"(",
"SECTIONS",
"[",
"'INCREMENTS'",
"]",
",",
"user",
",",
... | Set max ids of the current downloads
:param max_ids: A dictionary mapping users to ids | [
"Set",
"max",
"ids",
"of",
"the",
"current",
"downloads"
] | 32de6e8805edcbb431d08af861e9d2f0ab221106 | https://github.com/shichao-an/twitter-photos/blob/32de6e8805edcbb431d08af861e9d2f0ab221106/twphotos/increment.py#L34-L44 |
20,799 | davedoesdev/dxf | dxf/__init__.py | DXFBase.authenticate | def authenticate(self,
username=None, password=None,
actions=None, response=None,
authorization=None):
# pylint: disable=too-many-arguments,too-many-locals
"""
Authenticate to the registry using a username and password,
an authorization header or otherwise as the anonymous user.
:param username: User name to authenticate as.
:type username: str
:param password: User's password.
:type password: str
:param actions: If you know which types of operation you need to make on the registry, specify them here. Valid actions are ``pull``, ``push`` and ``*``.
:type actions: list
:param response: When the ``auth`` function you passed to :class:`DXFBase`'s constructor is called, it is passed a HTTP response object. Pass it back to :meth:`authenticate` to have it automatically detect which actions are required.
:type response: requests.Response
:param authorization: ``Authorization`` header value.
:type authorization: str
:rtype: str
:returns: Authentication token, if the registry supports bearer tokens. Otherwise ``None``, and HTTP Basic auth is used (if the registry requires authentication).
"""
if response is None:
with warnings.catch_warnings():
_ignore_warnings(self)
response = self._sessions[0].get(self._base_url, verify=self._tlsverify)
if response.ok:
return None
# pylint: disable=no-member
if response.status_code != requests.codes.unauthorized:
raise exceptions.DXFUnexpectedStatusCodeError(response.status_code,
requests.codes.unauthorized)
if self._insecure:
raise exceptions.DXFAuthInsecureError()
parsed = www_authenticate.parse(response.headers['www-authenticate'])
if username is not None and password is not None:
headers = {
'Authorization': 'Basic ' + base64.b64encode(_to_bytes_2and3(username + ':' + password)).decode('utf-8')
}
elif authorization is not None:
headers = {
'Authorization': authorization
}
else:
headers = {}
if 'bearer' in parsed:
info = parsed['bearer']
if actions and self._repo:
scope = 'repository:' + self._repo + ':' + ','.join(actions)
elif 'scope' in info:
scope = info['scope']
else:
scope = ''
url_parts = list(urlparse.urlparse(info['realm']))
query = urlparse.parse_qs(url_parts[4])
query.update({
'service': info['service'],
'scope': scope
})
url_parts[4] = urlencode(query, True)
url_parts[0] = 'https'
if self._auth_host:
url_parts[1] = self._auth_host
auth_url = urlparse.urlunparse(url_parts)
with warnings.catch_warnings():
_ignore_warnings(self)
r = self._sessions[0].get(auth_url, headers=headers, verify=self._tlsverify)
_raise_for_status(r)
rjson = r.json()
self.token = rjson['access_token'] if 'access_token' in rjson else rjson['token']
return self._token
self._headers = headers
return None | python | def authenticate(self,
username=None, password=None,
actions=None, response=None,
authorization=None):
# pylint: disable=too-many-arguments,too-many-locals
if response is None:
with warnings.catch_warnings():
_ignore_warnings(self)
response = self._sessions[0].get(self._base_url, verify=self._tlsverify)
if response.ok:
return None
# pylint: disable=no-member
if response.status_code != requests.codes.unauthorized:
raise exceptions.DXFUnexpectedStatusCodeError(response.status_code,
requests.codes.unauthorized)
if self._insecure:
raise exceptions.DXFAuthInsecureError()
parsed = www_authenticate.parse(response.headers['www-authenticate'])
if username is not None and password is not None:
headers = {
'Authorization': 'Basic ' + base64.b64encode(_to_bytes_2and3(username + ':' + password)).decode('utf-8')
}
elif authorization is not None:
headers = {
'Authorization': authorization
}
else:
headers = {}
if 'bearer' in parsed:
info = parsed['bearer']
if actions and self._repo:
scope = 'repository:' + self._repo + ':' + ','.join(actions)
elif 'scope' in info:
scope = info['scope']
else:
scope = ''
url_parts = list(urlparse.urlparse(info['realm']))
query = urlparse.parse_qs(url_parts[4])
query.update({
'service': info['service'],
'scope': scope
})
url_parts[4] = urlencode(query, True)
url_parts[0] = 'https'
if self._auth_host:
url_parts[1] = self._auth_host
auth_url = urlparse.urlunparse(url_parts)
with warnings.catch_warnings():
_ignore_warnings(self)
r = self._sessions[0].get(auth_url, headers=headers, verify=self._tlsverify)
_raise_for_status(r)
rjson = r.json()
self.token = rjson['access_token'] if 'access_token' in rjson else rjson['token']
return self._token
self._headers = headers
return None | [
"def",
"authenticate",
"(",
"self",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
",",
"actions",
"=",
"None",
",",
"response",
"=",
"None",
",",
"authorization",
"=",
"None",
")",
":",
"# pylint: disable=too-many-arguments,too-many-locals",
"if",
... | Authenticate to the registry using a username and password,
an authorization header or otherwise as the anonymous user.
:param username: User name to authenticate as.
:type username: str
:param password: User's password.
:type password: str
:param actions: If you know which types of operation you need to make on the registry, specify them here. Valid actions are ``pull``, ``push`` and ``*``.
:type actions: list
:param response: When the ``auth`` function you passed to :class:`DXFBase`'s constructor is called, it is passed a HTTP response object. Pass it back to :meth:`authenticate` to have it automatically detect which actions are required.
:type response: requests.Response
:param authorization: ``Authorization`` header value.
:type authorization: str
:rtype: str
:returns: Authentication token, if the registry supports bearer tokens. Otherwise ``None``, and HTTP Basic auth is used (if the registry requires authentication). | [
"Authenticate",
"to",
"the",
"registry",
"using",
"a",
"username",
"and",
"password",
"an",
"authorization",
"header",
"or",
"otherwise",
"as",
"the",
"anonymous",
"user",
"."
] | 63fad55e0f0086e5f6d3511670db1ef23b5298f6 | https://github.com/davedoesdev/dxf/blob/63fad55e0f0086e5f6d3511670db1ef23b5298f6/dxf/__init__.py#L228-L312 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.