body
stringlengths
26
98.2k
body_hash
int64
-9,222,864,604,528,158,000
9,221,803,474B
docstring
stringlengths
1
16.8k
path
stringlengths
5
230
name
stringlengths
1
96
repository_name
stringlengths
7
89
lang
stringclasses
1 value
body_without_docstring
stringlengths
20
98.2k
def __init__(self, ignore_validation: bool) -> None: 'Initialize Class properties.' super().__init__() self.ignore_validation = ignore_validation self._app_packages = [] self._install_json_schema = None self._layout_json_schema = None self.config = {} self.ij = InstallJson() self.inv...
2,886,200,466,622,236,700
Initialize Class properties.
tcex/bin/validate.py
__init__
benjaminPurdy/tcex
python
def __init__(self, ignore_validation: bool) -> None: super().__init__() self.ignore_validation = ignore_validation self._app_packages = [] self._install_json_schema = None self._layout_json_schema = None self.config = {} self.ij = InstallJson() self.invalid_json_files = [] self....
@property def _validation_data(self) -> Dict[(str, list)]: 'Return structure for validation data.' return {'errors': [], 'fileSyntax': [], 'layouts': [], 'moduleImports': [], 'schema': [], 'feeds': []}
5,958,275,173,923,295,000
Return structure for validation data.
tcex/bin/validate.py
_validation_data
benjaminPurdy/tcex
python
@property def _validation_data(self) -> Dict[(str, list)]: return {'errors': [], 'fileSyntax': [], 'layouts': [], 'moduleImports': [], 'schema': [], 'feeds': []}
def _check_node_import(self, node: Union[(ast.Import, ast.ImportFrom)], filename: str) -> None: '.' if isinstance(node, ast.Import): for n in node.names: m = n.name.split('.')[0] if (not self.check_import_stdlib(m)): m_status = self.check_imported(m) ...
-3,932,265,064,709,798,000
.
tcex/bin/validate.py
_check_node_import
benjaminPurdy/tcex
python
def _check_node_import(self, node: Union[(astImport, astImportFrom)], filename: str) -> None: if isinstance(node, astImport): for n in nodenames: m = nnamesplit()[0] if (not selfcheck_import_stdlib(m)): m_status = selfcheck_imported(m) if (not m_s...
def check_imports(self) -> None: 'Check the projects top level directory for missing imports.\n\n This method will check only files ending in **.py** and does not handle imports validation\n for sub-directories.\n ' for filename in sorted(os.listdir(self.app_path)): if (not filename...
8,037,250,862,082,015,000
Check the projects top level directory for missing imports. This method will check only files ending in **.py** and does not handle imports validation for sub-directories.
tcex/bin/validate.py
check_imports
benjaminPurdy/tcex
python
def check_imports(self) -> None: 'Check the projects top level directory for missing imports.\n\n This method will check only files ending in **.py** and does not handle imports validation\n for sub-directories.\n ' for filename in sorted(os.listdir(self.app_path)): if (not filename...
@staticmethod def check_import_stdlib(module: str) -> bool: 'Check if module is in Python stdlib.\n\n Args:\n module: The name of the module to check.\n\n Returns:\n bool: Returns True if the module is in the stdlib or template.\n ' if ((module in stdlib_list('3.6')) o...
574,623,895,274,065,000
Check if module is in Python stdlib. Args: module: The name of the module to check. Returns: bool: Returns True if the module is in the stdlib or template.
tcex/bin/validate.py
check_import_stdlib
benjaminPurdy/tcex
python
@staticmethod def check_import_stdlib(module: str) -> bool: 'Check if module is in Python stdlib.\n\n Args:\n module: The name of the module to check.\n\n Returns:\n bool: Returns True if the module is in the stdlib or template.\n ' if ((module in stdlib_list('3.6')) o...
@staticmethod def check_imported(module: str) -> bool: 'Check whether the provide module can be imported (package installed).\n\n Args:\n module: The name of the module to check availability.\n\n Returns:\n bool: True if the module can be imported, False otherwise.\n ' ...
556,081,726,153,656,300
Check whether the provide module can be imported (package installed). Args: module: The name of the module to check availability. Returns: bool: True if the module can be imported, False otherwise.
tcex/bin/validate.py
check_imported
benjaminPurdy/tcex
python
@staticmethod def check_imported(module: str) -> bool: 'Check whether the provide module can be imported (package installed).\n\n Args:\n module: The name of the module to check availability.\n\n Returns:\n bool: True if the module can be imported, False otherwise.\n ' ...
def check_install_json(self) -> None: 'Check all install.json files for valid schema.' if ('install.json' in self.invalid_json_files): return status = True try: self.ij.model except ValidationError as ex: self.invalid_json_files.append(self.ij.fqfn.name) status = Fals...
5,865,411,555,246,264,000
Check all install.json files for valid schema.
tcex/bin/validate.py
check_install_json
benjaminPurdy/tcex
python
def check_install_json(self) -> None: if ('install.json' in self.invalid_json_files): return status = True try: self.ij.model except ValidationError as ex: self.invalid_json_files.append(self.ij.fqfn.name) status = False for error in json.loads(ex.json()): ...
def check_job_json(self) -> None: 'Validate feed files for feed job apps.' if ('install.json' in self.invalid_json_files): return app_version = (self.tj.model.package.app_version or self.ij.model.package_version) program_name = f'{self.tj.model.package.app_name}_{app_version}'.replace('_', ' ') ...
5,187,031,783,895,453,000
Validate feed files for feed job apps.
tcex/bin/validate.py
check_job_json
benjaminPurdy/tcex
python
def check_job_json(self) -> None: if ('install.json' in self.invalid_json_files): return app_version = (self.tj.model.package.app_version or self.ij.model.package_version) program_name = f'{self.tj.model.package.app_name}_{app_version}'.replace('_', ' ') status = True for feed in self.i...
def check_layout_json(self) -> None: 'Check all layout.json files for valid schema.' if ((not self.lj.has_layout) or ('layout.json' in self.invalid_json_files)): return status = True try: self.lj.model except ValidationError as ex: self.invalid_json_files.append(self.ij.fqfn....
-9,029,930,225,845,429,000
Check all layout.json files for valid schema.
tcex/bin/validate.py
check_layout_json
benjaminPurdy/tcex
python
def check_layout_json(self) -> None: if ((not self.lj.has_layout) or ('layout.json' in self.invalid_json_files)): return status = True try: self.lj.model except ValidationError as ex: self.invalid_json_files.append(self.ij.fqfn.name) status = False for error ...
def check_layout_params(self) -> None: "Check that the layout.json is consistent with install.json.\n\n The layout.json files references the params.name from the install.json file. The method\n will validate that no reference appear for inputs in install.json that don't exist.\n " ij_input...
1,388,452,454,794,460,200
Check that the layout.json is consistent with install.json. The layout.json files references the params.name from the install.json file. The method will validate that no reference appear for inputs in install.json that don't exist.
tcex/bin/validate.py
check_layout_params
benjaminPurdy/tcex
python
def check_layout_params(self) -> None: "Check that the layout.json is consistent with install.json.\n\n The layout.json files references the params.name from the install.json file. The method\n will validate that no reference appear for inputs in install.json that don't exist.\n " ij_input...
def check_syntax(self, app_path=None) -> None: 'Run syntax on each ".py" and ".json" file.\n\n Args:\n app_path (str, optional): The path of Python files.\n ' fqpn = Path((app_path or os.getcwd())) for fqfn in sorted(fqpn.iterdir()): error = None status = True ...
8,878,062,756,795,646,000
Run syntax on each ".py" and ".json" file. Args: app_path (str, optional): The path of Python files.
tcex/bin/validate.py
check_syntax
benjaminPurdy/tcex
python
def check_syntax(self, app_path=None) -> None: 'Run syntax on each ".py" and ".json" file.\n\n Args:\n app_path (str, optional): The path of Python files.\n ' fqpn = Path((app_path or os.getcwd())) for fqfn in sorted(fqpn.iterdir()): error = None status = True ...
def interactive(self) -> None: '[App Builder] Run in interactive mode.' while True: line = sys.stdin.readline().strip() if (line == 'quit'): sys.exit() elif (line == 'validate'): self.check_syntax() self.check_imports() self.check_install_j...
-7,308,072,104,282,095,000
[App Builder] Run in interactive mode.
tcex/bin/validate.py
interactive
benjaminPurdy/tcex
python
def interactive(self) -> None: while True: line = sys.stdin.readline().strip() if (line == 'quit'): sys.exit() elif (line == 'validate'): self.check_syntax() self.check_imports() self.check_install_json() self.check_layout_json...
def print_json(self) -> None: '[App Builder] Print JSON output.' print(json.dumps({'validation_data': self.validation_data}))
-1,345,672,885,728,641,000
[App Builder] Print JSON output.
tcex/bin/validate.py
print_json
benjaminPurdy/tcex
python
def print_json(self) -> None: print(json.dumps({'validation_data': self.validation_data}))
def _print_file_syntax_results(self) -> None: 'Print file syntax results.' if self.validation_data.get('fileSyntax'): print(f''' {c.Style.BRIGHT}{c.Fore.BLUE}Validated File Syntax:''') print(f"{c.Style.BRIGHT}{'File:'!s:<60}{'Status:'!s:<25}") for f in self.validation_data.get('fileSynta...
-7,130,818,483,572,398,000
Print file syntax results.
tcex/bin/validate.py
_print_file_syntax_results
benjaminPurdy/tcex
python
def _print_file_syntax_results(self) -> None: if self.validation_data.get('fileSyntax'): print(f' {c.Style.BRIGHT}{c.Fore.BLUE}Validated File Syntax:') print(f"{c.Style.BRIGHT}{'File:'!s:<60}{'Status:'!s:<25}") for f in self.validation_data.get('fileSyntax'): status_color = ...
def _print_imports_results(self) -> None: 'Print import results.' if self.validation_data.get('moduleImports'): print(f''' {c.Style.BRIGHT}{c.Fore.BLUE}Validated Imports:''') print(f"{c.Style.BRIGHT}{'File:'!s:<30}{'Module:'!s:<30}{'Status:'!s:<25}") for f in self.validation_data.get('mo...
4,693,549,105,083,687,000
Print import results.
tcex/bin/validate.py
_print_imports_results
benjaminPurdy/tcex
python
def _print_imports_results(self) -> None: if self.validation_data.get('moduleImports'): print(f' {c.Style.BRIGHT}{c.Fore.BLUE}Validated Imports:') print(f"{c.Style.BRIGHT}{'File:'!s:<30}{'Module:'!s:<30}{'Status:'!s:<25}") for f in self.validation_data.get('moduleImports'): ...
def _print_schema_results(self) -> None: 'Print schema results.' if self.validation_data.get('schema'): print(f''' {c.Style.BRIGHT}{c.Fore.BLUE}Validated Schema:''') print(f"{c.Style.BRIGHT}{'File:'!s:<60}{'Status:'!s:<25}") for f in self.validation_data.get('schema'): status...
-5,820,603,044,823,452,000
Print schema results.
tcex/bin/validate.py
_print_schema_results
benjaminPurdy/tcex
python
def _print_schema_results(self) -> None: if self.validation_data.get('schema'): print(f' {c.Style.BRIGHT}{c.Fore.BLUE}Validated Schema:') print(f"{c.Style.BRIGHT}{'File:'!s:<60}{'Status:'!s:<25}") for f in self.validation_data.get('schema'): status_color = self.status_color(...
def _print_layouts_results(self) -> None: 'Print layout results.' if self.validation_data.get('layouts'): print(f''' {c.Style.BRIGHT}{c.Fore.BLUE}Validated Layouts:''') print(f"{c.Style.BRIGHT}{'Params:'!s:<60}{'Status:'!s:<25}") for f in self.validation_data.get('layouts'): ...
1,522,637,771,830,174,000
Print layout results.
tcex/bin/validate.py
_print_layouts_results
benjaminPurdy/tcex
python
def _print_layouts_results(self) -> None: if self.validation_data.get('layouts'): print(f' {c.Style.BRIGHT}{c.Fore.BLUE}Validated Layouts:') print(f"{c.Style.BRIGHT}{'Params:'!s:<60}{'Status:'!s:<25}") for f in self.validation_data.get('layouts'): status_color = self.status_...
def _print_feed_results(self) -> None: 'Print feed results.' if self.validation_data.get('feeds'): print(f''' {c.Style.BRIGHT}{c.Fore.BLUE}Validated Feed Jobs:''') print(f"{c.Style.BRIGHT}{'Feeds:'!s:<60}{'Status:'!s:<25}") for f in self.validation_data.get('feeds'): status_c...
7,289,236,692,831,736,000
Print feed results.
tcex/bin/validate.py
_print_feed_results
benjaminPurdy/tcex
python
def _print_feed_results(self) -> None: if self.validation_data.get('feeds'): print(f' {c.Style.BRIGHT}{c.Fore.BLUE}Validated Feed Jobs:') print(f"{c.Style.BRIGHT}{'Feeds:'!s:<60}{'Status:'!s:<25}") for f in self.validation_data.get('feeds'): status_color = self.status_color(...
def _print_errors(self) -> None: 'Print errors results.' if self.validation_data.get('errors'): print('\n') for error in self.validation_data.get('errors'): print(f'* {c.Fore.RED}{error}') if (not self.ignore_validation): self.exit_code = 1
2,625,961,558,882,467,300
Print errors results.
tcex/bin/validate.py
_print_errors
benjaminPurdy/tcex
python
def _print_errors(self) -> None: if self.validation_data.get('errors'): print('\n') for error in self.validation_data.get('errors'): print(f'* {c.Fore.RED}{error}') if (not self.ignore_validation): self.exit_code = 1
def print_results(self) -> None: 'Print results.' self._print_file_syntax_results() self._print_imports_results() self._print_schema_results() self._print_layouts_results() self._print_feed_results() self._print_errors()
5,307,456,271,778,884,000
Print results.
tcex/bin/validate.py
print_results
benjaminPurdy/tcex
python
def print_results(self) -> None: self._print_file_syntax_results() self._print_imports_results() self._print_schema_results() self._print_layouts_results() self._print_feed_results() self._print_errors()
@staticmethod def status_color(status) -> str: 'Return the appropriate status color.' return (c.Fore.GREEN if status else c.Fore.RED)
-5,684,548,797,497,374,000
Return the appropriate status color.
tcex/bin/validate.py
status_color
benjaminPurdy/tcex
python
@staticmethod def status_color(status) -> str: return (c.Fore.GREEN if status else c.Fore.RED)
@staticmethod def status_value(status) -> str: 'Return the appropriate status color.' return ('passed' if status else 'failed')
-6,747,285,470,334,901,000
Return the appropriate status color.
tcex/bin/validate.py
status_value
benjaminPurdy/tcex
python
@staticmethod def status_value(status) -> str: return ('passed' if status else 'failed')
@array_function_from_c_func_and_dispatcher(_multiarray_umath.empty_like) def empty_like(prototype, dtype=None, order=None, subok=None): "\n empty_like(prototype, dtype=None, order='K', subok=True)\n\n Return a new array with the same shape and type as a given array.\n\n Parameters\n ----------\n prot...
-1,656,268,581,539,844,600
empty_like(prototype, dtype=None, order='K', subok=True) Return a new array with the same shape and type as a given array. Parameters ---------- prototype : array_like The shape and data-type of `prototype` define these same attributes of the returned array. dtype : data-type, optional Overrides the data ...
venv/lib/python3.7/site-packages/numpy/core/multiarray.py
empty_like
180Studios/LoginApp
python
@array_function_from_c_func_and_dispatcher(_multiarray_umath.empty_like) def empty_like(prototype, dtype=None, order=None, subok=None): "\n empty_like(prototype, dtype=None, order='K', subok=True)\n\n Return a new array with the same shape and type as a given array.\n\n Parameters\n ----------\n prot...
@array_function_from_c_func_and_dispatcher(_multiarray_umath.concatenate) def concatenate(arrays, axis=None, out=None): '\n concatenate((a1, a2, ...), axis=0, out=None)\n\n Join a sequence of arrays along an existing axis.\n\n Parameters\n ----------\n a1, a2, ... : sequence of array_like\n Th...
-8,880,532,773,887,127,000
concatenate((a1, a2, ...), axis=0, out=None) Join a sequence of arrays along an existing axis. Parameters ---------- a1, a2, ... : sequence of array_like The arrays must have the same shape, except in the dimension corresponding to `axis` (the first, by default). axis : int, optional The axis along which ...
venv/lib/python3.7/site-packages/numpy/core/multiarray.py
concatenate
180Studios/LoginApp
python
@array_function_from_c_func_and_dispatcher(_multiarray_umath.concatenate) def concatenate(arrays, axis=None, out=None): '\n concatenate((a1, a2, ...), axis=0, out=None)\n\n Join a sequence of arrays along an existing axis.\n\n Parameters\n ----------\n a1, a2, ... : sequence of array_like\n Th...
@array_function_from_c_func_and_dispatcher(_multiarray_umath.inner) def inner(a, b): '\n inner(a, b)\n\n Inner product of two arrays.\n\n Ordinary inner product of vectors for 1-D arrays (without complex\n conjugation), in higher dimensions a sum product over the last axes.\n\n Parameters\n ------...
-7,448,896,873,532,278,000
inner(a, b) Inner product of two arrays. Ordinary inner product of vectors for 1-D arrays (without complex conjugation), in higher dimensions a sum product over the last axes. Parameters ---------- a, b : array_like If `a` and `b` are nonscalar, their last dimensions must match. Returns ------- out : ndarray ...
venv/lib/python3.7/site-packages/numpy/core/multiarray.py
inner
180Studios/LoginApp
python
@array_function_from_c_func_and_dispatcher(_multiarray_umath.inner) def inner(a, b): '\n inner(a, b)\n\n Inner product of two arrays.\n\n Ordinary inner product of vectors for 1-D arrays (without complex\n conjugation), in higher dimensions a sum product over the last axes.\n\n Parameters\n ------...
@array_function_from_c_func_and_dispatcher(_multiarray_umath.where) def where(condition, x=None, y=None): '\n where(condition, [x, y])\n\n Return elements chosen from `x` or `y` depending on `condition`.\n\n .. note::\n When only `condition` is provided, this function is a shorthand for\n ``n...
5,377,605,712,749,175,000
where(condition, [x, y]) Return elements chosen from `x` or `y` depending on `condition`. .. note:: When only `condition` is provided, this function is a shorthand for ``np.asarray(condition).nonzero()``. Using `nonzero` directly should be preferred, as it behaves correctly for subclasses. The rest of thi...
venv/lib/python3.7/site-packages/numpy/core/multiarray.py
where
180Studios/LoginApp
python
@array_function_from_c_func_and_dispatcher(_multiarray_umath.where) def where(condition, x=None, y=None): '\n where(condition, [x, y])\n\n Return elements chosen from `x` or `y` depending on `condition`.\n\n .. note::\n When only `condition` is provided, this function is a shorthand for\n ``n...
@array_function_from_c_func_and_dispatcher(_multiarray_umath.lexsort) def lexsort(keys, axis=None): '\n lexsort(keys, axis=-1)\n\n Perform an indirect stable sort using a sequence of keys.\n\n Given multiple sorting keys, which can be interpreted as columns in a\n spreadsheet, lexsort returns an array o...
4,072,387,893,560,209,000
lexsort(keys, axis=-1) Perform an indirect stable sort using a sequence of keys. Given multiple sorting keys, which can be interpreted as columns in a spreadsheet, lexsort returns an array of integer indices that describes the sort order by multiple columns. The last key in the sequence is used for the primary sort o...
venv/lib/python3.7/site-packages/numpy/core/multiarray.py
lexsort
180Studios/LoginApp
python
@array_function_from_c_func_and_dispatcher(_multiarray_umath.lexsort) def lexsort(keys, axis=None): '\n lexsort(keys, axis=-1)\n\n Perform an indirect stable sort using a sequence of keys.\n\n Given multiple sorting keys, which can be interpreted as columns in a\n spreadsheet, lexsort returns an array o...
@array_function_from_c_func_and_dispatcher(_multiarray_umath.can_cast) def can_cast(from_, to, casting=None): "\n can_cast(from_, to, casting='safe')\n\n Returns True if cast between data types can occur according to the\n casting rule. If from is a scalar or array scalar, also returns\n True if the sc...
420,385,678,301,806,100
can_cast(from_, to, casting='safe') Returns True if cast between data types can occur according to the casting rule. If from is a scalar or array scalar, also returns True if the scalar value can be cast without overflow or truncation to an integer. Parameters ---------- from_ : dtype, dtype specifier, scalar, or ar...
venv/lib/python3.7/site-packages/numpy/core/multiarray.py
can_cast
180Studios/LoginApp
python
@array_function_from_c_func_and_dispatcher(_multiarray_umath.can_cast) def can_cast(from_, to, casting=None): "\n can_cast(from_, to, casting='safe')\n\n Returns True if cast between data types can occur according to the\n casting rule. If from is a scalar or array scalar, also returns\n True if the sc...
@array_function_from_c_func_and_dispatcher(_multiarray_umath.min_scalar_type) def min_scalar_type(a): "\n min_scalar_type(a)\n\n For scalar ``a``, returns the data type with the smallest size\n and smallest scalar kind which can hold its value. For non-scalar\n array ``a``, returns the vector's dtype u...
-5,644,159,851,517,568,000
min_scalar_type(a) For scalar ``a``, returns the data type with the smallest size and smallest scalar kind which can hold its value. For non-scalar array ``a``, returns the vector's dtype unmodified. Floating point values are not demoted to integers, and complex values are not demoted to floats. Parameters --------...
venv/lib/python3.7/site-packages/numpy/core/multiarray.py
min_scalar_type
180Studios/LoginApp
python
@array_function_from_c_func_and_dispatcher(_multiarray_umath.min_scalar_type) def min_scalar_type(a): "\n min_scalar_type(a)\n\n For scalar ``a``, returns the data type with the smallest size\n and smallest scalar kind which can hold its value. For non-scalar\n array ``a``, returns the vector's dtype u...
@array_function_from_c_func_and_dispatcher(_multiarray_umath.result_type) def result_type(*arrays_and_dtypes): "\n result_type(*arrays_and_dtypes)\n\n Returns the type that results from applying the NumPy\n type promotion rules to the arguments.\n\n Type promotion in NumPy works similarly to the rules i...
6,623,818,526,093,711,000
result_type(*arrays_and_dtypes) Returns the type that results from applying the NumPy type promotion rules to the arguments. Type promotion in NumPy works similarly to the rules in languages like C++, with some slight differences. When both scalars and arrays are used, the array's type takes precedence and the actua...
venv/lib/python3.7/site-packages/numpy/core/multiarray.py
result_type
180Studios/LoginApp
python
@array_function_from_c_func_and_dispatcher(_multiarray_umath.result_type) def result_type(*arrays_and_dtypes): "\n result_type(*arrays_and_dtypes)\n\n Returns the type that results from applying the NumPy\n type promotion rules to the arguments.\n\n Type promotion in NumPy works similarly to the rules i...
@array_function_from_c_func_and_dispatcher(_multiarray_umath.dot) def dot(a, b, out=None): "\n dot(a, b, out=None)\n\n Dot product of two arrays. Specifically,\n\n - If both `a` and `b` are 1-D arrays, it is inner product of vectors\n (without complex conjugation).\n\n - If both `a` and `b` are 2-D...
-4,682,007,655,391,947,000
dot(a, b, out=None) Dot product of two arrays. Specifically, - If both `a` and `b` are 1-D arrays, it is inner product of vectors (without complex conjugation). - If both `a` and `b` are 2-D arrays, it is matrix multiplication, but using :func:`matmul` or ``a @ b`` is preferred. - If either `a` or `b` is 0-D (s...
venv/lib/python3.7/site-packages/numpy/core/multiarray.py
dot
180Studios/LoginApp
python
@array_function_from_c_func_and_dispatcher(_multiarray_umath.dot) def dot(a, b, out=None): "\n dot(a, b, out=None)\n\n Dot product of two arrays. Specifically,\n\n - If both `a` and `b` are 1-D arrays, it is inner product of vectors\n (without complex conjugation).\n\n - If both `a` and `b` are 2-D...
@array_function_from_c_func_and_dispatcher(_multiarray_umath.vdot) def vdot(a, b): '\n vdot(a, b)\n\n Return the dot product of two vectors.\n\n The vdot(`a`, `b`) function handles complex numbers differently than\n dot(`a`, `b`). If the first argument is complex the complex conjugate\n of the first...
-7,113,312,379,025,483,000
vdot(a, b) Return the dot product of two vectors. The vdot(`a`, `b`) function handles complex numbers differently than dot(`a`, `b`). If the first argument is complex the complex conjugate of the first argument is used for the calculation of the dot product. Note that `vdot` handles multidimensional arrays differen...
venv/lib/python3.7/site-packages/numpy/core/multiarray.py
vdot
180Studios/LoginApp
python
@array_function_from_c_func_and_dispatcher(_multiarray_umath.vdot) def vdot(a, b): '\n vdot(a, b)\n\n Return the dot product of two vectors.\n\n The vdot(`a`, `b`) function handles complex numbers differently than\n dot(`a`, `b`). If the first argument is complex the complex conjugate\n of the first...
@array_function_from_c_func_and_dispatcher(_multiarray_umath.bincount) def bincount(x, weights=None, minlength=None): '\n bincount(x, weights=None, minlength=0)\n\n Count number of occurrences of each value in array of non-negative ints.\n\n The number of bins (of size 1) is one larger than the largest val...
-8,931,369,888,445,359,000
bincount(x, weights=None, minlength=0) Count number of occurrences of each value in array of non-negative ints. The number of bins (of size 1) is one larger than the largest value in `x`. If `minlength` is specified, there will be at least this number of bins in the output array (though it will be longer if necessary...
venv/lib/python3.7/site-packages/numpy/core/multiarray.py
bincount
180Studios/LoginApp
python
@array_function_from_c_func_and_dispatcher(_multiarray_umath.bincount) def bincount(x, weights=None, minlength=None): '\n bincount(x, weights=None, minlength=0)\n\n Count number of occurrences of each value in array of non-negative ints.\n\n The number of bins (of size 1) is one larger than the largest val...
@array_function_from_c_func_and_dispatcher(_multiarray_umath.ravel_multi_index) def ravel_multi_index(multi_index, dims, mode=None, order=None): "\n ravel_multi_index(multi_index, dims, mode='raise', order='C')\n\n Converts a tuple of index arrays into an array of flat\n indices, applying boundary modes to...
6,791,245,878,041,759,000
ravel_multi_index(multi_index, dims, mode='raise', order='C') Converts a tuple of index arrays into an array of flat indices, applying boundary modes to the multi-index. Parameters ---------- multi_index : tuple of array_like A tuple of integer arrays, one array for each dimension. dims : tuple of ints The sh...
venv/lib/python3.7/site-packages/numpy/core/multiarray.py
ravel_multi_index
180Studios/LoginApp
python
@array_function_from_c_func_and_dispatcher(_multiarray_umath.ravel_multi_index) def ravel_multi_index(multi_index, dims, mode=None, order=None): "\n ravel_multi_index(multi_index, dims, mode='raise', order='C')\n\n Converts a tuple of index arrays into an array of flat\n indices, applying boundary modes to...
@array_function_from_c_func_and_dispatcher(_multiarray_umath.unravel_index) def unravel_index(indices, shape=None, order=None, dims=None): "\n unravel_index(indices, shape, order='C')\n\n Converts a flat index or array of flat indices into a tuple\n of coordinate arrays.\n\n Parameters\n ----------\n...
-5,508,050,244,993,584,000
unravel_index(indices, shape, order='C') Converts a flat index or array of flat indices into a tuple of coordinate arrays. Parameters ---------- indices : array_like An integer array whose elements are indices into the flattened version of an array of dimensions ``shape``. Before version 1.6.0, this funct...
venv/lib/python3.7/site-packages/numpy/core/multiarray.py
unravel_index
180Studios/LoginApp
python
@array_function_from_c_func_and_dispatcher(_multiarray_umath.unravel_index) def unravel_index(indices, shape=None, order=None, dims=None): "\n unravel_index(indices, shape, order='C')\n\n Converts a flat index or array of flat indices into a tuple\n of coordinate arrays.\n\n Parameters\n ----------\n...
@array_function_from_c_func_and_dispatcher(_multiarray_umath.copyto) def copyto(dst, src, casting=None, where=None): "\n copyto(dst, src, casting='same_kind', where=True)\n\n Copies values from one array to another, broadcasting as necessary.\n\n Raises a TypeError if the `casting` rule is violated, and if...
3,615,085,328,127,619,000
copyto(dst, src, casting='same_kind', where=True) Copies values from one array to another, broadcasting as necessary. Raises a TypeError if the `casting` rule is violated, and if `where` is provided, it selects which elements to copy. .. versionadded:: 1.7.0 Parameters ---------- dst : ndarray The array into wh...
venv/lib/python3.7/site-packages/numpy/core/multiarray.py
copyto
180Studios/LoginApp
python
@array_function_from_c_func_and_dispatcher(_multiarray_umath.copyto) def copyto(dst, src, casting=None, where=None): "\n copyto(dst, src, casting='same_kind', where=True)\n\n Copies values from one array to another, broadcasting as necessary.\n\n Raises a TypeError if the `casting` rule is violated, and if...
@array_function_from_c_func_and_dispatcher(_multiarray_umath.putmask) def putmask(a, mask, values): '\n putmask(a, mask, values)\n\n Changes elements of an array based on conditional and input values.\n\n Sets ``a.flat[n] = values[n]`` for each n where ``mask.flat[n]==True``.\n\n If `values` is not the ...
-2,530,559,739,271,771,600
putmask(a, mask, values) Changes elements of an array based on conditional and input values. Sets ``a.flat[n] = values[n]`` for each n where ``mask.flat[n]==True``. If `values` is not the same size as `a` and `mask` then it will repeat. This gives behavior different from ``a[mask] = values``. Parameters ---------- ...
venv/lib/python3.7/site-packages/numpy/core/multiarray.py
putmask
180Studios/LoginApp
python
@array_function_from_c_func_and_dispatcher(_multiarray_umath.putmask) def putmask(a, mask, values): '\n putmask(a, mask, values)\n\n Changes elements of an array based on conditional and input values.\n\n Sets ``a.flat[n] = values[n]`` for each n where ``mask.flat[n]==True``.\n\n If `values` is not the ...
@array_function_from_c_func_and_dispatcher(_multiarray_umath.packbits) def packbits(myarray, axis=None): '\n packbits(myarray, axis=None)\n\n Packs the elements of a binary-valued array into bits in a uint8 array.\n\n The result is padded to full bytes by inserting zero bits at the end.\n\n Parameters\n...
-5,699,911,325,572,923,000
packbits(myarray, axis=None) Packs the elements of a binary-valued array into bits in a uint8 array. The result is padded to full bytes by inserting zero bits at the end. Parameters ---------- myarray : array_like An array of integers or booleans whose elements should be packed to bits. axis : int, optional ...
venv/lib/python3.7/site-packages/numpy/core/multiarray.py
packbits
180Studios/LoginApp
python
@array_function_from_c_func_and_dispatcher(_multiarray_umath.packbits) def packbits(myarray, axis=None): '\n packbits(myarray, axis=None)\n\n Packs the elements of a binary-valued array into bits in a uint8 array.\n\n The result is padded to full bytes by inserting zero bits at the end.\n\n Parameters\n...
@array_function_from_c_func_and_dispatcher(_multiarray_umath.unpackbits) def unpackbits(myarray, axis=None): '\n unpackbits(myarray, axis=None)\n\n Unpacks elements of a uint8 array into a binary-valued output array.\n\n Each element of `myarray` represents a bit-field that should be unpacked\n into a b...
4,681,147,811,743,044,000
unpackbits(myarray, axis=None) Unpacks elements of a uint8 array into a binary-valued output array. Each element of `myarray` represents a bit-field that should be unpacked into a binary-valued output array. The shape of the output array is either 1-D (if `axis` is None) or the same shape as the input array with unpa...
venv/lib/python3.7/site-packages/numpy/core/multiarray.py
unpackbits
180Studios/LoginApp
python
@array_function_from_c_func_and_dispatcher(_multiarray_umath.unpackbits) def unpackbits(myarray, axis=None): '\n unpackbits(myarray, axis=None)\n\n Unpacks elements of a uint8 array into a binary-valued output array.\n\n Each element of `myarray` represents a bit-field that should be unpacked\n into a b...
@array_function_from_c_func_and_dispatcher(_multiarray_umath.shares_memory) def shares_memory(a, b, max_work=None): '\n shares_memory(a, b, max_work=None)\n\n Determine if two arrays share memory\n\n Parameters\n ----------\n a, b : ndarray\n Input arrays\n max_work : int, optional\n ...
-2,958,432,600,631,115,000
shares_memory(a, b, max_work=None) Determine if two arrays share memory Parameters ---------- a, b : ndarray Input arrays max_work : int, optional Effort to spend on solving the overlap problem (maximum number of candidate solutions to consider). The following special values are recognized: max_w...
venv/lib/python3.7/site-packages/numpy/core/multiarray.py
shares_memory
180Studios/LoginApp
python
@array_function_from_c_func_and_dispatcher(_multiarray_umath.shares_memory) def shares_memory(a, b, max_work=None): '\n shares_memory(a, b, max_work=None)\n\n Determine if two arrays share memory\n\n Parameters\n ----------\n a, b : ndarray\n Input arrays\n max_work : int, optional\n ...
@array_function_from_c_func_and_dispatcher(_multiarray_umath.may_share_memory) def may_share_memory(a, b, max_work=None): '\n may_share_memory(a, b, max_work=None)\n\n Determine if two arrays might share memory\n\n A return of True does not necessarily mean that the two arrays\n share any element. It j...
379,643,540,804,239,400
may_share_memory(a, b, max_work=None) Determine if two arrays might share memory A return of True does not necessarily mean that the two arrays share any element. It just means that they *might*. Only the memory bounds of a and b are checked by default. Parameters ---------- a, b : ndarray Input arrays max_wor...
venv/lib/python3.7/site-packages/numpy/core/multiarray.py
may_share_memory
180Studios/LoginApp
python
@array_function_from_c_func_and_dispatcher(_multiarray_umath.may_share_memory) def may_share_memory(a, b, max_work=None): '\n may_share_memory(a, b, max_work=None)\n\n Determine if two arrays might share memory\n\n A return of True does not necessarily mean that the two arrays\n share any element. It j...
@array_function_from_c_func_and_dispatcher(_multiarray_umath.is_busday) def is_busday(dates, weekmask=None, holidays=None, busdaycal=None, out=None): '\n is_busday(dates, weekmask=\'1111100\', holidays=None, busdaycal=None, out=None)\n\n Calculates which of the given dates are valid days, and which are not.\n...
-3,946,965,257,007,669,000
is_busday(dates, weekmask='1111100', holidays=None, busdaycal=None, out=None) Calculates which of the given dates are valid days, and which are not. .. versionadded:: 1.7.0 Parameters ---------- dates : array_like of datetime64[D] The array of dates to process. weekmask : str or array_like of bool, optional ...
venv/lib/python3.7/site-packages/numpy/core/multiarray.py
is_busday
180Studios/LoginApp
python
@array_function_from_c_func_and_dispatcher(_multiarray_umath.is_busday) def is_busday(dates, weekmask=None, holidays=None, busdaycal=None, out=None): '\n is_busday(dates, weekmask=\'1111100\', holidays=None, busdaycal=None, out=None)\n\n Calculates which of the given dates are valid days, and which are not.\n...
@array_function_from_c_func_and_dispatcher(_multiarray_umath.busday_offset) def busday_offset(dates, offsets, roll=None, weekmask=None, holidays=None, busdaycal=None, out=None): '\n busday_offset(dates, offsets, roll=\'raise\', weekmask=\'1111100\', holidays=None, busdaycal=None, out=None)\n\n First adjusts t...
-7,629,953,265,631,859,000
busday_offset(dates, offsets, roll='raise', weekmask='1111100', holidays=None, busdaycal=None, out=None) First adjusts the date to fall on a valid day according to the ``roll`` rule, then applies offsets to the given dates counted in valid days. .. versionadded:: 1.7.0 Parameters ---------- dates : array_like of dat...
venv/lib/python3.7/site-packages/numpy/core/multiarray.py
busday_offset
180Studios/LoginApp
python
@array_function_from_c_func_and_dispatcher(_multiarray_umath.busday_offset) def busday_offset(dates, offsets, roll=None, weekmask=None, holidays=None, busdaycal=None, out=None): '\n busday_offset(dates, offsets, roll=\'raise\', weekmask=\'1111100\', holidays=None, busdaycal=None, out=None)\n\n First adjusts t...
@array_function_from_c_func_and_dispatcher(_multiarray_umath.busday_count) def busday_count(begindates, enddates, weekmask=None, holidays=None, busdaycal=None, out=None): '\n busday_count(begindates, enddates, weekmask=\'1111100\', holidays=[], busdaycal=None, out=None)\n\n Counts the number of valid days bet...
2,000,849,704,293,497,000
busday_count(begindates, enddates, weekmask='1111100', holidays=[], busdaycal=None, out=None) Counts the number of valid days between `begindates` and `enddates`, not including the day of `enddates`. If ``enddates`` specifies a date value that is earlier than the corresponding ``begindates`` date value, the count wil...
venv/lib/python3.7/site-packages/numpy/core/multiarray.py
busday_count
180Studios/LoginApp
python
@array_function_from_c_func_and_dispatcher(_multiarray_umath.busday_count) def busday_count(begindates, enddates, weekmask=None, holidays=None, busdaycal=None, out=None): '\n busday_count(begindates, enddates, weekmask=\'1111100\', holidays=[], busdaycal=None, out=None)\n\n Counts the number of valid days bet...
@array_function_from_c_func_and_dispatcher(_multiarray_umath.datetime_as_string) def datetime_as_string(arr, unit=None, timezone=None, casting=None): "\n datetime_as_string(arr, unit=None, timezone='naive', casting='same_kind')\n\n Convert an array of datetimes into an array of strings.\n\n Parameters\n ...
7,093,229,090,673,673,000
datetime_as_string(arr, unit=None, timezone='naive', casting='same_kind') Convert an array of datetimes into an array of strings. Parameters ---------- arr : array_like of datetime64 The array of UTC timestamps to format. unit : str One of None, 'auto', or a :ref:`datetime unit <arrays.dtypes.dateunits>`. tim...
venv/lib/python3.7/site-packages/numpy/core/multiarray.py
datetime_as_string
180Studios/LoginApp
python
@array_function_from_c_func_and_dispatcher(_multiarray_umath.datetime_as_string) def datetime_as_string(arr, unit=None, timezone=None, casting=None): "\n datetime_as_string(arr, unit=None, timezone='naive', casting='same_kind')\n\n Convert an array of datetimes into an array of strings.\n\n Parameters\n ...
def set_seed(seed): 'Set seed for reproduction.\n ' seed = (seed + dist.get_rank()) random.seed(seed) np.random.seed(seed) paddle.seed(seed) os.environ['PYTHONHASHSEED'] = str(seed)
-1,180,362,922,598,118,700
Set seed for reproduction.
apps/Graph4KG/utils.py
set_seed
LemonNoel/PGL
python
def set_seed(seed): '\n ' seed = (seed + dist.get_rank()) random.seed(seed) np.random.seed(seed) paddle.seed(seed) os.environ['PYTHONHASHSEED'] = str(seed)
def set_logger(args): 'Write logs to console and log file.\n ' log_file = os.path.join(args.save_path, 'train.log') logging.basicConfig(format='%(asctime)s %(levelname)-8s %(message)s', level=logging.INFO, datefmt='%Y-%m-%d %H:%M:%S', filename=log_file, filemode='a+') if args.print_on_screen: ...
1,284,161,568,627,359,000
Write logs to console and log file.
apps/Graph4KG/utils.py
set_logger
LemonNoel/PGL
python
def set_logger(args): '\n ' log_file = os.path.join(args.save_path, 'train.log') logging.basicConfig(format='%(asctime)s %(levelname)-8s %(message)s', level=logging.INFO, datefmt='%Y-%m-%d %H:%M:%S', filename=log_file, filemode='a+') if args.print_on_screen: console = logging.StreamHandler() ...
def print_log(step, interval, log, timer, time_sum): 'Print log to logger.\n ' logging.info(('[GPU %d] step: %d, loss: %.5f, reg: %.4e, speed: %.2f steps/s, time: %.2f s' % (dist.get_rank(), step, (log['loss'] / interval), (log['reg'] / interval), (interval / time_sum), time_sum))) logging.info(('sample:...
-7,832,974,644,119,050,000
Print log to logger.
apps/Graph4KG/utils.py
print_log
LemonNoel/PGL
python
def print_log(step, interval, log, timer, time_sum): '\n ' logging.info(('[GPU %d] step: %d, loss: %.5f, reg: %.4e, speed: %.2f steps/s, time: %.2f s' % (dist.get_rank(), step, (log['loss'] / interval), (log['reg'] / interval), (interval / time_sum), time_sum))) logging.info(('sample: %f, forward: %f, ba...
def uniform(low, high, size, dtype=np.float32, seed=0): 'Memory efficient uniform implementation.\n ' rng = np.random.default_rng(seed) out = (((high - low) * rng.random(size, dtype=dtype)) + low) return out
5,091,072,456,343,243,000
Memory efficient uniform implementation.
apps/Graph4KG/utils.py
uniform
LemonNoel/PGL
python
def uniform(low, high, size, dtype=np.float32, seed=0): '\n ' rng = np.random.default_rng(seed) out = (((high - low) * rng.random(size, dtype=dtype)) + low) return out
def timer_wrapper(name): 'Time counter wrapper.\n ' def decorate(func): 'decorate func\n ' @functools.wraps(func) def wrapper(*args, **kwargs): 'wrapper func\n ' logging.info(f'[{name}] start...') ts = time.time() res...
-1,646,729,750,719,834,600
Time counter wrapper.
apps/Graph4KG/utils.py
timer_wrapper
LemonNoel/PGL
python
def timer_wrapper(name): '\n ' def decorate(func): 'decorate func\n ' @functools.wraps(func) def wrapper(*args, **kwargs): 'wrapper func\n ' logging.info(f'[{name}] start...') ts = time.time() result = func(*args, **k...
def calculate_metrics(scores, corr_idxs, filter_list): 'Calculate metrics according to scores.\n ' logs = [] for i in range(scores.shape[0]): rank = (scores[i] > scores[i][corr_idxs[i]]).astype('float32') if (filter_list is not None): mask = paddle.ones(rank.shape, dtype='floa...
-941,842,204,942,299,900
Calculate metrics according to scores.
apps/Graph4KG/utils.py
calculate_metrics
LemonNoel/PGL
python
def calculate_metrics(scores, corr_idxs, filter_list): '\n ' logs = [] for i in range(scores.shape[0]): rank = (scores[i] > scores[i][corr_idxs[i]]).astype('float32') if (filter_list is not None): mask = paddle.ones(rank.shape, dtype='float32') mask[filter_list[i]]...
@timer_wrapper('evaluation') def evaluate(model, loader, evaluate_mode='test', filter_dict=None, save_path='./tmp/', data_mode='hrt'): 'Evaluate given KGE model.\n ' if (data_mode == 'wikikg2'): evaluate_wikikg2(model, loader, evaluate_mode, save_path) elif (data_mode == 'wikikg90m'): eva...
8,041,928,486,932,966,000
Evaluate given KGE model.
apps/Graph4KG/utils.py
evaluate
LemonNoel/PGL
python
@timer_wrapper('evaluation') def evaluate(model, loader, evaluate_mode='test', filter_dict=None, save_path='./tmp/', data_mode='hrt'): '\n ' if (data_mode == 'wikikg2'): evaluate_wikikg2(model, loader, evaluate_mode, save_path) elif (data_mode == 'wikikg90m'): evaluate_wikikg90m(model, lo...
def gram_schimidt_process(embeds, num_elem, use_scale): ' Orthogonalize embeddings.\n ' num_embed = embeds.shape[0] assert (embeds.shape[1] == num_elem) assert (embeds.shape[2] == (num_elem + int(use_scale))) if use_scale: scales = embeds[:, :, (- 1)] embeds = embeds[:, :, :num_el...
8,071,425,646,455,714,000
Orthogonalize embeddings.
apps/Graph4KG/utils.py
gram_schimidt_process
LemonNoel/PGL
python
def gram_schimidt_process(embeds, num_elem, use_scale): ' \n ' num_embed = embeds.shape[0] assert (embeds.shape[1] == num_elem) assert (embeds.shape[2] == (num_elem + int(use_scale))) if use_scale: scales = embeds[:, :, (- 1)] embeds = embeds[:, :, :num_elem] u = [embeds[:, 0]...
def decorate(func): 'decorate func\n ' @functools.wraps(func) def wrapper(*args, **kwargs): 'wrapper func\n ' logging.info(f'[{name}] start...') ts = time.time() result = func(*args, **kwargs) te = time.time() costs = (te - ts) if (c...
-8,385,293,892,817,383,000
decorate func
apps/Graph4KG/utils.py
decorate
LemonNoel/PGL
python
def decorate(func): '\n ' @functools.wraps(func) def wrapper(*args, **kwargs): 'wrapper func\n ' logging.info(f'[{name}] start...') ts = time.time() result = func(*args, **kwargs) te = time.time() costs = (te - ts) if (costs < 0.0001...
@functools.wraps(func) def wrapper(*args, **kwargs): 'wrapper func\n ' logging.info(f'[{name}] start...') ts = time.time() result = func(*args, **kwargs) te = time.time() costs = (te - ts) if (costs < 0.0001): cost_str = ('%f sec' % costs) elif (costs > 3600): ...
5,612,435,469,472,388,000
wrapper func
apps/Graph4KG/utils.py
wrapper
LemonNoel/PGL
python
@functools.wraps(func) def wrapper(*args, **kwargs): '\n ' logging.info(f'[{name}] start...') ts = time.time() result = func(*args, **kwargs) te = time.time() costs = (te - ts) if (costs < 0.0001): cost_str = ('%f sec' % costs) elif (costs > 3600): cost_str = (...
def test_address(self): 'Tests address makes an address that identifies as the correct AddressSpace' user_id = addresser.user.unique_id() user_address = addresser.user.address(user_id) self.assertIsAddress(user_address) self.assertEqual(addresser.get_address_type(user_address), addresser.AddressSpac...
-6,768,783,794,536,796,000
Tests address makes an address that identifies as the correct AddressSpace
tests/rbac/common/addresser/user_test.py
test_address
kthblmfld/sawtooth-next-directory
python
def test_address(self): user_id = addresser.user.unique_id() user_address = addresser.user.address(user_id) self.assertIsAddress(user_address) self.assertEqual(addresser.get_address_type(user_address), addresser.AddressSpace.USER)
def test_unique_id(self): 'Tests that unique_id generates a unique identifier and is unique' id1 = addresser.user.unique_id() id2 = addresser.user.unique_id() self.assertIsIdentifier(id1) self.assertIsIdentifier(id2) self.assertNotEqual(id1, id2)
-7,196,710,362,681,734,000
Tests that unique_id generates a unique identifier and is unique
tests/rbac/common/addresser/user_test.py
test_unique_id
kthblmfld/sawtooth-next-directory
python
def test_unique_id(self): id1 = addresser.user.unique_id() id2 = addresser.user.unique_id() self.assertIsIdentifier(id1) self.assertIsIdentifier(id2) self.assertNotEqual(id1, id2)
def test_get_address_type(self): 'Tests that get_address_type returns AddressSpace.USER if it is a user\n address, and None if it is of another address type' user_address = addresser.user.address(addresser.user.unique_id()) role_address = addresser.role.address(addresser.role.unique_id()) self.as...
-2,365,047,442,419,383,000
Tests that get_address_type returns AddressSpace.USER if it is a user address, and None if it is of another address type
tests/rbac/common/addresser/user_test.py
test_get_address_type
kthblmfld/sawtooth-next-directory
python
def test_get_address_type(self): 'Tests that get_address_type returns AddressSpace.USER if it is a user\n address, and None if it is of another address type' user_address = addresser.user.address(addresser.user.unique_id()) role_address = addresser.role.address(addresser.role.unique_id()) self.as...
def test_get_addresser(self): 'Test that get_addresser returns the addresser class if it is a\n user address, and None if it is of another address type' user_address = addresser.user.address(addresser.user.unique_id()) other_address = addresser.role.address(addresser.role.unique_id()) self.assert...
-6,577,220,945,678,064,000
Test that get_addresser returns the addresser class if it is a user address, and None if it is of another address type
tests/rbac/common/addresser/user_test.py
test_get_addresser
kthblmfld/sawtooth-next-directory
python
def test_get_addresser(self): 'Test that get_addresser returns the addresser class if it is a\n user address, and None if it is of another address type' user_address = addresser.user.address(addresser.user.unique_id()) other_address = addresser.role.address(addresser.role.unique_id()) self.assert...
def test_user_parse(self): 'Test addresser.user.parse returns a parsed address if it is a user address' user_id = addresser.user.unique_id() user_address = addresser.user.address(user_id) parsed = addresser.user.parse(user_address) self.assertEqual(parsed.object_type, addresser.ObjectType.USER) ...
433,924,049,134,503,230
Test addresser.user.parse returns a parsed address if it is a user address
tests/rbac/common/addresser/user_test.py
test_user_parse
kthblmfld/sawtooth-next-directory
python
def test_user_parse(self): user_id = addresser.user.unique_id() user_address = addresser.user.address(user_id) parsed = addresser.user.parse(user_address) self.assertEqual(parsed.object_type, addresser.ObjectType.USER) self.assertEqual(parsed.related_type, addresser.ObjectType.NONE) self.as...
def test_addresser_parse(self): 'Test addresser.parse returns a parsed address' user_id = addresser.user.unique_id() user_address = addresser.user.address(user_id) parsed = addresser.parse(user_address) self.assertEqual(parsed.object_type, addresser.ObjectType.USER) self.assertEqual(parsed.relat...
7,162,493,697,817,564,000
Test addresser.parse returns a parsed address
tests/rbac/common/addresser/user_test.py
test_addresser_parse
kthblmfld/sawtooth-next-directory
python
def test_addresser_parse(self): user_id = addresser.user.unique_id() user_address = addresser.user.address(user_id) parsed = addresser.parse(user_address) self.assertEqual(parsed.object_type, addresser.ObjectType.USER) self.assertEqual(parsed.related_type, addresser.ObjectType.NONE) self.as...
def test_parse_other(self): 'Test that parse returns None if it is not a user address' other_address = addresser.role.address(addresser.role.unique_id()) self.assertIsNone(addresser.user.parse(other_address))
-610,400,045,570,985,700
Test that parse returns None if it is not a user address
tests/rbac/common/addresser/user_test.py
test_parse_other
kthblmfld/sawtooth-next-directory
python
def test_parse_other(self): other_address = addresser.role.address(addresser.role.unique_id()) self.assertIsNone(addresser.user.parse(other_address))
def test_addresses_are(self): 'Test that addresses_are returns True if all addresses are a user\n addresses, and False if any addresses are if a different address type' user_address1 = addresser.user.address(addresser.user.unique_id()) user_address2 = addresser.user.address(addresser.user.unique_id()...
779,494,870,157,806,300
Test that addresses_are returns True if all addresses are a user addresses, and False if any addresses are if a different address type
tests/rbac/common/addresser/user_test.py
test_addresses_are
kthblmfld/sawtooth-next-directory
python
def test_addresses_are(self): 'Test that addresses_are returns True if all addresses are a user\n addresses, and False if any addresses are if a different address type' user_address1 = addresser.user.address(addresser.user.unique_id()) user_address2 = addresser.user.address(addresser.user.unique_id()...
def test_address_deterministic(self): 'Tests address makes an address that identifies as the correct AddressSpace' user_id1 = addresser.user.unique_id() user_address1 = addresser.user.address(user_id1) user_address2 = addresser.user.address(user_id1) self.assertIsAddress(user_address1) self.asse...
507,684,526,630,221,630
Tests address makes an address that identifies as the correct AddressSpace
tests/rbac/common/addresser/user_test.py
test_address_deterministic
kthblmfld/sawtooth-next-directory
python
def test_address_deterministic(self): user_id1 = addresser.user.unique_id() user_address1 = addresser.user.address(user_id1) user_address2 = addresser.user.address(user_id1) self.assertIsAddress(user_address1) self.assertIsAddress(user_address2) self.assertEqual(user_address1, user_address2...
def test_address_random(self): 'Tests address makes a unique address given different inputs' user_id1 = addresser.user.unique_id() user_id2 = addresser.user.unique_id() user_address1 = addresser.user.address(user_id1) user_address2 = addresser.user.address(user_id2) self.assertIsAddress(user_add...
-283,297,163,203,004,260
Tests address makes a unique address given different inputs
tests/rbac/common/addresser/user_test.py
test_address_random
kthblmfld/sawtooth-next-directory
python
def test_address_random(self): user_id1 = addresser.user.unique_id() user_id2 = addresser.user.unique_id() user_address1 = addresser.user.address(user_id1) user_address2 = addresser.user.address(user_id2) self.assertIsAddress(user_address1) self.assertIsAddress(user_address2) self.asser...
def tile_index(A, B): '\n Entrywise comparison index of tile index (column) vectors.\n ' (AA, BB) = broadcast_arrays(A, B) if DEBUGGING: shape = (max(A.shape[0], B.shape[0]), 1) _check_shape('AA', AA, shape) _check_shape('BB', BB, shape) return (AA, BB)
1,716,995,872,579,375,000
Entrywise comparison index of tile index (column) vectors.
neuroswarms/matrix.py
tile_index
jdmonaco/neuroswarms
python
def tile_index(A, B): '\n \n ' (AA, BB) = broadcast_arrays(A, B) if DEBUGGING: shape = (max(A.shape[0], B.shape[0]), 1) _check_shape('AA', AA, shape) _check_shape('BB', BB, shape) return (AA, BB)
def pairwise_tile_index(A, B): '\n Pairwise comparison index of tile index (column) vectors.\n ' (AA, BB) = broadcast_arrays(A, B.T) if DEBUGGING: shape = (len(A), len(B)) _check_shape('AA', AA, shape) _check_shape('BB', BB, shape) return (AA, BB)
-8,375,266,190,173,897,000
Pairwise comparison index of tile index (column) vectors.
neuroswarms/matrix.py
pairwise_tile_index
jdmonaco/neuroswarms
python
def pairwise_tile_index(A, B): '\n \n ' (AA, BB) = broadcast_arrays(A, B.T) if DEBUGGING: shape = (len(A), len(B)) _check_shape('AA', AA, shape) _check_shape('BB', BB, shape) return (AA, BB)
def pairwise_phasediffs(A, B): '\n Compute synchronizing phase differences between phase pairs.\n ' N_A = len(A) N_B = len(B) DD_shape = (N_A, N_B) if DEBUGGING: _check_ndim('A', A, 2) _check_ndim('B', B, 2) _check_shape('A', A, 1, axis=1) _check_shape('B', B, 1...
3,069,492,397,436,846,000
Compute synchronizing phase differences between phase pairs.
neuroswarms/matrix.py
pairwise_phasediffs
jdmonaco/neuroswarms
python
def pairwise_phasediffs(A, B): '\n \n ' N_A = len(A) N_B = len(B) DD_shape = (N_A, N_B) if DEBUGGING: _check_ndim('A', A, 2) _check_ndim('B', B, 2) _check_shape('A', A, 1, axis=1) _check_shape('B', B, 1, axis=1) return (B.T - A)
def distances(A, B): '\n Compute distances between points in entrywise order.\n ' (AA, BB) = broadcast_arrays(A, B) shape = AA.shape if DEBUGGING: _check_ndim('AA', AA, 2) _check_ndim('BB', BB, 2) _check_shape('AA', AA, 2, axis=1) _check_shape('BB', BB, 2, axis=1) ...
-7,030,238,118,766,872,000
Compute distances between points in entrywise order.
neuroswarms/matrix.py
distances
jdmonaco/neuroswarms
python
def distances(A, B): '\n \n ' (AA, BB) = broadcast_arrays(A, B) shape = AA.shape if DEBUGGING: _check_ndim('AA', AA, 2) _check_ndim('BB', BB, 2) _check_shape('AA', AA, 2, axis=1) _check_shape('BB', BB, 2, axis=1) return hypot((AA[:, 0] - BB[:, 0]), (AA[:, 1] - B...
def pairwise_unit_diffs(A, B): '\n Compute attracting unit-vector differences between pairs of points.\n ' DD = pairwise_position_deltas(A, B) D_norm = hypot(DD[(..., 0)], DD[(..., 1)]) nz = D_norm.nonzero() DD[nz] /= D_norm[nz][(..., AX)] return DD
-424,086,748,636,339,500
Compute attracting unit-vector differences between pairs of points.
neuroswarms/matrix.py
pairwise_unit_diffs
jdmonaco/neuroswarms
python
def pairwise_unit_diffs(A, B): '\n \n ' DD = pairwise_position_deltas(A, B) D_norm = hypot(DD[(..., 0)], DD[(..., 1)]) nz = D_norm.nonzero() DD[nz] /= D_norm[nz][(..., AX)] return DD
def pairwise_distances(A, B): '\n Compute distances between pairs of points.\n ' DD = pairwise_position_deltas(A, B) return hypot(DD[(..., 0)], DD[(..., 1)])
721,351,548,684,608,900
Compute distances between pairs of points.
neuroswarms/matrix.py
pairwise_distances
jdmonaco/neuroswarms
python
def pairwise_distances(A, B): '\n \n ' DD = pairwise_position_deltas(A, B) return hypot(DD[(..., 0)], DD[(..., 1)])
def pairwise_position_deltas(A, B): '\n Compute attracting component deltas between pairs of points.\n ' N_A = len(A) N_B = len(B) if DEBUGGING: _check_ndim('A', A, 2) _check_ndim('B', B, 2) _check_shape('A', A, 2, axis=1) _check_shape('B', B, 2, axis=1) AA = em...
-5,928,309,153,118,387,000
Compute attracting component deltas between pairs of points.
neuroswarms/matrix.py
pairwise_position_deltas
jdmonaco/neuroswarms
python
def pairwise_position_deltas(A, B): '\n \n ' N_A = len(A) N_B = len(B) if DEBUGGING: _check_ndim('A', A, 2) _check_ndim('B', B, 2) _check_shape('A', A, 2, axis=1) _check_shape('B', B, 2, axis=1) AA = empty((N_A, N_B, 2), DISTANCE_DTYPE) AA[:] = A[:, AX, :] ...
def somatic_motion_update(D_up, D_cur, X, V): "\n Compute updated positions by averaging pairwise difference vectors for\n mutually visible pairs with equal bidirectional adjustments within each\n pair. The updated distance matrix does not need to be symmetric; it\n represents 'desired' updates based on...
5,209,787,987,385,210,000
Compute updated positions by averaging pairwise difference vectors for mutually visible pairs with equal bidirectional adjustments within each pair. The updated distance matrix does not need to be symmetric; it represents 'desired' updates based on recurrent learning. :D_up: R(N,N)-matrix of updated distances :D_cur: ...
neuroswarms/matrix.py
somatic_motion_update
jdmonaco/neuroswarms
python
def somatic_motion_update(D_up, D_cur, X, V): "\n Compute updated positions by averaging pairwise difference vectors for\n mutually visible pairs with equal bidirectional adjustments within each\n pair. The updated distance matrix does not need to be symmetric; it\n represents 'desired' updates based on...
def reward_motion_update(D_up, D_cur, X, R, V): "\n Compute updated positions by averaging reward-based unit vectors for\n adjustments of the point only. The updated distance matrix represents\n 'desired' updates based on reward learning.\n\n :D_up: R(N,N_R)-matrix of updated distances between points an...
7,204,605,029,253,445,000
Compute updated positions by averaging reward-based unit vectors for adjustments of the point only. The updated distance matrix represents 'desired' updates based on reward learning. :D_up: R(N,N_R)-matrix of updated distances between points and rewards :D_cur: R(N,N_R)-matrix of current distances between points and r...
neuroswarms/matrix.py
reward_motion_update
jdmonaco/neuroswarms
python
def reward_motion_update(D_up, D_cur, X, R, V): "\n Compute updated positions by averaging reward-based unit vectors for\n adjustments of the point only. The updated distance matrix represents\n 'desired' updates based on reward learning.\n\n :D_up: R(N,N_R)-matrix of updated distances between points an...
def run_shortcut(name: str): 'Runs a shortcut on macOS' pass
-6,645,128,257,056,837,000
Runs a shortcut on macOS
code/platforms/mac/user.py
run_shortcut
palexjo/pokey_talon
python
def run_shortcut(name: str): pass
def cleaner(dummy, value, *_): 'Cleans out unsafe HTML tags.\n\n Uses bleach and unescape until it reaches a fix point.\n\n Args:\n dummy: unused, sqalchemy will pass in the model class\n value: html (string) to be cleaned\n Returns:\n Html (string) without unsafe tags.\n ' if (value is None): ...
6,719,119,775,714,724,000
Cleans out unsafe HTML tags. Uses bleach and unescape until it reaches a fix point. Args: dummy: unused, sqalchemy will pass in the model class value: html (string) to be cleaned Returns: Html (string) without unsafe tags.
src/ggrc/utils/html_cleaner.py
cleaner
VRolich/ggrc-core
python
def cleaner(dummy, value, *_): 'Cleans out unsafe HTML tags.\n\n Uses bleach and unescape until it reaches a fix point.\n\n Args:\n dummy: unused, sqalchemy will pass in the model class\n value: html (string) to be cleaned\n Returns:\n Html (string) without unsafe tags.\n ' if (value is None): ...
def predict(self, X): ' Predict the class index of the feature X ' Y_predict = self.clf.predict(self.pca.transform(X)) return Y_predict
4,818,342,988,168,666,000
Predict the class index of the feature X
utils/lib_classifier.py
predict
eddylamhw/trAIner24
python
def predict(self, X): ' ' Y_predict = self.clf.predict(self.pca.transform(X)) return Y_predict
def predict_and_evaluate(self, te_X, te_Y): ' Test model on test set and obtain accuracy ' te_Y_predict = self.predict(te_X) N = len(te_Y) n = sum((te_Y_predict == te_Y)) accu = (n / N) return (accu, te_Y_predict)
-3,017,998,082,432,039,000
Test model on test set and obtain accuracy
utils/lib_classifier.py
predict_and_evaluate
eddylamhw/trAIner24
python
def predict_and_evaluate(self, te_X, te_Y): ' ' te_Y_predict = self.predict(te_X) N = len(te_Y) n = sum((te_Y_predict == te_Y)) accu = (n / N) return (accu, te_Y_predict)
def train(self, X, Y): ' Train model. The result is saved into self.clf ' n_components = min(NUM_FEATURES_FROM_PCA, X.shape[1]) self.pca = PCA(n_components=n_components, whiten=True) self.pca.fit(X) print('Sum eig values:', np.sum(self.pca.explained_variance_ratio_)) X_new = self.pca.transform(X...
-6,929,529,958,043,339,000
Train model. The result is saved into self.clf
utils/lib_classifier.py
train
eddylamhw/trAIner24
python
def train(self, X, Y): ' ' n_components = min(NUM_FEATURES_FROM_PCA, X.shape[1]) self.pca = PCA(n_components=n_components, whiten=True) self.pca.fit(X) print('Sum eig values:', np.sum(self.pca.explained_variance_ratio_)) X_new = self.pca.transform(X) print('After PCA, X.shape = ', X_new.sha...
def _predict_proba(self, X): ' Predict the probability of feature X belonging to each of the class Y[i] ' Y_probs = self.clf.predict_proba(self.pca.transform(X)) return Y_probs
-5,710,001,211,008,620,000
Predict the probability of feature X belonging to each of the class Y[i]
utils/lib_classifier.py
_predict_proba
eddylamhw/trAIner24
python
def _predict_proba(self, X): ' ' Y_probs = self.clf.predict_proba(self.pca.transform(X)) return Y_probs
def predict(self, skeleton): ' Predict the class (string) of the input raw skeleton ' LABEL_UNKNOWN = '' (is_features_good, features) = self.feature_generator.add_cur_skeleton(skeleton) if is_features_good: features = features.reshape((- 1), features.shape[0]) curr_scores = self.model._p...
-2,700,110,827,794,370,600
Predict the class (string) of the input raw skeleton
utils/lib_classifier.py
predict
eddylamhw/trAIner24
python
def predict(self, skeleton): ' ' LABEL_UNKNOWN = (is_features_good, features) = self.feature_generator.add_cur_skeleton(skeleton) if is_features_good: features = features.reshape((- 1), features.shape[0]) curr_scores = self.model._predict_proba(features)[0] self.scores = self.s...
def smooth_scores(self, curr_scores): ' Smooth the current prediction score\n by taking the average with previous scores\n ' self.scores_hist.append(curr_scores) DEQUE_MAX_SIZE = 2 if (len(self.scores_hist) > DEQUE_MAX_SIZE): self.scores_hist.popleft() if 1: score_s...
-7,176,214,101,721,385,000
Smooth the current prediction score by taking the average with previous scores
utils/lib_classifier.py
smooth_scores
eddylamhw/trAIner24
python
def smooth_scores(self, curr_scores): ' Smooth the current prediction score\n by taking the average with previous scores\n ' self.scores_hist.append(curr_scores) DEQUE_MAX_SIZE = 2 if (len(self.scores_hist) > DEQUE_MAX_SIZE): self.scores_hist.popleft() if 1: score_s...
def args(*types, **ktypes): 'Allow testing of input types:\n argkey=(types) or argkey=type' def decorator(func): def modified(*args, **kargs): position = 1 for (arg, T) in zip(args, types): if (not isinstance(arg, T)): raise TypeError(('Po...
8,286,300,610,226,825,000
Allow testing of input types: argkey=(types) or argkey=type
WolfEyes/Utils/TypeChecker.py
args
TBIproject/WolfEye
python
def args(*types, **ktypes): 'Allow testing of input types:\n argkey=(types) or argkey=type' def decorator(func): def modified(*args, **kargs): position = 1 for (arg, T) in zip(args, types): if (not isinstance(arg, T)): raise TypeError(('Po...
def update_sonic_environment(bootloader, binary_image_version): 'Prepare sonic environment variable using incoming image template file. If incoming image template does not exist\n use current image template file.\n ' SONIC_ENV_TEMPLATE_FILE = os.path.join('usr', 'share', 'sonic', 'templates', 'sonic-en...
-8,889,302,718,236,318,000
Prepare sonic environment variable using incoming image template file. If incoming image template does not exist use current image template file.
sonic_installer/main.py
update_sonic_environment
Cosmin-Jinga-MS/sonic-utilities
python
def update_sonic_environment(bootloader, binary_image_version): 'Prepare sonic environment variable using incoming image template file. If incoming image template does not exist\n use current image template file.\n ' SONIC_ENV_TEMPLATE_FILE = os.path.join('usr', 'share', 'sonic', 'templates', 'sonic-en...
def migrate_sonic_packages(bootloader, binary_image_version): ' Migrate SONiC packages to new SONiC image. ' SONIC_PACKAGE_MANAGER = 'sonic-package-manager' PACKAGE_MANAGER_DIR = '/var/lib/sonic-package-manager/' DOCKER_CTL_SCRIPT = '/usr/lib/docker/docker.sh' DOCKERD_SOCK = 'docker.sock' VAR_RU...
9,047,976,012,657,931,000
Migrate SONiC packages to new SONiC image.
sonic_installer/main.py
migrate_sonic_packages
Cosmin-Jinga-MS/sonic-utilities
python
def migrate_sonic_packages(bootloader, binary_image_version): ' ' SONIC_PACKAGE_MANAGER = 'sonic-package-manager' PACKAGE_MANAGER_DIR = '/var/lib/sonic-package-manager/' DOCKER_CTL_SCRIPT = '/usr/lib/docker/docker.sh' DOCKERD_SOCK = 'docker.sock' VAR_RUN_PATH = '/var/run/' tmp_dir = 'tmp' ...
def validate_positive_int(ctx, param, value): 'Callback to validate param passed is a positive integer.' if (isinstance(value, int) and (value > 0)): return value raise click.BadParameter('Must be a positive integer')
-7,279,381,408,099,939,000
Callback to validate param passed is a positive integer.
sonic_installer/main.py
validate_positive_int
Cosmin-Jinga-MS/sonic-utilities
python
def validate_positive_int(ctx, param, value): if (isinstance(value, int) and (value > 0)): return value raise click.BadParameter('Must be a positive integer')
@click.group(cls=AliasedGroup) def sonic_installer(): ' SONiC image installation manager ' if (os.geteuid() != 0): exit('Root privileges required for this operation') if (os.path.basename(sys.argv[0]) == 'sonic_installer'): print_deprecation_warning('sonic_installer', 'sonic-installer')
-2,693,594,652,722,779,600
SONiC image installation manager
sonic_installer/main.py
sonic_installer
Cosmin-Jinga-MS/sonic-utilities
python
@click.group(cls=AliasedGroup) def sonic_installer(): ' ' if (os.geteuid() != 0): exit('Root privileges required for this operation') if (os.path.basename(sys.argv[0]) == 'sonic_installer'): print_deprecation_warning('sonic_installer', 'sonic-installer')
@sonic_installer.command('install') @click.option('-y', '--yes', is_flag=True, callback=abort_if_false, expose_value=False, prompt='New image will be installed, continue?') @click.option('-f', '--force', is_flag=True, help='Force installation of an image of a type which differs from that of the current running image') ...
-8,643,368,970,254,067,000
Install image from local binary or URL
sonic_installer/main.py
install
Cosmin-Jinga-MS/sonic-utilities
python
@sonic_installer.command('install') @click.option('-y', '--yes', is_flag=True, callback=abort_if_false, expose_value=False, prompt='New image will be installed, continue?') @click.option('-f', '--force', is_flag=True, help='Force installation of an image of a type which differs from that of the current running image') ...
@sonic_installer.command('list') def list_command(): ' Print installed images ' bootloader = get_bootloader() images = bootloader.get_installed_images() curimage = bootloader.get_current_image() nextimage = bootloader.get_next_image() click.echo(('Current: ' + curimage)) click.echo(('Next: '...
2,618,359,676,817,890,300
Print installed images
sonic_installer/main.py
list_command
Cosmin-Jinga-MS/sonic-utilities
python
@sonic_installer.command('list') def list_command(): ' ' bootloader = get_bootloader() images = bootloader.get_installed_images() curimage = bootloader.get_current_image() nextimage = bootloader.get_next_image() click.echo(('Current: ' + curimage)) click.echo(('Next: ' + nextimage)) cli...
@sonic_installer.command('set-default') @click.argument('image') def set_default(image): ' Choose image to boot from by default ' if ('set_default' in sys.argv): print_deprecation_warning('set_default', 'set-default') bootloader = get_bootloader() if (image not in bootloader.get_installed_images...
-7,517,770,441,170,818,000
Choose image to boot from by default
sonic_installer/main.py
set_default
Cosmin-Jinga-MS/sonic-utilities
python
@sonic_installer.command('set-default') @click.argument('image') def set_default(image): ' ' if ('set_default' in sys.argv): print_deprecation_warning('set_default', 'set-default') bootloader = get_bootloader() if (image not in bootloader.get_installed_images()): echo_and_log('Error: Im...
@sonic_installer.command('set-next-boot') @click.argument('image') def set_next_boot(image): ' Choose image for next reboot (one time action) ' if ('set_next_boot' in sys.argv): print_deprecation_warning('set_next_boot', 'set-next-boot') bootloader = get_bootloader() if (image not in bootloader....
-6,706,689,704,284,489,000
Choose image for next reboot (one time action)
sonic_installer/main.py
set_next_boot
Cosmin-Jinga-MS/sonic-utilities
python
@sonic_installer.command('set-next-boot') @click.argument('image') def set_next_boot(image): ' ' if ('set_next_boot' in sys.argv): print_deprecation_warning('set_next_boot', 'set-next-boot') bootloader = get_bootloader() if (image not in bootloader.get_installed_images()): echo_and_log(...
@sonic_installer.command('remove') @click.option('-y', '--yes', is_flag=True, callback=abort_if_false, expose_value=False, prompt='Image will be removed, continue?') @click.argument('image') def remove(image): ' Uninstall image ' bootloader = get_bootloader() images = bootloader.get_installed_images() c...
-1,843,418,837,334,930,400
Uninstall image
sonic_installer/main.py
remove
Cosmin-Jinga-MS/sonic-utilities
python
@sonic_installer.command('remove') @click.option('-y', '--yes', is_flag=True, callback=abort_if_false, expose_value=False, prompt='Image will be removed, continue?') @click.argument('image') def remove(image): ' ' bootloader = get_bootloader() images = bootloader.get_installed_images() current = bootlo...
@sonic_installer.command('binary-version') @click.argument('binary_image_path') def binary_version(binary_image_path): ' Get version from local binary image file ' if ('binary_version' in sys.argv): print_deprecation_warning('binary_version', 'binary-version') bootloader = get_bootloader() versi...
3,922,998,441,759,064,600
Get version from local binary image file
sonic_installer/main.py
binary_version
Cosmin-Jinga-MS/sonic-utilities
python
@sonic_installer.command('binary-version') @click.argument('binary_image_path') def binary_version(binary_image_path): ' ' if ('binary_version' in sys.argv): print_deprecation_warning('binary_version', 'binary-version') bootloader = get_bootloader() version = bootloader.get_binary_image_version...
@sonic_installer.command('cleanup') @click.option('-y', '--yes', is_flag=True, callback=abort_if_false, expose_value=False, prompt='Remove images which are not current and next, continue?') def cleanup(): ' Remove installed images which are not current and next ' bootloader = get_bootloader() images = bootl...
-158,115,806,792,518,000
Remove installed images which are not current and next
sonic_installer/main.py
cleanup
Cosmin-Jinga-MS/sonic-utilities
python
@sonic_installer.command('cleanup') @click.option('-y', '--yes', is_flag=True, callback=abort_if_false, expose_value=False, prompt='Remove images which are not current and next, continue?') def cleanup(): ' ' bootloader = get_bootloader() images = bootloader.get_installed_images() curimage = bootloader...
@sonic_installer.command('upgrade-docker') @click.option('-y', '--yes', is_flag=True, callback=abort_if_false, expose_value=False, prompt='New docker image will be installed, continue?') @click.option('--cleanup_image', is_flag=True, help='Clean up old docker image') @click.option('--skip_check', is_flag=True, help='Sk...
-6,863,555,456,993,927,000
Upgrade docker image from local binary or URL
sonic_installer/main.py
upgrade_docker
Cosmin-Jinga-MS/sonic-utilities
python
@sonic_installer.command('upgrade-docker') @click.option('-y', '--yes', is_flag=True, callback=abort_if_false, expose_value=False, prompt='New docker image will be installed, continue?') @click.option('--cleanup_image', is_flag=True, help='Clean up old docker image') @click.option('--skip_check', is_flag=True, help='Sk...
@sonic_installer.command('rollback-docker') @click.option('-y', '--yes', is_flag=True, callback=abort_if_false, expose_value=False, prompt='Docker image will be rolled back, continue?') @click.argument('container_name', metavar='<container_name>', required=True, type=click.Choice(DOCKER_CONTAINER_LIST)) def rollback_do...
3,255,627,671,178,643,500
Rollback docker image to previous version
sonic_installer/main.py
rollback_docker
Cosmin-Jinga-MS/sonic-utilities
python
@sonic_installer.command('rollback-docker') @click.option('-y', '--yes', is_flag=True, callback=abort_if_false, expose_value=False, prompt='Docker image will be rolled back, continue?') @click.argument('container_name', metavar='<container_name>', required=True, type=click.Choice(DOCKER_CONTAINER_LIST)) def rollback_do...
@sonic_installer.command('verify-next-image') def verify_next_image(): ' Verify the next image for reboot' bootloader = get_bootloader() if (not bootloader.verify_next_image()): echo_and_log('Image verification failed', LOG_ERR) sys.exit(1) click.echo('Image successfully verified')
-3,142,566,014,996,444,000
Verify the next image for reboot
sonic_installer/main.py
verify_next_image
Cosmin-Jinga-MS/sonic-utilities
python
@sonic_installer.command('verify-next-image') def verify_next_image(): ' ' bootloader = get_bootloader() if (not bootloader.verify_next_image()): echo_and_log('Image verification failed', LOG_ERR) sys.exit(1) click.echo('Image successfully verified')
def __init__(self, allocate, swap_mem_size=None, total_mem_threshold=None, available_mem_threshold=None): '\n Initialize the SWAP memory allocator.\n The allocator will try to setup SWAP memory only if all the below conditions are met:\n - allocate evaluates to True\n - disk has ...
5,742,194,480,738,586,000
Initialize the SWAP memory allocator. The allocator will try to setup SWAP memory only if all the below conditions are met: - allocate evaluates to True - disk has enough space(> DISK_MEM_THRESHOLD) - either system total memory < total_mem_threshold or system available memory < available_mem_threshold @par...
sonic_installer/main.py
__init__
Cosmin-Jinga-MS/sonic-utilities
python
def __init__(self, allocate, swap_mem_size=None, total_mem_threshold=None, available_mem_threshold=None): '\n Initialize the SWAP memory allocator.\n The allocator will try to setup SWAP memory only if all the below conditions are met:\n - allocate evaluates to True\n - disk has ...
@staticmethod def get_disk_freespace(path): 'Return free disk space in bytes.' fs_stats = os.statvfs(path) return (fs_stats.f_bsize * fs_stats.f_bavail)
-6,005,371,022,862,676,000
Return free disk space in bytes.
sonic_installer/main.py
get_disk_freespace
Cosmin-Jinga-MS/sonic-utilities
python
@staticmethod def get_disk_freespace(path): fs_stats = os.statvfs(path) return (fs_stats.f_bsize * fs_stats.f_bavail)
@staticmethod def read_from_meminfo(): 'Read information from /proc/meminfo.' meminfo = {} with open('/proc/meminfo') as fd: for line in fd.readlines(): if line: fields = line.split() if ((len(fields) >= 2) and fields[1].isdigit()): mem...
5,057,307,792,526,469,000
Read information from /proc/meminfo.
sonic_installer/main.py
read_from_meminfo
Cosmin-Jinga-MS/sonic-utilities
python
@staticmethod def read_from_meminfo(): meminfo = {} with open('/proc/meminfo') as fd: for line in fd.readlines(): if line: fields = line.split() if ((len(fields) >= 2) and fields[1].isdigit()): meminfo[fields[0].rstrip(':')] = int(fiel...