buggy
stringlengths
35
5.03k
fixed
stringlengths
46
62.5k
class PeriodIndex(DatetimeIndexOpsMixin, Int64Index): def get_indexer_non_unique(self, target): target = ensure_index(target) if isinstance(target, PeriodIndex): if target.freq != self.freq: no_matches = -1 * np.ones(self.shape, dtype=np.intp) return no_m...
class PeriodIndex(DatetimeIndexOpsMixin, Int64Index): def get_indexer_non_unique(self, target): target = ensure_index(target) if not self._is_comparable_dtype(target.dtype): no_matches = -1 * np.ones(self.shape, dtype=np.intp) return no_matches, no_matches target = ...
""" implement the TimedeltaIndex """ from pandas._libs import NaT, Timedelta, index as libindex from pandas._typing import Label from pandas.util._decorators import Appender from pandas.core.dtypes.common import (
""" implement the TimedeltaIndex """ from pandas._libs import NaT, Timedelta, index as libindex from pandas._typing import DtypeObj, Label from pandas.util._decorators import Appender from pandas.core.dtypes.common import (
class TimedeltaIndex(DatetimeTimedeltaMixin, dtl.TimelikeOps): other = TimedeltaIndex(other) return self, other def get_loc(self, key, method=None, tolerance=None): """ Get integer location for requested label
class TimedeltaIndex(DatetimeTimedeltaMixin, dtl.TimelikeOps): other = TimedeltaIndex(other) return self, other def _is_comparable_dtype(self, dtype: DtypeObj) -> bool: """ Can we compare values of the given dtype to our own? """ return is_timedelta64_dtype(dtype...
def test_convert_almost_null_slice(indices): msg = "'>=' not supported between instances of 'str' and 'int'" with pytest.raises(TypeError, match=msg): idx._convert_slice_indexer(key, "loc")
def test_convert_almost_null_slice(indices): msg = "'>=' not supported between instances of 'str' and 'int'" with pytest.raises(TypeError, match=msg): idx._convert_slice_indexer(key, "loc") dtlike_dtypes = [ np.dtype("timedelta64[ns]"), np.dtype("datetime64[ns]"), pd.DatetimeTZ...
def test_loc_slice_disallows_positional(): with tm.assert_produces_warning(FutureWarning): # GH#31840 deprecated incorrect behavior df.loc[1:3, 1] = 2
def test_loc_slice_disallows_positional(): with tm.assert_produces_warning(FutureWarning): # GH#31840 deprecated incorrect behavior df.loc[1:3, 1] = 2 def test_loc_datetimelike_mismatched_dtypes(): # GH#32650 dont mix and match datetime/timedelta/period dtypes df = pd.DataFrame( n...
DEFAULT_FORCE_HANDLERS = get_config(p, DEFAULTS, 'force_handlers', 'ANSIBLE_F DEFAULT_INVENTORY_IGNORE = get_config(p, DEFAULTS, 'inventory_ignore_extensions', 'ANSIBLE_INVENTORY_IGNORE', ["~", ".orig", ".bak", ".ini", ".cfg", ".retry", ".pyc", ".pyo"], value_type='list') DEFAULT_VAR_COMPRESSION_LEVEL = get_config(...
DEFAULT_FORCE_HANDLERS = get_config(p, DEFAULTS, 'force_handlers', 'ANSIBLE_F DEFAULT_INVENTORY_IGNORE = get_config(p, DEFAULTS, 'inventory_ignore_extensions', 'ANSIBLE_INVENTORY_IGNORE', ["~", ".orig", ".bak", ".ini", ".cfg", ".retry", ".pyc", ".pyo"], value_type='list') DEFAULT_VAR_COMPRESSION_LEVEL = get_config(...
class Templar: loader=FileSystemLoader(self._basedir), ) self.SINGLE_VAR = re.compile(r"^%s\s*(\w*)\s*%s$" % (self.environment.variable_start_string, self.environment.variable_end_string)) self.block_start = self.environment.block_start_string
class Templar: loader=FileSystemLoader(self._basedir), ) # the current rendering context under which the templar class is working self.cur_context = None self.SINGLE_VAR = re.compile(r"^%s\s*(\w*)\s*%s$" % (self.environment.variable_start_string, self.environment.variable_e...
class Templar: if instance is not None: wantlist = kwargs.pop('wantlist', False) from ansible.utils.listify import listify_lookup_plugin_terms loop_terms = listify_lookup_plugin_terms(terms=args, templar=self, loader=self._loader, fail_on_undefined=True, convert_bare=False)
class Templar: if instance is not None: wantlist = kwargs.pop('wantlist', False) allow_unsafe = kwargs.pop('allow_unsafe', C.DEFAULT_ALLOW_UNSAFE_LOOKUPS) from ansible.utils.listify import listify_lookup_plugin_terms loop_terms = listify_lookup_plugin_terms(term...
class Templar: raise AnsibleError("An unhandled exception occurred while running the lookup plugin '%s'. Error was a %s, original message: %s" % (name, type(e), e)) ran = None if ran: if wantlist: ran = wrap_var(ran) el...
class Templar: raise AnsibleError("An unhandled exception occurred while running the lookup plugin '%s'. Error was a %s, original message: %s" % (name, type(e), e)) ran = None if ran and not allow_unsafe: from ansible.vars.unsafe_proxy import UnsafeProxy,...
class Templar: else: ran = wrap_var(ran) return ran else: raise AnsibleError("lookup plugin (%s) not found" % name)
class Templar: else: ran = wrap_var(ran) if self.cur_context: self.cur_context.unsafe = True return ran else: raise AnsibleError("lookup plugin (%s) not found" % name)
class Templar: jvars = AnsibleJ2Vars(self, t.globals) new_context = t.new_context(jvars, shared=True) rf = t.root_render_func(new_context) try:
class Templar: jvars = AnsibleJ2Vars(self, t.globals) self.cur_context = new_context = t.new_context(jvars, shared=True) rf = t.root_render_func(new_context) try:
def is_string_dtype(arr_or_dtype) -> bool: """ These have kind = "O" but aren't string dtypes so need to be explicitly excluded """ is_excluded_checks = (is_period_dtype, is_interval_dtype) return any(is_excluded(dtype) for is_excluded in is_excluded_checks) return _is_dtype...
def is_string_dtype(arr_or_dtype) -> bool: """ These have kind = "O" but aren't string dtypes so need to be explicitly excluded """ is_excluded_checks = (is_period_dtype, is_interval_dtype, is_categorical_dtype) return any(is_excluded(dtype) for is_excluded in is_excluded_checks)...
class TestCategoricalDtype(Base): result = str(Categorical(DatetimeIndex([])).categories.dtype) assert result == expected class TestDatetimeTZDtype(Base): @pytest.fixture
class TestCategoricalDtype(Base): result = str(Categorical(DatetimeIndex([])).categories.dtype) assert result == expected def test_not_string(self): # though CategoricalDtype has object kind, it cannot be string assert not is_string_dtype(CategoricalDtype()) class TestDatetimeTZDt...
def validate_baseindexer_support(func_name: Optional[str]) -> None: "median", "std", "var", "kurt", "quantile", }
def validate_baseindexer_support(func_name: Optional[str]) -> None: "median", "std", "var", "skew", "kurt", "quantile", }
class _Window(PandasObject, ShallowMixin, SelectionMixin): def calc(x): x = np.concatenate((x, additional_nans)) if not isinstance(window, BaseIndexer): min_periods = calculate_min_periods( window, self.min_peri...
class _Window(PandasObject, ShallowMixin, SelectionMixin): def calc(x): x = np.concatenate((x, additional_nans)) if not isinstance(self.window, BaseIndexer): min_periods = calculate_min_periods( window, self.min...
def test_win_type_not_implemented(): df.rolling(indexer, win_type="boxcar") @pytest.mark.parametrize("func", ["skew", "cov", "corr"]) def test_notimplemented_functions(func): # GH 32865 class CustomIndexer(BaseIndexer):
def test_win_type_not_implemented(): df.rolling(indexer, win_type="boxcar") @pytest.mark.parametrize("func", ["cov", "corr"]) def test_notimplemented_functions(func): # GH 32865 class CustomIndexer(BaseIndexer):
def test_rolling_forward_window(constructor, func, np_func, expected, np_kwargs) result3 = getattr(rolling3, func)() expected3 = constructor(rolling3.apply(lambda x: np_func(x, **np_kwargs))) tm.assert_equal(result3, expected3)
def test_rolling_forward_window(constructor, func, np_func, expected, np_kwargs) result3 = getattr(rolling3, func)() expected3 = constructor(rolling3.apply(lambda x: np_func(x, **np_kwargs))) tm.assert_equal(result3, expected3) @pytest.mark.parametrize("constructor", [Series, DataFrame]) def test_rolling_...
from thefuck.rules.mkdir_p import match, get_new_command from tests.utils import Command def test_match(): assert match(Command('mkdir foo/bar/baz', stderr='mkdir: foo/bar: No such file or directory'), None) @pytest.mark.parametrize('command', [ Command('mkdir foo/b...
from thefuck.rules.mkdir_p import match, get_new_command from tests.utils import Command @pytest.mark.parametrize('command', [ Command('mkdir foo/bar/baz', stderr='mkdir: foo/bar: No such file or directory'), Command('./bin/hdfs dfs -mkdir foo/bar/baz', stderr='mkdir: `foo/bar/baz\': No such file or directory...
def match(command, settings): @sudo_support def get_new_command(command, settings): return re.sub('^mkdir (.*)', 'mkdir -p \\1', command.script)
def match(command, settings): @sudo_support def get_new_command(command, settings): return re.sub('\\bmkdir (.*)', 'mkdir -p \\1', command.script)
from ellipticcurve.utils.compatibility import * from ellipticcurve.privateKey import PrivateKey from ellipticcurve.publicKey import PublicKey from ellipticcurve.signature import Signature from ellipticcurve.utils.file import File from ellipticcurve.ecdsa import Ecdsa
from .utils.compatibility import * from .privateKey import PrivateKey from .publicKey import PublicKey from .signature import Signature from .utils.file import File from .ecdsa import Ecdsa
def verify(cls, message, signature, publicKey, hashfunc=sha256): curve = publicKey.curve r = signature.r s = signature.s inv = Math.inv(s, curve.N) u1 = Math.multiply(curve.G, n=(numberMessage * inv) % curve.N, N=curve.N, A=curve.A, P=curve.P) u2 = Math.multiply(publicKey...
def verify(cls, message, signature, publicKey, hashfunc=sha256): curve = publicKey.curve r = signature.r s = signature.s if not 1 <= r <= curve.N - 1: return False if not 1 <= s <= curve.N - 1: return False inv = Math.inv(s, curve.N) u1 = M...
options: description: - Whether to disable the GPG checking of signatures of packages being installed. Has an effect only if state is I(present) or I(latest). type: bool default: 'no'
options: description: - Whether to disable the GPG checking of signatures of packages being installed. Has an effect only if state is I(present) or I(latest). - This setting affects packages installed from a repository as well as "local" packages installed from the filesystem or a URL. ...
class DnfModule(YumDnf): results=[], ) if self.download_only: for package in self.base.transaction.install_set: response['results'].append("Downloaded: {0}".format(package))
class DnfModule(YumDnf): results=[], ) # Validate GPG. This is NOT done in dnf.Base (it's done in the # upstream CLI subclass of dnf.Base) if not self.disable_gpg_check: for package in self.base.transaction....
def test_getproxies_environment_keep_no_proxies(self): self.assertTrue(urllib.request.proxy_bypass_environment('anotherdomain.com:8888')) self.assertTrue(urllib.request.proxy_bypass_environment('newdomain.com:1234')) def test_proxy_bypass_environment_host_match(self): bypass = urllib.reques...
def test_getproxies_environment_keep_no_proxies(self): self.assertTrue(urllib.request.proxy_bypass_environment('anotherdomain.com:8888')) self.assertTrue(urllib.request.proxy_bypass_environment('newdomain.com:1234')) def test_proxy_cgi_ignore(self): try: self.env.set('HTTP_PROXY...
def getproxies_environment(): name = name.lower() if value and name[-6:] == '_proxy': proxies[name[:-6]] = value for name, value in os.environ.items(): if name[-6:] == '_proxy': name = name.lower()
def getproxies_environment(): name = name.lower() if value and name[-6:] == '_proxy': proxies[name[:-6]] = value # CVE-2016-1000110 - If we are running as CGI script, forget HTTP_PROXY # (non-all-lowercase) as it may be set from the web server by a "Proxy:" # header from the clie...
class MultiPartParser: remaining = len(stripped_chunk) % 4 while remaining != 0: over_chunk = field_stream.read(4 - remaining) stripped_chunk += b"".join(over_chunk.split()) ...
class MultiPartParser: remaining = len(stripped_chunk) % 4 while remaining != 0: over_chunk = field_stream.read(4 - remaining) if not over_chunk: ...
class FileUploadTests(TestCase): def test_big_base64_newlines_upload(self): self._test_base64_upload("Big data" * 68000, encode=base64.encodebytes) def test_unicode_file_name(self): with sys_tempfile.TemporaryDirectory() as temp_dir: # This file contains Chinese symbols and an accen...
class FileUploadTests(TestCase): def test_big_base64_newlines_upload(self): self._test_base64_upload("Big data" * 68000, encode=base64.encodebytes) def test_base64_invalid_upload(self): payload = client.FakePayload('\r\n'.join([ '--' + client.BOUNDARY, 'Content-Dispositi...
def logical_volume_info(path): return dict(zip(*info)) def remove_logical_volumes(*paths): """Remove one or more logical volume.""" if paths: lvremove = ('lvremove', '-f') + paths execute(*lvremove, attempts=3, run_as_root=True)
def logical_volume_info(path): return dict(zip(*info)) def logical_volume_size(path): """Get logical volume size in bytes. :param path: logical volume path """ # TODO(p-draigbrady) POssibly replace with the more general # use of blockdev --getsize64 in future out, _err = execute('lvs', '-...
from thefuck.types import Command @pytest.fixture def pip_unknown_cmd(): return '''ERROR: unknown command "instatl" - maybe you meant "install"''' @pytest.fixture def pip_unknown_cmd_without_recommend(): return '''ERROR: unknown command "i"''' def test_match(pip_unknown_cmd, pip_unknown_cmd_without_recomm...
from thefuck.types import Command @pytest.fixture def pip_unknown_cmd_without_recommend(): return '''ERROR: unknown command "i"''' @pytest.fixture def broken(): return 'instatl' @pytest.fixture def suggested(): return 'install' @pytest.fixture def pip_unknown_cmd(broken, suggested): return 'ERRO...
def test_match(pip_unknown_cmd, pip_unknown_cmd_without_recommend): pip_unknown_cmd_without_recommend)) def test_get_new_command(pip_unknown_cmd): assert get_new_command(Command('pip instatl', pip_unknown_cmd)) == 'pip install'
def test_match(pip_unknown_cmd, pip_unknown_cmd_without_recommend): pip_unknown_cmd_without_recommend)) @pytest.mark.parametrize('script, broken, suggested, new_cmd', [ ('pip un+install thefuck', 'un+install', 'uninstall', 'pip uninstall thefuck'), ('pip instatl', 'instatl', 'inst...
def match(command): def get_new_command(command): broken_cmd = re.findall(r'ERROR: unknown command \"([a-z]+)\"', command.output)[0] new_cmd = re.findall(r'maybe you meant \"([a-z]+)\"', command.output)[0] return replace_argument(command.script, broken_cmd, new_cmd)
def match(command): def get_new_command(command): broken_cmd = re.findall(r'ERROR: unknown command "([^"]+)"', command.output)[0] new_cmd = re.findall(r'maybe you meant "([^"]+)"', command.output)[0] return replace_argument(command.script, broken_cmd, new_cmd)
class Connection(object): self.user = user self.password = password self.private_key_file = private_key_file self.HASHED_KEY_MAGIC = "|1|" def connect(self):
class Connection(object): self.user = user self.password = password self.private_key_file = private_key_file self.cp_dir = utils.prepare_writeable_dir('$HOME/.ansible/cp',mode=0700) self.HASHED_KEY_MAGIC = "|1|" def connect(self):
class Connection(object): else: self.common_args += ["-o", "ControlMaster=auto", "-o", "ControlPersist=60s", "-o", "ControlPath=/tmp/ansible-ssh-%h-%p-%r"] if not C.HOST_KEY_CHECKING: self.common_args += ["-o", "S...
class Connection(object): else: self.common_args += ["-o", "ControlMaster=auto", "-o", "ControlPersist=60s", "-o", "ControlPath=%s/ansible-ssh-%%h-%%p-%%r" % self.cp_dir] cp_in_use = False cp_path_set = False ...
def is_executable(path): or stat.S_IXGRP & os.stat(path)[stat.ST_MODE] or stat.S_IXOTH & os.stat(path)[stat.ST_MODE]) def prepare_writeable_dir(tree): ''' make sure a directory exists and is writeable ''' if tree != '/': tree = os.path.realpath(os.path.expanduser(tree)) if ...
def is_executable(path): or stat.S_IXGRP & os.stat(path)[stat.ST_MODE] or stat.S_IXOTH & os.stat(path)[stat.ST_MODE]) def unfrackpath(path): ''' returns a path that is free of symlinks, environment variables, relative path traversals and symbols (~) example: '$HOME/../../va...
def test_options(cli_runner, mocker): "bla", "--ca-bundle", "yay", "--no-render", "--login-cert", "puc", "--login-cert-key",
def test_options(cli_runner, mocker): "bla", "--ca-bundle", "yay", "--login-cert", "puc", "--login-cert-key",
def test_options(cli_runner, mocker): assert set(kwargs) == { "base_path", "ca_bundle", "render", "login_cert", "login_cert_key", "password",
def test_options(cli_runner, mocker): assert set(kwargs) == { "base_path", "ca_bundle", "login_cert", "login_cert_key", "password",
def test_options(cli_runner, mocker): assert kwargs["url"] == "https://foo" assert kwargs["username"] == "user" assert kwargs["verify"] is True assert kwargs["render"] is False @pytest.fixture
def test_options(cli_runner, mocker): assert kwargs["url"] == "https://foo" assert kwargs["username"] == "user" assert kwargs["verify"] is True @pytest.fixture
import itertools import pytest from vault_cli import client, exceptions, testing def test_get_client(mocker):
import pytest from vault_cli import client, exceptions def test_get_client(mocker):
def test_vault_client_base_render_template_path_not_found(vault, template): ({"a": {"value": "b"}}, {"value": "b"}), # Secret not a string ({"a": {"value": ["yay"]}}, {"value": ["yay"]}), # Secret is a template without variable expansion ({"a": {"value": "!template!b"}, "b": {"va...
def test_vault_client_base_render_template_path_not_found(vault, template): ({"a": {"value": "b"}}, {"value": "b"}), # Secret not a string ({"a": {"value": ["yay"]}}, {"value": ["yay"]}), ], ) def test_vault_client_base_get_secret(vault, vault_contents, expected):
def test_vault_client_base_get_secret(vault, vault_contents, expected): assert vault.get_secret("a") == expected def test_vault_client_base_get_secret_deprecation_warning(vault, caplog): vault.db = {"a": {"value": "!template!b"}} caplog.set_level("WARNING") vault.get_secret("a") assert "Templated...
def test_vault_client_base_get_secret(vault, vault_contents, expected): assert vault.get_secret("a") == expected def test_vault_client_base_get_secret_multiple_keys(vault): vault.db = {"rabbitmq/creds/role": {"username": "foo", "password": "bar"}} assert vault.get_secret("rabbitmq/creds/role") == {
def test_vault_client_base_get_secret_multiple_keys(vault): } def test_vault_client_base_get_secret_with_dict(vault): vault.db = { "credentials": {"value": {"username": "foo", "password": "bar"}}, "dsn": { "value": "!template!proto://{{ vault('credentials')['value']['username'] }}:...
def test_vault_client_base_get_secret_multiple_keys(vault): } def test_vault_client_base_get_secret_not_found(vault): vault.db = {} with pytest.raises(exceptions.VaultSecretNotFound): vault.get_secret("not-existing") def test_vault_client_base_get_secret_missing_key(vault):
def test_vault_client_base_get_secret_missing_key(vault): vault.get_secret("a", key="username") def test_vault_client_base_get_secret_template_error(vault, caplog): vault.db = {"a": {"key": "!template!{{"}} with pytest.raises(exceptions.VaultRenderTemplateError) as exc_info: vault.get_secret(...
def test_vault_client_base_get_secret_missing_key(vault): vault.get_secret("a", key="username") def test_vault_client_base_lookup_token(vault): assert vault.lookup_token() == {"data": {"expire_time": "2100-01-01T00:00:00"}}
def test_vault_client_base_get_secret_implicit_cache(vault): assert vault.get_secret("a") == {"value": "b"} class RaceConditionTestVaultClient(testing.TestVaultClient): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.counter = itertools.count() def _get_secret(...
def test_vault_client_base_get_secret_implicit_cache(vault): assert vault.get_secret("a") == {"value": "b"} def test_vault_client_base_get_secret_explicit_cache(vault): vault.db = {"a": {"value": "b"}} with vault:
def repr_octal(value: Optional[int]) -> Optional[str]: ) @click.option( "--render/--no-render", default=settings.DEFAULTS.render, help="Render templated values", ) @click.option( "--umask",
def repr_octal(value: Optional[int]) -> Optional[str]: ) @click.option( "--render/--no-render", default=False, help="Deprecated / unused", ) @click.option( "--umask",
def cli(ctx: click.Context, verbose: int, umask: int, **kwargs) -> None: (including VAULT_CLI_PASSWORD and VAULT_CLI_TOKEN). """ kwargs.pop("config_file") set_verbosity(verbose) set_umask(umask)
def cli(ctx: click.Context, verbose: int, umask: int, **kwargs) -> None: (including VAULT_CLI_PASSWORD and VAULT_CLI_TOKEN). """ kwargs.pop("render") kwargs.pop("config_file") set_verbosity(verbose) set_umask(umask)
import json import logging import pathlib from typing import Dict, Iterable, List, Optional, Set, Tuple, Type, Union, cast import hvac # type: ignore import jinja2
import json import logging import pathlib from typing import Dict, Iterable, List, Optional, Tuple, Type, cast import hvac # type: ignore import jinja2
logger = logging.getLogger(__name__) JSONRecursive = Union[types.JSONValue, utils.RecursiveValue] JSONDictRecursive = Dict[str, JSONRecursive] def get_client(**kwargs) -> "VaultClientBase": """
logger = logging.getLogger(__name__) def get_client(**kwargs) -> "VaultClientBase": """
def get_client(**kwargs) -> "VaultClientBase": Path to your config file, instead of the default ones safe_write : bool If set to True, will keep you from overwriting secrets without force=True render : bool If set to False, templated secrets will not be rendered Returns -------
def get_client(**kwargs) -> "VaultClientBase": Path to your config file, instead of the default ones safe_write : bool If set to True, will keep you from overwriting secrets without force=True Returns -------
def __init__( username: Optional[str] = settings.DEFAULTS.username, password: Optional[str] = settings.DEFAULTS.password, safe_write: bool = settings.DEFAULTS.safe_write, render: bool = settings.DEFAULTS.render, ): self.url = url self.verify: types.VerifyOrCABundle = ...
def __init__( username: Optional[str] = settings.DEFAULTS.username, password: Optional[str] = settings.DEFAULTS.password, safe_write: bool = settings.DEFAULTS.safe_write, ): self.url = url self.verify: types.VerifyOrCABundle = verify
def __init__( self.username = username self.password = password self.safe_write = safe_write self.render = render self.cache: Dict[str, types.JSONDict] = {} self.errors: List[str] = [] self._currently_fetching: Set[str] = set() @property def base_path(sel...
def __init__( self.username = username self.password = password self.safe_write = safe_write self.cache: Dict[str, types.JSONDict] = {} self.errors: List[str] = [] @property def base_path(self):
def _build_full_path(self, path: str) -> str: # path relative to base_path return self.base_path + path def _browse_recursive_secrets( self, path: str, render: bool = True ) -> Iterable[str]: """ Given a secret or folder path, return the path of all secrets ...
def _build_full_path(self, path: str) -> str: # path relative to base_path return self.base_path + path def _browse_recursive_secrets(self, path: str) -> Iterable[str]: """ Given a secret or folder path, return the path of all secrets under it (or the path itself)
def _browse_recursive_secrets( yield key_url continue for sub_path in self._browse_recursive_secrets(key_url, render=render): yield sub_path def get_all_secrets( self, *paths: str, render: bool = True, flat: bool = False ) -> JSONDictRecursiv...
def _browse_recursive_secrets( yield key_url continue for sub_path in self._browse_recursive_secrets(key_url): yield sub_path def get_all_secrets(self, *paths: str, flat: bool = False) -> types.JSONDict: """ Takes several paths, return th...
def get_all_secrets( ---------- *paths : str Paths to read recursively render : bool, optional Whether templated secrets should be rendered, by default True flat : bool, optional Whether to return flat structure with full path as keys or nested ...
def get_all_secrets( ---------- *paths : str Paths to read recursively flat : bool, optional Whether to return flat structure with full path as keys or nested structure that looks like a tree
def get_all_secrets( {"folder": {"subfolder": {"secret_key": "secret_value"}}} """ result: JSONDictRecursive = {} for path in paths: path_dict = self.get_secrets(path, render=render) if flat: result.update(path_dict) else:
def get_all_secrets( {"folder": {"subfolder": {"secret_key": "secret_value"}}} """ result: types.JSONDict = {} for path in paths: path_dict = self.get_secrets(path) if flat: result.update(path_dict) else:
def get_all_secrets( return result def get_secrets( self, path: str, render: bool = True, relative: bool = False ) -> Dict[str, JSONDictRecursive]: """ Takes a path, return all secrets below this path
def get_all_secrets( return result def get_secrets( self, path: str, relative: bool = False ) -> Dict[str, types.JSONDict]: """ Takes a path, return all secrets below this path
def get_secrets( ---------- path : str Path to read recursively render : bool, optional Whether templated secrets should be rendered, by default True relative: bool, optional When false (default), the keys of the returned dict are the paths of the secr...
def get_secrets( ---------- path : str Path to read recursively relative: bool, optional When false (default), the keys of the returned dict are the paths of the secrets When true, the keys are the relative paths of the secret to `path` (`""` if the secret is ...
def get_secrets( """ path = path.rstrip("/") try: secrets_paths = list( self._browse_recursive_secrets(path=path, render=render) ) except exceptions.VaultAPIException: # If we cannot list secrets, we can't browse them, but there's still...
def get_secrets( """ path = path.rstrip("/") try: secrets_paths = list(self._browse_recursive_secrets(path=path)) except exceptions.VaultAPIException: # If we cannot list secrets, we can't browse them, but there's still # a chance that the provided pat...
def get_secrets( key = subpath try: secret = self.get_secret(path=subpath, render=render) secret = cast(JSONDictRecursive, secret) result[key] = secret except ( exceptions.VaultAPIException, exceptio...
def get_secrets( key = subpath try: secret = self.get_secret(path=subpath) secret = cast(types.JSONDict, secret) result[key] = secret except exceptions.VaultAPIException as exc: for message in utils.extract_error_me...
def list_secrets(self, path: str) -> Iterable[str]: """ return self._list_secrets(path=self._build_full_path(path)) def get_secret( self, path: str, key: Optional[str] = None, render: bool = True ) -> Union[types.JSONValue, utils.RecursiveValue]: """ Retrieve the value o...
def list_secrets(self, path: str) -> Iterable[str]: """ return self._list_secrets(path=self._build_full_path(path)) def get_secret(self, path: str, key: Optional[str] = None) -> types.JSONValue: """ Retrieve the value of a single secret
def get_secret( key : str, optional If set, return only this key render : bool, optional Whether to render templated secret or not, by default True Returns ------- types.JSONValue Secret value """ full_path = self._build_full_...
def get_secret( key : str, optional If set, return only this key Returns ------- types.JSONValue Secret value """ full_path = self._build_full_path(path) assert self.cache is not None try: mapping = self.cache[full_pat...
def delete_secret(self, path: str, key: Optional[str] = None) -> None: else: # Delete only one attribute try: secret = self.get_secret(path, render=False) except exceptions.VaultSecretNotFound: # secret does not exist return
def delete_secret(self, path: str, key: Optional[str] = None) -> None: else: # Delete only one attribute try: secret = self.get_secret(path) except exceptions.VaultSecretNotFound: # secret does not exist return
def delete_secret(self, path: str, key: Optional[str] = None) -> None: def delete_all_secrets_iter(self, *paths: str) -> Iterable[str]: for path in paths: path = path.rstrip("/") secrets_paths = self._browse_recursive_secrets(path=path, render=False) for secret_path in se...
def delete_secret(self, path: str, key: Optional[str] = None) -> None: def delete_all_secrets_iter(self, *paths: str) -> Iterable[str]: for path in paths: path = path.rstrip("/") secrets_paths = self._browse_recursive_secrets(path=path) for secret_path in secrets_paths: ...
def copy_secrets_iter( delete_source: Optional[bool] = False, ) -> Iterable[Tuple[str, str]]: source_secrets = self.get_secrets(path=source, render=False) for old_path, secret in source_secrets.items(): new_path = dest + old_path[len(source) :]
def copy_secrets_iter( delete_source: Optional[bool] = False, ) -> Iterable[Tuple[str, str]]: source_secrets = self.get_secrets(path=source) for old_path, secret in source_secrets.items(): new_path = dest + old_path[len(source) :]
def copy_secrets( return iterator return list(iterator) template_prefix = "!template!" def _render_template_value(self, secret: types.JSONValue) -> types.JSONValue: if isinstance(secret, dict): return {k: self._render_template_value(v) for k, v in secret.items()} ...
def copy_secrets( return iterator return list(iterator) def render_template( self, template: str, search_path: pathlib.Path = pathlib.Path("."), ) -> str: """
def render_template( def vault(path): try: return self.get_secret(path, render=render) except exceptions.VaultException as exc: raise exceptions.VaultRenderTemplateError( "Error while rendering template"
def render_template( def vault(path): try: return self.get_secret(path) except exceptions.VaultException as exc: raise exceptions.VaultRenderTemplateError( "Error while rendering template"
def set_secret( force = self.get_force(force) try: existing_value = self.get_secret(path=path, render=False) assert isinstance(existing_value, dict) except exceptions.VaultSecretNotFound: pass
def set_secret( force = self.get_force(force) try: existing_value = self.get_secret(path=path) assert isinstance(existing_value, dict) except exceptions.VaultSecretNotFound: pass
def set_secret( path = path.rstrip("/") for parent in list(pathlib.PurePath(path).parents)[:-1]: try: self.get_secret(str(parent), render=False) except exceptions.VaultSecretNotFound: pass except exceptions.VaultForbidden:
def set_secret( path = path.rstrip("/") for parent in list(pathlib.PurePath(path).parents)[:-1]: try: self.get_secret(str(parent)) except exceptions.VaultSecretNotFound: pass except exceptions.VaultForbidden:
def set_secret( def set_secrets( self, secrets: Dict[str, JSONDictRecursive], force: Optional[bool] = None, update: Optional[bool] = None, ) -> None:
def set_secret( def set_secrets( self, secrets: Dict[str, types.JSONDict], force: Optional[bool] = None, update: Optional[bool] = None, ) -> None:
import re from typing import Dict, Mapping, NoReturn, Optional, Sequence from vault_cli import client, exceptions logger = logging.getLogger(__name__)
import re from typing import Dict, Mapping, NoReturn, Optional, Sequence from vault_cli import client, exceptions, types logger = logging.getLogger(__name__)
def _normalize(name: str) -> str: return envvar_name def _make_env_value(value: client.JSONRecursive) -> str: if isinstance(value, str): return value return json.dumps(value)
def _normalize(name: str) -> str: return envvar_name def _make_env_value(value: types.JSONValue) -> str: if isinstance(value, str): return value return json.dumps(value)
def exec_command( def get_envvars_for_secrets( secrets: Dict[str, client.JSONDictRecursive], path: str, prefix: str, omit_single_key: bool = False,
def exec_command( def get_envvars_for_secrets( secrets: Dict[str, types.JSONDict], path: str, prefix: str, omit_single_key: bool = False,
class DEFAULTS: verify = True ca_bundle = None safe_write = False render = True @staticmethod def _as_dict():
class DEFAULTS: verify = True ca_bundle = None safe_write = False @staticmethod def _as_dict():
def path_to_nested(dict_obj: Dict) -> Dict: return dict_obj class RecursiveValue: def __init__(self, name: str): self.name = name def __str__(self) -> str: return f'<recursive value "{self.name}">' def __getitem__(self, key: str) -> str: return str(self) def extract_error_m...
def path_to_nested(dict_obj: Dict) -> Dict: return dict_obj def extract_error_messages(exc: BaseException) -> Iterable[str]: while True: exc_str = str(exc).strip()
def load_model_from_path(model_path, meta=False, **overrides): for name in pipeline: if name not in disable: config = meta.get("pipeline_args", {}).get(name, {}) factory = factories.get(name, name) component = nlp.create_pipe(factory, config=config) nlp.add_pi...
def load_model_from_path(model_path, meta=False, **overrides): for name in pipeline: if name not in disable: config = meta.get("pipeline_args", {}).get(name, {}) config.update(overrides) factory = factories.get(name, name) component = nlp.create_pipe(factory, ...
class URLValidator(RegexValidator): ul = '\u00a1-\uffff' # unicode letters range (must not be a raw string) # IP patterns ipv4_re = r'(?:25[0-5]|2[0-4]\d|[0-1]?\d?\d)(?:\.(?:25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}' ipv6_re = r'\[[0-9a-f:\.]+\]' # (simple regex, validated later) # Host patterns
class URLValidator(RegexValidator): ul = '\u00a1-\uffff' # unicode letters range (must not be a raw string) # IP patterns ipv4_re = r'(?:0|25[0-5]|2[0-4]\d|1\d?\d?|[1-9]\d?)(?:\.(?:0|25[0-5]|2[0-4]\d|1\d?\d?|[1-9]\d?)){3}' ipv6_re = r'\[[0-9a-f:\.]+\]' # (simple regex, validated later) # Host pa...
def validate_ipv4_address(value): ipaddress.IPv4Address(value) except ValueError: raise ValidationError(_('Enter a valid IPv4 address.'), code='invalid') def validate_ipv6_address(value):
def validate_ipv4_address(value): ipaddress.IPv4Address(value) except ValueError: raise ValidationError(_('Enter a valid IPv4 address.'), code='invalid') else: # Leading zeros are forbidden to avoid ambiguity with the octal # notation. This restriction is included in Python 3.9.5...
TEST_DATA = [ (validate_ipv4_address, '1.1.1.1\n', ValidationError), (validate_ipv4_address, '٧.2٥.3٣.243', ValidationError), # validate_ipv6_address uses django.utils.ipv6, which # is tested in much greater detail in its own testcase (validate_ipv6_address, 'fe80::1', None),
TEST_DATA = [ (validate_ipv4_address, '1.1.1.1\n', ValidationError), (validate_ipv4_address, '٧.2٥.3٣.243', ValidationError), # Leading zeros are forbidden to avoid ambiguity with the octal notation. (validate_ipv4_address, '000.000.000.000', ValidationError), (validate_ipv4_address, '016.016.016.0...
TEST_DATA = [ (validate_ipv46_address, '::zzz', ValidationError), (validate_ipv46_address, '12345::', ValidationError), (validate_comma_separated_integer_list, '1', None), (validate_comma_separated_integer_list, '12', None), (validate_comma_separated_integer_list, '1,2', None),
TEST_DATA = [ (validate_ipv46_address, '::zzz', ValidationError), (validate_ipv46_address, '12345::', ValidationError), # Leading zeros are forbidden to avoid ambiguity with the octal notation. (validate_ipv46_address, '000.000.000.000', ValidationError), (validate_ipv46_address, '016.016.016.016',...
class Sequential(Model): def __init__(self, layers=None, name=None): super(Sequential, self).__init__(name=name) # Add to the model any layers passed to the constructor. if layers:
class Sequential(Model): def __init__(self, layers=None, name=None): super(Sequential, self).__init__(name=name) self._build_input_shape = None # Add to the model any layers passed to the constructor. if layers:
class Sequential(Model): for layer in self._layers: x = layer(x) self.outputs = [x] if self._layers: self._layers[0].batch_input_shape = batch_shape if self.inputs: self._init_graph_network(self.inputs,
class Sequential(Model): for layer in self._layers: x = layer(x) self.outputs = [x] self._build_input_shape = input_shape if self.inputs: self._init_graph_network(self.inputs,
class Sequential(Model): return (proba > 0.5).astype('int32') def get_config(self): config = [] for layer in self.layers: config.append({ 'class_name': layer.__class__.__name__, 'config': layer.get_config() }) return copy.d...
class Sequential(Model): return (proba > 0.5).astype('int32') def get_config(self): layer_configs = [] for layer in self.layers: layer_configs.append({ 'class_name': layer.__class__.__name__, 'config': layer.get_config() }) ...
def test_sequential(in_tmpdir): nloss = model.evaluate(x_test, y_test, verbose=0) assert(loss == nloss) # test serialization config = model.get_config() Sequential.from_config(config) model.summary() json_str = model.to_json()
def test_sequential(in_tmpdir): nloss = model.evaluate(x_test, y_test, verbose=0) assert(loss == nloss) # Test serialization config = model.get_config() assert 'name' in config new_model = Sequential.from_config(config) assert new_model.weights # Model should be built. model.summary()...
def test_nested_sequential(in_tmpdir): nloss = model.evaluate(x_test, y_test, verbose=0) assert(loss == nloss) # test serialization config = model.get_config() Sequential.from_config(config)
def test_nested_sequential(in_tmpdir): nloss = model.evaluate(x_test, y_test, verbose=0) assert(loss == nloss) # Test serialization config = model.get_config() Sequential.from_config(config)
def test_sequential_deferred_build(): assert len(model.layers) == 2 assert len(model.weights) == 4 config = model.get_config() new_model = keras.models.Sequential.from_config(config) assert new_model.built is True assert len(new_model.layers) == 2 assert len(new_model.weights) == 4
def test_sequential_deferred_build(): assert len(model.layers) == 2 assert len(model.weights) == 4 # Test serialization config = model.get_config() assert 'name' in config new_model = Sequential.from_config(config) assert new_model.built is True assert len(new_model.layers) == 2 ass...
def localpkgs(directory): cache[name] = {'path': fn, 'size': st.st_size, 'device': st.st_dev} return cache def parseArgs(): usage = _(""" Reposync is used to synchronize a remote yum repository to a local
def localpkgs(directory): cache[name] = {'path': fn, 'size': st.st_size, 'device': st.st_dev} return cache def is_subpath(path, root): root = os.path.realpath(root) path = os.path.realpath(os.path.join(root, path)) # join() is used below to ensure root ends with a slash return path.star...
def parseArgs(): parser.add_option("", "--download-metadata", dest="downloadmd", default=False, action="store_true", help=_("download all the non-default metadata")) (opts, args) = parser.parse_args() return (opts, args)
def parseArgs(): parser.add_option("", "--download-metadata", dest="downloadmd", default=False, action="store_true", help=_("download all the non-default metadata")) parser.add_option("", "--allow-path-traversal", default=False, action="store_true", help=_("Allow packages stored ...
def main(): else: local_repo_path = opts.destdir + '/' + repo.id if opts.delete and os.path.exists(local_repo_path): current_pkgs = localpkgs(local_repo_path) download_set = {} for pkg in download_list: remote = pkg.returnSimple('relative...
def main(): else: local_repo_path = opts.destdir + '/' + repo.id # Ensure we don't traverse out of local_repo_path by dropping any # packages whose remote_path is absolute or contains up-level # references (unless explicitly allowed). # See RHBZ#1600221 for details. ...
def main(): remote_size = 0 if not opts.urls: for pkg in download_list: remote = pkg.returnSimple('relativepath') local = local_repo_path + '/' + remote sz = int(pkg.returnSimple('packagesize')) if os.path.exists(local) and os.p...
def main(): remote_size = 0 if not opts.urls: for pkg in download_list: local = os.path.join(local_repo_path, pkg.remote_path) sz = int(pkg.returnSimple('packagesize')) if os.path.exists(local) and os.path.getsize(local) == sz: ...
def main(): download_list.sort(key=lambda pkg: pkg.name) if opts.urls: for pkg in download_list: remote = pkg.returnSimple('relativepath') local = os.path.join(local_repo_path, remote) if not (os.path.exists(local) and my.verifyPkg(local, pkg, ...
def main(): download_list.sort(key=lambda pkg: pkg.name) if opts.urls: for pkg in download_list: local = os.path.join(local_repo_path, pkg.remote_path) if not (os.path.exists(local) and my.verifyPkg(local, pkg, False)): print urljoin(pkg.re...
def main(): # set localpaths for pkg in download_list: rpmfn = pkg.remote_path pkg.localpath = os.path.join(local_repo_path, rpmfn) pkg.repo.copy_local = True pkg.repo.cache = 0 localdir = os.path.dirname(pkg.localpath)
def main(): # set localpaths for pkg in download_list: pkg.localpath = os.path.join(local_repo_path, pkg.remote_path) pkg.repo.copy_local = True pkg.repo.cache = 0 localdir = os.path.dirname(pkg.localpath)
Make api awesomeness ''' from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import inspect import os # Import Salt libs import salt.log # pylint: disable=W0611 import salt.client import salt.config import salt.runner import salt.syspaths import salt.wheel import salt.utils.a...
Make api awesomeness ''' from __future__ import absolute_import, print_function, unicode_literals import copy # Import Python libs import inspect import logging import os # Import Salt libs import salt.log # pylint: disable=W0611 import salt.auth import salt.client import salt.config import salt.daemons.masterapi i...
class NetapiClient(object): def __init__(self, opts): self.opts = opts def _is_master_running(self): '''
class NetapiClient(object): def __init__(self, opts): self.opts = opts self.loadauth = salt.auth.LoadAuth(opts) self.key = salt.daemons.masterapi.access_keys(self.opts) minopts = copy.deepcopy(self.opts) minopts["enable_ssh_minions"] = True self.ckminions = salt.util...
class NetapiClient(object): self.opts['sock_dir'], ipc_file)) def run(self, low): ''' Execute the specified function in the specified client by passing the
class NetapiClient(object): self.opts['sock_dir'], ipc_file)) def _prep_auth_info(self, clear_load): sensitive_load_keys = [] key = None if "token" in clear_load: auth_type = "token" err_name = "TokenAuthenticationError" sensitive_...
class NetapiClient(object): raise salt.exceptions.EauthAuthenticationError( 'Raw shell option not allowed.') l_fun = getattr(self, low['client']) f_call = salt.utils.args.format_call(l_fun, low) return l_fun(*f_call.get('args', ()), **f_call.get('kwargs', {}))
class NetapiClient(object): raise salt.exceptions.EauthAuthenticationError( 'Raw shell option not allowed.') if low['client'] == 'ssh': self._authorize_ssh(low) l_fun = getattr(self, low['client']) f_call = salt.utils.args.format_call(l_fun, low) ...
# encoding: utf-8 # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import os import time # Import Salt Testing libs from tests.support.paths import TMP_CONF_DIR, TMP from tests.support.runtests import RUNTIME_VARS from tests.support.unit import TestCase, ski...
# encoding: utf-8 # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import copy import logging import os import time import salt.config import salt.netapi import salt.utils.files import salt.utils.platform import salt.utils.pycrypto # Import Salt Testing libs from tests.sup...
class NetapiSSHClientTest(SSHCase): ''' opts = salt.config.client_config(os.path.join(TMP_CONF_DIR, 'master')) self.netapi = salt.netapi.NetapiClient(opts) self.priv_file = os.path.join(RUNTIME_VARS.TMP_CONF_DIR, 'key_test') self.rosters = os.path.join(RUNTIME_VARS.TMP_CONF_DIR)
class NetapiSSHClientTest(SSHCase): ''' opts = salt.config.client_config(os.path.join(TMP_CONF_DIR, 'master')) self.netapi = salt.netapi.NetapiClient(opts) opts = salt.config.client_config(os.path.join(TMP_CONF_DIR, "master")) naopts = copy.deepcopy(opts) naopts["ignore_h...
class NetapiSSHClientTest(SSHCase): "roster": "cache", "client": "ssh", "tgt": "www.zerodayinitiative.com", "fun": "xx", "eauth": "xx", "ssh_priv": "aaa|id>{} #".format(path), } ret = self.netapi.run(low) self.assertFalse(os...
class NetapiSSHClientTest(SSHCase): "roster": "cache", "client": "ssh", "tgt": "www.zerodayinitiative.com", "ssh_priv": "aaa|id>{} #".format(path), "fun": "test.ping", "eauth": "auto", "username": "saltdev_auto", "password":...
class NetapiSSHClientTest(SSHCase): "roster": "cache", "client": "ssh", "tgt": "root|id>{} #@127.0.0.1".format(path), "fun": "xx", "eauth": "xx", "roster_file": "/tmp/salt-tests-tmpdir/config/roaster", "rosters": "/", } ...
class NetapiSSHClientTest(SSHCase): "roster": "cache", "client": "ssh", "tgt": "root|id>{} #@127.0.0.1".format(path), "roster_file": "/tmp/salt-tests-tmpdir/config/roaster", "rosters": "/", "fun": "test.ping", "eauth": "auto", ...
class NetapiSSHClientTest(SSHCase): "client": "ssh", "tgt": "127.0.0.1", "renderer": "cheetah", "fun": "xx", "eauth": "xx", "roster_file": "/tmp/salt-tests-tmpdir/config/roaster", "rosters": "/", "ssh_options": ["|id>{} #".f...
class NetapiSSHClientTest(SSHCase): "client": "ssh", "tgt": "127.0.0.1", "renderer": "cheetah", "fun": "test.ping", "eauth": "auto", "username": "saltdev_auto", "password": "saltdev", "roster_file": "/tmp/salt-tests-tmpdir/c...
class NetapiSSHClientTest(SSHCase): "client": "ssh", "tgt": "127.0.0.1", "renderer": "cheetah", "fun": "xx", "eauth": "xx", "roster_file": "/tmp/salt-tests-tmpdir/config/roaster", "rosters": "/", "ssh_port": "hhhhh|id>{} #"....
class NetapiSSHClientTest(SSHCase): "client": "ssh", "tgt": "127.0.0.1", "renderer": "cheetah", "fun": "test.ping", "eauth": "auto", "username": "saltdev_auto", "password": "saltdev", "roster_file": "/tmp/salt-tests-tmpdir/c...