language
stringclasses
1 value
repo
stringclasses
346 values
path
stringlengths
6
201
class_span
dict
source
stringlengths
21
2.38M
target
stringlengths
1
96
python
django__django
tests/queries/models.py
{ "start": 13598, "end": 13742 }
class ____(models.Model): programs = models.ManyToManyField(Program) identifier = models.OneToOneField(Identifier, models.CASCADE)
Channel
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 1216702, "end": 1216936 }
class ____(VegaLiteSchema): """ Spec schema wrapper. Any specification in Vega-Lite. """ _schema = {"$ref": "#/definitions/Spec"} def __init__(self, *args, **kwds): super().__init__(*args, **kwds)
Spec
python
pandas-dev__pandas
pandas/tests/arrays/interval/test_interval.py
{ "start": 893, "end": 1682 }
class ____: @pytest.mark.parametrize( "left, right", [ (0, 1), (Timedelta("0 days"), Timedelta("1 day")), (Timestamp("2018-01-01"), Timestamp("2018-01-02")), ( Timestamp("2018-01-01", tz="US/Eastern"), Timestamp("2018-01-02", tz="US/Eastern"), ), ], ) @pytest.mark.parametrize("constructor", [IntervalArray, IntervalIndex]) def test_is_empty(self, constructor, left, right, closed): # GH27219 tuples = [(left, left), (left, right), np.nan] expected = np.array([closed != "both", False, False]) result = constructor.from_tuples(tuples, closed=closed).is_empty tm.assert_numpy_array_equal(result, expected)
TestAttributes
python
apache__airflow
airflow-ctl/src/airflowctl/api/datamodels/generated.py
{ "start": 15463, "end": 15696 }
class ____(BaseModel): """ Extra Links Response. """ extra_links: Annotated[dict[str, str | None], Field(title="Extra Links")] total_entries: Annotated[int, Field(title="Total Entries")]
ExtraLinkCollectionResponse
python
pytorch__pytorch
torch/testing/_internal/autograd_function_db.py
{ "start": 12903, "end": 13346 }
class ____(torch.autograd.Function): generate_vmap_rule = True scale = 3.14 @staticmethod def forward(x): return x.clone() @staticmethod def setup_context(ctx, inputs, outputs): pass @staticmethod def backward(ctx, grad_output): return grad_output * ScaleGradGenVmap.scale @staticmethod def jvp(ctx, x_tangent): return x_tangent * ScaleGradGenVmap.scale
ScaleGradGenVmap
python
pallets__jinja
src/jinja2/nodes.py
{ "start": 11232, "end": 11592 }
class ____(Stmt): """A macro definition. `name` is the name of the macro, `args` a list of arguments and `defaults` a list of defaults if there are any. `body` is a list of nodes for the macro body. """ fields = ("name", "args", "defaults", "body") name: str args: list["Name"] defaults: list["Expr"] body: list[Node]
Macro
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 1381845, "end": 1385515 }
class ____(sgqlc.types.Type, Node): """A threaded list of comments for a given pull request.""" __schema__ = github_schema __field_names__ = ( "comments", "diff_side", "is_collapsed", "is_outdated", "is_resolved", "line", "pull_request", "repository", "resolved_by", "start_diff_side", "start_line", "viewer_can_reply", "viewer_can_resolve", "viewer_can_unresolve", ) comments = sgqlc.types.Field( sgqlc.types.non_null(PullRequestReviewCommentConnection), graphql_name="comments", args=sgqlc.types.ArgDict( ( ("after", sgqlc.types.Arg(String, graphql_name="after", default=None)), ("before", sgqlc.types.Arg(String, graphql_name="before", default=None)), ("first", sgqlc.types.Arg(Int, graphql_name="first", default=None)), ("last", sgqlc.types.Arg(Int, graphql_name="last", default=None)), ("skip", sgqlc.types.Arg(Int, graphql_name="skip", default=None)), ) ), ) """A list of pull request comments associated with the thread. Arguments: * `after` (`String`): Returns the elements in the list that come after the specified cursor. * `before` (`String`): Returns the elements in the list that come before the specified cursor. * `first` (`Int`): Returns the first _n_ elements from the list. * `last` (`Int`): Returns the last _n_ elements from the list. * `skip` (`Int`): Skips the first _n_ elements in the list. """ diff_side = sgqlc.types.Field(sgqlc.types.non_null(DiffSide), graphql_name="diffSide") """The side of the diff on which this thread was placed.""" is_collapsed = sgqlc.types.Field(sgqlc.types.non_null(Boolean), graphql_name="isCollapsed") """Whether or not the thread has been collapsed (resolved)""" is_outdated = sgqlc.types.Field(sgqlc.types.non_null(Boolean), graphql_name="isOutdated") """Indicates whether this thread was outdated by newer changes.""" is_resolved = sgqlc.types.Field(sgqlc.types.non_null(Boolean), graphql_name="isResolved") """Whether this thread has been resolved""" line = sgqlc.types.Field(Int, graphql_name="line") """The line in the file to which this thread refers""" pull_request = sgqlc.types.Field(sgqlc.types.non_null(PullRequest), graphql_name="pullRequest") """Identifies the pull request associated with this thread.""" repository = sgqlc.types.Field(sgqlc.types.non_null("Repository"), graphql_name="repository") """Identifies the repository associated with this thread.""" resolved_by = sgqlc.types.Field("User", graphql_name="resolvedBy") """The user who resolved this thread""" start_diff_side = sgqlc.types.Field(DiffSide, graphql_name="startDiffSide") """The side of the diff that the first line of the thread starts on (multi-line only) """ start_line = sgqlc.types.Field(Int, graphql_name="startLine") """The line of the first file diff in the thread.""" viewer_can_reply = sgqlc.types.Field(sgqlc.types.non_null(Boolean), graphql_name="viewerCanReply") """Indicates whether the current viewer can reply to this thread.""" viewer_can_resolve = sgqlc.types.Field(sgqlc.types.non_null(Boolean), graphql_name="viewerCanResolve") """Whether or not the viewer can resolve this thread""" viewer_can_unresolve = sgqlc.types.Field(sgqlc.types.non_null(Boolean), graphql_name="viewerCanUnresolve") """Whether or not the viewer can unresolve this thread"""
PullRequestThread
python
apache__airflow
providers/google/tests/unit/google/cloud/links/test_dataplex.py
{ "start": 7474, "end": 8647 }
class ____: @pytest.mark.db_test def test_get_link(self, create_task_instance_of_operator, session, mock_supervisor_comms): expected_url = EXPECTED_DATAPLEX_CATALOG_ENTRY_GROUP_LINK link = DataplexCatalogEntryGroupLink() ti = create_task_instance_of_operator( DataplexCatalogGetEntryGroupOperator, dag_id="test_link_dag", task_id="test_link_task", location=TEST_LOCATION, entry_group_id=TEST_ENTRY_GROUP_ID, project_id=TEST_PROJECT_ID, ) session.add(ti) session.commit() link.persist(context={"ti": ti, "task": ti.task}) if AIRFLOW_V_3_0_PLUS and mock_supervisor_comms: mock_supervisor_comms.send.return_value = XComResult( key="key", value={ "entry_group_id": ti.task.entry_group_id, "location": ti.task.location, "project_id": ti.task.project_id, }, ) actual_url = link.get_link(operator=ti.task, ti_key=ti.key) assert actual_url == expected_url
TestDataplexCatalogEntryGroupLink
python
huggingface__transformers
src/transformers/models/data2vec/modeling_data2vec_vision.py
{ "start": 3377, "end": 7515 }
class ____(nn.Module): """ Construct the CLS token, position and patch embeddings. Optionally, also the mask token. """ def __init__(self, config: Data2VecVisionConfig) -> None: super().__init__() self.cls_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size)) if config.use_mask_token: self.mask_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size)) else: self.mask_token = None self.patch_embeddings = Data2VecVisionPatchEmbeddings(config) self.patch_size = config.patch_size self.image_size = ( config.image_size if isinstance(config.image_size, collections.abc.Iterable) else (config.image_size, config.image_size) ) num_patches = self.patch_embeddings.num_patches if config.use_absolute_position_embeddings: self.position_embeddings = nn.Parameter(torch.zeros(1, num_patches + 1, config.hidden_size)) else: self.position_embeddings = None self.dropout = nn.Dropout(config.hidden_dropout_prob) # Copied from transformers.models.vit.modeling_vit.ViTEmbeddings.interpolate_pos_encoding def interpolate_pos_encoding(self, embeddings: torch.Tensor, height: int, width: int) -> torch.Tensor: """ This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher resolution images. This method is also adapted to support torch.jit tracing. Adapted from: - https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174-L194, and - https://github.com/facebookresearch/dinov2/blob/e1277af2ba9496fbadf7aec6eba56e8d882d1e35/dinov2/models/vision_transformer.py#L179-L211 """ num_patches = embeddings.shape[1] - 1 num_positions = self.position_embeddings.shape[1] - 1 # always interpolate when tracing to ensure the exported model works for dynamic input shapes if not torch.jit.is_tracing() and num_patches == num_positions and height == width: return self.position_embeddings class_pos_embed = self.position_embeddings[:, :1] patch_pos_embed = self.position_embeddings[:, 1:] dim = embeddings.shape[-1] new_height = height // self.patch_size new_width = width // self.patch_size sqrt_num_positions = torch_int(num_positions**0.5) patch_pos_embed = patch_pos_embed.reshape(1, sqrt_num_positions, sqrt_num_positions, dim) patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2) patch_pos_embed = nn.functional.interpolate( patch_pos_embed, size=(new_height, new_width), mode="bicubic", align_corners=False, ) patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim) return torch.cat((class_pos_embed, patch_pos_embed), dim=1) def forward( self, pixel_values: torch.Tensor, bool_masked_pos: Optional[torch.BoolTensor] = None, ) -> torch.Tensor: _, _, height, width = pixel_values.shape embeddings, (patch_height, patch_width) = self.patch_embeddings(pixel_values) batch_size, seq_len, _ = embeddings.size() if bool_masked_pos is not None: mask_tokens = self.mask_token.expand(batch_size, seq_len, -1) # replace the masked visual tokens by mask_tokens w = bool_masked_pos.unsqueeze(-1).type_as(mask_tokens) embeddings = embeddings * (1 - w) + mask_tokens * w cls_tokens = self.cls_token.expand(batch_size, -1, -1) embeddings = torch.cat((cls_tokens, embeddings), dim=1) if self.position_embeddings is not None: embeddings = embeddings + self.interpolate_pos_encoding(embeddings, height, width) embeddings = self.dropout(embeddings) return embeddings, (patch_height, patch_width) # Copied from transformers.models.beit.modeling_beit.BeitPatchEmbeddings with Beit->Data2VecVision
Data2VecVisionEmbeddings
python
scrapy__scrapy
tests/test_spidermiddleware_process_start.py
{ "start": 784, "end": 1011 }
class ____: async def process_start(self, start): await maybe_deferred_to_future(twisted_sleep(SLEEP_SECONDS)) async for item_or_request in start: yield item_or_request
TwistedSleepSpiderMiddleware
python
pennersr__django-allauth
tests/apps/socialaccount/providers/twitter_oauth2/tests.py
{ "start": 264, "end": 990 }
class ____(OAuth2TestsMixin, TestCase): provider_id = TwitterOAuth2Provider.id def get_mocked_response(self): return MockedResponse( HTTPStatus.OK, """{ "data": { "created_at": "2020-09-02T13:39:14.000Z", "id": "1301152652357595137", "verified": false, "username": "realllkk520", "name": "realllkk520", "profile_image_url": "https://pbs.twimg.com/profile_images/1537259565632593920/OoRGPbUg_normal.jpg" } } """, ) # noqa def get_expected_to_str(self): return "realllkk520"
TwitterOAuth2Tests
python
xlwings__xlwings
xlwings/constants.py
{ "start": 71133, "end": 71303 }
class ____: xlPivotTableReport = 1 # from enum XlImportDataAs xlQueryTable = 0 # from enum XlImportDataAs xlTable = 2 # from enum XlImportDataAs
ImportDataAs
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/testing/suite/test_results.py
{ "start": 676, "end": 3601 }
class ____(fixtures.TablesTest): __backend__ = True @classmethod def define_tables(cls, metadata): Table( "plain_pk", metadata, Column("id", Integer, primary_key=True), Column("data", String(50)), ) Table( "has_dates", metadata, Column("id", Integer, primary_key=True), Column("today", DateTime), ) @classmethod def insert_data(cls, connection): connection.execute( cls.tables.plain_pk.insert(), [ {"id": 1, "data": "d1"}, {"id": 2, "data": "d2"}, {"id": 3, "data": "d3"}, ], ) connection.execute( cls.tables.has_dates.insert(), [{"id": 1, "today": datetime.datetime(2006, 5, 12, 12, 0, 0)}], ) def test_via_attr(self, connection): row = connection.execute( self.tables.plain_pk.select().order_by(self.tables.plain_pk.c.id) ).first() eq_(row.id, 1) eq_(row.data, "d1") def test_via_string(self, connection): row = connection.execute( self.tables.plain_pk.select().order_by(self.tables.plain_pk.c.id) ).first() eq_(row._mapping["id"], 1) eq_(row._mapping["data"], "d1") def test_via_int(self, connection): row = connection.execute( self.tables.plain_pk.select().order_by(self.tables.plain_pk.c.id) ).first() eq_(row[0], 1) eq_(row[1], "d1") def test_via_col_object(self, connection): row = connection.execute( self.tables.plain_pk.select().order_by(self.tables.plain_pk.c.id) ).first() eq_(row._mapping[self.tables.plain_pk.c.id], 1) eq_(row._mapping[self.tables.plain_pk.c.data], "d1") @requirements.duplicate_names_in_cursor_description def test_row_with_dupe_names(self, connection): result = connection.execute( select( self.tables.plain_pk.c.data, self.tables.plain_pk.c.data.label("data"), ).order_by(self.tables.plain_pk.c.id) ) row = result.first() eq_(result.keys(), ["data", "data"]) eq_(row, ("d1", "d1")) def test_row_w_scalar_select(self, connection): """test that a scalar select as a column is returned as such and that type conversion works OK. (this is half a SQLAlchemy Core test and half to catch database backends that may have unusual behavior with scalar selects.) """ datetable = self.tables.has_dates s = select(datetable.alias("x").c.today).scalar_subquery() s2 = select(datetable.c.id, s.label("somelabel")) row = connection.execute(s2).first() eq_(row.somelabel, datetime.datetime(2006, 5, 12, 12, 0, 0))
RowFetchTest
python
mlflow__mlflow
examples/pytorch/MNIST/mnist_autolog_example.py
{ "start": 2670, "end": 7375 }
class ____(L.LightningModule): def __init__(self, learning_rate=0.01): """ Initializes the network """ super().__init__() # mnist images are (1, 28, 28) (channels, width, height) self.optimizer = None self.scheduler = None self.layer_1 = torch.nn.Linear(28 * 28, 128) self.layer_2 = torch.nn.Linear(128, 256) self.layer_3 = torch.nn.Linear(256, 10) self.learning_rate = learning_rate self.val_outputs = [] self.test_outputs = [] def forward(self, x): """ Args: x: Input data Returns: output - mnist digit label for the input image """ batch_size = x.size()[0] # (b, 1, 28, 28) -> (b, 1*28*28) x = x.view(batch_size, -1) # layer 1 (b, 1*28*28) -> (b, 128) x = self.layer_1(x) x = torch.relu(x) # layer 2 (b, 128) -> (b, 256) x = self.layer_2(x) x = torch.relu(x) # layer 3 (b, 256) -> (b, 10) x = self.layer_3(x) # probability distribution over labels x = torch.log_softmax(x, dim=1) return x def cross_entropy_loss(self, logits, labels): """ Initializes the loss function Returns: output: Initialized cross entropy loss function. """ return F.nll_loss(logits, labels) def training_step(self, train_batch, batch_idx): """ Training the data as batches and returns training loss on each batch Args: train_batch: Batch data batch_idx: Batch indices Returns: output - Training loss """ x, y = train_batch logits = self.forward(x) loss = self.cross_entropy_loss(logits, y) return {"loss": loss} def validation_step(self, val_batch, batch_idx): """ Performs validation of data in batches Args: val_batch: Batch data batch_idx: Batch indices Returns: output: valid step loss """ x, y = val_batch logits = self.forward(x) loss = self.cross_entropy_loss(logits, y) self.val_outputs.append(loss) return {"val_step_loss": loss} def on_validation_epoch_end(self): """ Computes average validation loss """ avg_loss = torch.stack(self.val_outputs).mean() self.log("val_loss", avg_loss, sync_dist=True) self.val_outputs.clear() def test_step(self, test_batch, batch_idx): """ Performs test and computes the accuracy of the model Args: test_batch: Batch data batch_idx: Batch indices Returns: output: Testing accuracy """ x, y = test_batch output = self.forward(x) _, y_hat = torch.max(output, dim=1) test_acc = (y_hat == y).float().mean() self.test_outputs.append(test_acc) return {"test_acc": test_acc} def on_test_epoch_end(self): """ Computes average test accuracy score """ avg_test_acc = torch.stack(self.test_outputs).mean() self.log("avg_test_acc", avg_test_acc, sync_dist=True) self.test_outputs.clear() def configure_optimizers(self): """ Initializes the optimizer and learning rate scheduler Returns: output: Initialized optimizer and scheduler """ self.optimizer = torch.optim.Adam(self.parameters(), lr=self.learning_rate) self.scheduler = { "scheduler": torch.optim.lr_scheduler.ReduceLROnPlateau( self.optimizer, mode="min", factor=0.2, patience=2, min_lr=1e-6, ), "monitor": "val_loss", } return [self.optimizer], [self.scheduler] def cli_main(): early_stopping = EarlyStopping( monitor="val_loss", ) checkpoint_callback = ModelCheckpoint( dirpath=os.getcwd(), save_top_k=1, verbose=True, monitor="val_loss", mode="min" ) lr_logger = LearningRateMonitor() cli = LightningCLI( LightningMNISTClassifier, MNISTDataModule, run=False, save_config_callback=None, trainer_defaults={"callbacks": [early_stopping, checkpoint_callback, lr_logger]}, ) if cli.trainer.global_rank == 0: mlflow.pytorch.autolog() cli.trainer.fit(cli.model, datamodule=cli.datamodule) cli.trainer.test(ckpt_path="best", datamodule=cli.datamodule) if __name__ == "__main__": cli_main()
LightningMNISTClassifier
python
numpy__numpy
numpy/distutils/armccompiler.py
{ "start": 81, "end": 962 }
class ____(UnixCCompiler): """ Arm compiler. """ compiler_type = 'arm' cc_exe = 'armclang' cxx_exe = 'armclang++' def __init__(self, verbose=0, dry_run=0, force=0): UnixCCompiler.__init__(self, verbose, dry_run, force) cc_compiler = self.cc_exe cxx_compiler = self.cxx_exe self.set_executables(compiler=cc_compiler + ' -O3 -fPIC', compiler_so=cc_compiler + ' -O3 -fPIC', compiler_cxx=cxx_compiler + ' -O3 -fPIC', linker_exe=cc_compiler + ' -lamath', linker_so=cc_compiler + ' -lamath -shared')
ArmCCompiler
python
dagster-io__dagster
python_modules/libraries/dagster-wandb/dagster_wandb/utils/errors.py
{ "start": 0, "end": 2744 }
class ____(Exception): """Represents an execution error of the W&B Artifacts IO Manager.""" def __init__(self, message="A W&B Artifacts IO Manager error occurred."): self.message = message super().__init__(self.message) SUPPORTED_READ_CONFIG_KEYS = [ "alias", "get_path", "get", "name", "partitions", "version", ] SUPPORTED_WRITE_CONFIG_KEYS = [ "add_dirs", "add_files", "add_references", "aliases", "description", "name", "partitions", "serialization_module", "type", ] SUPPORTED_PARTITION_CONFIG_KEYS = ["get", "get_path", "version", "alias"] def raise_on_empty_configuration(partition_key, dictionary): if dictionary is not None and len(dictionary) == 0: raise WandbArtifactsIOManagerError( f"The configuration is empty for the partition identified by the key '{partition_key}'." " This happened within the 'wandb_artifact_configuration' metadata dictionary." ) def raise_on_unknown_keys(supported_config_keys, dictionary, is_read_config): if dictionary is None: return unsupported_keys = [key for key in dictionary.keys() if key not in supported_config_keys] if len(unsupported_keys) > 0: if is_read_config: raise WandbArtifactsIOManagerError( f"The configuration keys '{unsupported_keys}' you are trying to use are not" " supported within the 'wandb_artifact_configuration' metadata dictionary when" " reading an Artifact." ) else: raise WandbArtifactsIOManagerError( f"The configuration keys '{unsupported_keys}' you are trying to use are not" " supported within the 'wandb_artifact_configuration' metadata dictionary when" " writing an Artifact." ) def raise_on_unknown_write_configuration_keys(dictionary): raise_on_unknown_keys(SUPPORTED_WRITE_CONFIG_KEYS, dictionary, False) def raise_on_unknown_read_configuration_keys(dictionary): raise_on_unknown_keys(SUPPORTED_READ_CONFIG_KEYS, dictionary, True) def raise_on_unknown_partition_keys(partition_key, dictionary): if dictionary is None: return unsupported_keys = [ key for key in dictionary.keys() if key not in SUPPORTED_PARTITION_CONFIG_KEYS ] if len(unsupported_keys) > 0: raise WandbArtifactsIOManagerError( f"The configuration keys '{unsupported_keys}' you are trying to use are not supported" f" for the partition identified by the key '{partition_key}'. This happened within the" " 'wandb_artifact_configuration' metadata dictionary." )
WandbArtifactsIOManagerError
python
huggingface__transformers
src/transformers/models/auto/tokenization_auto.py
{ "start": 48634, "end": 63261 }
class ____: r""" This is a generic tokenizer class that will be instantiated as one of the tokenizer classes of the library when created with the [`AutoTokenizer.from_pretrained`] class method. This class cannot be instantiated directly using `__init__()` (throws an error). """ def __init__(self): raise OSError( "AutoTokenizer is designed to be instantiated " "using the `AutoTokenizer.from_pretrained(pretrained_model_name_or_path)` method." ) @classmethod @replace_list_option_in_docstrings(TOKENIZER_MAPPING_NAMES) def from_pretrained( cls, pretrained_model_name_or_path, *inputs, **kwargs ) -> Union[TokenizersBackend, SentencePieceBackend]: r""" Instantiate one of the tokenizer classes of the library from a pretrained model vocabulary. The tokenizer class to instantiate is selected based on the `model_type` property of the config object (either passed as an argument or loaded from `pretrained_model_name_or_path` if possible), or when it's missing, by falling back to using pattern matching on `pretrained_model_name_or_path`: List options Params: pretrained_model_name_or_path (`str` or `os.PathLike`): Can be either: - A string, the *model id* of a predefined tokenizer hosted inside a model repo on huggingface.co. - A path to a *directory* containing vocabulary files required by the tokenizer, for instance saved using the [`~PreTrainedTokenizer.save_pretrained`] method, e.g., `./my_model_directory/`. - A path or url to a single saved vocabulary file if and only if the tokenizer only requires a single vocabulary file (like Bert or XLNet), e.g.: `./my_model_directory/vocab.txt`. (Not applicable to all derived classes) inputs (additional positional arguments, *optional*): Will be passed along to the Tokenizer `__init__()` method. config ([`PreTrainedConfig`], *optional*) The configuration object used to determine the tokenizer class to instantiate. cache_dir (`str` or `os.PathLike`, *optional*): Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. force_download (`bool`, *optional*, defaults to `False`): Whether or not to force the (re-)download the model weights and configuration files and override the cached versions if they exist. proxies (`dict[str, str]`, *optional*): A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request. revision (`str`, *optional*, defaults to `"main"`): The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any identifier allowed by git. subfolder (`str`, *optional*): In case the relevant files are located inside a subfolder of the model repo on huggingface.co (e.g. for facebook/rag-token-base), specify it here. tokenizer_type (`str`, *optional*): Tokenizer type to be loaded. backend (`str`, *optional*, defaults to `"tokenizers"`): Backend to use for tokenization. Valid options are: - `"tokenizers"`: Use the HuggingFace tokenizers library backend (default) - `"sentencepiece"`: Use the SentencePiece backend trust_remote_code (`bool`, *optional*, defaults to `False`): Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be set to `True` for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. kwargs (additional keyword arguments, *optional*): Will be passed to the Tokenizer `__init__()` method. Can be used to set special tokens like `bos_token`, `eos_token`, `unk_token`, `sep_token`, `pad_token`, `cls_token`, `mask_token`, `additional_special_tokens`. See parameters in the `__init__()` for more details. Examples: ```python >>> from transformers import AutoTokenizer >>> # Download vocabulary from huggingface.co and cache. >>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased") >>> # Download vocabulary from huggingface.co (user-uploaded) and cache. >>> tokenizer = AutoTokenizer.from_pretrained("dbmdz/bert-base-german-cased") >>> # If vocabulary files are in a directory (e.g. tokenizer was saved using *save_pretrained('./test/saved_model/')*) >>> # tokenizer = AutoTokenizer.from_pretrained("./test/bert_saved_model/") >>> # Download vocabulary from huggingface.co and define model-specific arguments >>> tokenizer = AutoTokenizer.from_pretrained("FacebookAI/roberta-base", add_prefix_space=True) >>> # Explicitly use the tokenizers backend >>> tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/llama-tokenizer", backend="tokenizers") >>> # Explicitly use the sentencepiece backend >>> tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/llama-tokenizer", backend="sentencepiece") ```""" use_auth_token = kwargs.pop("use_auth_token", None) if use_auth_token is not None: logger.warning( "The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.", FutureWarning, ) if kwargs.get("token") is not None: raise ValueError( "`token` and `use_auth_token` are both specified. Please set only the argument `token`." ) kwargs["token"] = use_auth_token config = kwargs.pop("config", None) kwargs["_from_auto"] = True # V5: Always use fast tokenizers, ignore use_fast parameter _ = kwargs.pop("use_fast", None) tokenizer_type = kwargs.pop("tokenizer_type", None) trust_remote_code = kwargs.pop("trust_remote_code", None) gguf_file = kwargs.get("gguf_file") # First, let's see whether the tokenizer_type is passed so that we can leverage it if tokenizer_type is not None: tokenizer_class_name = TOKENIZER_MAPPING_NAMES.get(tokenizer_type, None) if tokenizer_class_name is None: raise ValueError( f"Passed `tokenizer_type` {tokenizer_type} does not exist. `tokenizer_type` should be one of " f"{', '.join(c for c in TOKENIZER_MAPPING_NAMES)}." ) tokenizer_class = tokenizer_class_from_name(tokenizer_class_name) if tokenizer_class is None: raise ValueError(f"Tokenizer class {tokenizer_class_name} is not currently imported.") return tokenizer_class.from_pretrained(pretrained_model_name_or_path, *inputs, **kwargs) # Next, let's try to use the tokenizer_config file to get the tokenizer class. tokenizer_config = get_tokenizer_config(pretrained_model_name_or_path, **kwargs) if "_commit_hash" in tokenizer_config: kwargs["_commit_hash"] = tokenizer_config["_commit_hash"] config_tokenizer_class = tokenizer_config.get("tokenizer_class") tokenizer_auto_map = None if "auto_map" in tokenizer_config: if isinstance(tokenizer_config["auto_map"], (tuple, list)): # Legacy format for dynamic tokenizers tokenizer_auto_map = tokenizer_config["auto_map"] else: tokenizer_auto_map = tokenizer_config["auto_map"].get("AutoTokenizer", None) # If that did not work, let's try to use the config. if config_tokenizer_class is None: if not isinstance(config, PreTrainedConfig): if gguf_file: gguf_path = cached_file(pretrained_model_name_or_path, gguf_file, **kwargs) config_dict = load_gguf_checkpoint(gguf_path, return_tensors=False)["config"] config = AutoConfig.for_model(**config_dict) else: config = AutoConfig.from_pretrained( pretrained_model_name_or_path, trust_remote_code=trust_remote_code, **kwargs ) config_tokenizer_class = config.tokenizer_class if hasattr(config, "auto_map") and "AutoTokenizer" in config.auto_map: tokenizer_auto_map = config.auto_map["AutoTokenizer"] if ( config_tokenizer_class is not None and config_tokenizer_class != "PreTrainedTokenizerFast" and "Fast" in config_tokenizer_class ): config_tokenizer_class = config_tokenizer_class[:-4] has_remote_code = tokenizer_auto_map is not None has_local_code = type(config) in TOKENIZER_MAPPING or ( config_tokenizer_class is not None and ( tokenizer_class_from_name(config_tokenizer_class) is not None or tokenizer_class_from_name(config_tokenizer_class + "Fast") is not None ) ) if has_remote_code: # V5: Always prefer fast tokenizer (index 1), fallback to slow (index 0) if tokenizer_auto_map[1] is not None: class_ref = tokenizer_auto_map[1] else: class_ref = tokenizer_auto_map[0] if "--" in class_ref: upstream_repo = class_ref.split("--")[0] else: upstream_repo = None trust_remote_code = resolve_trust_remote_code( trust_remote_code, pretrained_model_name_or_path, has_local_code, has_remote_code, upstream_repo ) if has_remote_code and trust_remote_code: tokenizer_class = get_class_from_dynamic_module(class_ref, pretrained_model_name_or_path, **kwargs) _ = kwargs.pop("code_revision", None) tokenizer_class.register_for_auto_class() return tokenizer_class.from_pretrained( pretrained_model_name_or_path, *inputs, trust_remote_code=trust_remote_code, **kwargs ) elif config_tokenizer_class is not None: fast_tokenizer_class = None if fast_tokenizer_class is None: tokenizer_class_candidate = config_tokenizer_class tokenizer_class = tokenizer_class_from_name(tokenizer_class_candidate) if tokenizer_class is None and not tokenizer_class_candidate.endswith("Fast"): tokenizer_class = tokenizer_class_from_name(tokenizer_class_candidate + "Fast") else: tokenizer_class = fast_tokenizer_class return _try_load_tokenizer_with_fallbacks(tokenizer_class, pretrained_model_name_or_path, inputs, kwargs) # Otherwise we have to be creative. # if model is an encoder decoder, the encoder tokenizer class is used by default if isinstance(config, EncoderDecoderConfig): if type(config.decoder) is not type(config.encoder): logger.warning( f"The encoder model config class: {config.encoder.__class__} is different from the decoder model " f"config class: {config.decoder.__class__}. It is not recommended to use the " "`AutoTokenizer.from_pretrained()` method in this case. Please use the encoder and decoder " "specific tokenizer classes." ) config = config.encoder model_type = config_class_to_model_type(type(config).__name__) if model_type is not None: tokenizer_class = TOKENIZER_MAPPING[type(config)] if tokenizer_class is not None: return _try_load_tokenizer_with_fallbacks( tokenizer_class, pretrained_model_name_or_path, inputs, kwargs ) else: raise ValueError( "This tokenizer cannot be instantiated. Please make sure you have `sentencepiece` installed " "in order to use this tokenizer." ) raise ValueError( f"Unrecognized configuration class {config.__class__} to build an AutoTokenizer.\n" f"Model type should be one of {', '.join(c.__name__ for c in TOKENIZER_MAPPING)}." ) @staticmethod def register( config_class, tokenizer_class=None, slow_tokenizer_class=None, fast_tokenizer_class=None, exist_ok=False ): """ Register a new tokenizer in this mapping. Args: config_class ([`PreTrainedConfig`]): The configuration corresponding to the model to register. tokenizer_class: The tokenizer class to register (V5 - preferred parameter). slow_tokenizer_class: (Deprecated) The slow tokenizer to register. fast_tokenizer_class: (Deprecated) The fast tokenizer to register. """ if tokenizer_class is None: # Legacy: prefer fast over slow if fast_tokenizer_class is not None: tokenizer_class = fast_tokenizer_class elif slow_tokenizer_class is not None: tokenizer_class = slow_tokenizer_class else: raise ValueError("You need to pass a `tokenizer_class`") for candidate in (slow_tokenizer_class, fast_tokenizer_class, tokenizer_class): if candidate is not None: REGISTERED_TOKENIZER_CLASSES[candidate.__name__] = candidate if slow_tokenizer_class is not None and fast_tokenizer_class is not None: REGISTERED_FAST_ALIASES[slow_tokenizer_class.__name__] = fast_tokenizer_class TOKENIZER_MAPPING.register(config_class, tokenizer_class, exist_ok=exist_ok) __all__ = ["TOKENIZER_MAPPING", "AutoTokenizer"]
AutoTokenizer
python
scipy__scipy
benchmarks/benchmarks/sparse_linalg_onenormest.py
{ "start": 286, "end": 1998 }
class ____(Benchmark): params = [ [2, 3, 5, 10, 30, 100, 300, 500, 1000, 1e4, 1e5, 1e6], ['exact', 'onenormest'] ] param_names = ['n', 'solver'] def setup(self, n, solver): rng = np.random.default_rng(1234) nrepeats = 100 shape = (int(n), int(n)) if solver == 'exact' and n >= 300: # skip: slow, and not useful to benchmark raise NotImplementedError() if n <= 1000: # Sample the matrices. self.matrices = [] for i in range(nrepeats): M = rng.standard_normal(shape) self.matrices.append(M) else: max_nnz = 100000 nrepeats = 1 self.matrices = [] for i in range(nrepeats): M = scipy.sparse.rand( shape[0], shape[1], min(max_nnz/(shape[0]*shape[1]), 1e-5), random_state=rng, ) self.matrices.append(M) def time_onenormest(self, n, solver): if solver == 'exact': # Get the exact values of one-norms of squares. for M in self.matrices: M.dot(M) scipy.sparse.linalg._matfuncs._onenorm(M) elif solver == 'onenormest': # Get the estimates of one-norms of squares. for M in self.matrices: scipy.sparse.linalg._matfuncs._onenormest_matrix_power(M, 2) # Retain old benchmark results (remove this if changing the benchmark) time_onenormest.version = ( "f7b31b4bf5caa50d435465e78dab6e133f3c263a52c4523eec785446185fdb6f" )
BenchmarkOneNormEst
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/overload5.py
{ "start": 804, "end": 871 }
class ____(Protocol): def method2(self, x: Any) -> Any: ...
BBase
python
getsentry__sentry
src/sentry/integrations/vsts/repository.py
{ "start": 591, "end": 5322 }
class ____(IntegrationRepositoryProvider): name = "Azure DevOps" repo_provider = IntegrationProviderSlug.AZURE_DEVOPS.value def get_repository_data( self, organization: Organization, config: MutableMapping[str, Any] ) -> Mapping[str, str]: from sentry.integrations.vsts.integration import VstsIntegration installation = self.get_installation(config.get("installation"), organization.id) assert isinstance(installation, VstsIntegration), installation client = installation.get_client() repo_id = config["identifier"] try: repo = client.get_repo(repo_id) except Exception as e: raise installation.raise_error(e) config.update( { "instance": installation.instance, "project": repo["project"]["name"], "name": repo["name"], "external_id": str(repo["id"]), "url": repo["_links"]["web"]["href"], } ) return config def build_repository_config( self, organization: RpcOrganization, data: dict[str, Any] ) -> RepositoryConfig: return { "name": data["name"], "external_id": data["external_id"], "url": data["url"], "config": { "instance": data["instance"], "project": data["project"], "name": data["name"], }, "integration_id": data["installation"], } def transform_changes( self, patch_set: Sequence[Mapping[str, Any]] ) -> Sequence[Mapping[str, str]]: type_mapping = {"add": "A", "delete": "D", "edit": "M"} file_changes = [] # https://docs.microsoft.com/en-us/rest/api/vsts/git/commits/get%20changes#versioncontrolchangetype for change in patch_set: change_type = type_mapping.get(change["changeType"]) if change_type and change.get("item") and change["item"]["gitObjectType"] == "blob": file_changes.append({"path": change["item"]["path"], "type": change_type}) return file_changes def zip_commit_data( self, repo: Repository, commit_list: list[dict[str, Any]], organization_id: int ) -> list[dict[str, Any]]: installation = self.get_installation(repo.integration_id, organization_id) client = installation.get_client() n = 0 for commit in commit_list: # Azure will truncate commit comments to only the first line. # We need to make an additional API call to get the full commit message. # This is important because issue refs could be anywhere in the commit # message. if commit.get("commentTruncated", False): full_commit = client.get_commit(repo.external_id, commit["commitId"]) commit["comment"] = full_commit["comment"] commit["patch_set"] = self.transform_changes( client.get_commit_filechanges(repo.external_id, commit["commitId"]) ) # We only fetch patch data for 90 commits. n += 1 if n > MAX_COMMIT_DATA_REQUESTS: break return commit_list def compare_commits( self, repo: Repository, start_sha: str | None, end_sha: str ) -> Sequence[Mapping[str, str]]: """TODO(mgaeta): This function is kinda a mess.""" installation = self.get_installation(repo.integration_id, repo.organization_id) client = installation.get_client() try: if start_sha is None: res = client.get_commits(repo.external_id, commit=end_sha, limit=10) else: res = client.get_commit_range(repo.external_id, start_sha, end_sha) except Exception as e: raise installation.raise_error(e) commits = self.zip_commit_data(repo, res["value"], repo.organization_id) return self._format_commits(repo, commits) def _format_commits( self, repo: Repository, commit_list: Sequence[Mapping[str, Any]] ) -> Sequence[Mapping[str, Any]]: return [ { "id": c["commitId"], "repository": repo.name, "author_email": c["author"]["email"], "author_name": c["author"]["name"], "message": c["comment"], "patch_set": c.get("patch_set"), "timestamp": self.format_date(c["author"]["date"]), } for c in commit_list ] def repository_external_slug(self, repo: Repository) -> str | None: return repo.external_id
VstsRepositoryProvider
python
PyCQA__pylint
doc/data/messages/r/redefined-slots-in-subclass/bad.py
{ "start": 41, "end": 123 }
class ____(Base): __slots__ = ("a", "d") # [redefined-slots-in-subclass]
Subclass
python
coleifer__peewee
tests/keys.py
{ "start": 1923, "end": 2781 }
class ____(ModelTestCase): requires = [Package, PackageItem] def setUp(self): super(TestForeignKeyToNonPrimaryKey, self).setUp() for barcode in ['101', '102']: Package.create(barcode=barcode) for i in range(2): PackageItem.create( package=barcode, title='%s-%s' % (barcode, i)) def test_fk_resolution(self): pi = PackageItem.get(PackageItem.title == '101-0') self.assertEqual(pi.__data__['package'], '101') self.assertEqual(pi.package, Package.get(Package.barcode == '101')) def test_select_generation(self): p = Package.get(Package.barcode == '101') self.assertEqual( [item.title for item in p.items.order_by(PackageItem.title)], ['101-0', '101-1'])
TestForeignKeyToNonPrimaryKey
python
facebook__pyre-check
client/commands/infer.py
{ "start": 15769, "end": 21976 }
class ____: qualifier: str path: str options: StubGenerationOptions globals_: List[GlobalAnnotation] = dataclasses.field(default_factory=list) attributes: List[AttributeAnnotation] = dataclasses.field(default_factory=list) functions: List[FunctionAnnotation] = dataclasses.field(default_factory=list) methods: List[MethodAnnotation] = dataclasses.field(default_factory=list) @staticmethod def from_infer_output( path: str, infer_output: RawInferOutputForPath, options: StubGenerationOptions, ) -> "ModuleAnnotations": def type_annotation( annotation: Optional[str], parent_class: Optional[str] = None ) -> TypeAnnotation: return TypeAnnotation.from_raw( annotation, qualifier=infer_output.qualifier, options=options, runtime_defined=parent_class != annotation if parent_class else True, ) return ModuleAnnotations( qualifier=infer_output.qualifier, path=path, globals_=[ GlobalAnnotation( name=global_.name, annotation=type_annotation(global_.annotation) ) for global_ in infer_output.global_annotations ], attributes=( [ AttributeAnnotation( parent=attribute.parent, name=attribute.name, annotation=type_annotation( attribute.annotation, attribute.parent ), ) for attribute in infer_output.attribute_annotations ] if options.annotate_attributes else [] ), functions=[ FunctionAnnotation( name=define.name, return_annotation=type_annotation(define.return_), parameters=[ Parameter( name=parameter.name, annotation=type_annotation(parameter.annotation), has_default=parameter.value is not None, ) for parameter in define.parameters ], is_async=define.is_async, ) for define in infer_output.define_annotations if define.parent is None ], methods=[ MethodAnnotation( parent=define.parent, name=define.name, return_annotation=type_annotation(define.return_, define.parent), parameters=[ Parameter( name=parameter.name, annotation=type_annotation( parameter.annotation, define.parent ), has_default=parameter.value is not None, ) for parameter in define.parameters ], is_async=define.is_async, ) for define in infer_output.define_annotations if define.parent is not None ], options=options, ) def is_empty(self) -> bool: return ( len(self.globals_) + len(self.attributes) + len(self.functions) + len(self.methods) ) == 0 @staticmethod def _indent(stub: str) -> str: return " " + stub.replace("\n", "\n ") @property def classes(self) -> Dict[str, List[Union[AttributeAnnotation, MethodAnnotation]]]: """ Find all classes with attributes or methods to annotate. Anything in nested classes is currently ignored, e.g.: ``` class X: class Y: [ALL OF THIS IS IGNORED] ``` """ classes: Dict[str, List[Union[AttributeAnnotation, MethodAnnotation]]] = {} nested_classes = set() for annotation in [*self.attributes, *self.methods]: relative_parent_class = _remove_prefix( text=annotation.parent, prefix=self.qualifier + "." ) if "." in relative_parent_class: nested_classes.add(relative_parent_class) else: classes.setdefault(relative_parent_class, []).append(annotation) if len(nested_classes) > 0: nested_classes_string = textwrap.shorten( ", ".join(sorted(nested_classes)), width=MAX_NESTED_CLASS_STRING_LENGTH, placeholder="...", ) LOG.warning( f"In file {self.path}, ignored {len(nested_classes)} nested classes: {nested_classes_string}" ) return classes def _class_stub( self, classname: str, annotations: Sequence[Union[AttributeAnnotation, MethodAnnotation]], ) -> str: body = "\n".join( self._indent(annotation.to_stub()) for annotation in annotations ) return f"class {classname}:\n{body}\n" def to_stubs(self) -> str: """ Output annotation information as a stub file. """ return "\n".join( [ *(global_.to_stub() for global_ in self.globals_), *(function.to_stub() for function in self.functions), *( self._class_stub(classname, annotations) for classname, annotations in self.classes.items() ), "", ] ) def stubs_path(self, directory: Path) -> Path: return (directory / self.path).with_suffix(".pyi") def write_stubs(self, type_directory: Path) -> None: path = self.stubs_path(type_directory) path.parent.mkdir(parents=True, exist_ok=True) path.write_text(self.to_stubs()) @dataclasses.dataclass
ModuleAnnotations
python
huggingface__transformers
src/transformers/models/deepseek_vl_hybrid/configuration_deepseek_vl_hybrid.py
{ "start": 1386, "end": 5217 }
class ____(PreTrainedConfig): r""" This is the configuration class to store the configuration of a [`DeepseekVLHybridModel`]. It is used to instantiate a DeepseekVLHybrid model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the DeepseekVLHybrid [deepseek-community/deepseek-vl-7b-chat](https://huggingface.co/deepseek-community/deepseek-vl-7b-chat) architecture. Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the documentation from [`PreTrainedConfig`] for more information. Args: text_config (`Union[AutoConfig, dict]`, *optional*, defaults to `LlamaConfig`): The config object or dictionary of the text backbone. vision_config (`Union[AutoConfig, dict]`, *optional*, defaults to `SiglipVisionConfig`): The config object or dictionary of the vision backbone. high_res_vision_config (`Union[AutoConfig, dict]`, *optional*, defaults to `SamVisionConfig`): The config object or dictionary of the high resolution vision backbone. image_token_id (`int`, *optional*, defaults to 100015): The index representing image tokens in the model's token vocabulary. Example: ```python >>> from transformers import DeepseekVLHybridConfig, DeepseekVLHybridModel >>> # Initializing a DeepseekVLHybrid deepseek-community/deepseek-vl-7b-chat style configuration >>> configuration = DeepseekVLHybridConfig() >>> # Initializing a model (with random weights) from the deepseek-community/deepseek-vl-7b-chat style configuration >>> model = DeepseekVLHybridModel(configuration) >>> # Accessing the model configuration >>> configuration = model.config ```""" model_type = "deepseek_vl_hybrid" sub_configs = {"text_config": AutoConfig, "vision_config": AutoConfig, "high_res_vision_config": AutoConfig} def __init__( self, text_config: Optional[AutoConfig] = None, vision_config: Optional[AutoConfig] = None, high_res_vision_config: Optional[AutoConfig] = None, image_token_id: int = 100015, **kwargs, ): if high_res_vision_config is None: high_res_vision_config = {} logger.info("`high_res_vision_config` is `None`. Initializing the `SamVisionConfig` with default values.") if isinstance(high_res_vision_config, dict): high_res_vision_config["model_type"] = high_res_vision_config.get("model_type", "sam_vision_model") high_res_vision_config = CONFIG_MAPPING[high_res_vision_config["model_type"]](**high_res_vision_config) self.high_res_vision_config = high_res_vision_config if text_config is None: text_config = {} logger.info("`text_config` is `None`. Initializing the `LlamaConfig` with default values.") if vision_config is None: vision_config = {} logger.info("`vision_config` is `None`. Initializing the `SiglipVisionConfig` with default values.") if isinstance(text_config, dict): text_config["model_type"] = text_config.get("model_type", "llama") text_config = CONFIG_MAPPING[text_config["model_type"]](**text_config) if isinstance(vision_config, dict): vision_config["model_type"] = vision_config.get("model_type", "siglip_vision_model") vision_config = CONFIG_MAPPING[vision_config["model_type"]](**vision_config) self.text_config = text_config self.vision_config = vision_config self.image_token_id = image_token_id super().__init__(**kwargs) __all__ = ["DeepseekVLHybridConfig"]
DeepseekVLHybridConfig
python
huggingface__transformers
src/transformers/models/mra/modeling_mra.py
{ "start": 31916, "end": 32306 }
class ____(PreTrainedModel): config: MraConfig base_model_prefix = "mra" supports_gradient_checkpointing = True @torch.no_grad() def _init_weights(self, module: nn.Module): """Initialize the weights""" super()._init_weights(module) if isinstance(module, MraLMPredictionHead): init.zeros_(module.bias) @auto_docstring
MraPreTrainedModel
python
walkccc__LeetCode
solutions/2212. Maximum Points in an Archery Competition/2212.py
{ "start": 0, "end": 951 }
class ____: def maximumBobPoints( self, numArrows: int, aliceArrows: list[int], ) -> list[int]: FULL_MASK = (1 << 12) - 1 maxPoint = 0 maxMask = 0 def getShotableAndPoint(mask: int, leftArrows: int) -> tuple[bool, int]: point = 0 for i in range(12): if mask >> i & 1: leftArrows -= aliceArrows[i] + 1 point += i return leftArrows >= 0, point for mask in range(FULL_MASK): shotable, point = getShotableAndPoint(mask, numArrows) if shotable and point > maxPoint: maxPoint = point maxMask = mask def getBobsArrows(mask: int, leftArrows: int) -> list[int]: bobsArrows = [0] * 12 for i in range(12): if mask >> i & 1: bobsArrows[i] = aliceArrows[i] + 1 leftArrows -= aliceArrows[i] + 1 bobsArrows[0] = leftArrows return bobsArrows return getBobsArrows(maxMask, numArrows)
Solution
python
pandas-dev__pandas
asv_bench/benchmarks/rolling.py
{ "start": 11149, "end": 11628 }
class ____: params = ["single", "table"] param_names = ["method"] def setup(self, method): self.df = pd.DataFrame(np.random.randn(10, 1000)) def time_apply(self, method): self.df.rolling(2, method=method).apply( table_method_func, raw=True, engine="numba" ) def time_ewm_mean(self, method): self.df.ewm(1, method=method).mean(engine="numba") from .pandas_vb_common import setup # noqa: F401 isort:skip
TableMethod
python
numba__numba
numba/np/ufunc/decorators.py
{ "start": 252, "end": 838 }
class ____(object): @classmethod def get_identity(cls, kwargs): return kwargs.pop('identity', None) @classmethod def get_cache(cls, kwargs): return kwargs.pop('cache', False) @classmethod def get_writable_args(cls, kwargs): return kwargs.pop('writable_args', ()) @classmethod def get_target_implementation(cls, kwargs): target = kwargs.pop('target', 'cpu') try: return cls.target_registry[target] except KeyError: raise ValueError("Unsupported target: %s" % target)
_BaseVectorize
python
conda__conda
conda/plugins/types.py
{ "start": 17383, "end": 18766 }
class ____(CondaPlugin): """ **EXPERIMENTAL** Return type to use when defining a conda environment exporter plugin hook supporting a single platform. :param name: name of the exporter (e.g., ``environment-yaml``) :param aliases: user-friendly format aliases (e.g., ("yaml",)) :param default_filenames: default filenames this exporter handles (e.g., ("environment.yml", "environment.yaml")) :param export: callable that exports an Environment to string format """ name: str aliases: tuple[str, ...] default_filenames: tuple[str, ...] export: SinglePlatformEnvironmentExport | None = None multiplatform_export: MultiPlatformEnvironmentExport | None = None def __post_init__(self): super().__post_init__() # Handle name normalization # Normalize aliases using same pattern as name normalization try: self.aliases = tuple( dict.fromkeys(alias.lower().strip() for alias in self.aliases) ) except AttributeError: # AttributeError: alias is not a string raise PluginError(f"Invalid plugin aliases for {self!r}") if bool(self.export) == bool(self.multiplatform_export): raise PluginError( f"Exactly one of export or multiplatform_export must be set for {self!r}" )
CondaEnvironmentExporter
python
sqlalchemy__sqlalchemy
test/orm/test_recursive_loaders.py
{ "start": 1356, "end": 2080 }
class ____: @classmethod def define_tables(cls, metadata): Table( "nodes", metadata, Column("id", Integer, primary_key=True), Column("parent_id", Integer, ForeignKey("nodes.id")), Column("data", String(30)), ) @classmethod def setup_mappers(cls): nodes = cls.tables.nodes Node = cls.classes.Node cls.mapper_registry.map_imperatively( Node, nodes, properties={"children": relationship(Node)}, ) @classmethod def setup_classes(cls): class Node(cls.Comparable): def append(self, node): self.children.append(node)
_NodeTest
python
great-expectations__great_expectations
tests/datasource/fluent/test_spark_google_cloud_storage_datasource.py
{ "start": 848, "end": 9000 }
class ____: # noinspection PyMethodMayBeStatic,PyUnusedLocal def list_blobs( self, bucket_or_name, max_results=None, prefix=None, delimiter=None, **kwargs, ) -> Iterator: return iter([]) def _build_spark_gcs_datasource( gcs_options: Dict[str, Any] | None = None, ) -> SparkGoogleCloudStorageDatasource: gcs_client: google.Client = cast("google.Client", MockGCSClient()) spark_gcs_datasource = SparkGoogleCloudStorageDatasource( name="spark_gcs_datasource", bucket_or_name="test_bucket", gcs_options=gcs_options or {}, ) spark_gcs_datasource._gcs_client = gcs_client return spark_gcs_datasource @pytest.fixture def spark_gcs_datasource() -> SparkGoogleCloudStorageDatasource: spark_gcs_datasource: SparkGoogleCloudStorageDatasource = _build_spark_gcs_datasource() return spark_gcs_datasource @pytest.fixture def object_keys() -> List[str]: return [ "alex_20200809_1000.csv", "eugene_20200809_1500.csv", "james_20200811_1009.csv", "abe_20200809_1040.csv", "will_20200809_1002.csv", "james_20200713_1567.csv", "eugene_20201129_1900.csv", "will_20200810_1001.csv", "james_20200810_1003.csv", "alex_20200819_1300.csv", ] @pytest.fixture @mock.patch( "great_expectations.datasource.fluent.data_asset.data_connector.google_cloud_storage_data_connector.list_gcs_keys" ) def csv_asset( mock_list_keys, object_keys: List[str], spark_gcs_datasource: SparkGoogleCloudStorageDatasource, ) -> PathDataAsset: mock_list_keys.return_value = object_keys asset = spark_gcs_datasource.add_csv_asset( name="csv_asset", ) return asset @pytest.mark.big def test_construct_spark_gcs_datasource_without_gcs_options(): google_cred_file = os.getenv("GOOGLE_APPLICATION_CREDENTIALS") if not google_cred_file: pytest.skip('No "GOOGLE_APPLICATION_CREDENTIALS" environment variable found.') spark_gcs_datasource = SparkGoogleCloudStorageDatasource( name="spark_gcs_datasource", bucket_or_name="test_bucket", gcs_options={}, ) # noinspection PyUnresolvedReferences gcs_client: google.Client = spark_gcs_datasource._get_gcs_client() assert gcs_client is not None assert spark_gcs_datasource.name == "spark_gcs_datasource" @pytest.mark.big @mock.patch( "great_expectations.datasource.fluent.data_asset.data_connector.google_cloud_storage_data_connector.list_gcs_keys" ) @mock.patch("google.oauth2.service_account.Credentials.from_service_account_file") @mock.patch("google.cloud.storage.Client") def test_construct_spark_gcs_datasource_with_filename_in_gcs_options( mock_gcs_client, mock_gcs_service_account_credentials, mock_list_keys ): spark_gcs_datasource = SparkGoogleCloudStorageDatasource( name="spark_gcs_datasource", bucket_or_name="test_bucket", gcs_options={ "filename": "my_filename.csv", }, ) # noinspection PyUnresolvedReferences gcs_client: google.Client = spark_gcs_datasource._get_gcs_client() assert gcs_client is not None assert spark_gcs_datasource.name == "spark_gcs_datasource" @pytest.mark.big @mock.patch( "great_expectations.datasource.fluent.data_asset.data_connector.google_cloud_storage_data_connector.list_gcs_keys" ) @mock.patch("google.oauth2.service_account.Credentials.from_service_account_info") @mock.patch("google.cloud.storage.Client") def test_construct_spark_gcs_datasource_with_info_in_gcs_options( mock_gcs_client, mock_gcs_service_account_credentials, mock_list_keys ): spark_gcs_datasource = SparkGoogleCloudStorageDatasource( name="spark_gcs_datasource", bucket_or_name="test_bucket", gcs_options={ "info": "{my_csv: my_content,}", }, ) # noinspection PyUnresolvedReferences gcs_client: google.Client = spark_gcs_datasource._get_gcs_client() assert gcs_client is not None assert spark_gcs_datasource.name == "spark_gcs_datasource" @pytest.mark.big @mock.patch( "great_expectations.datasource.fluent.data_asset.data_connector.google_cloud_storage_data_connector.list_gcs_keys" ) @mock.patch("google.cloud.storage.Client") def test_add_csv_asset_to_datasource( mock_gcs_client, mock_list_keys, object_keys: List[str], spark_gcs_datasource: SparkGoogleCloudStorageDatasource, ): mock_list_keys.return_value = object_keys asset_specified_metadata = {"asset_level_metadata": "my_metadata"} asset = spark_gcs_datasource.add_csv_asset( name="csv_asset", batch_metadata=asset_specified_metadata, ) assert asset.name == "csv_asset" assert asset.batch_metadata == asset_specified_metadata @pytest.mark.big @mock.patch( "great_expectations.datasource.fluent.data_asset.data_connector.google_cloud_storage_data_connector.list_gcs_keys" ) @mock.patch("google.cloud.storage.Client") def test_construct_csv_asset_directly(mock_gcs_client, mock_list_keys, object_keys: List[str]): mock_list_keys.return_value = object_keys asset = CSVAsset( # type: ignore[call-arg] # missing args name="csv_asset", ) assert asset.name == "csv_asset" @pytest.mark.big @mock.patch( "great_expectations.datasource.fluent.data_asset.data_connector.google_cloud_storage_data_connector.list_gcs_keys" ) @mock.patch("google.cloud.storage.Client") def test_csv_asset_with_batching_regex_named_parameters( mock_gcs_client, mock_list_keys, object_keys: List[str], spark_gcs_datasource: SparkGoogleCloudStorageDatasource, ): mock_list_keys.return_value = object_keys asset = spark_gcs_datasource.add_csv_asset( name="csv_asset", ) batching_regex = r"yellow_tripdata_sample_(?P<year>\d{4})-(?P<month>\d{2})\.csv" batch_def = asset.add_batch_definition_monthly(name="batch def", regex=batching_regex) options = asset.get_batch_parameters_keys(partitioner=batch_def.partitioner) assert options == ("path", "year", "month") @pytest.mark.big @mock.patch( "great_expectations.datasource.fluent.data_asset.data_connector.google_cloud_storage_data_connector.list_gcs_keys" ) @mock.patch("google.cloud.storage.Client") def test_csv_asset_with_non_string_batching_regex_named_parameters( mock_gcs_client, mock_list_keys, object_keys: List[str], spark_gcs_datasource: SparkGoogleCloudStorageDatasource, ): mock_list_keys.return_value = object_keys asset = spark_gcs_datasource.add_csv_asset( name="csv_asset", ) batching_regex = re.compile(r"(.+)_(.+)_(?P<price>\d{4})\.csv") with pytest.raises(ge_exceptions.InvalidBatchRequestError): # price is an int which will raise an error asset.build_batch_request( {"name": "alex", "timestamp": "1234567890", "price": 1300}, partitioner=FileNamePartitionerPath(regex=batching_regex), ) @pytest.mark.big @mock.patch( "great_expectations.datasource.fluent.data_asset.data_connector.google_cloud_storage_data_connector.list_gcs_keys" ) @mock.patch("google.cloud.storage.Client") def test_add_csv_asset_with_recursive_file_discovery_to_datasource( mock_gcs_client, mock_list_keys, object_keys: List[str], spark_gcs_datasource: SparkGoogleCloudStorageDatasource, ): """ Tests that the gcs_recursive_file_discovery-flag is passed on to the list_keys-function as the recursive-parameter This makes the list_keys-function search and return files also from sub-directories on GCS, not just the files in the folder specified with the abs_name_starts_with-parameter """ mock_list_keys.return_value = object_keys asset_specified_metadata = {"asset_level_metadata": "my_metadata"} spark_gcs_datasource.add_csv_asset( name="csv_asset", batch_metadata=asset_specified_metadata, gcs_recursive_file_discovery=True, ) assert "recursive" in mock_list_keys.call_args.kwargs assert mock_list_keys.call_args.kwargs["recursive"] is True
MockGCSClient
python
huggingface__transformers
src/transformers/models/layoutlmv2/image_processing_layoutlmv2_fast.py
{ "start": 1299, "end": 4579 }
class ____(BaseImageProcessorFast): resample = PILImageResampling.BILINEAR size = {"height": 224, "width": 224} rescale_factor = None do_resize = True apply_ocr = True ocr_lang = None tesseract_config = "" valid_kwargs = LayoutLMv2ImageProcessorKwargs def __init__(self, **kwargs: Unpack[LayoutLMv2ImageProcessorKwargs]): super().__init__(**kwargs) @auto_docstring def preprocess(self, images: ImageInput, **kwargs: Unpack[LayoutLMv2ImageProcessorKwargs]) -> BatchFeature: return super().preprocess(images, **kwargs) def _preprocess( self, images: list["torch.Tensor"], do_resize: bool, size: SizeDict, interpolation: Optional["F.InterpolationMode"], apply_ocr: bool, ocr_lang: Optional[str], tesseract_config: Optional[str], disable_grouping: Optional[bool], return_tensors: Optional[Union[str, TensorType]], **kwargs, ) -> BatchFeature: # Tesseract OCR to get words + normalized bounding boxes if apply_ocr: requires_backends(self, "pytesseract") words_batch = [] boxes_batch = [] for image in images: if image.is_cuda: logger.warning_once( "apply_ocr can only be performed on cpu. Tensors will be transferred to cpu before processing." ) words, boxes = apply_tesseract( image.cpu(), ocr_lang, tesseract_config, input_data_format=ChannelDimension.FIRST ) words_batch.append(words) boxes_batch.append(boxes) # Group images by size for batched resizing grouped_images, grouped_images_index = group_images_by_shape(images, disable_grouping=disable_grouping) resized_images_grouped = {} for shape, stacked_images in grouped_images.items(): if do_resize: stacked_images = self.resize(image=stacked_images, size=size, interpolation=interpolation) resized_images_grouped[shape] = stacked_images resized_images = reorder_images(resized_images_grouped, grouped_images_index) # Group images by size for further processing # Needed in case do_resize is False, or resize returns images with different sizes grouped_images, grouped_images_index = group_images_by_shape(resized_images, disable_grouping=disable_grouping) processed_images_grouped = {} for shape, stacked_images in grouped_images.items(): # flip color channels from RGB to BGR (as Detectron2 requires this) stacked_images = stacked_images.flip(1) processed_images_grouped[shape] = stacked_images processed_images = reorder_images(processed_images_grouped, grouped_images_index) processed_images = torch.stack(processed_images, dim=0) if return_tensors else processed_images data = BatchFeature(data={"pixel_values": processed_images}, tensor_type=return_tensors) if apply_ocr: data["words"] = words_batch data["boxes"] = boxes_batch return data __all__ = ["LayoutLMv2ImageProcessorFast"]
LayoutLMv2ImageProcessorFast
python
walkccc__LeetCode
solutions/746. Min Cost Climbing Stairs/746.py
{ "start": 0, "end": 197 }
class ____: def minCostClimbingStairs(self, cost: list[int]) -> int: cost.append(0) for i in range(2, len(cost)): cost[i] += min(cost[i - 1], cost[i - 2]) return cost[-1]
Solution
python
run-llama__llama_index
llama-index-core/llama_index/core/chat_ui/events.py
{ "start": 247, "end": 311 }
class ____(Event): nodes: List[NodeWithScore]
SourceNodesEvent
python
walkccc__LeetCode
solutions/812. Largest Triangle Area/812.py
{ "start": 0, "end": 314 }
class ____: def largestTriangleArea(self, points: list[list[int]]) -> float: ans = 0 for Ax, Ay in points: for Bx, By in points: for Cx, Cy in points: ans = max(ans, 0.5 * abs((Bx - Ax) * (Cy - Ay) - (Cx - Ax) * (By - Ay))) return ans
Solution
python
apache__airflow
providers/fab/tests/unit/fab/auth_manager/api_endpoints/test_role_and_permission_endpoint.py
{ "start": 15300, "end": 22518 }
class ____(TestRoleEndpoint): @pytest.mark.parametrize( ("payload", "expected_name", "expected_actions"), [ ({"name": "mytest"}, "mytest", []), ( { "name": "mytest2", "actions": [{"resource": {"name": "Connections"}, "action": {"name": "can_create"}}], }, "mytest2", [{"resource": {"name": "Connections"}, "action": {"name": "can_create"}}], ), ], ) def test_patch_should_respond_200(self, payload, expected_name, expected_actions): role = create_role(self.app, "mytestrole") response = self.client.patch( f"/fab/v1/roles/{role.name}", json=payload, environ_overrides={"REMOTE_USER": "test"} ) assert response.status_code == 200 assert response.json["name"] == expected_name assert response.json["actions"] == expected_actions def test_patch_should_update_correct_roles_permissions(self): create_role(self.app, "role_to_change") create_role(self.app, "already_exists") response = self.client.patch( "/fab/v1/roles/role_to_change", json={ "name": "already_exists", "actions": [{"action": {"name": "can_delete"}, "resource": {"name": "XComs"}}], }, environ_overrides={"REMOTE_USER": "test"}, ) assert response.status_code == 200 updated_permissions = self.app.appbuilder.sm.find_role("role_to_change").permissions assert len(updated_permissions) == 1 assert updated_permissions[0].resource.name == "XComs" assert updated_permissions[0].action.name == "can_delete" assert len(self.app.appbuilder.sm.find_role("already_exists").permissions) == 0 @pytest.mark.parametrize( ("update_mask", "payload", "expected_name", "expected_actions"), [ ( "?update_mask=name", { "name": "mytest2", "actions": [{"resource": {"name": "Connections"}, "action": {"name": "can_create"}}], }, "mytest2", [], ), ( "?update_mask=name, actions", # both name and actions in update mask { "name": "mytest2", "actions": [{"resource": {"name": "Connections"}, "action": {"name": "can_create"}}], }, "mytest2", [{"resource": {"name": "Connections"}, "action": {"name": "can_create"}}], ), ], ) def test_patch_should_respond_200_with_update_mask( self, update_mask, payload, expected_name, expected_actions ): role = create_role(self.app, "mytestrole") assert role.permissions == [] response = self.client.patch( f"/fab/v1/roles/{role.name}{update_mask}", json=payload, environ_overrides={"REMOTE_USER": "test"}, ) assert response.status_code == 200 assert response.json["name"] == expected_name assert response.json["actions"] == expected_actions def test_patch_should_respond_400_for_invalid_fields_in_update_mask(self): role = create_role(self.app, "mytestrole") payload = {"name": "testme"} response = self.client.patch( f"/fab/v1/roles/{role.name}?update_mask=invalid_name", json=payload, environ_overrides={"REMOTE_USER": "test"}, ) assert response.status_code == 400 assert response.json["detail"] == "'invalid_name' in update_mask is unknown" @pytest.mark.parametrize( ("payload", "expected_error"), [ ( { "name": "testme", "permissions": [ # Using permissions instead of actions should raise {"resource": {"name": "Connections"}, "action": {"name": "can_create"}} ], }, "{'permissions': ['Unknown field.']}", ), ( { "name": "testme", "actions": [ { "view_menu": {"name": "Connections"}, # Using view_menu instead of resource "action": {"name": "can_create"}, } ], }, "{'actions': {0: {'view_menu': ['Unknown field.']}}}", ), ( { "name": "testme", "actions": [ { "resource": {"name": "FooBars"}, # Using wrong resource name "action": {"name": "can_create"}, } ], }, "The specified resource: 'FooBars' was not found", ), ( { "name": "testme", "actions": [ { "resource": {"name": "Connections"}, # Using wrong action name "action": {"name": "can_invalid"}, } ], }, "The specified action: 'can_invalid' was not found", ), ], ) def test_patch_should_respond_400_for_invalid_update(self, payload, expected_error): role = create_role(self.app, "mytestrole") response = self.client.patch( f"/fab/v1/roles/{role.name}", json=payload, environ_overrides={"REMOTE_USER": "test"}, ) assert response.status_code == 400 assert response.json["detail"] == expected_error def test_should_raises_401_unauthenticated(self): response = self.client.patch( "/fab/v1/roles/test", json={ "name": "mytest2", "actions": [{"resource": {"name": "Connections"}, "action": {"name": "can_create"}}], }, ) assert_401(response) def test_should_raise_403_forbidden(self): response = self.client.patch( "/fab/v1/roles/test", json={ "name": "mytest2", "actions": [{"resource": {"name": "Connections"}, "action": {"name": "can_create"}}], }, environ_overrides={"REMOTE_USER": "test_no_permissions"}, ) assert response.status_code == 403 @pytest.mark.parametrize( ("set_auth_role_public", "expected_status_code"), (("Public", 403), ("Admin", 200)), indirect=["set_auth_role_public"], ) def test_with_auth_role_public_set(self, set_auth_role_public, expected_status_code): role = create_role(self.app, "mytestrole") response = self.client.patch( f"/fab/v1/roles/{role.name}", json={"name": "mytest"}, ) assert response.status_code == expected_status_code, response.json
TestPatchRole
python
giampaolo__psutil
psutil/test/memleak.py
{ "start": 4890, "end": 11141 }
class ____(unittest.TestCase): # Number of times to call the tested function in each iteration. times = 200 # Maximum number of retries if memory growth is detected. retries = 5 # Number of warm-up calls before measurements begin. warmup_times = 10 # Allowed memory difference (in bytes) before considering it a leak. tolerance = 0 # 0 = no messages; 1 = print diagnostics when memory increases. verbosity = 1 __doc__ = __doc__ @classmethod def setUpClass(cls): cls._psutil_debug_orig = bool(os.getenv("PSUTIL_DEBUG")) psutil._set_debug(False) # avoid spamming to stderr @classmethod def tearDownClass(cls): psutil._set_debug(cls._psutil_debug_orig) def _log(self, msg, level): if level <= self.verbosity: if WINDOWS: # On Windows we use ctypes to add colors. Avoid that to # not interfere with memory observations. print(msg) # noqa: T201 else: print_color(msg, color="yellow") # Force flush to not interfere with memory observations. sys.stdout.flush() def _trim_mem(self): """Release unused memory. Aims to stabilize memory measurements.""" # flush standard streams sys.stdout.flush() sys.stderr.flush() # flush logging handlers for handler in logging.root.handlers: handler.flush() # full garbage collection gc.collect() assert gc.garbage == [] # release free heap memory back to the OS if hasattr(psutil, "heap_trim"): psutil.heap_trim() def _warmup(self, fun, warmup_times): for _ in range(warmup_times): self.call(fun) # --- getters def _get_oneshot(self): return { "num_fds": thisproc.num_fds() if POSIX else 0, "num_handles": thisproc.num_handles() if WINDOWS else 0, "heap_count": psutil.heap_info().heap_count if WINDOWS else 0, } def _get_mem(self): mem = thisproc.memory_full_info() heap_used = mmap_used = 0 if hasattr(psutil, "heap_info"): heap = psutil.heap_info() heap_used = heap.heap_used mmap_used = heap.mmap_used return { "heap": heap_used, "mmap": mmap_used, "uss": getattr(mem, "uss", 0), "rss": mem.rss, "vms": mem.vms, } # --- checkers def _check_oneshot(self, fun): before = self._get_oneshot() self.call(fun) after = self._get_oneshot() for what, value_before in before.items(): value_after = after[what] diff = value_after - value_before if diff < 0: msg = ( f"WARNING: {what!r} decreased by {abs(diff)} after calling" f" {qualname(fun)!r} 1 time" ) self._log(msg, 0) elif diff > 0: mapping = { "num_fds": UnclosedFdError, "num_handles": UnclosedHandleError, "heap_count": UnclosedHeapCreateError, } exc = mapping.get(what) if exc is None: raise ValueError(what) raise exc(diff, qualname(fun)) def _call_ntimes(self, fun, times): """Get memory samples before and after calling fun repeatedly, and return the diffs as a dict. """ self._trim_mem() mem1 = self._get_mem() for _ in range(times): self.call(fun) self._trim_mem() mem2 = self._get_mem() diffs = {k: mem2[k] - mem1[k] for k in mem1} return diffs def _check_mem(self, fun, times, retries, tolerance): prev = {} messages = [] for idx in range(1, retries + 1): diffs = self._call_ntimes(fun, times) leaks = {k: v for k, v in diffs.items() if v > 0} if leaks: line = format_run_line(idx, leaks, times) messages.append(line) self._log(line, 1) stable = all( diffs.get(k, 0) <= tolerance or diffs.get(k, 0) <= prev.get(k, 0) for k in diffs ) if stable: if idx > 1 and leaks: self._log( "Memory stabilized (no further growth detected)", 1 ) return prev = diffs times *= 2 # double calls each retry msg = f"memory kept increasing after {retries} runs" + "\n".join( messages ) raise MemoryLeakError(msg) # --- def call(self, fun): return fun() def execute( self, fun, *args, times=None, warmup_times=None, retries=None, tolerance=None, ): """Run a full leak test on a callable. If specified, the optional arguments override the class attributes with the same name. """ times = times if times is not None else self.times warmup_times = ( warmup_times if warmup_times is not None else self.warmup_times ) retries = retries if retries is not None else self.retries tolerance = tolerance if tolerance is not None else self.tolerance if times < 1: msg = f"times must be >= 1 (got {times})" raise ValueError(msg) if warmup_times < 0: msg = f"warmup_times must be >= 0 (got {warmup_times})" raise ValueError(msg) if retries < 0: msg = f"retries must be >= 0 (got {retries})" raise ValueError(msg) if tolerance < 0: msg = f"tolerance must be >= 0 (got {tolerance})" raise ValueError(msg) if args: fun = functools.partial(fun, *args) self._check_oneshot(fun) self._warmup(fun, warmup_times) self._check_mem(fun, times=times, retries=retries, tolerance=tolerance)
MemoryLeakTestCase
python
anthropics__anthropic-sdk-python
src/anthropic/types/beta/beta_bash_code_execution_output_block_param.py
{ "start": 237, "end": 392 }
class ____(TypedDict, total=False): file_id: Required[str] type: Required[Literal["bash_code_execution_output"]]
BetaBashCodeExecutionOutputBlockParam
python
matplotlib__matplotlib
lib/matplotlib/_type1font.py
{ "start": 3714, "end": 7832 }
class ____(_Token): kind = 'number' def is_number(self): return True def value(self): if '.' not in self.raw: return int(self.raw) else: return float(self.raw) def _tokenize(data: bytes, skip_ws: bool) -> T.Generator[_Token, int, None]: """ A generator that produces _Token instances from Type-1 font code. The consumer of the generator may send an integer to the tokenizer to indicate that the next token should be _BinaryToken of the given length. Parameters ---------- data : bytes The data of the font to tokenize. skip_ws : bool If true, the generator will drop any _WhitespaceTokens from the output. """ text = data.decode('ascii', 'replace') whitespace_or_comment_re = re.compile(r'[\0\t\r\f\n ]+|%[^\r\n]*') token_re = re.compile(r'/{0,2}[^]\0\t\r\f\n ()<>{}/%[]+') instring_re = re.compile(r'[()\\]') hex_re = re.compile(r'^<[0-9a-fA-F\0\t\r\f\n ]*>$') oct_re = re.compile(r'[0-7]{1,3}') pos = 0 next_binary: int | None = None while pos < len(text): if next_binary is not None: n = next_binary next_binary = (yield _BinaryToken(pos, data[pos:pos+n])) pos += n continue match = whitespace_or_comment_re.match(text, pos) if match: if not skip_ws: next_binary = (yield _WhitespaceToken(pos, match.group())) pos = match.end() elif text[pos] == '(': # PostScript string rules: # - parentheses must be balanced # - backslashes escape backslashes and parens # - also codes \n\r\t\b\f and octal escapes are recognized # - other backslashes do not escape anything start = pos pos += 1 depth = 1 while depth: match = instring_re.search(text, pos) if match is None: raise ValueError( f'Unterminated string starting at {start}') pos = match.end() if match.group() == '(': depth += 1 elif match.group() == ')': depth -= 1 else: # a backslash char = text[pos] if char in r'\()nrtbf': pos += 1 else: octal = oct_re.match(text, pos) if octal: pos = octal.end() else: pass # non-escaping backslash next_binary = (yield _StringToken(start, text[start:pos])) elif text[pos:pos + 2] in ('<<', '>>'): next_binary = (yield _DelimiterToken(pos, text[pos:pos + 2])) pos += 2 elif text[pos] == '<': start = pos try: pos = text.index('>', pos) + 1 except ValueError as e: raise ValueError(f'Unterminated hex string starting at {start}' ) from e if not hex_re.match(text[start:pos]): raise ValueError(f'Malformed hex string starting at {start}') next_binary = (yield _StringToken(pos, text[start:pos])) else: match = token_re.match(text, pos) if match: raw = match.group() if raw.startswith('/'): next_binary = (yield _NameToken(pos, raw)) elif match.group() in ('true', 'false'): next_binary = (yield _BooleanToken(pos, raw)) else: try: float(raw) next_binary = (yield _NumberToken(pos, raw)) except ValueError: next_binary = (yield _KeywordToken(pos, raw)) pos = match.end() else: next_binary = (yield _DelimiterToken(pos, text[pos])) pos += 1
_NumberToken
python
huggingface__transformers
src/transformers/models/timesformer/modeling_timesformer.py
{ "start": 20405, "end": 25586 }
class ____(TimesformerPreTrainedModel): def __init__(self, config): super().__init__(config) self.config = config self.embeddings = TimesformerEmbeddings(config) self.encoder = TimesformerEncoder(config) self.layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) # Initialize weights and apply final processing self.post_init() def get_input_embeddings(self): return self.embeddings.patch_embeddings @auto_docstring def forward( self, pixel_values: torch.FloatTensor, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, ) -> Union[tuple[torch.FloatTensor], BaseModelOutput]: r""" Examples: ```python >>> import av >>> import numpy as np >>> from transformers import AutoImageProcessor, TimesformerModel >>> from huggingface_hub import hf_hub_download >>> np.random.seed(0) >>> def read_video_pyav(container, indices): ... ''' ... Decode the video with PyAV decoder. ... Args: ... container (`av.container.input.InputContainer`): PyAV container. ... indices (`list[int]`): List of frame indices to decode. ... Returns: ... result (np.ndarray): np array of decoded frames of shape (num_frames, height, width, 3). ... ''' ... frames = [] ... container.seek(0) ... start_index = indices[0] ... end_index = indices[-1] ... for i, frame in enumerate(container.decode(video=0)): ... if i > end_index: ... break ... if i >= start_index and i in indices: ... frames.append(frame) ... return np.stack([x.to_ndarray(format="rgb24") for x in frames]) >>> def sample_frame_indices(clip_len, frame_sample_rate, seg_len): ... ''' ... Sample a given number of frame indices from the video. ... Args: ... clip_len (`int`): Total number of frames to sample. ... frame_sample_rate (`int`): Sample every n-th frame. ... seg_len (`int`): Maximum allowed index of sample's last frame. ... Returns: ... indices (`list[int]`): List of sampled frame indices ... ''' ... converted_len = int(clip_len * frame_sample_rate) ... end_idx = np.random.randint(converted_len, seg_len) ... start_idx = end_idx - converted_len ... indices = np.linspace(start_idx, end_idx, num=clip_len) ... indices = np.clip(indices, start_idx, end_idx - 1).astype(np.int64) ... return indices >>> # video clip consists of 300 frames (10 seconds at 30 FPS) >>> file_path = hf_hub_download( ... repo_id="nielsr/video-demo", filename="eating_spaghetti.mp4", repo_type="dataset" ... ) >>> container = av.open(file_path) >>> # sample 8 frames >>> indices = sample_frame_indices(clip_len=8, frame_sample_rate=4, seg_len=container.streams.video[0].frames) >>> video = read_video_pyav(container, indices) >>> image_processor = AutoImageProcessor.from_pretrained("MCG-NJU/videomae-base") >>> model = TimesformerModel.from_pretrained("facebook/timesformer-base-finetuned-k400") >>> # prepare video for the model >>> inputs = image_processor(list(video), return_tensors="pt") >>> # forward pass >>> outputs = model(**inputs) >>> last_hidden_states = outputs.last_hidden_state >>> list(last_hidden_states.shape) [1, 1569, 768] ```""" output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) return_dict = return_dict if return_dict is not None else self.config.use_return_dict embedding_output = self.embeddings(pixel_values) encoder_outputs = self.encoder( embedding_output, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) sequence_output = encoder_outputs[0] if self.layernorm is not None: sequence_output = self.layernorm(sequence_output) if not return_dict: return (sequence_output,) + encoder_outputs[1:] return BaseModelOutput( last_hidden_state=sequence_output, hidden_states=encoder_outputs.hidden_states, attentions=encoder_outputs.attentions, ) @auto_docstring( custom_intro=""" TimeSformer Model transformer with a video classification head on top (a linear layer on top of the final hidden state of the [CLS] token) e.g. for ImageNet. """ )
TimesformerModel
python
langchain-ai__langchain
libs/langchain/langchain_classic/chains/router/base.py
{ "start": 414, "end": 544 }
class ____(NamedTuple): """A route to a destination chain.""" destination: str | None next_inputs: dict[str, Any]
Route
python
anthropics__anthropic-sdk-python
src/anthropic/types/beta/beta_web_search_tool_20250305_param.py
{ "start": 861, "end": 2117 }
class ____(TypedDict, total=False): name: Required[Literal["web_search"]] """Name of the tool. This is how the tool will be called by the model and in `tool_use` blocks. """ type: Required[Literal["web_search_20250305"]] allowed_callers: List[Literal["direct", "code_execution_20250825"]] allowed_domains: Optional[SequenceNotStr[str]] """If provided, only these domains will be included in results. Cannot be used alongside `blocked_domains`. """ blocked_domains: Optional[SequenceNotStr[str]] """If provided, these domains will never appear in results. Cannot be used alongside `allowed_domains`. """ cache_control: Optional[BetaCacheControlEphemeralParam] """Create a cache control breakpoint at this content block.""" defer_loading: bool """If true, tool will not be included in initial system prompt. Only loaded when returned via tool_reference from tool search. """ max_uses: Optional[int] """Maximum number of times the tool can be used in the API request.""" strict: bool user_location: Optional[UserLocation] """Parameters for the user's location. Used to provide more relevant search results. """
BetaWebSearchTool20250305Param
python
altair-viz__altair
altair/vegalite/v6/api.py
{ "start": 148040, "end": 160344 }
class ____( TopLevelMixin, _EncodingMixin, mixins.MarkMethodMixin, core.TopLevelUnitSpec ): """ Create a basic Altair/Vega-Lite chart. Although it is possible to set all Chart properties as constructor attributes, it is more idiomatic to use methods such as ``mark_point()``, ``encode()``, ``transform_filter()``, ``properties()``, etc. See Altair's documentation for details and examples: http://altair-viz.github.io/. Parameters ---------- data : Data An object describing the data source mark : AnyMark A `MarkDef` or `CompositeMarkDef` object, or a string describing the mark type (one of `"arc"`, `"area"`, `"bar"`, `"circle"`, `"geoshape"`, `"image"`, `"line"`, `"point"`, `"rule"`, `"rect"`, `"square"`, `"text"`, `"tick"`, `"trail"`, `"boxplot"`, `"errorband"`, and `"errorbar"`). encoding : FacetedEncoding A key-value mapping between encoding channels and definition of fields. autosize : anyOf(AutosizeType, AutoSizeParams) Sets how the visualization size should be determined. If a string, should be one of `"pad"`, `"fit"` or `"none"`. Object values can additionally specify parameters for content sizing and automatic resizing. `"fit"` is only supported for single and layered views that don't use `rangeStep`. Default value: `pad` background : string CSS color property to use as the background of visualization. **Default value:** none (transparent) config : Config Vega-Lite configuration object. This property can only be defined at the top-level of a specification. description : string Description of this mark for commenting purpose. height : float The height of a visualization. name : string Name of the visualization for later reference. padding : Padding The default visualization padding, in pixels, from the edge of the visualization canvas to the data rectangle. If a number, specifies padding for all sides. If an object, the value should have the format `{"left": 5, "top": 5, "right": 5, "bottom": 5}` to specify padding for each side of the visualization. Default value: `5` projection : Projection An object defining properties of geographic projection. Works with `"geoshape"` marks and `"point"` or `"line"` marks that have a channel (one or more of `"X"`, `"X2"`, `"Y"`, `"Y2"`) with type `"latitude"`, or `"longitude"`. selection : Mapping(required=[]) A key-value mapping between selection names and definitions. title : anyOf(string, TitleParams) Title for the plot. transform : List(Transform) An array of data transformations such as filter and new field calculation. width : float The width of a visualization. """ def __init__( self, data: Optional[ChartDataType] = Undefined, encoding: Optional[FacetedEncoding] = Undefined, mark: Optional[AnyMark | Mark_T | CompositeMark_T] = Undefined, width: Optional[float | dict | Step | Literal["container"]] = Undefined, height: Optional[float | dict | Step | Literal["container"]] = Undefined, **kwargs: Any, ) -> None: super().__init__( data=data, encoding=encoding, mark=mark, width=width, height=height, **kwargs, ) def _compute_hash(self) -> str: """Compute a deterministic hash of the chart specification.""" # Get data name if available, otherwise use data object data = getattr(self, "data", None) if data is not None and hasattr(data, "name") and data.name is not None: data_for_hash = data.name else: data_for_hash = data # Use basic chart attributes for hash computation. hash_data = { "class": self.__class__.__name__, "mark": getattr(self, "mark", None), "encoding": getattr(self, "encoding", None), "data": data_for_hash, "transform": getattr(self, "transform", None), } hash_json = json.dumps(hash_data, sort_keys=True, default=str) hsh = hashlib.sha256(hash_json.encode()).hexdigest()[:16] return f"view_{hsh}" def _get_view_hash_name(self) -> str: """Get a deterministic name based on the chart specification hash.""" return self._compute_hash() @classmethod def from_dict( cls: type[_TSchemaBase], dct: dict[str, Any], validate: bool = True ) -> _TSchemaBase: """ Construct a ``Chart`` from a dictionary representation. Parameters ---------- dct : dictionary The dict from which to construct the ``Chart``. validate : boolean If True (default), then validate the input against the schema. Raises ------ jsonschema.ValidationError : If ``validate`` and ``dct`` does not conform to the schema """ _tp: Any for tp in TopLevelMixin.__subclasses__(): _tp = super() if tp is Chart else tp try: return _tp.from_dict(dct, validate=validate) except jsonschema.ValidationError: pass # As a last resort, try using the Root vegalite object return t.cast("_TSchemaBase", core.Root.from_dict(dct, validate)) def to_dict( self, validate: bool = True, *, format: Literal["vega-lite", "vega"] = "vega-lite", ignore: list[str] | None = None, context: dict[str, Any] | None = None, ) -> dict[str, Any]: """ Convert the ``Chart`` to a dictionary suitable for JSON export. Parameters ---------- validate : bool, optional If True (default), then validate the result against the schema. format : {"vega-lite", "vega"}, optional The chart specification format. The `"vega"` format relies on the active Vega-Lite compiler plugin, which by default requires the vl-convert-python package. ignore : list[str], optional A list of keys to ignore. context : dict[str, Any], optional A context dictionary. Raises ------ SchemaValidationError : If ``validate`` and the result does not conform to the schema. Notes ----- - ``ignore``, ``context`` are usually not needed to be specified as a user. - *Technical*: ``ignore`` will **not** be passed to child :meth:`.to_dict()`. """ context = context or {} kwds: Map = {"validate": validate, "format": format, "ignore": ignore, "context": context} # fmt: skip if self.data is Undefined and "data" not in context: # No data specified here or in parent: inject empty data # for easier specification of datum encodings. copy = self.copy(deep=False) copy.data = core.InlineData(values=[{}]) return super(Chart, copy).to_dict(**kwds) return super().to_dict(**kwds) def transformed_data( self, row_limit: int | None = None, exclude: Iterable[str] | None = None ) -> DataFrameLike | None: """ Evaluate a Chart's transforms. Evaluate the data transforms associated with a Chart and return the transformed data a DataFrame Parameters ---------- row_limit : int (optional) Maximum number of rows to return for each DataFrame. None (default) for unlimited exclude : iterable of str Set of the names of charts to exclude Returns ------- DataFrame Transformed data as a DataFrame """ from altair.utils._transformed_data import transformed_data return transformed_data(self, row_limit=row_limit, exclude=exclude) def add_params(self, *params: Parameter) -> Self: """Add one or more parameters to the chart.""" if not params: return self copy = self.copy(deep=["params"]) if copy.params is Undefined: copy.params = [] # Track existing parameter names existing_names = {param.name for param in copy.params} for param in params: if param.name in existing_names: if param._name_is_hashed: continue # deduplicate hash-based else: # If we see a duplicate explicit name, raise msg = f"Duplicate explicit parameter name: {param.name}" raise ValueError(msg) copy.params.append(param.param) existing_names.add(param.name) return copy @utils.deprecated(version="5.0.0", alternative="add_params") def add_selection(self, *params) -> Self: # noqa: ANN002 """'add_selection' is deprecated. Use 'add_params' instead.""" return self.add_params(*params) def interactive( self, name: str | None = None, bind_x: bool = True, bind_y: bool = True ) -> Self: """ Make chart axes scales interactive. Parameters ---------- name : string The parameter name to use for the axes scales. This name should be unique among all parameters within the chart. bind_x : boolean, default True If true, then bind the interactive scales to the x-axis bind_y : boolean, default True If true, then bind the interactive scales to the y-axis Returns ------- chart : copy of self, with interactive axes added """ encodings: list[SingleDefUnitChannel_T] = [] if bind_x: encodings.append("x") if bind_y: encodings.append("y") return self.add_params( selection_interval(name=name, bind="scales", encodings=encodings) ) def _check_if_valid_subspec( spec: ConcatType | LayerType, classname: Literal[ "ConcatChart", "FacetChart", "HConcatChart", "LayerChart", "RepeatChart", "VConcatChart", ], ) -> None: """Raise a `TypeError` if `spec` is not a valid sub-spec.""" if not isinstance(spec, SchemaBase): msg = f"Only chart objects can be used in {classname}." raise TypeError(msg) for attr in TOPLEVEL_ONLY_KEYS: if spec._get(attr) is not Undefined: msg = ( f"Objects with {attr!r} attribute cannot be used within {classname}. " f"Consider defining the {attr} attribute in the {classname} object instead." ) raise TypeError(msg) def _check_if_can_be_layered(spec: LayerType) -> None: """Raise a `TypeError` if `spec` cannot be layered.""" def _get_any(spec: LayerType, *attrs: str) -> bool: return any(spec._get(attr) is not Undefined for attr in attrs) base_msg = "charts cannot be layered. Instead, layer the charts before" encoding: Any = spec._get("encoding") if not utils.is_undefined(encoding): for channel in ["row", "column", "facet"]: if encoding._get(channel) is not Undefined: msg = f"Faceted {base_msg} faceting." raise TypeError(msg) if isinstance(spec, (Chart, LayerChart)): return elif is_chart_type(spec) or _get_any( spec, "facet", "repeat", "concat", "hconcat", "vconcat" ): if isinstance(spec, FacetChart) or spec._get("facet") is not Undefined: msg = f"Faceted {base_msg} faceting." elif isinstance(spec, RepeatChart) or spec._get("repeat") is not Undefined: msg = f"Repeat {base_msg} repeating." elif isinstance(spec, (ConcatChart, HConcatChart, VConcatChart)) or _get_any( spec, "concat", "hconcat", "vconcat" ): msg = f"Concatenated {base_msg} concatenating." else: msg = "Should be unreachable" raise NotImplementedError(msg) raise TypeError(msg)
Chart
python
django__django
tests/decorators/test_clickjacking.py
{ "start": 2654, "end": 4567 }
class ____(SimpleTestCase): def test_wrapped_sync_function_is_not_coroutine_function(self): def sync_view(request): return HttpResponse() wrapped_view = xframe_options_exempt(sync_view) self.assertIs(iscoroutinefunction(wrapped_view), False) def test_wrapped_async_function_is_coroutine_function(self): async def async_view(request): return HttpResponse() wrapped_view = xframe_options_exempt(async_view) self.assertIs(iscoroutinefunction(wrapped_view), True) def test_decorator_stops_x_frame_options_being_set(self): """ @xframe_options_exempt instructs the XFrameOptionsMiddleware to NOT set the header. """ @xframe_options_exempt def a_view(request): return HttpResponse() request = HttpRequest() response = a_view(request) self.assertIsNone(response.get("X-Frame-Options", None)) self.assertIs(response.xframe_options_exempt, True) # The real purpose of the exempt decorator is to suppress the # middleware's functionality. middleware_response = XFrameOptionsMiddleware(a_view)(request) self.assertIsNone(middleware_response.get("X-Frame-Options")) async def test_exempt_decorator_async_view(self): @xframe_options_exempt async def an_async_view(request): return HttpResponse() request = HttpRequest() response = await an_async_view(request) self.assertIsNone(response.get("X-Frame-Options")) self.assertIs(response.xframe_options_exempt, True) # The real purpose of the exempt decorator is to suppress the # middleware's functionality. middleware_response = await XFrameOptionsMiddleware(an_async_view)(request) self.assertIsNone(middleware_response.get("X-Frame-Options"))
XFrameOptionsExemptTests
python
altair-viz__altair
altair/vegalite/v6/schema/channels.py
{ "start": 370565, "end": 377148 }
class ____(DatumChannelMixin, core.DatumDef): """ Longitude2Datum schema wrapper. Parameters ---------- bandPosition : float Relative position on a band of a stacked, binned, time unit, or band scale. For example, the marks will be positioned at the beginning of the band if set to ``0``, and at the middle of the band if set to ``0.5``. datum : str, bool, dict, float, :class:`ExprRef`, :class:`DateTime`, :class:`RepeatRef`, :class:`PrimitiveValue`, None A constant value in data domain. title : str, :class:`Text`, Sequence[str], None A title for the field. If ``null``, the title will be removed. **Default value:** derived from the field's name and transformation function (``aggregate``, ``bin`` and ``timeUnit``). If the field has an aggregate function, the function is displayed as part of the title (e.g., ``"Sum of Profit"``). If the field is binned or has a time unit applied, the applied function is shown in parentheses (e.g., ``"Profit (binned)"``, ``"Transaction Date (year-month)"``). Otherwise, the title is simply the field name. **Notes**: 1) You can customize the default field title format by providing the `fieldTitle <https://vega.github.io/vega-lite/docs/config.html#top-level-config>`__ property in the `config <https://vega.github.io/vega-lite/docs/config.html>`__ or `fieldTitle function via the compile function's options <https://vega.github.io/vega-lite/usage/compile.html#field-title>`__. 2) If both field definition's ``title`` and axis, header, or legend ``title`` are defined, axis/header/legend title will be used. type : :class:`Type`, Literal['quantitative', 'ordinal', 'temporal', 'nominal', 'geojson'] The type of measurement (``"quantitative"``, ``"temporal"``, ``"ordinal"``, or ``"nominal"``) for the encoded field or constant value (``datum``). It can also be a ``"geojson"`` type for encoding `'geoshape' <https://vega.github.io/vega-lite/docs/geoshape.html>`__. Vega-Lite automatically infers data types in many cases as discussed below. However, type is required for a field if: (1) the field is not nominal and the field encoding has no specified ``aggregate`` (except ``argmin`` and ``argmax``), ``bin``, scale type, custom ``sort`` order, nor ``timeUnit`` or (2) if you wish to use an ordinal scale for a field with ``bin`` or ``timeUnit``. **Default value:** 1) For a data ``field``, ``"nominal"`` is the default data type unless the field encoding has ``aggregate``, ``channel``, ``bin``, scale type, ``sort``, or ``timeUnit`` that satisfies the following criteria: * ``"quantitative"`` is the default type if (1) the encoded field contains ``bin`` or ``aggregate`` except ``"argmin"`` and ``"argmax"``, (2) the encoding channel is ``latitude`` or ``longitude`` channel or (3) if the specified scale type is `a quantitative scale <https://vega.github.io/vega-lite/docs/scale.html#type>`__. * ``"temporal"`` is the default type if (1) the encoded field contains ``timeUnit`` or (2) the specified scale type is a time or utc scale * ``"ordinal"`` is the default type if (1) the encoded field contains a `custom sort order <https://vega.github.io/vega-lite/docs/sort.html#specifying-custom-sort-order>`__, (2) the specified scale type is an ordinal/point/band scale, or (3) the encoding channel is ``order``. 2) For a constant value in data domain (``datum``): * ``"quantitative"`` if the datum is a number * ``"nominal"`` if the datum is a string * ``"temporal"`` if the datum is `a date time object <https://vega.github.io/vega-lite/docs/datetime.html>`__ **Note:** * Data ``type`` describes the semantics of the data rather than the primitive data types (number, string, etc.). The same primitive data type can have different types of measurement. For example, numeric data can represent quantitative, ordinal, or nominal data. * Data values for a temporal field can be either a date-time string (e.g., ``"2015-03-07 12:32:17"``, ``"17:01"``, ``"2015-03-16"``. ``"2015"``) or a timestamp number (e.g., ``1552199579097``). * When using with `bin <https://vega.github.io/vega-lite/docs/bin.html>`__, the ``type`` property can be either ``"quantitative"`` (for using a linear bin scale) or `"ordinal" (for using an ordinal bin scale) <https://vega.github.io/vega-lite/docs/type.html#cast-bin>`__. * When using with `timeUnit <https://vega.github.io/vega-lite/docs/timeunit.html>`__, the ``type`` property can be either ``"temporal"`` (default, for using a temporal scale) or `"ordinal" (for using an ordinal scale) <https://vega.github.io/vega-lite/docs/type.html#cast-bin>`__. * When using with `aggregate <https://vega.github.io/vega-lite/docs/aggregate.html>`__, the ``type`` property refers to the post-aggregation data type. For example, we can calculate count ``distinct`` of a categorical field ``"cat"`` using ``{"aggregate": "distinct", "field": "cat"}``. The ``"type"`` of the aggregate output is ``"quantitative"``. * Secondary channels (e.g., ``x2``, ``y2``, ``xError``, ``yError``) do not have ``type`` as they must have exactly the same type as their primary channels (e.g., ``x``, ``y``). **See also:** `type <https://vega.github.io/vega-lite/docs/type.html>`__ documentation. """ _class_is_valid_at_instantiation = False _encoding_name = "longitude2" @overload def bandPosition(self, _: float, /) -> Longitude2Datum: ... @overload def title(self, _: str | Sequence[str] | None, /) -> Longitude2Datum: ... @overload def type(self, _: Type_T, /) -> Longitude2Datum: ... def __init__( self, datum, bandPosition: Optional[float] = Undefined, title: Optional[str | SchemaBase | Sequence[str] | None] = Undefined, type: Optional[SchemaBase | Type_T] = Undefined, **kwds, ): super().__init__( datum=datum, bandPosition=bandPosition, title=title, type=type, **kwds ) @with_property_setters
Longitude2Datum
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/operators/sagemaker.py
{ "start": 18288, "end": 20567 }
class ____(SageMakerBaseOperator): """ Creates an endpoint configuration that Amazon SageMaker hosting services uses to deploy models. In the configuration, you identify one or more models, created using the CreateModel API, to deploy and the resources that you want Amazon SageMaker to provision. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:SageMakerEndpointConfigOperator` :param config: The configuration necessary to create an endpoint config. For details of the configuration parameter see :py:meth:`SageMaker.Client.create_endpoint_config` :param aws_conn_id: The Airflow connection used for AWS credentials. If this is ``None`` or empty then the default boto3 behaviour is used. If running Airflow in a distributed manner and aws_conn_id is None or empty, then default boto3 configuration would be used (and must be maintained on each worker node). :param region_name: AWS region_name. If not specified then the default boto3 behaviour is used. :param verify: Whether or not to verify SSL certificates. See: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/core/session.html :return Dict: Returns The ARN of the endpoint config created in Amazon SageMaker. """ def __init__( self, *, config: dict, **kwargs, ): super().__init__(config=config, **kwargs) def _create_integer_fields(self) -> None: """Set fields which should be cast to integers.""" self.integer_fields: list[list[str]] = [["ProductionVariants", "InitialInstanceCount"]] def execute(self, context: Context) -> dict: self.preprocess_config() self.log.info("Creating SageMaker Endpoint Config %s.", self.config["EndpointConfigName"]) response = self.hook.create_endpoint_config(self.config) if response["ResponseMetadata"]["HTTPStatusCode"] != 200: raise AirflowException(f"Sagemaker endpoint config creation failed: {response}") return { "EndpointConfig": serialize(self.hook.describe_endpoint_config(self.config["EndpointConfigName"])) }
SageMakerEndpointConfigOperator
python
python-markdown__markdown
markdown/extensions/legacy_em.py
{ "start": 1294, "end": 1693 }
class ____(Extension): """ Add legacy_em extension to Markdown class.""" def extendMarkdown(self, md): """ Modify inline patterns. """ md.inlinePatterns.register(LegacyUnderscoreProcessor(r'_'), 'em_strong2', 50) def makeExtension(**kwargs): # pragma: no cover """ Return an instance of the `LegacyEmExtension` """ return LegacyEmExtension(**kwargs)
LegacyEmExtension
python
numpy__numpy
numpy/_core/tests/test_multiarray.py
{ "start": 388795, "end": 389422 }
class ____: @pytest.mark.parametrize("cls", [np.datetime64, np.timedelta64]) def test_dt_tuple(self, cls): # two valid uses - (unit, num) and (unit, num, den, None) cls(1, ('ms', 2)) cls(1, ('ms', 2, 1, None)) # trying to use the event argument, removed in 1.7.0 # it used to be a uint8 assert_raises(TypeError, cls, args=(1, ('ms', 2, 'event'))) assert_raises(TypeError, cls, args=(1, ('ms', 2, 63))) assert_raises(TypeError, cls, args=(1, ('ms', 2, 1, 'event'))) assert_raises(TypeError, cls, args=(1, ('ms', 2, 1, 63)))
TestDateTimeCreationTuple
python
lazyprogrammer__machine_learning_examples
ann_class2/theano_ann.py
{ "start": 630, "end": 1087 }
class ____(object): def __init__(self, M1, M2, f): self.M1 = M1 self.M2 = M2 self.f = f W = init_weight(M1, M2) b = np.zeros(M2) self.W = theano.shared(W) self.b = theano.shared(b) self.params = [self.W, self.b] def forward(self, X): if self.f == T.nnet.relu: return self.f(X.dot(self.W) + self.b, alpha=0.1) return self.f(X.dot(self.W) + self.b)
HiddenLayer
python
Textualize__textual
tests/snapshot_tests/snapshot_apps/pretty_grid_gutter_interaction.py
{ "start": 247, "end": 320 }
class ____(Grid): """A simple grid with 2 columns and 2 rows."""
MyGrid
python
weaviate__weaviate-python-client
weaviate/rbac/models.py
{ "start": 10099, "end": 10157 }
class ____(_RolesPermission): pass
RolesPermissionOutput
python
mkdocstrings__mkdocstrings
src/mkdocstrings/_internal/inventory.py
{ "start": 2856, "end": 5901 }
class ____(dict): """Inventory of collected and rendered objects.""" def __init__(self, items: list[InventoryItem] | None = None, project: str = "project", version: str = "0.0.0"): """Initialize the object. Arguments: items: A list of items. project: The project name. version: The project version. """ super().__init__() items = items or [] for item in items: self[item.name] = item self.project = project """The project name.""" self.version = version """The project version.""" def register( self, name: str, domain: str, role: str, uri: str, priority: int = 1, dispname: str | None = None, ) -> None: """Create and register an item. Arguments: name: The item name. domain: The item domain, like 'python' or 'crystal'. role: The item role, like 'class' or 'method'. uri: The item URI. priority: The item priority. Only used internally by mkdocstrings and Sphinx. dispname: The item display name. """ self[name] = InventoryItem( name=name, domain=domain, role=role, uri=uri, priority=priority, dispname=dispname, ) def format_sphinx(self) -> bytes: """Format this inventory as a Sphinx `objects.inv` file. Returns: The inventory as bytes. """ header = ( dedent( f""" # Sphinx inventory version 2 # Project: {self.project} # Version: {self.version} # The remainder of this file is compressed using zlib. """, ) .lstrip() .encode("utf8") ) lines = [ item.format_sphinx().encode("utf8") for item in sorted(self.values(), key=lambda item: (item.domain, item.name)) ] return header + zlib.compress(b"\n".join(lines) + b"\n", 9) @classmethod def parse_sphinx(cls, in_file: BinaryIO, *, domain_filter: Collection[str] = ()) -> Inventory: """Parse a Sphinx v2 inventory file and return an `Inventory` from it. Arguments: in_file: The binary file-like object to read from. domain_filter: A collection of domain values to allow (and filter out all other ones). Returns: An inventory containing the collected items. """ for _ in range(4): in_file.readline() lines = zlib.decompress(in_file.read()).splitlines() items: list[InventoryItem] = [ item for line in lines if (item := InventoryItem.parse_sphinx(line.decode("utf8"), return_none=True)) ] if domain_filter: items = [item for item in items if item.domain in domain_filter] return cls(items)
Inventory
python
ansible__ansible
test/lib/ansible_test/_internal/containers.py
{ "start": 1674, "end": 10541 }
class ____: """Enum representing the types of hosts involved in running tests.""" origin = 'origin' control = 'control' managed = 'managed' def run_support_container( args: EnvironmentConfig, context: str, image: str, name: str, ports: list[int], aliases: t.Optional[list[str]] = None, start: bool = True, cleanup: bool = True, cmd: t.Optional[list[str]] = None, env: t.Optional[dict[str, str]] = None, options: t.Optional[list[str]] = None, publish_ports: bool = True, ) -> t.Optional[ContainerDescriptor]: """ Start a container used to support tests, but not run them. Containers created this way will be accessible from tests. """ name = get_session_container_name(args, name) if args.prime_containers: docker_pull(args, image) return None # SSH is required for publishing ports, as well as modifying the hosts file. # Initializing the SSH key here makes sure it is available for use after delegation. SshKey(args) aliases = aliases or [sanitize_host_name(name)] docker_command = require_docker().command current_container_id = get_docker_container_id() if docker_command == 'docker': if isinstance(args.controller, DockerConfig) and all(isinstance(target, (ControllerConfig, DockerConfig)) for target in args.targets): publish_ports = False # publishing ports is not needed when test hosts are on the docker network if current_container_id: publish_ports = False # publishing ports is pointless if already running in a docker container options = options or [] if start: options.append('-dt') # the -t option is required to cause systemd in the container to log output to the console if publish_ports: for port in ports: options.extend(['-p', str(port)]) if env: for key, value in env.items(): options.extend(['--env', '%s=%s' % (key, value)]) max_open_files = detect_host_properties(args).max_open_files options.extend(['--ulimit', 'nofile=%s' % max_open_files]) if args.dev_systemd_debug: options.extend(('--env', 'SYSTEMD_LOG_LEVEL=debug')) display.info('Starting new "%s" container.' % name) docker_pull(args, image) support_container_id = run_container(args, image, name, options, create_only=not start, cmd=cmd) running = start descriptor = ContainerDescriptor( image, context, name, support_container_id, ports, aliases, publish_ports, running, cleanup, env, ) with support_containers_mutex: if name in support_containers: raise Exception(f'Container already defined: {name}') if not support_containers: ExitHandler.register(cleanup_containers, args) support_containers[name] = descriptor display.info(f'Adding "{name}" to container database.') if start: descriptor.register(args) return descriptor def run_container( args: EnvironmentConfig, image: str, name: str, options: t.Optional[list[str]], cmd: t.Optional[list[str]] = None, create_only: bool = False, ) -> str: """Run a container using the given docker image.""" options = list(options or []) cmd = list(cmd or []) options.extend(['--name', name]) network = get_docker_preferred_network_name(args) if is_docker_user_defined_network(network): # Only when the network is not the default bridge network. options.extend(['--network', network]) for _iteration in range(1, 3): try: if create_only: stdout = docker_create(args, image, options, cmd)[0] else: stdout = docker_run(args, image, options, cmd)[0] except SubprocessError as ex: display.error(ex.message) display.warning(f'Failed to run docker image "{image}". Waiting a few seconds before trying again.') docker_rm(args, name) # podman doesn't remove containers after create if run fails time.sleep(3) else: if args.explain: stdout = ''.join(random.choice('0123456789abcdef') for _iteration in range(64)) return stdout.strip() raise ApplicationError(f'Failed to run docker image "{image}".') def start_container(args: EnvironmentConfig, container_id: str) -> tuple[t.Optional[str], t.Optional[str]]: """Start a docker container by name or ID.""" options: list[str] = [] for _iteration in range(1, 3): try: return docker_start(args, container_id, options) except SubprocessError as ex: display.error(ex.message) display.warning(f'Failed to start docker container "{container_id}". Waiting a few seconds before trying again.') time.sleep(3) raise ApplicationError(f'Failed to start docker container "{container_id}".') def get_container_ip_address(args: EnvironmentConfig, container: DockerInspect) -> t.Optional[str]: """Return the IP address of the container for the preferred docker network.""" if container.networks: network_name = get_docker_preferred_network_name(args) if not network_name: # Sort networks and use the first available. # This assumes all containers will have access to the same networks. network_name = sorted(container.networks.keys()).pop(0) ipaddress = container.networks[network_name]['IPAddress'] else: ipaddress = container.network_settings['IPAddress'] if not ipaddress: return None return ipaddress @mutex def get_docker_preferred_network_name(args: EnvironmentConfig) -> t.Optional[str]: """ Return the preferred network name for use with Docker. The selection logic is: - the network selected by the user with `--docker-network` - the network of the currently running docker container (if any) - the default docker network (returns None) """ try: return get_docker_preferred_network_name.network # type: ignore[attr-defined] except AttributeError: pass network = None if args.docker_network: network = args.docker_network else: current_container_id = get_docker_container_id() if current_container_id: try: # Make sure any additional containers we launch use the same network as the current container we're running in. # This is needed when ansible-test is running in a container that is not connected to Docker's default network. container = docker_inspect(args, current_container_id, always=True) network = container.get_network_name() except ContainerNotFoundError: display.warning('Unable to detect the network for the current container. Use the `--docker-network` option if containers are unreachable.') # The default docker behavior puts containers on the same network. # The default podman behavior puts containers on isolated networks which don't allow communication between containers or network disconnect. # Starting with podman version 2.1.0 rootless containers are able to join networks. # Starting with podman version 2.2.0 containers can be disconnected from networks. # To maintain feature parity with docker, detect and use the default "podman" network when running under podman. if network is None and require_docker().command == 'podman' and docker_network_inspect(args, 'podman', always=True): network = 'podman' get_docker_preferred_network_name.network = network # type: ignore[attr-defined] return network def is_docker_user_defined_network(network: str) -> bool: """Return True if the network being used is a user-defined network.""" return bool(network) and network != 'bridge' @mutex def get_container_database(args: EnvironmentConfig) -> ContainerDatabase: """Return the current container database, creating it as needed, or returning the one provided on the command line through delegation.""" try: return get_container_database.database # type: ignore[attr-defined] except AttributeError: pass if args.containers: display.info('Parsing container database.', verbosity=1) database = ContainerDatabase.from_dict(json.loads(args.containers)) else: display.info('Creating container database.', verbosity=1) database = create_container_database(args) display.info('>>> Container Database\n%s' % json.dumps(database.to_dict(), indent=4, sort_keys=True), verbosity=3) get_container_database.database = database # type: ignore[attr-defined] return database
HostType
python
realpython__materials
python-maze-solver/source_code_step_3/src/maze_solver/view/primitives.py
{ "start": 1129, "end": 1287 }
class ____(tuple[Line, ...]): def draw(self, **attributes) -> str: return "".join(line.draw(**attributes) for line in self) @dataclass
DisjointLines
python
boto__boto3
boto3/s3/transfer.py
{ "start": 18581, "end": 18998 }
class ____(BaseSubscriber): """A back-compat wrapper to invoke a provided callback via a subscriber :param callback: A callable that takes a single positional argument for how many bytes were transferred. """ def __init__(self, callback): self._callback = callback def on_progress(self, bytes_transferred, **kwargs): self._callback(bytes_transferred)
ProgressCallbackInvoker
python
astropy__astropy
astropy/io/ascii/core.py
{ "start": 7193, "end": 7383 }
class ____: """ Superclass for ``StrType`` and ``NumType`` classes. This class is the default type of ``Column`` and provides a base class for other data types. """
NoType
python
run-llama__llama_index
llama-index-integrations/embeddings/llama-index-embeddings-instructor/llama_index/embeddings/instructor/base.py
{ "start": 468, "end": 3383 }
class ____(BaseEmbedding): query_instruction: Optional[str] = Field( description="Instruction to prepend to query text." ) text_instruction: Optional[str] = Field( description="Instruction to prepend to text." ) cache_folder: Optional[str] = Field( description="Cache folder for huggingface files." ) _model: Any = PrivateAttr() def __init__( self, model_name: str = DEFAULT_INSTRUCT_MODEL, query_instruction: Optional[str] = None, text_instruction: Optional[str] = None, embed_batch_size: int = DEFAULT_EMBED_BATCH_SIZE, cache_folder: Optional[str] = None, device: Optional[str] = None, callback_manager: Optional[CallbackManager] = None, ): super().__init__( embed_batch_size=embed_batch_size, callback_manager=callback_manager, model_name=model_name, query_instruction=query_instruction, text_instruction=text_instruction, cache_folder=cache_folder, ) self._model = INSTRUCTOR(model_name, cache_folder=cache_folder, device=device) @classmethod def class_name(cls) -> str: return "InstructorEmbedding" def _format_query_text(self, query_text: str) -> List[str]: """Format query text.""" instruction = self.query_instruction if instruction is None: instruction = get_query_instruct_for_model_name(self.model_name) return [instruction, query_text] def _format_text(self, text: str) -> List[str]: """Format text.""" instruction = self.text_instruction if instruction is None: instruction = get_text_instruct_for_model_name(self.model_name) return [instruction, text] def _embed(self, instruct_sentence_pairs: List[List[str]]) -> List[List[float]]: """Embed sentences.""" return self._model.encode(instruct_sentence_pairs).tolist() def _get_query_embedding(self, query: str) -> List[float]: """Get query embedding.""" query_pair = self._format_query_text(query) return self._embed([query_pair])[0] async def _aget_query_embedding(self, query: str) -> List[float]: """Get query embedding async.""" return self._get_query_embedding(query) async def _aget_text_embedding(self, text: str) -> List[float]: """Get text embedding async.""" return self._get_text_embedding(text) def _get_text_embedding(self, text: str) -> List[float]: """Get text embedding.""" text_pair = self._format_text(text) return self._embed([text_pair])[0] def _get_text_embeddings(self, texts: List[str]) -> List[List[float]]: """Get text embeddings.""" text_pairs = [self._format_text(text) for text in texts] return self._embed(text_pairs)
InstructorEmbedding
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 260990, "end": 261662 }
class ____(sgqlc.types.relay.Connection): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("edges", "nodes", "page_info", "total_count") edges = sgqlc.types.Field( sgqlc.types.list_of("CreatedIssueContributionEdge"), graphql_name="edges" ) nodes = sgqlc.types.Field( sgqlc.types.list_of("CreatedIssueContribution"), graphql_name="nodes" ) page_info = sgqlc.types.Field( sgqlc.types.non_null("PageInfo"), graphql_name="pageInfo" ) total_count = sgqlc.types.Field( sgqlc.types.non_null(Int), graphql_name="totalCount" )
CreatedIssueContributionConnection
python
kubernetes-client__python
kubernetes/client/api/networking_v1_api.py
{ "start": 543, "end": 564884 }
class ____(object): """NOTE: This class is auto generated by OpenAPI Generator Ref: https://openapi-generator.tech Do not edit the class manually. """ def __init__(self, api_client=None): if api_client is None: api_client = ApiClient() self.api_client = api_client def create_ingress_class(self, body, **kwargs): # noqa: E501 """create_ingress_class # noqa: E501 create an IngressClass # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.create_ingress_class(body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param V1IngressClass body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1IngressClass If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.create_ingress_class_with_http_info(body, **kwargs) # noqa: E501 def create_ingress_class_with_http_info(self, body, **kwargs): # noqa: E501 """create_ingress_class # noqa: E501 create an IngressClass # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.create_ingress_class_with_http_info(body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param V1IngressClass body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1IngressClass, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'body', 'pretty', 'dry_run', 'field_manager', 'field_validation' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method create_ingress_class" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'body' is set if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501 local_var_params['body'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `body` when calling `create_ingress_class`") # noqa: E501 collection_formats = {} path_params = {} query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501 query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501 if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501 query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/networking.k8s.io/v1/ingressclasses', 'POST', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1IngressClass', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def create_ip_address(self, body, **kwargs): # noqa: E501 """create_ip_address # noqa: E501 create an IPAddress # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.create_ip_address(body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param V1IPAddress body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1IPAddress If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.create_ip_address_with_http_info(body, **kwargs) # noqa: E501 def create_ip_address_with_http_info(self, body, **kwargs): # noqa: E501 """create_ip_address # noqa: E501 create an IPAddress # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.create_ip_address_with_http_info(body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param V1IPAddress body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1IPAddress, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'body', 'pretty', 'dry_run', 'field_manager', 'field_validation' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method create_ip_address" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'body' is set if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501 local_var_params['body'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `body` when calling `create_ip_address`") # noqa: E501 collection_formats = {} path_params = {} query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501 query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501 if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501 query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/networking.k8s.io/v1/ipaddresses', 'POST', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1IPAddress', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def create_namespaced_ingress(self, namespace, body, **kwargs): # noqa: E501 """create_namespaced_ingress # noqa: E501 create an Ingress # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.create_namespaced_ingress(namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str namespace: object name and auth scope, such as for teams and projects (required) :param V1Ingress body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1Ingress If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.create_namespaced_ingress_with_http_info(namespace, body, **kwargs) # noqa: E501 def create_namespaced_ingress_with_http_info(self, namespace, body, **kwargs): # noqa: E501 """create_namespaced_ingress # noqa: E501 create an Ingress # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.create_namespaced_ingress_with_http_info(namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str namespace: object name and auth scope, such as for teams and projects (required) :param V1Ingress body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1Ingress, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'namespace', 'body', 'pretty', 'dry_run', 'field_manager', 'field_validation' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method create_namespaced_ingress" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `create_namespaced_ingress`") # noqa: E501 # verify the required parameter 'body' is set if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501 local_var_params['body'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `body` when calling `create_namespaced_ingress`") # noqa: E501 collection_formats = {} path_params = {} if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501 query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501 if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501 query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/networking.k8s.io/v1/namespaces/{namespace}/ingresses', 'POST', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1Ingress', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def create_namespaced_network_policy(self, namespace, body, **kwargs): # noqa: E501 """create_namespaced_network_policy # noqa: E501 create a NetworkPolicy # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.create_namespaced_network_policy(namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str namespace: object name and auth scope, such as for teams and projects (required) :param V1NetworkPolicy body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1NetworkPolicy If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.create_namespaced_network_policy_with_http_info(namespace, body, **kwargs) # noqa: E501 def create_namespaced_network_policy_with_http_info(self, namespace, body, **kwargs): # noqa: E501 """create_namespaced_network_policy # noqa: E501 create a NetworkPolicy # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.create_namespaced_network_policy_with_http_info(namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str namespace: object name and auth scope, such as for teams and projects (required) :param V1NetworkPolicy body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1NetworkPolicy, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'namespace', 'body', 'pretty', 'dry_run', 'field_manager', 'field_validation' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method create_namespaced_network_policy" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `create_namespaced_network_policy`") # noqa: E501 # verify the required parameter 'body' is set if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501 local_var_params['body'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `body` when calling `create_namespaced_network_policy`") # noqa: E501 collection_formats = {} path_params = {} if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501 query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501 if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501 query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/networking.k8s.io/v1/namespaces/{namespace}/networkpolicies', 'POST', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1NetworkPolicy', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def create_service_cidr(self, body, **kwargs): # noqa: E501 """create_service_cidr # noqa: E501 create a ServiceCIDR # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.create_service_cidr(body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param V1ServiceCIDR body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1ServiceCIDR If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.create_service_cidr_with_http_info(body, **kwargs) # noqa: E501 def create_service_cidr_with_http_info(self, body, **kwargs): # noqa: E501 """create_service_cidr # noqa: E501 create a ServiceCIDR # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.create_service_cidr_with_http_info(body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param V1ServiceCIDR body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1ServiceCIDR, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'body', 'pretty', 'dry_run', 'field_manager', 'field_validation' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method create_service_cidr" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'body' is set if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501 local_var_params['body'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `body` when calling `create_service_cidr`") # noqa: E501 collection_formats = {} path_params = {} query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501 query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501 if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501 query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/networking.k8s.io/v1/servicecidrs', 'POST', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1ServiceCIDR', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def delete_collection_ingress_class(self, **kwargs): # noqa: E501 """delete_collection_ingress_class # noqa: E501 delete collection of IngressClass # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_collection_ingress_class(async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. :param bool ignore_store_read_error_with_cluster_breaking_potential: if set to true, it will trigger an unsafe deletion of the resource in case the normal deletion flow fails with a corrupt object error. A resource is considered corrupt if it can not be retrieved from the underlying storage successfully because of a) its data can not be transformed e.g. decryption failure, or b) it fails to decode into an object. NOTE: unsafe deletion ignores finalizer constraints, skips precondition checks, and removes the object from the storage. WARNING: This may potentially break the cluster if the workload associated with the resource being unsafe-deleted relies on normal deletion flow. Use only if you REALLY know what you are doing. The default value is false, and the user must opt in to enable it :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. :param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. :param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param V1DeleteOptions body: :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1Status If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.delete_collection_ingress_class_with_http_info(**kwargs) # noqa: E501 def delete_collection_ingress_class_with_http_info(self, **kwargs): # noqa: E501 """delete_collection_ingress_class # noqa: E501 delete collection of IngressClass # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_collection_ingress_class_with_http_info(async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. :param bool ignore_store_read_error_with_cluster_breaking_potential: if set to true, it will trigger an unsafe deletion of the resource in case the normal deletion flow fails with a corrupt object error. A resource is considered corrupt if it can not be retrieved from the underlying storage successfully because of a) its data can not be transformed e.g. decryption failure, or b) it fails to decode into an object. NOTE: unsafe deletion ignores finalizer constraints, skips precondition checks, and removes the object from the storage. WARNING: This may potentially break the cluster if the workload associated with the resource being unsafe-deleted relies on normal deletion flow. Use only if you REALLY know what you are doing. The default value is false, and the user must opt in to enable it :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. :param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. :param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param V1DeleteOptions body: :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1Status, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'pretty', '_continue', 'dry_run', 'field_selector', 'grace_period_seconds', 'ignore_store_read_error_with_cluster_breaking_potential', 'label_selector', 'limit', 'orphan_dependents', 'propagation_policy', 'resource_version', 'resource_version_match', 'send_initial_events', 'timeout_seconds', 'body' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method delete_collection_ingress_class" % key ) local_var_params[key] = val del local_var_params['kwargs'] collection_formats = {} path_params = {} query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501 query_params.append(('continue', local_var_params['_continue'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501 query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501 if 'grace_period_seconds' in local_var_params and local_var_params['grace_period_seconds'] is not None: # noqa: E501 query_params.append(('gracePeriodSeconds', local_var_params['grace_period_seconds'])) # noqa: E501 if 'ignore_store_read_error_with_cluster_breaking_potential' in local_var_params and local_var_params['ignore_store_read_error_with_cluster_breaking_potential'] is not None: # noqa: E501 query_params.append(('ignoreStoreReadErrorWithClusterBreakingPotential', local_var_params['ignore_store_read_error_with_cluster_breaking_potential'])) # noqa: E501 if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501 query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501 if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501 query_params.append(('limit', local_var_params['limit'])) # noqa: E501 if 'orphan_dependents' in local_var_params and local_var_params['orphan_dependents'] is not None: # noqa: E501 query_params.append(('orphanDependents', local_var_params['orphan_dependents'])) # noqa: E501 if 'propagation_policy' in local_var_params and local_var_params['propagation_policy'] is not None: # noqa: E501 query_params.append(('propagationPolicy', local_var_params['propagation_policy'])) # noqa: E501 if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501 query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501 if 'resource_version_match' in local_var_params and local_var_params['resource_version_match'] is not None: # noqa: E501 query_params.append(('resourceVersionMatch', local_var_params['resource_version_match'])) # noqa: E501 if 'send_initial_events' in local_var_params and local_var_params['send_initial_events'] is not None: # noqa: E501 query_params.append(('sendInitialEvents', local_var_params['send_initial_events'])) # noqa: E501 if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501 query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/networking.k8s.io/v1/ingressclasses', 'DELETE', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1Status', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def delete_collection_ip_address(self, **kwargs): # noqa: E501 """delete_collection_ip_address # noqa: E501 delete collection of IPAddress # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_collection_ip_address(async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. :param bool ignore_store_read_error_with_cluster_breaking_potential: if set to true, it will trigger an unsafe deletion of the resource in case the normal deletion flow fails with a corrupt object error. A resource is considered corrupt if it can not be retrieved from the underlying storage successfully because of a) its data can not be transformed e.g. decryption failure, or b) it fails to decode into an object. NOTE: unsafe deletion ignores finalizer constraints, skips precondition checks, and removes the object from the storage. WARNING: This may potentially break the cluster if the workload associated with the resource being unsafe-deleted relies on normal deletion flow. Use only if you REALLY know what you are doing. The default value is false, and the user must opt in to enable it :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. :param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. :param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param V1DeleteOptions body: :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1Status If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.delete_collection_ip_address_with_http_info(**kwargs) # noqa: E501 def delete_collection_ip_address_with_http_info(self, **kwargs): # noqa: E501 """delete_collection_ip_address # noqa: E501 delete collection of IPAddress # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_collection_ip_address_with_http_info(async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. :param bool ignore_store_read_error_with_cluster_breaking_potential: if set to true, it will trigger an unsafe deletion of the resource in case the normal deletion flow fails with a corrupt object error. A resource is considered corrupt if it can not be retrieved from the underlying storage successfully because of a) its data can not be transformed e.g. decryption failure, or b) it fails to decode into an object. NOTE: unsafe deletion ignores finalizer constraints, skips precondition checks, and removes the object from the storage. WARNING: This may potentially break the cluster if the workload associated with the resource being unsafe-deleted relies on normal deletion flow. Use only if you REALLY know what you are doing. The default value is false, and the user must opt in to enable it :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. :param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. :param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param V1DeleteOptions body: :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1Status, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'pretty', '_continue', 'dry_run', 'field_selector', 'grace_period_seconds', 'ignore_store_read_error_with_cluster_breaking_potential', 'label_selector', 'limit', 'orphan_dependents', 'propagation_policy', 'resource_version', 'resource_version_match', 'send_initial_events', 'timeout_seconds', 'body' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method delete_collection_ip_address" % key ) local_var_params[key] = val del local_var_params['kwargs'] collection_formats = {} path_params = {} query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501 query_params.append(('continue', local_var_params['_continue'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501 query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501 if 'grace_period_seconds' in local_var_params and local_var_params['grace_period_seconds'] is not None: # noqa: E501 query_params.append(('gracePeriodSeconds', local_var_params['grace_period_seconds'])) # noqa: E501 if 'ignore_store_read_error_with_cluster_breaking_potential' in local_var_params and local_var_params['ignore_store_read_error_with_cluster_breaking_potential'] is not None: # noqa: E501 query_params.append(('ignoreStoreReadErrorWithClusterBreakingPotential', local_var_params['ignore_store_read_error_with_cluster_breaking_potential'])) # noqa: E501 if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501 query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501 if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501 query_params.append(('limit', local_var_params['limit'])) # noqa: E501 if 'orphan_dependents' in local_var_params and local_var_params['orphan_dependents'] is not None: # noqa: E501 query_params.append(('orphanDependents', local_var_params['orphan_dependents'])) # noqa: E501 if 'propagation_policy' in local_var_params and local_var_params['propagation_policy'] is not None: # noqa: E501 query_params.append(('propagationPolicy', local_var_params['propagation_policy'])) # noqa: E501 if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501 query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501 if 'resource_version_match' in local_var_params and local_var_params['resource_version_match'] is not None: # noqa: E501 query_params.append(('resourceVersionMatch', local_var_params['resource_version_match'])) # noqa: E501 if 'send_initial_events' in local_var_params and local_var_params['send_initial_events'] is not None: # noqa: E501 query_params.append(('sendInitialEvents', local_var_params['send_initial_events'])) # noqa: E501 if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501 query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/networking.k8s.io/v1/ipaddresses', 'DELETE', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1Status', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def delete_collection_namespaced_ingress(self, namespace, **kwargs): # noqa: E501 """delete_collection_namespaced_ingress # noqa: E501 delete collection of Ingress # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_collection_namespaced_ingress(namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. :param bool ignore_store_read_error_with_cluster_breaking_potential: if set to true, it will trigger an unsafe deletion of the resource in case the normal deletion flow fails with a corrupt object error. A resource is considered corrupt if it can not be retrieved from the underlying storage successfully because of a) its data can not be transformed e.g. decryption failure, or b) it fails to decode into an object. NOTE: unsafe deletion ignores finalizer constraints, skips precondition checks, and removes the object from the storage. WARNING: This may potentially break the cluster if the workload associated with the resource being unsafe-deleted relies on normal deletion flow. Use only if you REALLY know what you are doing. The default value is false, and the user must opt in to enable it :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. :param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. :param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param V1DeleteOptions body: :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1Status If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.delete_collection_namespaced_ingress_with_http_info(namespace, **kwargs) # noqa: E501 def delete_collection_namespaced_ingress_with_http_info(self, namespace, **kwargs): # noqa: E501 """delete_collection_namespaced_ingress # noqa: E501 delete collection of Ingress # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_collection_namespaced_ingress_with_http_info(namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. :param bool ignore_store_read_error_with_cluster_breaking_potential: if set to true, it will trigger an unsafe deletion of the resource in case the normal deletion flow fails with a corrupt object error. A resource is considered corrupt if it can not be retrieved from the underlying storage successfully because of a) its data can not be transformed e.g. decryption failure, or b) it fails to decode into an object. NOTE: unsafe deletion ignores finalizer constraints, skips precondition checks, and removes the object from the storage. WARNING: This may potentially break the cluster if the workload associated with the resource being unsafe-deleted relies on normal deletion flow. Use only if you REALLY know what you are doing. The default value is false, and the user must opt in to enable it :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. :param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. :param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param V1DeleteOptions body: :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1Status, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'namespace', 'pretty', '_continue', 'dry_run', 'field_selector', 'grace_period_seconds', 'ignore_store_read_error_with_cluster_breaking_potential', 'label_selector', 'limit', 'orphan_dependents', 'propagation_policy', 'resource_version', 'resource_version_match', 'send_initial_events', 'timeout_seconds', 'body' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method delete_collection_namespaced_ingress" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `delete_collection_namespaced_ingress`") # noqa: E501 collection_formats = {} path_params = {} if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501 query_params.append(('continue', local_var_params['_continue'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501 query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501 if 'grace_period_seconds' in local_var_params and local_var_params['grace_period_seconds'] is not None: # noqa: E501 query_params.append(('gracePeriodSeconds', local_var_params['grace_period_seconds'])) # noqa: E501 if 'ignore_store_read_error_with_cluster_breaking_potential' in local_var_params and local_var_params['ignore_store_read_error_with_cluster_breaking_potential'] is not None: # noqa: E501 query_params.append(('ignoreStoreReadErrorWithClusterBreakingPotential', local_var_params['ignore_store_read_error_with_cluster_breaking_potential'])) # noqa: E501 if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501 query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501 if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501 query_params.append(('limit', local_var_params['limit'])) # noqa: E501 if 'orphan_dependents' in local_var_params and local_var_params['orphan_dependents'] is not None: # noqa: E501 query_params.append(('orphanDependents', local_var_params['orphan_dependents'])) # noqa: E501 if 'propagation_policy' in local_var_params and local_var_params['propagation_policy'] is not None: # noqa: E501 query_params.append(('propagationPolicy', local_var_params['propagation_policy'])) # noqa: E501 if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501 query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501 if 'resource_version_match' in local_var_params and local_var_params['resource_version_match'] is not None: # noqa: E501 query_params.append(('resourceVersionMatch', local_var_params['resource_version_match'])) # noqa: E501 if 'send_initial_events' in local_var_params and local_var_params['send_initial_events'] is not None: # noqa: E501 query_params.append(('sendInitialEvents', local_var_params['send_initial_events'])) # noqa: E501 if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501 query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/networking.k8s.io/v1/namespaces/{namespace}/ingresses', 'DELETE', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1Status', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def delete_collection_namespaced_network_policy(self, namespace, **kwargs): # noqa: E501 """delete_collection_namespaced_network_policy # noqa: E501 delete collection of NetworkPolicy # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_collection_namespaced_network_policy(namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. :param bool ignore_store_read_error_with_cluster_breaking_potential: if set to true, it will trigger an unsafe deletion of the resource in case the normal deletion flow fails with a corrupt object error. A resource is considered corrupt if it can not be retrieved from the underlying storage successfully because of a) its data can not be transformed e.g. decryption failure, or b) it fails to decode into an object. NOTE: unsafe deletion ignores finalizer constraints, skips precondition checks, and removes the object from the storage. WARNING: This may potentially break the cluster if the workload associated with the resource being unsafe-deleted relies on normal deletion flow. Use only if you REALLY know what you are doing. The default value is false, and the user must opt in to enable it :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. :param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. :param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param V1DeleteOptions body: :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1Status If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.delete_collection_namespaced_network_policy_with_http_info(namespace, **kwargs) # noqa: E501 def delete_collection_namespaced_network_policy_with_http_info(self, namespace, **kwargs): # noqa: E501 """delete_collection_namespaced_network_policy # noqa: E501 delete collection of NetworkPolicy # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_collection_namespaced_network_policy_with_http_info(namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. :param bool ignore_store_read_error_with_cluster_breaking_potential: if set to true, it will trigger an unsafe deletion of the resource in case the normal deletion flow fails with a corrupt object error. A resource is considered corrupt if it can not be retrieved from the underlying storage successfully because of a) its data can not be transformed e.g. decryption failure, or b) it fails to decode into an object. NOTE: unsafe deletion ignores finalizer constraints, skips precondition checks, and removes the object from the storage. WARNING: This may potentially break the cluster if the workload associated with the resource being unsafe-deleted relies on normal deletion flow. Use only if you REALLY know what you are doing. The default value is false, and the user must opt in to enable it :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. :param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. :param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param V1DeleteOptions body: :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1Status, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'namespace', 'pretty', '_continue', 'dry_run', 'field_selector', 'grace_period_seconds', 'ignore_store_read_error_with_cluster_breaking_potential', 'label_selector', 'limit', 'orphan_dependents', 'propagation_policy', 'resource_version', 'resource_version_match', 'send_initial_events', 'timeout_seconds', 'body' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method delete_collection_namespaced_network_policy" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `delete_collection_namespaced_network_policy`") # noqa: E501 collection_formats = {} path_params = {} if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501 query_params.append(('continue', local_var_params['_continue'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501 query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501 if 'grace_period_seconds' in local_var_params and local_var_params['grace_period_seconds'] is not None: # noqa: E501 query_params.append(('gracePeriodSeconds', local_var_params['grace_period_seconds'])) # noqa: E501 if 'ignore_store_read_error_with_cluster_breaking_potential' in local_var_params and local_var_params['ignore_store_read_error_with_cluster_breaking_potential'] is not None: # noqa: E501 query_params.append(('ignoreStoreReadErrorWithClusterBreakingPotential', local_var_params['ignore_store_read_error_with_cluster_breaking_potential'])) # noqa: E501 if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501 query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501 if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501 query_params.append(('limit', local_var_params['limit'])) # noqa: E501 if 'orphan_dependents' in local_var_params and local_var_params['orphan_dependents'] is not None: # noqa: E501 query_params.append(('orphanDependents', local_var_params['orphan_dependents'])) # noqa: E501 if 'propagation_policy' in local_var_params and local_var_params['propagation_policy'] is not None: # noqa: E501 query_params.append(('propagationPolicy', local_var_params['propagation_policy'])) # noqa: E501 if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501 query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501 if 'resource_version_match' in local_var_params and local_var_params['resource_version_match'] is not None: # noqa: E501 query_params.append(('resourceVersionMatch', local_var_params['resource_version_match'])) # noqa: E501 if 'send_initial_events' in local_var_params and local_var_params['send_initial_events'] is not None: # noqa: E501 query_params.append(('sendInitialEvents', local_var_params['send_initial_events'])) # noqa: E501 if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501 query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/networking.k8s.io/v1/namespaces/{namespace}/networkpolicies', 'DELETE', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1Status', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def delete_collection_service_cidr(self, **kwargs): # noqa: E501 """delete_collection_service_cidr # noqa: E501 delete collection of ServiceCIDR # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_collection_service_cidr(async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. :param bool ignore_store_read_error_with_cluster_breaking_potential: if set to true, it will trigger an unsafe deletion of the resource in case the normal deletion flow fails with a corrupt object error. A resource is considered corrupt if it can not be retrieved from the underlying storage successfully because of a) its data can not be transformed e.g. decryption failure, or b) it fails to decode into an object. NOTE: unsafe deletion ignores finalizer constraints, skips precondition checks, and removes the object from the storage. WARNING: This may potentially break the cluster if the workload associated with the resource being unsafe-deleted relies on normal deletion flow. Use only if you REALLY know what you are doing. The default value is false, and the user must opt in to enable it :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. :param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. :param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param V1DeleteOptions body: :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1Status If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.delete_collection_service_cidr_with_http_info(**kwargs) # noqa: E501 def delete_collection_service_cidr_with_http_info(self, **kwargs): # noqa: E501 """delete_collection_service_cidr # noqa: E501 delete collection of ServiceCIDR # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_collection_service_cidr_with_http_info(async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. :param bool ignore_store_read_error_with_cluster_breaking_potential: if set to true, it will trigger an unsafe deletion of the resource in case the normal deletion flow fails with a corrupt object error. A resource is considered corrupt if it can not be retrieved from the underlying storage successfully because of a) its data can not be transformed e.g. decryption failure, or b) it fails to decode into an object. NOTE: unsafe deletion ignores finalizer constraints, skips precondition checks, and removes the object from the storage. WARNING: This may potentially break the cluster if the workload associated with the resource being unsafe-deleted relies on normal deletion flow. Use only if you REALLY know what you are doing. The default value is false, and the user must opt in to enable it :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. :param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. :param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param V1DeleteOptions body: :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1Status, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'pretty', '_continue', 'dry_run', 'field_selector', 'grace_period_seconds', 'ignore_store_read_error_with_cluster_breaking_potential', 'label_selector', 'limit', 'orphan_dependents', 'propagation_policy', 'resource_version', 'resource_version_match', 'send_initial_events', 'timeout_seconds', 'body' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method delete_collection_service_cidr" % key ) local_var_params[key] = val del local_var_params['kwargs'] collection_formats = {} path_params = {} query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501 query_params.append(('continue', local_var_params['_continue'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501 query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501 if 'grace_period_seconds' in local_var_params and local_var_params['grace_period_seconds'] is not None: # noqa: E501 query_params.append(('gracePeriodSeconds', local_var_params['grace_period_seconds'])) # noqa: E501 if 'ignore_store_read_error_with_cluster_breaking_potential' in local_var_params and local_var_params['ignore_store_read_error_with_cluster_breaking_potential'] is not None: # noqa: E501 query_params.append(('ignoreStoreReadErrorWithClusterBreakingPotential', local_var_params['ignore_store_read_error_with_cluster_breaking_potential'])) # noqa: E501 if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501 query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501 if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501 query_params.append(('limit', local_var_params['limit'])) # noqa: E501 if 'orphan_dependents' in local_var_params and local_var_params['orphan_dependents'] is not None: # noqa: E501 query_params.append(('orphanDependents', local_var_params['orphan_dependents'])) # noqa: E501 if 'propagation_policy' in local_var_params and local_var_params['propagation_policy'] is not None: # noqa: E501 query_params.append(('propagationPolicy', local_var_params['propagation_policy'])) # noqa: E501 if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501 query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501 if 'resource_version_match' in local_var_params and local_var_params['resource_version_match'] is not None: # noqa: E501 query_params.append(('resourceVersionMatch', local_var_params['resource_version_match'])) # noqa: E501 if 'send_initial_events' in local_var_params and local_var_params['send_initial_events'] is not None: # noqa: E501 query_params.append(('sendInitialEvents', local_var_params['send_initial_events'])) # noqa: E501 if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501 query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/networking.k8s.io/v1/servicecidrs', 'DELETE', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1Status', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def delete_ingress_class(self, name, **kwargs): # noqa: E501 """delete_ingress_class # noqa: E501 delete an IngressClass # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_ingress_class(name, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the IngressClass (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. :param bool ignore_store_read_error_with_cluster_breaking_potential: if set to true, it will trigger an unsafe deletion of the resource in case the normal deletion flow fails with a corrupt object error. A resource is considered corrupt if it can not be retrieved from the underlying storage successfully because of a) its data can not be transformed e.g. decryption failure, or b) it fails to decode into an object. NOTE: unsafe deletion ignores finalizer constraints, skips precondition checks, and removes the object from the storage. WARNING: This may potentially break the cluster if the workload associated with the resource being unsafe-deleted relies on normal deletion flow. Use only if you REALLY know what you are doing. The default value is false, and the user must opt in to enable it :param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. :param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. :param V1DeleteOptions body: :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1Status If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.delete_ingress_class_with_http_info(name, **kwargs) # noqa: E501 def delete_ingress_class_with_http_info(self, name, **kwargs): # noqa: E501 """delete_ingress_class # noqa: E501 delete an IngressClass # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_ingress_class_with_http_info(name, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the IngressClass (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. :param bool ignore_store_read_error_with_cluster_breaking_potential: if set to true, it will trigger an unsafe deletion of the resource in case the normal deletion flow fails with a corrupt object error. A resource is considered corrupt if it can not be retrieved from the underlying storage successfully because of a) its data can not be transformed e.g. decryption failure, or b) it fails to decode into an object. NOTE: unsafe deletion ignores finalizer constraints, skips precondition checks, and removes the object from the storage. WARNING: This may potentially break the cluster if the workload associated with the resource being unsafe-deleted relies on normal deletion flow. Use only if you REALLY know what you are doing. The default value is false, and the user must opt in to enable it :param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. :param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. :param V1DeleteOptions body: :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1Status, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'pretty', 'dry_run', 'grace_period_seconds', 'ignore_store_read_error_with_cluster_breaking_potential', 'orphan_dependents', 'propagation_policy', 'body' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method delete_ingress_class" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `delete_ingress_class`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'grace_period_seconds' in local_var_params and local_var_params['grace_period_seconds'] is not None: # noqa: E501 query_params.append(('gracePeriodSeconds', local_var_params['grace_period_seconds'])) # noqa: E501 if 'ignore_store_read_error_with_cluster_breaking_potential' in local_var_params and local_var_params['ignore_store_read_error_with_cluster_breaking_potential'] is not None: # noqa: E501 query_params.append(('ignoreStoreReadErrorWithClusterBreakingPotential', local_var_params['ignore_store_read_error_with_cluster_breaking_potential'])) # noqa: E501 if 'orphan_dependents' in local_var_params and local_var_params['orphan_dependents'] is not None: # noqa: E501 query_params.append(('orphanDependents', local_var_params['orphan_dependents'])) # noqa: E501 if 'propagation_policy' in local_var_params and local_var_params['propagation_policy'] is not None: # noqa: E501 query_params.append(('propagationPolicy', local_var_params['propagation_policy'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/networking.k8s.io/v1/ingressclasses/{name}', 'DELETE', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1Status', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def delete_ip_address(self, name, **kwargs): # noqa: E501 """delete_ip_address # noqa: E501 delete an IPAddress # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_ip_address(name, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the IPAddress (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. :param bool ignore_store_read_error_with_cluster_breaking_potential: if set to true, it will trigger an unsafe deletion of the resource in case the normal deletion flow fails with a corrupt object error. A resource is considered corrupt if it can not be retrieved from the underlying storage successfully because of a) its data can not be transformed e.g. decryption failure, or b) it fails to decode into an object. NOTE: unsafe deletion ignores finalizer constraints, skips precondition checks, and removes the object from the storage. WARNING: This may potentially break the cluster if the workload associated with the resource being unsafe-deleted relies on normal deletion flow. Use only if you REALLY know what you are doing. The default value is false, and the user must opt in to enable it :param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. :param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. :param V1DeleteOptions body: :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1Status If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.delete_ip_address_with_http_info(name, **kwargs) # noqa: E501 def delete_ip_address_with_http_info(self, name, **kwargs): # noqa: E501 """delete_ip_address # noqa: E501 delete an IPAddress # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_ip_address_with_http_info(name, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the IPAddress (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. :param bool ignore_store_read_error_with_cluster_breaking_potential: if set to true, it will trigger an unsafe deletion of the resource in case the normal deletion flow fails with a corrupt object error. A resource is considered corrupt if it can not be retrieved from the underlying storage successfully because of a) its data can not be transformed e.g. decryption failure, or b) it fails to decode into an object. NOTE: unsafe deletion ignores finalizer constraints, skips precondition checks, and removes the object from the storage. WARNING: This may potentially break the cluster if the workload associated with the resource being unsafe-deleted relies on normal deletion flow. Use only if you REALLY know what you are doing. The default value is false, and the user must opt in to enable it :param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. :param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. :param V1DeleteOptions body: :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1Status, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'pretty', 'dry_run', 'grace_period_seconds', 'ignore_store_read_error_with_cluster_breaking_potential', 'orphan_dependents', 'propagation_policy', 'body' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method delete_ip_address" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `delete_ip_address`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'grace_period_seconds' in local_var_params and local_var_params['grace_period_seconds'] is not None: # noqa: E501 query_params.append(('gracePeriodSeconds', local_var_params['grace_period_seconds'])) # noqa: E501 if 'ignore_store_read_error_with_cluster_breaking_potential' in local_var_params and local_var_params['ignore_store_read_error_with_cluster_breaking_potential'] is not None: # noqa: E501 query_params.append(('ignoreStoreReadErrorWithClusterBreakingPotential', local_var_params['ignore_store_read_error_with_cluster_breaking_potential'])) # noqa: E501 if 'orphan_dependents' in local_var_params and local_var_params['orphan_dependents'] is not None: # noqa: E501 query_params.append(('orphanDependents', local_var_params['orphan_dependents'])) # noqa: E501 if 'propagation_policy' in local_var_params and local_var_params['propagation_policy'] is not None: # noqa: E501 query_params.append(('propagationPolicy', local_var_params['propagation_policy'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/networking.k8s.io/v1/ipaddresses/{name}', 'DELETE', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1Status', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def delete_namespaced_ingress(self, name, namespace, **kwargs): # noqa: E501 """delete_namespaced_ingress # noqa: E501 delete an Ingress # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_namespaced_ingress(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the Ingress (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. :param bool ignore_store_read_error_with_cluster_breaking_potential: if set to true, it will trigger an unsafe deletion of the resource in case the normal deletion flow fails with a corrupt object error. A resource is considered corrupt if it can not be retrieved from the underlying storage successfully because of a) its data can not be transformed e.g. decryption failure, or b) it fails to decode into an object. NOTE: unsafe deletion ignores finalizer constraints, skips precondition checks, and removes the object from the storage. WARNING: This may potentially break the cluster if the workload associated with the resource being unsafe-deleted relies on normal deletion flow. Use only if you REALLY know what you are doing. The default value is false, and the user must opt in to enable it :param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. :param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. :param V1DeleteOptions body: :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1Status If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.delete_namespaced_ingress_with_http_info(name, namespace, **kwargs) # noqa: E501 def delete_namespaced_ingress_with_http_info(self, name, namespace, **kwargs): # noqa: E501 """delete_namespaced_ingress # noqa: E501 delete an Ingress # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_namespaced_ingress_with_http_info(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the Ingress (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. :param bool ignore_store_read_error_with_cluster_breaking_potential: if set to true, it will trigger an unsafe deletion of the resource in case the normal deletion flow fails with a corrupt object error. A resource is considered corrupt if it can not be retrieved from the underlying storage successfully because of a) its data can not be transformed e.g. decryption failure, or b) it fails to decode into an object. NOTE: unsafe deletion ignores finalizer constraints, skips precondition checks, and removes the object from the storage. WARNING: This may potentially break the cluster if the workload associated with the resource being unsafe-deleted relies on normal deletion flow. Use only if you REALLY know what you are doing. The default value is false, and the user must opt in to enable it :param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. :param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. :param V1DeleteOptions body: :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1Status, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'namespace', 'pretty', 'dry_run', 'grace_period_seconds', 'ignore_store_read_error_with_cluster_breaking_potential', 'orphan_dependents', 'propagation_policy', 'body' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method delete_namespaced_ingress" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `delete_namespaced_ingress`") # noqa: E501 # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `delete_namespaced_ingress`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'grace_period_seconds' in local_var_params and local_var_params['grace_period_seconds'] is not None: # noqa: E501 query_params.append(('gracePeriodSeconds', local_var_params['grace_period_seconds'])) # noqa: E501 if 'ignore_store_read_error_with_cluster_breaking_potential' in local_var_params and local_var_params['ignore_store_read_error_with_cluster_breaking_potential'] is not None: # noqa: E501 query_params.append(('ignoreStoreReadErrorWithClusterBreakingPotential', local_var_params['ignore_store_read_error_with_cluster_breaking_potential'])) # noqa: E501 if 'orphan_dependents' in local_var_params and local_var_params['orphan_dependents'] is not None: # noqa: E501 query_params.append(('orphanDependents', local_var_params['orphan_dependents'])) # noqa: E501 if 'propagation_policy' in local_var_params and local_var_params['propagation_policy'] is not None: # noqa: E501 query_params.append(('propagationPolicy', local_var_params['propagation_policy'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/networking.k8s.io/v1/namespaces/{namespace}/ingresses/{name}', 'DELETE', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1Status', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def delete_namespaced_network_policy(self, name, namespace, **kwargs): # noqa: E501 """delete_namespaced_network_policy # noqa: E501 delete a NetworkPolicy # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_namespaced_network_policy(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the NetworkPolicy (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. :param bool ignore_store_read_error_with_cluster_breaking_potential: if set to true, it will trigger an unsafe deletion of the resource in case the normal deletion flow fails with a corrupt object error. A resource is considered corrupt if it can not be retrieved from the underlying storage successfully because of a) its data can not be transformed e.g. decryption failure, or b) it fails to decode into an object. NOTE: unsafe deletion ignores finalizer constraints, skips precondition checks, and removes the object from the storage. WARNING: This may potentially break the cluster if the workload associated with the resource being unsafe-deleted relies on normal deletion flow. Use only if you REALLY know what you are doing. The default value is false, and the user must opt in to enable it :param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. :param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. :param V1DeleteOptions body: :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1Status If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.delete_namespaced_network_policy_with_http_info(name, namespace, **kwargs) # noqa: E501 def delete_namespaced_network_policy_with_http_info(self, name, namespace, **kwargs): # noqa: E501 """delete_namespaced_network_policy # noqa: E501 delete a NetworkPolicy # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_namespaced_network_policy_with_http_info(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the NetworkPolicy (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. :param bool ignore_store_read_error_with_cluster_breaking_potential: if set to true, it will trigger an unsafe deletion of the resource in case the normal deletion flow fails with a corrupt object error. A resource is considered corrupt if it can not be retrieved from the underlying storage successfully because of a) its data can not be transformed e.g. decryption failure, or b) it fails to decode into an object. NOTE: unsafe deletion ignores finalizer constraints, skips precondition checks, and removes the object from the storage. WARNING: This may potentially break the cluster if the workload associated with the resource being unsafe-deleted relies on normal deletion flow. Use only if you REALLY know what you are doing. The default value is false, and the user must opt in to enable it :param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. :param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. :param V1DeleteOptions body: :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1Status, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'namespace', 'pretty', 'dry_run', 'grace_period_seconds', 'ignore_store_read_error_with_cluster_breaking_potential', 'orphan_dependents', 'propagation_policy', 'body' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method delete_namespaced_network_policy" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `delete_namespaced_network_policy`") # noqa: E501 # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `delete_namespaced_network_policy`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'grace_period_seconds' in local_var_params and local_var_params['grace_period_seconds'] is not None: # noqa: E501 query_params.append(('gracePeriodSeconds', local_var_params['grace_period_seconds'])) # noqa: E501 if 'ignore_store_read_error_with_cluster_breaking_potential' in local_var_params and local_var_params['ignore_store_read_error_with_cluster_breaking_potential'] is not None: # noqa: E501 query_params.append(('ignoreStoreReadErrorWithClusterBreakingPotential', local_var_params['ignore_store_read_error_with_cluster_breaking_potential'])) # noqa: E501 if 'orphan_dependents' in local_var_params and local_var_params['orphan_dependents'] is not None: # noqa: E501 query_params.append(('orphanDependents', local_var_params['orphan_dependents'])) # noqa: E501 if 'propagation_policy' in local_var_params and local_var_params['propagation_policy'] is not None: # noqa: E501 query_params.append(('propagationPolicy', local_var_params['propagation_policy'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/networking.k8s.io/v1/namespaces/{namespace}/networkpolicies/{name}', 'DELETE', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1Status', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def delete_service_cidr(self, name, **kwargs): # noqa: E501 """delete_service_cidr # noqa: E501 delete a ServiceCIDR # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_service_cidr(name, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the ServiceCIDR (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. :param bool ignore_store_read_error_with_cluster_breaking_potential: if set to true, it will trigger an unsafe deletion of the resource in case the normal deletion flow fails with a corrupt object error. A resource is considered corrupt if it can not be retrieved from the underlying storage successfully because of a) its data can not be transformed e.g. decryption failure, or b) it fails to decode into an object. NOTE: unsafe deletion ignores finalizer constraints, skips precondition checks, and removes the object from the storage. WARNING: This may potentially break the cluster if the workload associated with the resource being unsafe-deleted relies on normal deletion flow. Use only if you REALLY know what you are doing. The default value is false, and the user must opt in to enable it :param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. :param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. :param V1DeleteOptions body: :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1Status If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.delete_service_cidr_with_http_info(name, **kwargs) # noqa: E501 def delete_service_cidr_with_http_info(self, name, **kwargs): # noqa: E501 """delete_service_cidr # noqa: E501 delete a ServiceCIDR # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_service_cidr_with_http_info(name, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the ServiceCIDR (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. :param bool ignore_store_read_error_with_cluster_breaking_potential: if set to true, it will trigger an unsafe deletion of the resource in case the normal deletion flow fails with a corrupt object error. A resource is considered corrupt if it can not be retrieved from the underlying storage successfully because of a) its data can not be transformed e.g. decryption failure, or b) it fails to decode into an object. NOTE: unsafe deletion ignores finalizer constraints, skips precondition checks, and removes the object from the storage. WARNING: This may potentially break the cluster if the workload associated with the resource being unsafe-deleted relies on normal deletion flow. Use only if you REALLY know what you are doing. The default value is false, and the user must opt in to enable it :param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. :param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. :param V1DeleteOptions body: :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1Status, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'pretty', 'dry_run', 'grace_period_seconds', 'ignore_store_read_error_with_cluster_breaking_potential', 'orphan_dependents', 'propagation_policy', 'body' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method delete_service_cidr" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `delete_service_cidr`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'grace_period_seconds' in local_var_params and local_var_params['grace_period_seconds'] is not None: # noqa: E501 query_params.append(('gracePeriodSeconds', local_var_params['grace_period_seconds'])) # noqa: E501 if 'ignore_store_read_error_with_cluster_breaking_potential' in local_var_params and local_var_params['ignore_store_read_error_with_cluster_breaking_potential'] is not None: # noqa: E501 query_params.append(('ignoreStoreReadErrorWithClusterBreakingPotential', local_var_params['ignore_store_read_error_with_cluster_breaking_potential'])) # noqa: E501 if 'orphan_dependents' in local_var_params and local_var_params['orphan_dependents'] is not None: # noqa: E501 query_params.append(('orphanDependents', local_var_params['orphan_dependents'])) # noqa: E501 if 'propagation_policy' in local_var_params and local_var_params['propagation_policy'] is not None: # noqa: E501 query_params.append(('propagationPolicy', local_var_params['propagation_policy'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/networking.k8s.io/v1/servicecidrs/{name}', 'DELETE', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1Status', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def get_api_resources(self, **kwargs): # noqa: E501 """get_api_resources # noqa: E501 get available resources # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_api_resources(async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1APIResourceList If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.get_api_resources_with_http_info(**kwargs) # noqa: E501 def get_api_resources_with_http_info(self, **kwargs): # noqa: E501 """get_api_resources # noqa: E501 get available resources # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_api_resources_with_http_info(async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1APIResourceList, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method get_api_resources" % key ) local_var_params[key] = val del local_var_params['kwargs'] collection_formats = {} path_params = {} query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/networking.k8s.io/v1/', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1APIResourceList', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def list_ingress_class(self, **kwargs): # noqa: E501 """list_ingress_class # noqa: E501 list or watch objects of kind IngressClass # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_ingress_class(async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1IngressClassList If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.list_ingress_class_with_http_info(**kwargs) # noqa: E501 def list_ingress_class_with_http_info(self, **kwargs): # noqa: E501 """list_ingress_class # noqa: E501 list or watch objects of kind IngressClass # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_ingress_class_with_http_info(async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1IngressClassList, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'pretty', 'allow_watch_bookmarks', '_continue', 'field_selector', 'label_selector', 'limit', 'resource_version', 'resource_version_match', 'send_initial_events', 'timeout_seconds', 'watch' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method list_ingress_class" % key ) local_var_params[key] = val del local_var_params['kwargs'] collection_formats = {} path_params = {} query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'allow_watch_bookmarks' in local_var_params and local_var_params['allow_watch_bookmarks'] is not None: # noqa: E501 query_params.append(('allowWatchBookmarks', local_var_params['allow_watch_bookmarks'])) # noqa: E501 if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501 query_params.append(('continue', local_var_params['_continue'])) # noqa: E501 if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501 query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501 if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501 query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501 if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501 query_params.append(('limit', local_var_params['limit'])) # noqa: E501 if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501 query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501 if 'resource_version_match' in local_var_params and local_var_params['resource_version_match'] is not None: # noqa: E501 query_params.append(('resourceVersionMatch', local_var_params['resource_version_match'])) # noqa: E501 if 'send_initial_events' in local_var_params and local_var_params['send_initial_events'] is not None: # noqa: E501 query_params.append(('sendInitialEvents', local_var_params['send_initial_events'])) # noqa: E501 if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501 query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501 if 'watch' in local_var_params and local_var_params['watch'] is not None: # noqa: E501 query_params.append(('watch', local_var_params['watch'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor', 'application/json;stream=watch', 'application/vnd.kubernetes.protobuf;stream=watch', 'application/cbor-seq']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/networking.k8s.io/v1/ingressclasses', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1IngressClassList', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def list_ingress_for_all_namespaces(self, **kwargs): # noqa: E501 """list_ingress_for_all_namespaces # noqa: E501 list or watch objects of kind Ingress # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_ingress_for_all_namespaces(async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1IngressList If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.list_ingress_for_all_namespaces_with_http_info(**kwargs) # noqa: E501 def list_ingress_for_all_namespaces_with_http_info(self, **kwargs): # noqa: E501 """list_ingress_for_all_namespaces # noqa: E501 list or watch objects of kind Ingress # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_ingress_for_all_namespaces_with_http_info(async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1IngressList, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'allow_watch_bookmarks', '_continue', 'field_selector', 'label_selector', 'limit', 'pretty', 'resource_version', 'resource_version_match', 'send_initial_events', 'timeout_seconds', 'watch' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method list_ingress_for_all_namespaces" % key ) local_var_params[key] = val del local_var_params['kwargs'] collection_formats = {} path_params = {} query_params = [] if 'allow_watch_bookmarks' in local_var_params and local_var_params['allow_watch_bookmarks'] is not None: # noqa: E501 query_params.append(('allowWatchBookmarks', local_var_params['allow_watch_bookmarks'])) # noqa: E501 if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501 query_params.append(('continue', local_var_params['_continue'])) # noqa: E501 if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501 query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501 if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501 query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501 if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501 query_params.append(('limit', local_var_params['limit'])) # noqa: E501 if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501 query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501 if 'resource_version_match' in local_var_params and local_var_params['resource_version_match'] is not None: # noqa: E501 query_params.append(('resourceVersionMatch', local_var_params['resource_version_match'])) # noqa: E501 if 'send_initial_events' in local_var_params and local_var_params['send_initial_events'] is not None: # noqa: E501 query_params.append(('sendInitialEvents', local_var_params['send_initial_events'])) # noqa: E501 if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501 query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501 if 'watch' in local_var_params and local_var_params['watch'] is not None: # noqa: E501 query_params.append(('watch', local_var_params['watch'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor', 'application/json;stream=watch', 'application/vnd.kubernetes.protobuf;stream=watch', 'application/cbor-seq']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/networking.k8s.io/v1/ingresses', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1IngressList', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def list_ip_address(self, **kwargs): # noqa: E501 """list_ip_address # noqa: E501 list or watch objects of kind IPAddress # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_ip_address(async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1IPAddressList If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.list_ip_address_with_http_info(**kwargs) # noqa: E501 def list_ip_address_with_http_info(self, **kwargs): # noqa: E501 """list_ip_address # noqa: E501 list or watch objects of kind IPAddress # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_ip_address_with_http_info(async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1IPAddressList, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'pretty', 'allow_watch_bookmarks', '_continue', 'field_selector', 'label_selector', 'limit', 'resource_version', 'resource_version_match', 'send_initial_events', 'timeout_seconds', 'watch' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method list_ip_address" % key ) local_var_params[key] = val del local_var_params['kwargs'] collection_formats = {} path_params = {} query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'allow_watch_bookmarks' in local_var_params and local_var_params['allow_watch_bookmarks'] is not None: # noqa: E501 query_params.append(('allowWatchBookmarks', local_var_params['allow_watch_bookmarks'])) # noqa: E501 if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501 query_params.append(('continue', local_var_params['_continue'])) # noqa: E501 if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501 query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501 if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501 query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501 if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501 query_params.append(('limit', local_var_params['limit'])) # noqa: E501 if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501 query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501 if 'resource_version_match' in local_var_params and local_var_params['resource_version_match'] is not None: # noqa: E501 query_params.append(('resourceVersionMatch', local_var_params['resource_version_match'])) # noqa: E501 if 'send_initial_events' in local_var_params and local_var_params['send_initial_events'] is not None: # noqa: E501 query_params.append(('sendInitialEvents', local_var_params['send_initial_events'])) # noqa: E501 if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501 query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501 if 'watch' in local_var_params and local_var_params['watch'] is not None: # noqa: E501 query_params.append(('watch', local_var_params['watch'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor', 'application/json;stream=watch', 'application/vnd.kubernetes.protobuf;stream=watch', 'application/cbor-seq']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/networking.k8s.io/v1/ipaddresses', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1IPAddressList', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def list_namespaced_ingress(self, namespace, **kwargs): # noqa: E501 """list_namespaced_ingress # noqa: E501 list or watch objects of kind Ingress # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_namespaced_ingress(namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1IngressList If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.list_namespaced_ingress_with_http_info(namespace, **kwargs) # noqa: E501 def list_namespaced_ingress_with_http_info(self, namespace, **kwargs): # noqa: E501 """list_namespaced_ingress # noqa: E501 list or watch objects of kind Ingress # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_namespaced_ingress_with_http_info(namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1IngressList, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'namespace', 'pretty', 'allow_watch_bookmarks', '_continue', 'field_selector', 'label_selector', 'limit', 'resource_version', 'resource_version_match', 'send_initial_events', 'timeout_seconds', 'watch' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method list_namespaced_ingress" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `list_namespaced_ingress`") # noqa: E501 collection_formats = {} path_params = {} if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'allow_watch_bookmarks' in local_var_params and local_var_params['allow_watch_bookmarks'] is not None: # noqa: E501 query_params.append(('allowWatchBookmarks', local_var_params['allow_watch_bookmarks'])) # noqa: E501 if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501 query_params.append(('continue', local_var_params['_continue'])) # noqa: E501 if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501 query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501 if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501 query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501 if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501 query_params.append(('limit', local_var_params['limit'])) # noqa: E501 if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501 query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501 if 'resource_version_match' in local_var_params and local_var_params['resource_version_match'] is not None: # noqa: E501 query_params.append(('resourceVersionMatch', local_var_params['resource_version_match'])) # noqa: E501 if 'send_initial_events' in local_var_params and local_var_params['send_initial_events'] is not None: # noqa: E501 query_params.append(('sendInitialEvents', local_var_params['send_initial_events'])) # noqa: E501 if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501 query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501 if 'watch' in local_var_params and local_var_params['watch'] is not None: # noqa: E501 query_params.append(('watch', local_var_params['watch'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor', 'application/json;stream=watch', 'application/vnd.kubernetes.protobuf;stream=watch', 'application/cbor-seq']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/networking.k8s.io/v1/namespaces/{namespace}/ingresses', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1IngressList', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def list_namespaced_network_policy(self, namespace, **kwargs): # noqa: E501 """list_namespaced_network_policy # noqa: E501 list or watch objects of kind NetworkPolicy # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_namespaced_network_policy(namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1NetworkPolicyList If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.list_namespaced_network_policy_with_http_info(namespace, **kwargs) # noqa: E501 def list_namespaced_network_policy_with_http_info(self, namespace, **kwargs): # noqa: E501 """list_namespaced_network_policy # noqa: E501 list or watch objects of kind NetworkPolicy # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_namespaced_network_policy_with_http_info(namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1NetworkPolicyList, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'namespace', 'pretty', 'allow_watch_bookmarks', '_continue', 'field_selector', 'label_selector', 'limit', 'resource_version', 'resource_version_match', 'send_initial_events', 'timeout_seconds', 'watch' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method list_namespaced_network_policy" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `list_namespaced_network_policy`") # noqa: E501 collection_formats = {} path_params = {} if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'allow_watch_bookmarks' in local_var_params and local_var_params['allow_watch_bookmarks'] is not None: # noqa: E501 query_params.append(('allowWatchBookmarks', local_var_params['allow_watch_bookmarks'])) # noqa: E501 if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501 query_params.append(('continue', local_var_params['_continue'])) # noqa: E501 if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501 query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501 if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501 query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501 if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501 query_params.append(('limit', local_var_params['limit'])) # noqa: E501 if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501 query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501 if 'resource_version_match' in local_var_params and local_var_params['resource_version_match'] is not None: # noqa: E501 query_params.append(('resourceVersionMatch', local_var_params['resource_version_match'])) # noqa: E501 if 'send_initial_events' in local_var_params and local_var_params['send_initial_events'] is not None: # noqa: E501 query_params.append(('sendInitialEvents', local_var_params['send_initial_events'])) # noqa: E501 if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501 query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501 if 'watch' in local_var_params and local_var_params['watch'] is not None: # noqa: E501 query_params.append(('watch', local_var_params['watch'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor', 'application/json;stream=watch', 'application/vnd.kubernetes.protobuf;stream=watch', 'application/cbor-seq']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/networking.k8s.io/v1/namespaces/{namespace}/networkpolicies', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1NetworkPolicyList', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def list_network_policy_for_all_namespaces(self, **kwargs): # noqa: E501 """list_network_policy_for_all_namespaces # noqa: E501 list or watch objects of kind NetworkPolicy # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_network_policy_for_all_namespaces(async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1NetworkPolicyList If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.list_network_policy_for_all_namespaces_with_http_info(**kwargs) # noqa: E501 def list_network_policy_for_all_namespaces_with_http_info(self, **kwargs): # noqa: E501 """list_network_policy_for_all_namespaces # noqa: E501 list or watch objects of kind NetworkPolicy # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_network_policy_for_all_namespaces_with_http_info(async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1NetworkPolicyList, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'allow_watch_bookmarks', '_continue', 'field_selector', 'label_selector', 'limit', 'pretty', 'resource_version', 'resource_version_match', 'send_initial_events', 'timeout_seconds', 'watch' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method list_network_policy_for_all_namespaces" % key ) local_var_params[key] = val del local_var_params['kwargs'] collection_formats = {} path_params = {} query_params = [] if 'allow_watch_bookmarks' in local_var_params and local_var_params['allow_watch_bookmarks'] is not None: # noqa: E501 query_params.append(('allowWatchBookmarks', local_var_params['allow_watch_bookmarks'])) # noqa: E501 if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501 query_params.append(('continue', local_var_params['_continue'])) # noqa: E501 if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501 query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501 if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501 query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501 if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501 query_params.append(('limit', local_var_params['limit'])) # noqa: E501 if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501 query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501 if 'resource_version_match' in local_var_params and local_var_params['resource_version_match'] is not None: # noqa: E501 query_params.append(('resourceVersionMatch', local_var_params['resource_version_match'])) # noqa: E501 if 'send_initial_events' in local_var_params and local_var_params['send_initial_events'] is not None: # noqa: E501 query_params.append(('sendInitialEvents', local_var_params['send_initial_events'])) # noqa: E501 if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501 query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501 if 'watch' in local_var_params and local_var_params['watch'] is not None: # noqa: E501 query_params.append(('watch', local_var_params['watch'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor', 'application/json;stream=watch', 'application/vnd.kubernetes.protobuf;stream=watch', 'application/cbor-seq']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/networking.k8s.io/v1/networkpolicies', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1NetworkPolicyList', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def list_service_cidr(self, **kwargs): # noqa: E501 """list_service_cidr # noqa: E501 list or watch objects of kind ServiceCIDR # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_service_cidr(async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1ServiceCIDRList If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.list_service_cidr_with_http_info(**kwargs) # noqa: E501 def list_service_cidr_with_http_info(self, **kwargs): # noqa: E501 """list_service_cidr # noqa: E501 list or watch objects of kind ServiceCIDR # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_service_cidr_with_http_info(async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param bool allow_watch_bookmarks: allowWatchBookmarks requests watch events with type \"BOOKMARK\". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param str resource_version: resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param str resource_version_match: resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset :param bool send_initial_events: `sendInitialEvents=true` may be set together with `watch=true`. In that case, the watch stream will begin with synthetic events to produce the current state of objects in the collection. Once all such events have been sent, a synthetic \"Bookmark\" event will be sent. The bookmark will report the ResourceVersion (RV) corresponding to the set of objects, and be marked with `\"k8s.io/initial-events-end\": \"true\"` annotation. Afterwards, the watch stream will proceed as usual, sending watch events corresponding to changes (subsequent to the RV) to objects watched. When `sendInitialEvents` option is set, we require `resourceVersionMatch` option to also be set. The semantic of the watch request is as following: - `resourceVersionMatch` = NotOlderThan is interpreted as \"data at least as new as the provided `resourceVersion`\" and the bookmark event is send when the state is synced to a `resourceVersion` at least as fresh as the one provided by the ListOptions. If `resourceVersion` is unset, this is interpreted as \"consistent read\" and the bookmark event is send when the state is synced at least to the moment when request started being processed. - `resourceVersionMatch` set to any other value or unset Invalid error is returned. Defaults to true if `resourceVersion=\"\"` or `resourceVersion=\"0\"` (for backward compatibility reasons) and to false otherwise. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1ServiceCIDRList, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'pretty', 'allow_watch_bookmarks', '_continue', 'field_selector', 'label_selector', 'limit', 'resource_version', 'resource_version_match', 'send_initial_events', 'timeout_seconds', 'watch' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method list_service_cidr" % key ) local_var_params[key] = val del local_var_params['kwargs'] collection_formats = {} path_params = {} query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'allow_watch_bookmarks' in local_var_params and local_var_params['allow_watch_bookmarks'] is not None: # noqa: E501 query_params.append(('allowWatchBookmarks', local_var_params['allow_watch_bookmarks'])) # noqa: E501 if '_continue' in local_var_params and local_var_params['_continue'] is not None: # noqa: E501 query_params.append(('continue', local_var_params['_continue'])) # noqa: E501 if 'field_selector' in local_var_params and local_var_params['field_selector'] is not None: # noqa: E501 query_params.append(('fieldSelector', local_var_params['field_selector'])) # noqa: E501 if 'label_selector' in local_var_params and local_var_params['label_selector'] is not None: # noqa: E501 query_params.append(('labelSelector', local_var_params['label_selector'])) # noqa: E501 if 'limit' in local_var_params and local_var_params['limit'] is not None: # noqa: E501 query_params.append(('limit', local_var_params['limit'])) # noqa: E501 if 'resource_version' in local_var_params and local_var_params['resource_version'] is not None: # noqa: E501 query_params.append(('resourceVersion', local_var_params['resource_version'])) # noqa: E501 if 'resource_version_match' in local_var_params and local_var_params['resource_version_match'] is not None: # noqa: E501 query_params.append(('resourceVersionMatch', local_var_params['resource_version_match'])) # noqa: E501 if 'send_initial_events' in local_var_params and local_var_params['send_initial_events'] is not None: # noqa: E501 query_params.append(('sendInitialEvents', local_var_params['send_initial_events'])) # noqa: E501 if 'timeout_seconds' in local_var_params and local_var_params['timeout_seconds'] is not None: # noqa: E501 query_params.append(('timeoutSeconds', local_var_params['timeout_seconds'])) # noqa: E501 if 'watch' in local_var_params and local_var_params['watch'] is not None: # noqa: E501 query_params.append(('watch', local_var_params['watch'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor', 'application/json;stream=watch', 'application/vnd.kubernetes.protobuf;stream=watch', 'application/cbor-seq']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/networking.k8s.io/v1/servicecidrs', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1ServiceCIDRList', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def patch_ingress_class(self, name, body, **kwargs): # noqa: E501 """patch_ingress_class # noqa: E501 partially update the specified IngressClass # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_ingress_class(name, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the IngressClass (required) :param object body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1IngressClass If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.patch_ingress_class_with_http_info(name, body, **kwargs) # noqa: E501 def patch_ingress_class_with_http_info(self, name, body, **kwargs): # noqa: E501 """patch_ingress_class # noqa: E501 partially update the specified IngressClass # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_ingress_class_with_http_info(name, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the IngressClass (required) :param object body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1IngressClass, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'body', 'pretty', 'dry_run', 'field_manager', 'field_validation', 'force' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method patch_ingress_class" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `patch_ingress_class`") # noqa: E501 # verify the required parameter 'body' is set if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501 local_var_params['body'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `body` when calling `patch_ingress_class`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501 query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501 if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501 query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501 if 'force' in local_var_params and local_var_params['force'] is not None: # noqa: E501 query_params.append(('force', local_var_params['force'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json', 'application/apply-patch+yaml', 'application/apply-patch+cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/networking.k8s.io/v1/ingressclasses/{name}', 'PATCH', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1IngressClass', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def patch_ip_address(self, name, body, **kwargs): # noqa: E501 """patch_ip_address # noqa: E501 partially update the specified IPAddress # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_ip_address(name, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the IPAddress (required) :param object body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1IPAddress If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.patch_ip_address_with_http_info(name, body, **kwargs) # noqa: E501 def patch_ip_address_with_http_info(self, name, body, **kwargs): # noqa: E501 """patch_ip_address # noqa: E501 partially update the specified IPAddress # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_ip_address_with_http_info(name, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the IPAddress (required) :param object body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1IPAddress, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'body', 'pretty', 'dry_run', 'field_manager', 'field_validation', 'force' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method patch_ip_address" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `patch_ip_address`") # noqa: E501 # verify the required parameter 'body' is set if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501 local_var_params['body'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `body` when calling `patch_ip_address`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501 query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501 if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501 query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501 if 'force' in local_var_params and local_var_params['force'] is not None: # noqa: E501 query_params.append(('force', local_var_params['force'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json', 'application/apply-patch+yaml', 'application/apply-patch+cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/networking.k8s.io/v1/ipaddresses/{name}', 'PATCH', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1IPAddress', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def patch_namespaced_ingress(self, name, namespace, body, **kwargs): # noqa: E501 """patch_namespaced_ingress # noqa: E501 partially update the specified Ingress # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_namespaced_ingress(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the Ingress (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param object body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1Ingress If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.patch_namespaced_ingress_with_http_info(name, namespace, body, **kwargs) # noqa: E501 def patch_namespaced_ingress_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501 """patch_namespaced_ingress # noqa: E501 partially update the specified Ingress # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_namespaced_ingress_with_http_info(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the Ingress (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param object body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1Ingress, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'namespace', 'body', 'pretty', 'dry_run', 'field_manager', 'field_validation', 'force' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method patch_namespaced_ingress" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `patch_namespaced_ingress`") # noqa: E501 # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `patch_namespaced_ingress`") # noqa: E501 # verify the required parameter 'body' is set if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501 local_var_params['body'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `body` when calling `patch_namespaced_ingress`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501 query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501 if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501 query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501 if 'force' in local_var_params and local_var_params['force'] is not None: # noqa: E501 query_params.append(('force', local_var_params['force'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json', 'application/apply-patch+yaml', 'application/apply-patch+cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/networking.k8s.io/v1/namespaces/{namespace}/ingresses/{name}', 'PATCH', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1Ingress', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def patch_namespaced_ingress_status(self, name, namespace, body, **kwargs): # noqa: E501 """patch_namespaced_ingress_status # noqa: E501 partially update status of the specified Ingress # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_namespaced_ingress_status(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the Ingress (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param object body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1Ingress If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.patch_namespaced_ingress_status_with_http_info(name, namespace, body, **kwargs) # noqa: E501 def patch_namespaced_ingress_status_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501 """patch_namespaced_ingress_status # noqa: E501 partially update status of the specified Ingress # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_namespaced_ingress_status_with_http_info(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the Ingress (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param object body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1Ingress, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'namespace', 'body', 'pretty', 'dry_run', 'field_manager', 'field_validation', 'force' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method patch_namespaced_ingress_status" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `patch_namespaced_ingress_status`") # noqa: E501 # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `patch_namespaced_ingress_status`") # noqa: E501 # verify the required parameter 'body' is set if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501 local_var_params['body'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `body` when calling `patch_namespaced_ingress_status`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501 query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501 if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501 query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501 if 'force' in local_var_params and local_var_params['force'] is not None: # noqa: E501 query_params.append(('force', local_var_params['force'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json', 'application/apply-patch+yaml', 'application/apply-patch+cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/networking.k8s.io/v1/namespaces/{namespace}/ingresses/{name}/status', 'PATCH', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1Ingress', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def patch_namespaced_network_policy(self, name, namespace, body, **kwargs): # noqa: E501 """patch_namespaced_network_policy # noqa: E501 partially update the specified NetworkPolicy # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_namespaced_network_policy(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the NetworkPolicy (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param object body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1NetworkPolicy If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.patch_namespaced_network_policy_with_http_info(name, namespace, body, **kwargs) # noqa: E501 def patch_namespaced_network_policy_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501 """patch_namespaced_network_policy # noqa: E501 partially update the specified NetworkPolicy # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_namespaced_network_policy_with_http_info(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the NetworkPolicy (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param object body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1NetworkPolicy, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'namespace', 'body', 'pretty', 'dry_run', 'field_manager', 'field_validation', 'force' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method patch_namespaced_network_policy" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `patch_namespaced_network_policy`") # noqa: E501 # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `patch_namespaced_network_policy`") # noqa: E501 # verify the required parameter 'body' is set if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501 local_var_params['body'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `body` when calling `patch_namespaced_network_policy`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501 query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501 if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501 query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501 if 'force' in local_var_params and local_var_params['force'] is not None: # noqa: E501 query_params.append(('force', local_var_params['force'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json', 'application/apply-patch+yaml', 'application/apply-patch+cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/networking.k8s.io/v1/namespaces/{namespace}/networkpolicies/{name}', 'PATCH', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1NetworkPolicy', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def patch_service_cidr(self, name, body, **kwargs): # noqa: E501 """patch_service_cidr # noqa: E501 partially update the specified ServiceCIDR # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_service_cidr(name, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the ServiceCIDR (required) :param object body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1ServiceCIDR If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.patch_service_cidr_with_http_info(name, body, **kwargs) # noqa: E501 def patch_service_cidr_with_http_info(self, name, body, **kwargs): # noqa: E501 """patch_service_cidr # noqa: E501 partially update the specified ServiceCIDR # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_service_cidr_with_http_info(name, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the ServiceCIDR (required) :param object body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1ServiceCIDR, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'body', 'pretty', 'dry_run', 'field_manager', 'field_validation', 'force' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method patch_service_cidr" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `patch_service_cidr`") # noqa: E501 # verify the required parameter 'body' is set if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501 local_var_params['body'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `body` when calling `patch_service_cidr`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501 query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501 if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501 query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501 if 'force' in local_var_params and local_var_params['force'] is not None: # noqa: E501 query_params.append(('force', local_var_params['force'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json', 'application/apply-patch+yaml', 'application/apply-patch+cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/networking.k8s.io/v1/servicecidrs/{name}', 'PATCH', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1ServiceCIDR', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def patch_service_cidr_status(self, name, body, **kwargs): # noqa: E501 """patch_service_cidr_status # noqa: E501 partially update status of the specified ServiceCIDR # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_service_cidr_status(name, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the ServiceCIDR (required) :param object body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1ServiceCIDR If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.patch_service_cidr_status_with_http_info(name, body, **kwargs) # noqa: E501 def patch_service_cidr_status_with_http_info(self, name, body, **kwargs): # noqa: E501 """patch_service_cidr_status # noqa: E501 partially update status of the specified ServiceCIDR # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_service_cidr_status_with_http_info(name, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the ServiceCIDR (required) :param object body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1ServiceCIDR, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'body', 'pretty', 'dry_run', 'field_manager', 'field_validation', 'force' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method patch_service_cidr_status" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `patch_service_cidr_status`") # noqa: E501 # verify the required parameter 'body' is set if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501 local_var_params['body'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `body` when calling `patch_service_cidr_status`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501 query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501 if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501 query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501 if 'force' in local_var_params and local_var_params['force'] is not None: # noqa: E501 query_params.append(('force', local_var_params['force'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json', 'application/apply-patch+yaml', 'application/apply-patch+cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/networking.k8s.io/v1/servicecidrs/{name}/status', 'PATCH', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1ServiceCIDR', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def read_ingress_class(self, name, **kwargs): # noqa: E501 """read_ingress_class # noqa: E501 read the specified IngressClass # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_ingress_class(name, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the IngressClass (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1IngressClass If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.read_ingress_class_with_http_info(name, **kwargs) # noqa: E501 def read_ingress_class_with_http_info(self, name, **kwargs): # noqa: E501 """read_ingress_class # noqa: E501 read the specified IngressClass # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_ingress_class_with_http_info(name, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the IngressClass (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1IngressClass, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'pretty' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method read_ingress_class" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `read_ingress_class`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/networking.k8s.io/v1/ingressclasses/{name}', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1IngressClass', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def read_ip_address(self, name, **kwargs): # noqa: E501 """read_ip_address # noqa: E501 read the specified IPAddress # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_ip_address(name, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the IPAddress (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1IPAddress If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.read_ip_address_with_http_info(name, **kwargs) # noqa: E501 def read_ip_address_with_http_info(self, name, **kwargs): # noqa: E501 """read_ip_address # noqa: E501 read the specified IPAddress # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_ip_address_with_http_info(name, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the IPAddress (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1IPAddress, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'pretty' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method read_ip_address" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `read_ip_address`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/networking.k8s.io/v1/ipaddresses/{name}', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1IPAddress', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def read_namespaced_ingress(self, name, namespace, **kwargs): # noqa: E501 """read_namespaced_ingress # noqa: E501 read the specified Ingress # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_namespaced_ingress(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the Ingress (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1Ingress If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.read_namespaced_ingress_with_http_info(name, namespace, **kwargs) # noqa: E501 def read_namespaced_ingress_with_http_info(self, name, namespace, **kwargs): # noqa: E501 """read_namespaced_ingress # noqa: E501 read the specified Ingress # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_namespaced_ingress_with_http_info(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the Ingress (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1Ingress, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'namespace', 'pretty' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method read_namespaced_ingress" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `read_namespaced_ingress`") # noqa: E501 # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `read_namespaced_ingress`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/networking.k8s.io/v1/namespaces/{namespace}/ingresses/{name}', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1Ingress', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def read_namespaced_ingress_status(self, name, namespace, **kwargs): # noqa: E501 """read_namespaced_ingress_status # noqa: E501 read status of the specified Ingress # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_namespaced_ingress_status(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the Ingress (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1Ingress If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.read_namespaced_ingress_status_with_http_info(name, namespace, **kwargs) # noqa: E501 def read_namespaced_ingress_status_with_http_info(self, name, namespace, **kwargs): # noqa: E501 """read_namespaced_ingress_status # noqa: E501 read status of the specified Ingress # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_namespaced_ingress_status_with_http_info(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the Ingress (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1Ingress, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'namespace', 'pretty' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method read_namespaced_ingress_status" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `read_namespaced_ingress_status`") # noqa: E501 # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `read_namespaced_ingress_status`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/networking.k8s.io/v1/namespaces/{namespace}/ingresses/{name}/status', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1Ingress', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def read_namespaced_network_policy(self, name, namespace, **kwargs): # noqa: E501 """read_namespaced_network_policy # noqa: E501 read the specified NetworkPolicy # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_namespaced_network_policy(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the NetworkPolicy (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1NetworkPolicy If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.read_namespaced_network_policy_with_http_info(name, namespace, **kwargs) # noqa: E501 def read_namespaced_network_policy_with_http_info(self, name, namespace, **kwargs): # noqa: E501 """read_namespaced_network_policy # noqa: E501 read the specified NetworkPolicy # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_namespaced_network_policy_with_http_info(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the NetworkPolicy (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1NetworkPolicy, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'namespace', 'pretty' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method read_namespaced_network_policy" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `read_namespaced_network_policy`") # noqa: E501 # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `read_namespaced_network_policy`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/networking.k8s.io/v1/namespaces/{namespace}/networkpolicies/{name}', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1NetworkPolicy', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def read_service_cidr(self, name, **kwargs): # noqa: E501 """read_service_cidr # noqa: E501 read the specified ServiceCIDR # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_service_cidr(name, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the ServiceCIDR (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1ServiceCIDR If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.read_service_cidr_with_http_info(name, **kwargs) # noqa: E501 def read_service_cidr_with_http_info(self, name, **kwargs): # noqa: E501 """read_service_cidr # noqa: E501 read the specified ServiceCIDR # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_service_cidr_with_http_info(name, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the ServiceCIDR (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1ServiceCIDR, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'pretty' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method read_service_cidr" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `read_service_cidr`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/networking.k8s.io/v1/servicecidrs/{name}', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1ServiceCIDR', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def read_service_cidr_status(self, name, **kwargs): # noqa: E501 """read_service_cidr_status # noqa: E501 read status of the specified ServiceCIDR # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_service_cidr_status(name, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the ServiceCIDR (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1ServiceCIDR If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.read_service_cidr_status_with_http_info(name, **kwargs) # noqa: E501 def read_service_cidr_status_with_http_info(self, name, **kwargs): # noqa: E501 """read_service_cidr_status # noqa: E501 read status of the specified ServiceCIDR # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_service_cidr_status_with_http_info(name, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the ServiceCIDR (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1ServiceCIDR, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'pretty' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method read_service_cidr_status" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `read_service_cidr_status`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/networking.k8s.io/v1/servicecidrs/{name}/status', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1ServiceCIDR', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def replace_ingress_class(self, name, body, **kwargs): # noqa: E501 """replace_ingress_class # noqa: E501 replace the specified IngressClass # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_ingress_class(name, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the IngressClass (required) :param V1IngressClass body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1IngressClass If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.replace_ingress_class_with_http_info(name, body, **kwargs) # noqa: E501 def replace_ingress_class_with_http_info(self, name, body, **kwargs): # noqa: E501 """replace_ingress_class # noqa: E501 replace the specified IngressClass # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_ingress_class_with_http_info(name, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the IngressClass (required) :param V1IngressClass body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1IngressClass, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'body', 'pretty', 'dry_run', 'field_manager', 'field_validation' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method replace_ingress_class" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `replace_ingress_class`") # noqa: E501 # verify the required parameter 'body' is set if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501 local_var_params['body'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `body` when calling `replace_ingress_class`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501 query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501 if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501 query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/networking.k8s.io/v1/ingressclasses/{name}', 'PUT', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1IngressClass', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def replace_ip_address(self, name, body, **kwargs): # noqa: E501 """replace_ip_address # noqa: E501 replace the specified IPAddress # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_ip_address(name, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the IPAddress (required) :param V1IPAddress body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1IPAddress If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.replace_ip_address_with_http_info(name, body, **kwargs) # noqa: E501 def replace_ip_address_with_http_info(self, name, body, **kwargs): # noqa: E501 """replace_ip_address # noqa: E501 replace the specified IPAddress # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_ip_address_with_http_info(name, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the IPAddress (required) :param V1IPAddress body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1IPAddress, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'body', 'pretty', 'dry_run', 'field_manager', 'field_validation' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method replace_ip_address" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `replace_ip_address`") # noqa: E501 # verify the required parameter 'body' is set if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501 local_var_params['body'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `body` when calling `replace_ip_address`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501 query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501 if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501 query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/networking.k8s.io/v1/ipaddresses/{name}', 'PUT', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1IPAddress', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def replace_namespaced_ingress(self, name, namespace, body, **kwargs): # noqa: E501 """replace_namespaced_ingress # noqa: E501 replace the specified Ingress # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_namespaced_ingress(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the Ingress (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param V1Ingress body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1Ingress If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.replace_namespaced_ingress_with_http_info(name, namespace, body, **kwargs) # noqa: E501 def replace_namespaced_ingress_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501 """replace_namespaced_ingress # noqa: E501 replace the specified Ingress # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_namespaced_ingress_with_http_info(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the Ingress (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param V1Ingress body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1Ingress, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'namespace', 'body', 'pretty', 'dry_run', 'field_manager', 'field_validation' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method replace_namespaced_ingress" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `replace_namespaced_ingress`") # noqa: E501 # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `replace_namespaced_ingress`") # noqa: E501 # verify the required parameter 'body' is set if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501 local_var_params['body'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `body` when calling `replace_namespaced_ingress`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501 query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501 if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501 query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/networking.k8s.io/v1/namespaces/{namespace}/ingresses/{name}', 'PUT', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1Ingress', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def replace_namespaced_ingress_status(self, name, namespace, body, **kwargs): # noqa: E501 """replace_namespaced_ingress_status # noqa: E501 replace status of the specified Ingress # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_namespaced_ingress_status(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the Ingress (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param V1Ingress body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1Ingress If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.replace_namespaced_ingress_status_with_http_info(name, namespace, body, **kwargs) # noqa: E501 def replace_namespaced_ingress_status_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501 """replace_namespaced_ingress_status # noqa: E501 replace status of the specified Ingress # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_namespaced_ingress_status_with_http_info(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the Ingress (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param V1Ingress body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1Ingress, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'namespace', 'body', 'pretty', 'dry_run', 'field_manager', 'field_validation' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method replace_namespaced_ingress_status" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `replace_namespaced_ingress_status`") # noqa: E501 # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `replace_namespaced_ingress_status`") # noqa: E501 # verify the required parameter 'body' is set if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501 local_var_params['body'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `body` when calling `replace_namespaced_ingress_status`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501 query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501 if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501 query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/networking.k8s.io/v1/namespaces/{namespace}/ingresses/{name}/status', 'PUT', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1Ingress', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def replace_namespaced_network_policy(self, name, namespace, body, **kwargs): # noqa: E501 """replace_namespaced_network_policy # noqa: E501 replace the specified NetworkPolicy # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_namespaced_network_policy(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the NetworkPolicy (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param V1NetworkPolicy body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1NetworkPolicy If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.replace_namespaced_network_policy_with_http_info(name, namespace, body, **kwargs) # noqa: E501 def replace_namespaced_network_policy_with_http_info(self, name, namespace, body, **kwargs): # noqa: E501 """replace_namespaced_network_policy # noqa: E501 replace the specified NetworkPolicy # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_namespaced_network_policy_with_http_info(name, namespace, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the NetworkPolicy (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param V1NetworkPolicy body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1NetworkPolicy, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'namespace', 'body', 'pretty', 'dry_run', 'field_manager', 'field_validation' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method replace_namespaced_network_policy" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `replace_namespaced_network_policy`") # noqa: E501 # verify the required parameter 'namespace' is set if self.api_client.client_side_validation and ('namespace' not in local_var_params or # noqa: E501 local_var_params['namespace'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `namespace` when calling `replace_namespaced_network_policy`") # noqa: E501 # verify the required parameter 'body' is set if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501 local_var_params['body'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `body` when calling `replace_namespaced_network_policy`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 if 'namespace' in local_var_params: path_params['namespace'] = local_var_params['namespace'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501 query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501 if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501 query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/networking.k8s.io/v1/namespaces/{namespace}/networkpolicies/{name}', 'PUT', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1NetworkPolicy', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def replace_service_cidr(self, name, body, **kwargs): # noqa: E501 """replace_service_cidr # noqa: E501 replace the specified ServiceCIDR # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_service_cidr(name, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the ServiceCIDR (required) :param V1ServiceCIDR body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1ServiceCIDR If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.replace_service_cidr_with_http_info(name, body, **kwargs) # noqa: E501 def replace_service_cidr_with_http_info(self, name, body, **kwargs): # noqa: E501 """replace_service_cidr # noqa: E501 replace the specified ServiceCIDR # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_service_cidr_with_http_info(name, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the ServiceCIDR (required) :param V1ServiceCIDR body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1ServiceCIDR, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'body', 'pretty', 'dry_run', 'field_manager', 'field_validation' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method replace_service_cidr" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `replace_service_cidr`") # noqa: E501 # verify the required parameter 'body' is set if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501 local_var_params['body'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `body` when calling `replace_service_cidr`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501 query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501 if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501 query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/networking.k8s.io/v1/servicecidrs/{name}', 'PUT', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1ServiceCIDR', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) def replace_service_cidr_status(self, name, body, **kwargs): # noqa: E501 """replace_service_cidr_status # noqa: E501 replace status of the specified ServiceCIDR # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_service_cidr_status(name, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the ServiceCIDR (required) :param V1ServiceCIDR body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1ServiceCIDR If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.replace_service_cidr_status_with_http_info(name, body, **kwargs) # noqa: E501 def replace_service_cidr_status_with_http_info(self, name, body, **kwargs): # noqa: E501 """replace_service_cidr_status # noqa: E501 replace status of the specified ServiceCIDR # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_service_cidr_status_with_http_info(name, body, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the ServiceCIDR (required) :param V1ServiceCIDR body: (required) :param str pretty: If 'true', then the output is pretty printed. Defaults to 'false' unless the user-agent indicates a browser or command-line HTTP tool (curl and wget). :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. :param str field_validation: fieldValidation instructs the server on how to handle objects in the request (POST/PUT/PATCH) containing unknown or duplicate fields. Valid values are: - Ignore: This will ignore any unknown fields that are silently dropped from the object, and will ignore all but the last duplicate field that the decoder encounters. This is the default behavior prior to v1.23. - Warn: This will send a warning via the standard warning response header for each unknown field that is dropped from the object, and for each duplicate field that is encountered. The request will still succeed if there are no other errors, and will only persist the last of any duplicate fields. This is the default in v1.23+ - Strict: This will fail the request with a BadRequest error if any unknown fields would be dropped from the object, or if any duplicate fields are present. The error returned from the server will contain all unknown and duplicate fields encountered. :param _return_http_data_only: response data without head status code and headers :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: tuple(V1ServiceCIDR, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ local_var_params = locals() all_params = [ 'name', 'body', 'pretty', 'dry_run', 'field_manager', 'field_validation' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method replace_service_cidr_status" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'name' is set if self.api_client.client_side_validation and ('name' not in local_var_params or # noqa: E501 local_var_params['name'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `name` when calling `replace_service_cidr_status`") # noqa: E501 # verify the required parameter 'body' is set if self.api_client.client_side_validation and ('body' not in local_var_params or # noqa: E501 local_var_params['body'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `body` when calling `replace_service_cidr_status`") # noqa: E501 collection_formats = {} path_params = {} if 'name' in local_var_params: path_params['name'] = local_var_params['name'] # noqa: E501 query_params = [] if 'pretty' in local_var_params and local_var_params['pretty'] is not None: # noqa: E501 query_params.append(('pretty', local_var_params['pretty'])) # noqa: E501 if 'dry_run' in local_var_params and local_var_params['dry_run'] is not None: # noqa: E501 query_params.append(('dryRun', local_var_params['dry_run'])) # noqa: E501 if 'field_manager' in local_var_params and local_var_params['field_manager'] is not None: # noqa: E501 query_params.append(('fieldManager', local_var_params['field_manager'])) # noqa: E501 if 'field_validation' in local_var_params and local_var_params['field_validation'] is not None: # noqa: E501 query_params.append(('fieldValidation', local_var_params['field_validation'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/cbor']) # noqa: E501 # Authentication setting auth_settings = ['BearerToken'] # noqa: E501 return self.api_client.call_api( '/apis/networking.k8s.io/v1/servicecidrs/{name}/status', 'PUT', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1ServiceCIDR', # noqa: E501 auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats)
NetworkingV1Api
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/dataproc.py
{ "start": 122875, "end": 125862 }
class ____(GoogleCloudBaseOperator): """ Delete the batch workload resource. :param batch_id: Required. The ID to use for the batch, which will become the final component of the batch's resource name. This value must be 4-63 characters. Valid characters are /[a-z][0-9]-/. :param region: Required. The Cloud Dataproc region in which to handle the request. :param project_id: Optional. The ID of the Google Cloud project that the cluster belongs to. :param retry: A retry object used to retry requests. If ``None`` is specified, requests will not be retried. :param timeout: The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. :param metadata: Additional metadata that is provided to the method. :param gcp_conn_id: The connection ID to use connecting to Google Cloud. :param impersonation_chain: Optional service account to impersonate using short-term credentials, or chained list of accounts required to get the access_token of the last account in the list, which will be impersonated in the request. If set as a string, the account must grant the originating account the Service Account Token Creator IAM role. If set as a sequence, the identities from the list must grant Service Account Token Creator IAM role to the directly preceding identity, with first account from the list granting this role to the originating account (templated). """ template_fields: Sequence[str] = ( "batch_id", "region", "project_id", "gcp_conn_id", "impersonation_chain", ) def __init__( self, *, batch_id: str, region: str, project_id: str = PROVIDE_PROJECT_ID, retry: Retry | _MethodDefault = DEFAULT, timeout: float | None = None, metadata: Sequence[tuple[str, str]] = (), gcp_conn_id: str = "google_cloud_default", impersonation_chain: str | Sequence[str] | None = None, **kwargs, ): super().__init__(**kwargs) self.batch_id = batch_id self.region = region self.project_id = project_id self.retry = retry self.timeout = timeout self.metadata = metadata self.gcp_conn_id = gcp_conn_id self.impersonation_chain = impersonation_chain def execute(self, context: Context): hook = DataprocHook(gcp_conn_id=self.gcp_conn_id, impersonation_chain=self.impersonation_chain) self.log.info("Deleting batch: %s", self.batch_id) hook.delete_batch( batch_id=self.batch_id, region=self.region, project_id=self.project_id, retry=self.retry, timeout=self.timeout, metadata=self.metadata, ) self.log.info("Batch deleted.")
DataprocDeleteBatchOperator
python
huggingface__transformers
src/transformers/models/mlcd/modular_mlcd.py
{ "start": 18725, "end": 20174 }
class ____(CLIPVisionModel): @check_model_inputs(tie_last_hidden_states=False) @auto_docstring def forward( self, pixel_values: Optional[torch.FloatTensor] = None, **kwargs: Unpack[TransformersKwargs], ) -> Union[tuple, BaseModelOutputWithPooling]: r""" Example: ```python >>> import requests >>> from PIL import Image >>> from transformers import AutoProcessor, MLCDVisionModel >>> model = MLCDVisionModel.from_pretrained("DeepGlint-AI/mlcd-vit-bigG-patch14-448") >>> processor = AutoProcessor.from_pretrained("DeepGlint-AI/mlcd-vit-bigG-patch14-448") >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg" >>> image = Image.open(requests.get(url, stream=True).raw) >>> inputs = processor(images=image, return_tensors="pt") >>> with torch.no_grad(): ... outputs = model(**inputs, output_attentions=True) >>> features = outputs.last_hidden_state >>> print(f"Extracted features shape: {features.shape}") >>> print(f"Number of attention layers: {len(outputs.attentions)}") >>> print(f"Attention shape: {outputs.attentions[0].shape}") ```""" return self.vision_model( pixel_values=pixel_values, **kwargs, ) __all__ = [ "MLCDVisionConfig", "MLCDPreTrainedModel", "MLCDVisionModel", ]
MLCDVisionModel
python
gevent__gevent
src/greentest/3.9/test_subprocess.py
{ "start": 147182, "end": 152003 }
class ____(unittest.TestCase): class RecordingPopen(subprocess.Popen): """A Popen that saves a reference to each instance for testing.""" instances_created = [] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.instances_created.append(self) @mock.patch.object(subprocess.Popen, "_communicate") def _test_keyboardinterrupt_no_kill(self, popener, mock__communicate, **kwargs): """Fake a SIGINT happening during Popen._communicate() and ._wait(). This avoids the need to actually try and get test environments to send and receive signals reliably across platforms. The net effect of a ^C happening during a blocking subprocess execution which we want to clean up from is a KeyboardInterrupt coming out of communicate() or wait(). """ mock__communicate.side_effect = KeyboardInterrupt try: with mock.patch.object(subprocess.Popen, "_wait") as mock__wait: # We patch out _wait() as no signal was involved so the # child process isn't actually going to exit rapidly. mock__wait.side_effect = KeyboardInterrupt with mock.patch.object(subprocess, "Popen", self.RecordingPopen): with self.assertRaises(KeyboardInterrupt): popener([sys.executable, "-c", "import time\ntime.sleep(9)\nimport sys\n" "sys.stderr.write('\\n!runaway child!\\n')"], stdout=subprocess.DEVNULL, **kwargs) for call in mock__wait.call_args_list[1:]: self.assertNotEqual( call, mock.call(timeout=None), "no open-ended wait() after the first allowed: " f"{mock__wait.call_args_list}") sigint_calls = [] for call in mock__wait.call_args_list: if call == mock.call(timeout=0.25): # from Popen.__init__ sigint_calls.append(call) self.assertLessEqual(mock__wait.call_count, 2, msg=mock__wait.call_args_list) self.assertEqual(len(sigint_calls), 1, msg=mock__wait.call_args_list) finally: # cleanup the forgotten (due to our mocks) child process process = self.RecordingPopen.instances_created.pop() process.kill() process.wait() self.assertEqual([], self.RecordingPopen.instances_created) def test_call_keyboardinterrupt_no_kill(self): self._test_keyboardinterrupt_no_kill(subprocess.call, timeout=6.282) def test_run_keyboardinterrupt_no_kill(self): self._test_keyboardinterrupt_no_kill(subprocess.run, timeout=6.282) def test_context_manager_keyboardinterrupt_no_kill(self): def popen_via_context_manager(*args, **kwargs): with subprocess.Popen(*args, **kwargs) as unused_process: raise KeyboardInterrupt # Test how __exit__ handles ^C. self._test_keyboardinterrupt_no_kill(popen_via_context_manager) def test_getoutput(self): self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy') self.assertEqual(subprocess.getstatusoutput('echo xyzzy'), (0, 'xyzzy')) # we use mkdtemp in the next line to create an empty directory # under our exclusive control; from that, we can invent a pathname # that we _know_ won't exist. This is guaranteed to fail. dir = None try: dir = tempfile.mkdtemp() name = os.path.join(dir, "foo") status, output = subprocess.getstatusoutput( ("type " if mswindows else "cat ") + name) self.assertNotEqual(status, 0) finally: if dir is not None: os.rmdir(dir) def test__all__(self): """Ensure that __all__ is populated properly.""" intentionally_excluded = {"list2cmdline", "Handle", "pwd", "grp"} exported = set(subprocess.__all__) possible_exports = set() import types for name, value in subprocess.__dict__.items(): if name.startswith('_'): continue if isinstance(value, (types.ModuleType,)): continue possible_exports.add(name) self.assertEqual(exported, possible_exports - intentionally_excluded) @unittest.skipUnless(hasattr(selectors, 'PollSelector'), "Test needs selectors.PollSelector")
MiscTests
python
google__pytype
pytype/errors/errors_test.py
{ "start": 11741, "end": 13401 }
class ____(unittest.TestCase): dirname = path_utils.dirname ERROR_FILE_PATH = path_utils.join( dirname(dirname(errors.__file__)), "../docs/errors.md" ) def _check_and_get_documented_errors(self): with open(self.ERROR_FILE_PATH) as f: lines = f.readlines() entries = [line[3:].strip() for line in lines if line.startswith("##")] counts = collections.Counter(entries) if any(count > 1 for count in counts.values()): raise AssertionError( "These errors.md entries have duplicates:\n " + "\n ".join(name for name, count in counts.items() if count > 1) ) sorted_entries = sorted(entries) if sorted_entries != entries: raise AssertionError( "These errors.md entries are out of alphabetical order:\n " + "\n ".join( actual for expected, actual in zip(sorted_entries, entries) if expected != actual ) ) return set(entries) def test_error_doc(self): documented_errors = self._check_and_get_documented_errors() all_errors = errors._ERROR_NAMES - {_TEST_ERROR} undocumented_errors = all_errors - documented_errors if undocumented_errors: raise AssertionError( "These errors are missing entries in errors.md:\n " + "\n ".join(undocumented_errors) + "\n" ) deprecated_errors = documented_errors - all_errors if deprecated_errors: raise AssertionError( "These errors.md entries do not correspond to errors:\n " + "\n ".join(deprecated_errors) ) if __name__ == "__main__": unittest.main()
ErrorDocTest
python
numpy__numpy
numpy/_core/tests/test_numerictypes.py
{ "start": 12503, "end": 12701 }
class ____(ReadValuesNested): """Check the values of heterogeneous arrays (nested, multiple rows)""" _descr = Ndescr multiple_rows = True _buffer = NbufferT
TestReadValuesNestedMultiple
python
huggingface__transformers
src/transformers/models/x_clip/configuration_x_clip.py
{ "start": 783, "end": 5078 }
class ____(PreTrainedConfig): r""" This is the configuration class to store the configuration of a [`XCLIPModel`]. It is used to instantiate an X-CLIP model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the X-CLIP [microsoft/xclip-base-patch32](https://huggingface.co/microsoft/xclip-base-patch32) architecture. Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the documentation from [`PreTrainedConfig`] for more information. Args: vocab_size (`int`, *optional*, defaults to 49408): Vocabulary size of the X-CLIP text model. Defines the number of different tokens that can be represented by the `inputs_ids` passed when calling [`XCLIPModel`]. hidden_size (`int`, *optional*, defaults to 512): Dimensionality of the encoder layers and the pooler layer. intermediate_size (`int`, *optional*, defaults to 2048): Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder. num_hidden_layers (`int`, *optional*, defaults to 12): Number of hidden layers in the Transformer encoder. num_attention_heads (`int`, *optional*, defaults to 8): Number of attention heads for each attention layer in the Transformer encoder. max_position_embeddings (`int`, *optional*, defaults to 77): The maximum sequence length that this model might ever be used with. Typically set this to something large just in case (e.g., 512 or 1024 or 2048). hidden_act (`str` or `function`, *optional*, defaults to `"quick_gelu"`): The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`, `"relu"`, `"selu"` and `"gelu_new"` `"quick_gelu"` are supported. layer_norm_eps (`float`, *optional*, defaults to 1e-5): The epsilon used by the layer normalization layers. attention_dropout (`float`, *optional*, defaults to 0.0): The dropout ratio for the attention probabilities. initializer_range (`float`, *optional*, defaults to 0.02): The standard deviation of the truncated_normal_initializer for initializing all weight matrices. initializer_factor (`float`, *optional*, defaults to 1): A factor for initializing all weight matrices (should be kept to 1, used internally for initialization testing). Example: ```python >>> from transformers import XCLIPTextModel, XCLIPTextConfig >>> # Initializing a XCLIPTextModel with microsoft/xclip-base-patch32 style configuration >>> configuration = XCLIPTextConfig() >>> # Initializing a XCLIPTextConfig from the microsoft/xclip-base-patch32 style configuration >>> model = XCLIPTextModel(configuration) >>> # Accessing the model configuration >>> configuration = model.config ```""" model_type = "xclip_text_model" base_config_key = "text_config" def __init__( self, vocab_size=49408, hidden_size=512, intermediate_size=2048, num_hidden_layers=12, num_attention_heads=8, max_position_embeddings=77, hidden_act="quick_gelu", layer_norm_eps=1e-5, attention_dropout=0.0, initializer_range=0.02, initializer_factor=1.0, pad_token_id=1, bos_token_id=0, eos_token_id=2, **kwargs, ): super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs) self.vocab_size = vocab_size self.hidden_size = hidden_size self.intermediate_size = intermediate_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.max_position_embeddings = max_position_embeddings self.layer_norm_eps = layer_norm_eps self.hidden_act = hidden_act self.initializer_range = initializer_range self.initializer_factor = initializer_factor self.attention_dropout = attention_dropout
XCLIPTextConfig
python
scipy__scipy
scipy/linalg/tests/test_fblas.py
{ "start": 8603, "end": 8833 }
class ____(BaseSwap): blas_func = fblas.dswap dtype = float64 try: class TestCswap(BaseSwap): blas_func = fblas.cswap dtype = complex64 except AttributeError: class TestCswap: pass
TestDswap
python
django__django
tests/select_related_onetoone/models.py
{ "start": 737, "end": 807 }
class ____(UserStat): karma = models.IntegerField()
AdvancedUserStat
python
jazzband__django-oauth-toolkit
oauth2_provider/views/device.py
{ "start": 817, "end": 1480 }
class ____(OAuthLibMixin, View): server_class = DeviceApplicationServer def post(self, request, *args, **kwargs): headers, response, status = self.create_device_authorization_response(request) if status != 200: return http.JsonResponse(data=json.loads(response), status=status, headers=headers) device_request = DeviceRequest(client_id=request.POST["client_id"], scope=request.POST.get("scope")) device_response = DeviceCodeResponse(**response) create_device_grant(device_request, device_response) return http.JsonResponse(data=response, status=status, headers=headers)
DeviceAuthorizationView
python
getsentry__sentry
src/sentry/preprod/models.py
{ "start": 12617, "end": 13076 }
class ____(DefaultFieldsModel): """The build configuration used to build the artifact, e.g. "Debug" or "Release".""" __relocation_scope__ = RelocationScope.Excluded project = FlexibleForeignKey("sentry.Project") name = models.CharField(max_length=255) class Meta: app_label = "preprod" db_table = "sentry_preprodbuildconfiguration" unique_together = ("project", "name") @region_silo_model
PreprodBuildConfiguration
python
weaviate__weaviate-python-client
weaviate/rbac/models.py
{ "start": 10395, "end": 10457 }
class ____(_BackupsPermission): pass
BackupsPermissionOutput
python
Pylons__pyramid
tests/test_authentication.py
{ "start": 60314, "end": 64543 }
class ____(unittest.TestCase): def _getTargetClass(self): from pyramid.authentication import BasicAuthAuthenticationPolicy as cls return cls def _makeOne(self, check): return self._getTargetClass()(check, realm='SomeRealm') def test_class_implements_IAuthenticationPolicy(self): from zope.interface.verify import verifyClass from pyramid.interfaces import IAuthenticationPolicy verifyClass(IAuthenticationPolicy, self._getTargetClass()) def test_unauthenticated_userid(self): import base64 request = testing.DummyRequest() request.headers['Authorization'] = 'Basic %s' % base64.b64encode( bytes_('chrisr:password') ).decode('ascii') policy = self._makeOne(None) self.assertEqual(policy.unauthenticated_userid(request), 'chrisr') def test_unauthenticated_userid_no_credentials(self): request = testing.DummyRequest() policy = self._makeOne(None) self.assertEqual(policy.unauthenticated_userid(request), None) def test_unauthenticated_bad_header(self): request = testing.DummyRequest() request.headers['Authorization'] = '...' policy = self._makeOne(None) self.assertEqual(policy.unauthenticated_userid(request), None) def test_unauthenticated_userid_not_basic(self): request = testing.DummyRequest() request.headers['Authorization'] = 'Complicated things' policy = self._makeOne(None) self.assertEqual(policy.unauthenticated_userid(request), None) def test_unauthenticated_userid_corrupt_base64(self): request = testing.DummyRequest() request.headers['Authorization'] = 'Basic chrisr:password' policy = self._makeOne(None) self.assertEqual(policy.unauthenticated_userid(request), None) def test_authenticated_userid(self): import base64 request = testing.DummyRequest() request.headers['Authorization'] = 'Basic %s' % base64.b64encode( bytes_('chrisr:password') ).decode('ascii') def check(username, password, request): return [] policy = self._makeOne(check) self.assertEqual(policy.authenticated_userid(request), 'chrisr') def test_authenticated_userid_utf8(self): import base64 request = testing.DummyRequest() inputs = ( b'm\xc3\xb6rk\xc3\xb6:' b'm\xc3\xb6rk\xc3\xb6password' ).decode('utf-8') request.headers['Authorization'] = 'Basic %s' % ( base64.b64encode(inputs.encode('utf-8')).decode('latin-1') ) def check(username, password, request): return [] policy = self._makeOne(check) self.assertEqual( policy.authenticated_userid(request), b'm\xc3\xb6rk\xc3\xb6'.decode('utf-8'), ) def test_authenticated_userid_latin1(self): import base64 request = testing.DummyRequest() inputs = ( b'm\xc3\xb6rk\xc3\xb6:' b'm\xc3\xb6rk\xc3\xb6password' ).decode('utf-8') request.headers['Authorization'] = 'Basic %s' % ( base64.b64encode(inputs.encode('latin-1')).decode('latin-1') ) def check(username, password, request): return [] policy = self._makeOne(check) self.assertEqual( policy.authenticated_userid(request), b'm\xc3\xb6rk\xc3\xb6'.decode('utf-8'), ) def test_unauthenticated_userid_invalid_payload(self): import base64 request = testing.DummyRequest() request.headers['Authorization'] = 'Basic %s' % base64.b64encode( bytes_('chrisrpassword') ).decode('ascii') policy = self._makeOne(None) self.assertEqual(policy.unauthenticated_userid(request), None) def test_remember(self): policy = self._makeOne(None) self.assertEqual(policy.remember(None, None), []) def test_forget(self): policy = self._makeOne(None) self.assertEqual( policy.forget(None), [('WWW-Authenticate', 'Basic realm="SomeRealm"')], )
TestBasicAuthAuthenticationPolicy
python
great-expectations__great_expectations
great_expectations/expectations/core/expect_column_chisquare_test_p_value_to_be_greater_than.py
{ "start": 269, "end": 894 }
class ____(BatchExpectation): def __init__(self, *args, **kwargs): raise NotImplementedError library_metadata = { "maturity": "production", "tags": [ "core expectation", "column aggregate expectation", "needs migration to modular expectations api", ], "contributors": ["@great_expectations"], "requirements": [], } metric_dependencies = tuple() success_keys = () args_keys = ( "column", "partition_object", "p", "tail_weight_holdout", )
ExpectColumnChiSquareTestPValueToBeGreaterThan
python
kamyu104__LeetCode-Solutions
Python/find-the-distance-value-between-two-arrays.py
{ "start": 606, "end": 1097 }
class ____(object): def findTheDistanceValue(self, arr1, arr2, d): """ :type arr1: List[int] :type arr2: List[int] :type d: int :rtype: int """ arr1.sort(), arr2.sort() result, i, j = 0, 0, 0 while i < len(arr1) and j < len(arr2): if arr1[i]-arr2[j] > d: j += 1 continue result += arr2[j]-arr1[i] > d i += 1 return result+len(arr1)-i
Solution2
python
spack__spack
lib/spack/spack/vendor/jsonschema/_format.py
{ "start": 169, "end": 6752 }
class ____(object): """ A ``format`` property checker. JSON Schema does not mandate that the ``format`` property actually do any validation. If validation is desired however, instances of this class can be hooked into validators to enable format validation. `FormatChecker` objects always return ``True`` when asked about formats that they do not know how to validate. To check a custom format using a function that takes an instance and returns a ``bool``, use the `FormatChecker.checks` or `FormatChecker.cls_checks` decorators. Arguments: formats (~collections.Iterable): The known formats to validate. This argument can be used to limit which formats will be used during validation. """ checkers = {} def __init__(self, formats=None): if formats is None: self.checkers = self.checkers.copy() else: self.checkers = dict((k, self.checkers[k]) for k in formats) def __repr__(self): return "<FormatChecker checkers={}>".format(sorted(self.checkers)) def checks(self, format, raises=()): """ Register a decorated function as validating a new format. Arguments: format (str): The format that the decorated function will check. raises (Exception): The exception(s) raised by the decorated function when an invalid instance is found. The exception object will be accessible as the `jsonschema.exceptions.ValidationError.cause` attribute of the resulting validation error. """ def _checks(func): self.checkers[format] = (func, raises) return func return _checks cls_checks = classmethod(checks) def check(self, instance, format): """ Check whether the instance conforms to the given format. Arguments: instance (*any primitive type*, i.e. str, number, bool): The instance to check format (str): The format that instance should conform to Raises: FormatError: if the instance does not conform to ``format`` """ if format not in self.checkers: return func, raises = self.checkers[format] result, cause = None, None try: result = func(instance) except raises as e: cause = e if not result: raise FormatError( "%r is not a %r" % (instance, format), cause=cause, ) def conforms(self, instance, format): """ Check whether the instance conforms to the given format. Arguments: instance (*any primitive type*, i.e. str, number, bool): The instance to check format (str): The format that instance should conform to Returns: bool: whether it conformed """ try: self.check(instance, format) except FormatError: return False else: return True draft3_format_checker = FormatChecker() draft4_format_checker = FormatChecker() draft6_format_checker = FormatChecker() draft7_format_checker = FormatChecker() _draft_checkers = dict( draft3=draft3_format_checker, draft4=draft4_format_checker, draft6=draft6_format_checker, draft7=draft7_format_checker, ) def _checks_drafts( name=None, draft3=None, draft4=None, draft6=None, draft7=None, raises=(), ): draft3 = draft3 or name draft4 = draft4 or name draft6 = draft6 or name draft7 = draft7 or name def wrap(func): if draft3: func = _draft_checkers["draft3"].checks(draft3, raises)(func) if draft4: func = _draft_checkers["draft4"].checks(draft4, raises)(func) if draft6: func = _draft_checkers["draft6"].checks(draft6, raises)(func) if draft7: func = _draft_checkers["draft7"].checks(draft7, raises)(func) # Oy. This is bad global state, but relied upon for now, until # deprecation. See https://github.com/Julian/jsonschema/issues/519 # and test_format_checkers_come_with_defaults FormatChecker.cls_checks(draft7 or draft6 or draft4 or draft3, raises)( func, ) return func return wrap @_checks_drafts(name="idn-email") @_checks_drafts(name="email") def is_email(instance): if not isinstance(instance, str_types): return True return "@" in instance _ipv4_re = re.compile(r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$") @_checks_drafts( draft3="ip-address", draft4="ipv4", draft6="ipv4", draft7="ipv4", ) def is_ipv4(instance): if not isinstance(instance, str_types): return True if not _ipv4_re.match(instance): return False return all(0 <= int(component) <= 255 for component in instance.split(".")) if hasattr(socket, "inet_pton"): # FIXME: Really this only should raise struct.error, but see the sadness # that is https://twistedmatrix.com/trac/ticket/9409 @_checks_drafts( name="ipv6", raises=(socket.error, struct.error, ValueError), ) def is_ipv6(instance): if not isinstance(instance, str_types): return True return socket.inet_pton(socket.AF_INET6, instance) _host_name_re = re.compile(r"^[A-Za-z0-9][A-Za-z0-9\.\-]{1,255}$") @_checks_drafts( draft3="host-name", draft4="hostname", draft6="hostname", draft7="hostname", ) def is_host_name(instance): if not isinstance(instance, str_types): return True if not _host_name_re.match(instance): return False components = instance.split(".") for component in components: if len(component) > 63: return False return True @_checks_drafts(name="regex", raises=re.error) def is_regex(instance): if not isinstance(instance, str_types): return True return re.compile(instance) @_checks_drafts(draft3="date", draft7="date", raises=ValueError) def is_date(instance): if not isinstance(instance, str_types): return True return datetime.datetime.strptime(instance, "%Y-%m-%d") @_checks_drafts(draft3="time", raises=ValueError) def is_draft3_time(instance): if not isinstance(instance, str_types): return True return datetime.datetime.strptime(instance, "%H:%M:%S")
FormatChecker
python
optuna__optuna
optuna/samplers/_gp/sampler.py
{ "start": 1916, "end": 21549 }
class ____(BaseSampler): """Sampler using Gaussian process-based Bayesian optimization. This sampler fits a Gaussian process (GP) to the objective function and optimizes the acquisition function to suggest the next parameters. The current implementation uses Matern kernel with nu=2.5 (twice differentiable) with automatic relevance determination (ARD) for the length scale of each parameter. The hyperparameters of the kernel are obtained by maximizing the marginal log-likelihood of the hyperparameters given the past trials. To prevent overfitting, Gamma prior is introduced for kernel scale and noise variance and a hand-crafted prior is introduced for inverse squared lengthscales. As an acquisition function, we use: - log expected improvement (logEI) for single-objective optimization, - log expected hypervolume improvement (logEHVI) for Multi-objective optimization, and - the summation of logEI and the logarithm of the feasible probability with the independent assumption of each constraint for (black-box inequality) constrained optimization. For further information about these acquisition functions, please refer to the following papers: - `Unexpected Improvements to Expected Improvement for Bayesian Optimization <https://arxiv.org/abs/2310.20708>`__ - `Differentiable Expected Hypervolume Improvement for Parallel Multi-Objective Bayesian Optimization <https://arxiv.org/abs/2006.05078>`__ - `Bayesian Optimization with Inequality Constraints <https://proceedings.mlr.press/v32/gardner14.pdf>`__ Please also check our articles: - `[Optuna v4.5] Gaussian Process-Based Sampler (GPSampler) Can Now Perform Constrained Multi-Objective Optimization <https://medium.com/optuna/optuna-v4-5-81e78d8e077a>`__ - `[Optuna v4.2] Gaussian Process-Based Sampler (GPSampler) Can Now Handle Inequality Constraints <https://medium.com/optuna/optuna-v4-2-gaussian-process-based-sampler-can-now-handle-inequality-constraints-a4f68e8ee810>`__ - `Introducing Optuna's Native GPSampler <https://medium.com/optuna/introducing-optunas-native-gpsampler-0aa9aa3b4840>`__ The optimization of the acquisition function is performed via: 1. Collect the best param from the past trials, 2. Collect ``n_preliminary_samples`` points using Quasi-Monte Carlo (QMC) sampling, 3. Choose the best point from the collected points, 4. Choose ``n_local_search - 2`` points from the collected points using the roulette selection, 5. Perform a local search for each chosen point as an initial point, and 6. Return the point with the best acquisition function value as the next parameter. Decoupled optimizer update with a batched evaluation is employed to perform a batch of local searches simultaneously, specifically speeding up Step 5 above. The following paper details the methodology: - `Batch Acquisition Function Evaluations and Decouple Optimizer Updates for Faster Bayesian Optimization <https://arxiv.org/abs/2511.13625>`__ Note that the procedures for non single-objective optimization setups are slightly different from the single-objective version described above, but we omit the descriptions for the others for brevity. The local search iteratively optimizes the acquisition function by repeating: 1. Gradient ascent using l-BFGS-B for continuous parameters, and 2. Line search or exhaustive search for each discrete parameter independently. The local search is terminated if the routine stops updating the best parameter set or the maximum number of iterations is reached. We use line search instead of rounding the results from the continuous optimization since EI typically yields a high value between one grid and its adjacent grid. .. note:: This sampler requires ``scipy`` and ``torch``. You can install these dependencies with ``pip install scipy torch``. Args: seed: Random seed to initialize internal random number generator. Defaults to :obj:`None` (a seed is picked randomly). independent_sampler: Sampler used for initial sampling (for the first ``n_startup_trials`` trials) and for conditional parameters. Defaults to :obj:`None` (a random sampler with the same ``seed`` is used). n_startup_trials: Number of initial trials. Defaults to 10. deterministic_objective: Whether the objective function is deterministic or not. If :obj:`True`, the sampler will fix the noise variance of the surrogate model to the minimum value (slightly above 0 to ensure numerical stability). Defaults to :obj:`False`. Currently, all the objectives will be assume to be deterministic if :obj:`True`. constraints_func: An optional function that computes the objective constraints. It must take a :class:`~optuna.trial.FrozenTrial` and return the constraints. The return value must be a sequence of :obj:`float` s. A value strictly larger than 0 means that a constraints is violated. A value equal to or smaller than 0 is considered feasible. If ``constraints_func`` returns more than one value for a trial, that trial is considered feasible if and only if all values are equal to 0 or smaller. The ``constraints_func`` will be evaluated after each successful trial. The function won't be called when trials fail or are pruned, but this behavior is subject to change in future releases. warn_independent_sampling: If this is :obj:`True`, a warning message is emitted when the value of a parameter is sampled by using an independent sampler, meaning that no GP model is used in the sampling. Note that the parameters of the first trial in a study are always sampled via an independent sampler, so no warning messages are emitted in this case. """ def __init__( self, *, seed: int | None = None, independent_sampler: BaseSampler | None = None, n_startup_trials: int = 10, deterministic_objective: bool = False, constraints_func: Callable[[FrozenTrial], Sequence[float]] | None = None, warn_independent_sampling: bool = True, ) -> None: self._rng = LazyRandomState(seed) self._independent_sampler = independent_sampler or optuna.samplers.RandomSampler(seed=seed) self._intersection_search_space = optuna.search_space.IntersectionSearchSpace() self._n_startup_trials = n_startup_trials self._log_prior: Callable[[gp.GPRegressor], torch.Tensor] = prior.default_log_prior self._minimum_noise: float = prior.DEFAULT_MINIMUM_NOISE_VAR # We cache the kernel parameters for initial values of fitting the next time. # TODO(nabenabe): Make the cache lists system_attrs to make GPSampler stateless. self._gprs_cache_list: list[gp.GPRegressor] | None = None self._constraints_gprs_cache_list: list[gp.GPRegressor] | None = None self._deterministic = deterministic_objective self._constraints_func = constraints_func self._warn_independent_sampling = warn_independent_sampling if constraints_func is not None: warn_experimental_argument("constraints_func") # Control parameters of the acquisition function optimization. self._n_preliminary_samples: int = 2048 # NOTE(nabenabe): ehvi in BoTorchSampler uses 20. self._n_local_search = 10 self._tol = 1e-4 def _log_independent_sampling(self, trial: FrozenTrial, param_name: str) -> None: msg = _INDEPENDENT_SAMPLING_WARNING_TEMPLATE.format( param_name=param_name, trial_number=trial.number, independent_sampler_name=self._independent_sampler.__class__.__name__, sampler_name=self.__class__.__name__, fallback_reason="dynamic search space is not supported by GPSampler", ) _logger.warning(msg) def reseed_rng(self) -> None: self._rng.rng.seed() self._independent_sampler.reseed_rng() def infer_relative_search_space( self, study: Study, trial: FrozenTrial ) -> dict[str, BaseDistribution]: search_space = {} for name, distribution in self._intersection_search_space.calculate(study).items(): if distribution.single(): continue search_space[name] = distribution return search_space def _optimize_acqf( self, acqf: acqf_module.BaseAcquisitionFunc, best_params: np.ndarray | None ) -> np.ndarray: # Advanced users can override this method to change the optimization algorithm. # However, we do not make any effort to keep backward compatibility between versions. # Particularly, we may remove this function in future refactoring. assert best_params is None or len(best_params.shape) == 2 normalized_params, _acqf_val = optim_mixed.optimize_acqf_mixed( acqf, warmstart_normalized_params_array=best_params, n_preliminary_samples=self._n_preliminary_samples, n_local_search=self._n_local_search, tol=self._tol, rng=self._rng.rng, ) return normalized_params def _get_constraints_acqf_args( self, constraint_vals: np.ndarray, internal_search_space: gp_search_space.SearchSpace, normalized_params: np.ndarray, ) -> tuple[list[gp.GPRegressor], list[float]]: # NOTE(nabenabe): Flip the sign of constraints since they are always to be minimized. standardized_constraint_vals, means, stds = _standardize_values(-constraint_vals) if ( self._gprs_cache_list is not None and len(self._gprs_cache_list[0].inverse_squared_lengthscales) != internal_search_space.dim ): # Clear cache if the search space changes. self._constraints_gprs_cache_list = None is_categorical = internal_search_space.is_categorical constraints_gprs = [] constraints_threshold_list = [] constraints_threshold_list = (-means / np.maximum(EPS, stds)).tolist() for i, vals in enumerate(standardized_constraint_vals.T): cache = ( self._constraints_gprs_cache_list[i] if self._constraints_gprs_cache_list is not None else None ) gpr = gp.fit_kernel_params( X=normalized_params, Y=vals, is_categorical=is_categorical, log_prior=self._log_prior, minimum_noise=self._minimum_noise, gpr_cache=cache, deterministic_objective=self._deterministic, ) constraints_gprs.append(gpr) self._constraints_gprs_cache_list = constraints_gprs return constraints_gprs, constraints_threshold_list def _get_best_params_for_multi_objective( self, normalized_params: np.ndarray, standardized_score_vals: np.ndarray, ) -> np.ndarray: pareto_params = normalized_params[ _is_pareto_front(-standardized_score_vals, assume_unique_lexsorted=False) ] n_pareto_sols = len(pareto_params) # TODO(nabenabe): Verify the validity of this choice. size = min(self._n_local_search // 2, n_pareto_sols) chosen_indices = self._rng.rng.choice(n_pareto_sols, size=size, replace=False) return pareto_params[chosen_indices] def sample_relative( self, study: Study, trial: FrozenTrial, search_space: dict[str, BaseDistribution] ) -> dict[str, Any]: if search_space == {}: return {} states = (TrialState.COMPLETE,) trials = study._get_trials(deepcopy=False, states=states, use_cache=True) if len(trials) < self._n_startup_trials: return {} internal_search_space = gp_search_space.SearchSpace(search_space) normalized_params = internal_search_space.get_normalized_params(trials) _sign = np.array([-1.0 if d == StudyDirection.MINIMIZE else 1.0 for d in study.directions]) standardized_score_vals, _, _ = _standardize_values( _sign * np.array([trial.values for trial in trials]) ) if ( self._gprs_cache_list is not None and len(self._gprs_cache_list[0].inverse_squared_lengthscales) != internal_search_space.dim ): # Clear cache if the search space changes. self._gprs_cache_list = None gprs_list = [] n_objectives = standardized_score_vals.shape[-1] is_categorical = internal_search_space.is_categorical for i in range(n_objectives): cache = self._gprs_cache_list[i] if self._gprs_cache_list is not None else None gprs_list.append( gp.fit_kernel_params( X=normalized_params, Y=standardized_score_vals[:, i], is_categorical=is_categorical, log_prior=self._log_prior, minimum_noise=self._minimum_noise, gpr_cache=cache, deterministic_objective=self._deterministic, ) ) self._gprs_cache_list = gprs_list best_params: np.ndarray | None acqf: acqf_module.BaseAcquisitionFunc if self._constraints_func is None: if n_objectives == 1: assert len(gprs_list) == 1 acqf = acqf_module.LogEI( gpr=gprs_list[0], search_space=internal_search_space, threshold=standardized_score_vals[:, 0].max(), ) best_params = normalized_params[np.argmax(standardized_score_vals), np.newaxis] else: acqf = acqf_module.LogEHVI( gpr_list=gprs_list, search_space=internal_search_space, Y_train=torch.from_numpy(standardized_score_vals), n_qmc_samples=128, # NOTE(nabenabe): The BoTorch default value. qmc_seed=self._rng.rng.randint(1 << 30), ) best_params = self._get_best_params_for_multi_objective( normalized_params, standardized_score_vals ) else: if n_objectives == 1: assert len(gprs_list) == 1 constraint_vals, is_feasible = _get_constraint_vals_and_feasibility(study, trials) y_with_neginf = np.where(is_feasible, standardized_score_vals[:, 0], -np.inf) # TODO(kAIto47802): If all trials are infeasible, the acquisition function # for the objective function can be ignored, so skipping the computation # of gpr can speed up. # TODO(kAIto47802): Consider the case where all trials are feasible. # We can ignore constraints in this case. constr_gpr_list, constr_threshold_list = self._get_constraints_acqf_args( constraint_vals, internal_search_space, normalized_params ) i_opt = np.argmax(y_with_neginf) best_feasible_y = y_with_neginf[i_opt] acqf = acqf_module.ConstrainedLogEI( gpr=gprs_list[0], search_space=internal_search_space, threshold=best_feasible_y, constraints_gpr_list=constr_gpr_list, constraints_threshold_list=constr_threshold_list, ) assert normalized_params.shape[:-1] == y_with_neginf.shape best_params = ( None if np.isneginf(best_feasible_y) else normalized_params[i_opt, np.newaxis] ) else: constraint_vals, is_feasible = _get_constraint_vals_and_feasibility(study, trials) constr_gpr_list, constr_threshold_list = self._get_constraints_acqf_args( constraint_vals, internal_search_space, normalized_params ) is_all_infeasible = not any(is_feasible) acqf = acqf_module.ConstrainedLogEHVI( gpr_list=gprs_list, search_space=internal_search_space, Y_feasible=( torch.from_numpy(standardized_score_vals[is_feasible]) if not is_all_infeasible else None ), n_qmc_samples=128, # NOTE(nabenabe): The BoTorch default value. qmc_seed=self._rng.rng.randint(1 << 30), constraints_gpr_list=constr_gpr_list, constraints_threshold_list=constr_threshold_list, ) best_params = ( self._get_best_params_for_multi_objective( normalized_params[is_feasible], standardized_score_vals[is_feasible], ) if not is_all_infeasible else None ) normalized_param = self._optimize_acqf(acqf, best_params) return internal_search_space.get_unnormalized_param(normalized_param) def sample_independent( self, study: Study, trial: FrozenTrial, param_name: str, param_distribution: BaseDistribution, ) -> Any: if self._warn_independent_sampling: states = (TrialState.COMPLETE,) complete_trials = study._get_trials(deepcopy=False, states=states, use_cache=True) if len(complete_trials) >= self._n_startup_trials: self._log_independent_sampling(trial, param_name) return self._independent_sampler.sample_independent( study, trial, param_name, param_distribution ) def before_trial(self, study: Study, trial: FrozenTrial) -> None: self._independent_sampler.before_trial(study, trial) def after_trial( self, study: Study, trial: FrozenTrial, state: TrialState, values: Sequence[float] | None, ) -> None: if self._constraints_func is not None: _process_constraints_after_trial(self._constraints_func, study, trial, state) self._independent_sampler.after_trial(study, trial, state, values) def _get_constraint_vals_and_feasibility( study: Study, trials: list[FrozenTrial] ) -> tuple[np.ndarray, np.ndarray]: _constraint_vals = [ study._storage.get_trial_system_attrs(trial._trial_id).get(_CONSTRAINTS_KEY, ()) for trial in trials ] if any(len(_constraint_vals[0]) != len(c) for c in _constraint_vals): raise ValueError("The number of constraints must be the same for all trials.") constraint_vals = np.array(_constraint_vals) assert len(constraint_vals.shape) == 2, "constraint_vals must be a 2d array." is_feasible = np.all(constraint_vals <= 0, axis=1) assert not isinstance(is_feasible, np.bool_), "MyPy Redefinition for NumPy v2.2.0." return constraint_vals, is_feasible
GPSampler
python
plotly__plotly.py
plotly/graph_objs/_sunburst.py
{ "start": 215, "end": 67181 }
class ____(_BaseTraceType): _parent_path_str = "" _path_str = "sunburst" _valid_props = { "branchvalues", "count", "customdata", "customdatasrc", "domain", "hoverinfo", "hoverinfosrc", "hoverlabel", "hovertemplate", "hovertemplatefallback", "hovertemplatesrc", "hovertext", "hovertextsrc", "ids", "idssrc", "insidetextfont", "insidetextorientation", "labels", "labelssrc", "leaf", "legend", "legendgrouptitle", "legendrank", "legendwidth", "level", "marker", "maxdepth", "meta", "metasrc", "name", "opacity", "outsidetextfont", "parents", "parentssrc", "root", "rotation", "sort", "stream", "text", "textfont", "textinfo", "textsrc", "texttemplate", "texttemplatefallback", "texttemplatesrc", "type", "uid", "uirevision", "values", "valuessrc", "visible", } @property def branchvalues(self): """ Determines how the items in `values` are summed. When set to "total", items in `values` are taken to be value of all its descendants. When set to "remainder", items in `values` corresponding to the root and the branches sectors are taken to be the extra part not part of the sum of the values at their leaves. The 'branchvalues' property is an enumeration that may be specified as: - One of the following enumeration values: ['remainder', 'total'] Returns ------- Any """ return self["branchvalues"] @branchvalues.setter def branchvalues(self, val): self["branchvalues"] = val @property def count(self): """ Determines default for `values` when it is not provided, by inferring a 1 for each of the "leaves" and/or "branches", otherwise 0. The 'count' property is a flaglist and may be specified as a string containing: - Any combination of ['branches', 'leaves'] joined with '+' characters (e.g. 'branches+leaves') Returns ------- Any """ return self["count"] @count.setter def count(self, val): self["count"] = val @property def customdata(self): """ Assigns extra data each datum. This may be useful when listening to hover, click and selection events. Note that, "scatter" traces also appends customdata items in the markers DOM elements The 'customdata' property is an array that may be specified as a tuple, list, numpy array, or pandas Series Returns ------- numpy.ndarray """ return self["customdata"] @customdata.setter def customdata(self, val): self["customdata"] = val @property def customdatasrc(self): """ Sets the source reference on Chart Studio Cloud for `customdata`. The 'customdatasrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["customdatasrc"] @customdatasrc.setter def customdatasrc(self, val): self["customdatasrc"] = val @property def domain(self): """ The 'domain' property is an instance of Domain that may be specified as: - An instance of :class:`plotly.graph_objs.sunburst.Domain` - A dict of string/value properties that will be passed to the Domain constructor Returns ------- plotly.graph_objs.sunburst.Domain """ return self["domain"] @domain.setter def domain(self, val): self["domain"] = val @property def hoverinfo(self): """ Determines which trace information appear on hover. If `none` or `skip` are set, no information is displayed upon hovering. But, if `none` is set, click and hover events are still fired. The 'hoverinfo' property is a flaglist and may be specified as a string containing: - Any combination of ['label', 'text', 'value', 'name', 'current path', 'percent root', 'percent entry', 'percent parent'] joined with '+' characters (e.g. 'label+text') OR exactly one of ['all', 'none', 'skip'] (e.g. 'skip') - A list or array of the above Returns ------- Any|numpy.ndarray """ return self["hoverinfo"] @hoverinfo.setter def hoverinfo(self, val): self["hoverinfo"] = val @property def hoverinfosrc(self): """ Sets the source reference on Chart Studio Cloud for `hoverinfo`. The 'hoverinfosrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["hoverinfosrc"] @hoverinfosrc.setter def hoverinfosrc(self, val): self["hoverinfosrc"] = val @property def hoverlabel(self): """ The 'hoverlabel' property is an instance of Hoverlabel that may be specified as: - An instance of :class:`plotly.graph_objs.sunburst.Hoverlabel` - A dict of string/value properties that will be passed to the Hoverlabel constructor Returns ------- plotly.graph_objs.sunburst.Hoverlabel """ return self["hoverlabel"] @hoverlabel.setter def hoverlabel(self, val): self["hoverlabel"] = val @property def hovertemplate(self): """ Template string used for rendering the information that appear on hover box. Note that this will override `hoverinfo`. Variables are inserted using %{variable}, for example "y: %{y}" as well as %{xother}, {%_xother}, {%_xother_}, {%xother_}. When showing info for several points, "xother" will be added to those with different x positions from the first point. An underscore before or after "(x|y)other" will add a space on that side, only when this field is shown. Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-format/tree/v1.4.5#d3-format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time-format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-time- format/tree/v2.2.3#locale_format for details on the date formatting syntax. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. The variables available in `hovertemplate` are the ones emitted as event data described at this link https://plotly.com/javascript/plotlyjs-events/#event- data. Additionally, all attributes that can be specified per- point (the ones that are `arrayOk: true`) are available. Finally, the template string has access to variables `currentPath`, `root`, `entry`, `percentRoot`, `percentEntry` and `percentParent`. Anything contained in tag `<extra>` is displayed in the secondary box, for example `<extra>%{fullData.name}</extra>`. To hide the secondary box completely, use an empty tag `<extra></extra>`. The 'hovertemplate' property is a string and must be specified as: - A string - A number that will be converted to a string - A tuple, list, or one-dimensional numpy array of the above Returns ------- str|numpy.ndarray """ return self["hovertemplate"] @hovertemplate.setter def hovertemplate(self, val): self["hovertemplate"] = val @property def hovertemplatefallback(self): """ Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. The 'hovertemplatefallback' property accepts values of any type Returns ------- Any """ return self["hovertemplatefallback"] @hovertemplatefallback.setter def hovertemplatefallback(self, val): self["hovertemplatefallback"] = val @property def hovertemplatesrc(self): """ Sets the source reference on Chart Studio Cloud for `hovertemplate`. The 'hovertemplatesrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["hovertemplatesrc"] @hovertemplatesrc.setter def hovertemplatesrc(self, val): self["hovertemplatesrc"] = val @property def hovertext(self): """ Sets hover text elements associated with each sector. If a single string, the same string appears for all data points. If an array of string, the items are mapped in order of this trace's sectors. To be seen, trace `hoverinfo` must contain a "text" flag. The 'hovertext' property is a string and must be specified as: - A string - A number that will be converted to a string - A tuple, list, or one-dimensional numpy array of the above Returns ------- str|numpy.ndarray """ return self["hovertext"] @hovertext.setter def hovertext(self, val): self["hovertext"] = val @property def hovertextsrc(self): """ Sets the source reference on Chart Studio Cloud for `hovertext`. The 'hovertextsrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["hovertextsrc"] @hovertextsrc.setter def hovertextsrc(self, val): self["hovertextsrc"] = val @property def ids(self): """ Assigns id labels to each datum. These ids for object constancy of data points during animation. Should be an array of strings, not numbers or any other type. The 'ids' property is an array that may be specified as a tuple, list, numpy array, or pandas Series Returns ------- numpy.ndarray """ return self["ids"] @ids.setter def ids(self, val): self["ids"] = val @property def idssrc(self): """ Sets the source reference on Chart Studio Cloud for `ids`. The 'idssrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["idssrc"] @idssrc.setter def idssrc(self, val): self["idssrc"] = val @property def insidetextfont(self): """ Sets the font used for `textinfo` lying inside the sector. The 'insidetextfont' property is an instance of Insidetextfont that may be specified as: - An instance of :class:`plotly.graph_objs.sunburst.Insidetextfont` - A dict of string/value properties that will be passed to the Insidetextfont constructor Returns ------- plotly.graph_objs.sunburst.Insidetextfont """ return self["insidetextfont"] @insidetextfont.setter def insidetextfont(self, val): self["insidetextfont"] = val @property def insidetextorientation(self): """ Controls the orientation of the text inside chart sectors. When set to "auto", text may be oriented in any direction in order to be as big as possible in the middle of a sector. The "horizontal" option orients text to be parallel with the bottom of the chart, and may make text smaller in order to achieve that goal. The "radial" option orients text along the radius of the sector. The "tangential" option orients text perpendicular to the radius of the sector. The 'insidetextorientation' property is an enumeration that may be specified as: - One of the following enumeration values: ['horizontal', 'radial', 'tangential', 'auto'] Returns ------- Any """ return self["insidetextorientation"] @insidetextorientation.setter def insidetextorientation(self, val): self["insidetextorientation"] = val @property def labels(self): """ Sets the labels of each of the sectors. The 'labels' property is an array that may be specified as a tuple, list, numpy array, or pandas Series Returns ------- numpy.ndarray """ return self["labels"] @labels.setter def labels(self, val): self["labels"] = val @property def labelssrc(self): """ Sets the source reference on Chart Studio Cloud for `labels`. The 'labelssrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["labelssrc"] @labelssrc.setter def labelssrc(self, val): self["labelssrc"] = val @property def leaf(self): """ The 'leaf' property is an instance of Leaf that may be specified as: - An instance of :class:`plotly.graph_objs.sunburst.Leaf` - A dict of string/value properties that will be passed to the Leaf constructor Returns ------- plotly.graph_objs.sunburst.Leaf """ return self["leaf"] @leaf.setter def leaf(self, val): self["leaf"] = val @property def legend(self): """ Sets the reference to a legend to show this trace in. References to these legends are "legend", "legend2", "legend3", etc. Settings for these legends are set in the layout, under `layout.legend`, `layout.legend2`, etc. The 'legend' property is an identifier of a particular subplot, of type 'legend', that may be specified as the string 'legend' optionally followed by an integer >= 1 (e.g. 'legend', 'legend1', 'legend2', 'legend3', etc.) Returns ------- str """ return self["legend"] @legend.setter def legend(self, val): self["legend"] = val @property def legendgrouptitle(self): """ The 'legendgrouptitle' property is an instance of Legendgrouptitle that may be specified as: - An instance of :class:`plotly.graph_objs.sunburst.Legendgrouptitle` - A dict of string/value properties that will be passed to the Legendgrouptitle constructor Returns ------- plotly.graph_objs.sunburst.Legendgrouptitle """ return self["legendgrouptitle"] @legendgrouptitle.setter def legendgrouptitle(self, val): self["legendgrouptitle"] = val @property def legendrank(self): """ Sets the legend rank for this trace. Items and groups with smaller ranks are presented on top/left side while with "reversed" `legend.traceorder` they are on bottom/right side. The default legendrank is 1000, so that you can use ranks less than 1000 to place certain items before all unranked items, and ranks greater than 1000 to go after all unranked items. When having unranked or equal rank items shapes would be displayed after traces i.e. according to their order in data and layout. The 'legendrank' property is a number and may be specified as: - An int or float Returns ------- int|float """ return self["legendrank"] @legendrank.setter def legendrank(self, val): self["legendrank"] = val @property def legendwidth(self): """ Sets the width (in px or fraction) of the legend for this trace. The 'legendwidth' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ return self["legendwidth"] @legendwidth.setter def legendwidth(self, val): self["legendwidth"] = val @property def level(self): """ Sets the level from which this trace hierarchy is rendered. Set `level` to `''` to start from the root node in the hierarchy. Must be an "id" if `ids` is filled in, otherwise plotly attempts to find a matching item in `labels`. The 'level' property accepts values of any type Returns ------- Any """ return self["level"] @level.setter def level(self, val): self["level"] = val @property def marker(self): """ The 'marker' property is an instance of Marker that may be specified as: - An instance of :class:`plotly.graph_objs.sunburst.Marker` - A dict of string/value properties that will be passed to the Marker constructor Returns ------- plotly.graph_objs.sunburst.Marker """ return self["marker"] @marker.setter def marker(self, val): self["marker"] = val @property def maxdepth(self): """ Sets the number of rendered sectors from any given `level`. Set `maxdepth` to "-1" to render all the levels in the hierarchy. The 'maxdepth' property is a integer and may be specified as: - An int (or float that will be cast to an int) Returns ------- int """ return self["maxdepth"] @maxdepth.setter def maxdepth(self, val): self["maxdepth"] = val @property def meta(self): """ Assigns extra meta information associated with this trace that can be used in various text attributes. Attributes such as trace `name`, graph, axis and colorbar `title.text`, annotation `text` `rangeselector`, `updatemenues` and `sliders` `label` text all support `meta`. To access the trace `meta` values in an attribute in the same trace, simply use `%{meta[i]}` where `i` is the index or key of the `meta` item in question. To access trace `meta` in layout attributes, use `%{data[n[.meta[i]}` where `i` is the index or key of the `meta` and `n` is the trace index. The 'meta' property accepts values of any type Returns ------- Any|numpy.ndarray """ return self["meta"] @meta.setter def meta(self, val): self["meta"] = val @property def metasrc(self): """ Sets the source reference on Chart Studio Cloud for `meta`. The 'metasrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["metasrc"] @metasrc.setter def metasrc(self, val): self["metasrc"] = val @property def name(self): """ Sets the trace name. The trace name appears as the legend item and on hover. The 'name' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str """ return self["name"] @name.setter def name(self, val): self["name"] = val @property def opacity(self): """ Sets the opacity of the trace. The 'opacity' property is a number and may be specified as: - An int or float in the interval [0, 1] Returns ------- int|float """ return self["opacity"] @opacity.setter def opacity(self, val): self["opacity"] = val @property def outsidetextfont(self): """ Sets the font used for `textinfo` lying outside the sector. This option refers to the root of the hierarchy presented at the center of a sunburst graph. Please note that if a hierarchy has multiple root nodes, this option won't have any effect and `insidetextfont` would be used. The 'outsidetextfont' property is an instance of Outsidetextfont that may be specified as: - An instance of :class:`plotly.graph_objs.sunburst.Outsidetextfont` - A dict of string/value properties that will be passed to the Outsidetextfont constructor Returns ------- plotly.graph_objs.sunburst.Outsidetextfont """ return self["outsidetextfont"] @outsidetextfont.setter def outsidetextfont(self, val): self["outsidetextfont"] = val @property def parents(self): """ Sets the parent sectors for each of the sectors. Empty string items '' are understood to reference the root node in the hierarchy. If `ids` is filled, `parents` items are understood to be "ids" themselves. When `ids` is not set, plotly attempts to find matching items in `labels`, but beware they must be unique. The 'parents' property is an array that may be specified as a tuple, list, numpy array, or pandas Series Returns ------- numpy.ndarray """ return self["parents"] @parents.setter def parents(self, val): self["parents"] = val @property def parentssrc(self): """ Sets the source reference on Chart Studio Cloud for `parents`. The 'parentssrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["parentssrc"] @parentssrc.setter def parentssrc(self, val): self["parentssrc"] = val @property def root(self): """ The 'root' property is an instance of Root that may be specified as: - An instance of :class:`plotly.graph_objs.sunburst.Root` - A dict of string/value properties that will be passed to the Root constructor Returns ------- plotly.graph_objs.sunburst.Root """ return self["root"] @root.setter def root(self, val): self["root"] = val @property def rotation(self): """ Rotates the whole diagram counterclockwise by some angle. By default the first slice starts at 3 o'clock. The 'rotation' property is a angle (in degrees) that may be specified as a number between -180 and 180. Numeric values outside this range are converted to the equivalent value (e.g. 270 is converted to -90). Returns ------- int|float """ return self["rotation"] @rotation.setter def rotation(self, val): self["rotation"] = val @property def sort(self): """ Determines whether or not the sectors are reordered from largest to smallest. The 'sort' property must be specified as a bool (either True, or False) Returns ------- bool """ return self["sort"] @sort.setter def sort(self, val): self["sort"] = val @property def stream(self): """ The 'stream' property is an instance of Stream that may be specified as: - An instance of :class:`plotly.graph_objs.sunburst.Stream` - A dict of string/value properties that will be passed to the Stream constructor Returns ------- plotly.graph_objs.sunburst.Stream """ return self["stream"] @stream.setter def stream(self, val): self["stream"] = val @property def text(self): """ Sets text elements associated with each sector. If trace `textinfo` contains a "text" flag, these elements will be seen on the chart. If trace `hoverinfo` contains a "text" flag and "hovertext" is not set, these elements will be seen in the hover labels. The 'text' property is an array that may be specified as a tuple, list, numpy array, or pandas Series Returns ------- numpy.ndarray """ return self["text"] @text.setter def text(self, val): self["text"] = val @property def textfont(self): """ Sets the font used for `textinfo`. The 'textfont' property is an instance of Textfont that may be specified as: - An instance of :class:`plotly.graph_objs.sunburst.Textfont` - A dict of string/value properties that will be passed to the Textfont constructor Returns ------- plotly.graph_objs.sunburst.Textfont """ return self["textfont"] @textfont.setter def textfont(self, val): self["textfont"] = val @property def textinfo(self): """ Determines which trace information appear on the graph. The 'textinfo' property is a flaglist and may be specified as a string containing: - Any combination of ['label', 'text', 'value', 'current path', 'percent root', 'percent entry', 'percent parent'] joined with '+' characters (e.g. 'label+text') OR exactly one of ['none'] (e.g. 'none') Returns ------- Any """ return self["textinfo"] @textinfo.setter def textinfo(self, val): self["textinfo"] = val @property def textsrc(self): """ Sets the source reference on Chart Studio Cloud for `text`. The 'textsrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["textsrc"] @textsrc.setter def textsrc(self, val): self["textsrc"] = val @property def texttemplate(self): """ Template string used for rendering the information text that appears on points. Note that this will override `textinfo`. Variables are inserted using %{variable}, for example "y: %{y}". Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-format/tree/v1.4.5#d3-format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time-format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-time- format/tree/v2.2.3#locale_format for details on the date formatting syntax. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. All attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. Finally, the template string has access to variables `currentPath`, `root`, `entry`, `percentRoot`, `percentEntry`, `percentParent`, `label` and `value`. The 'texttemplate' property is a string and must be specified as: - A string - A number that will be converted to a string - A tuple, list, or one-dimensional numpy array of the above Returns ------- str|numpy.ndarray """ return self["texttemplate"] @texttemplate.setter def texttemplate(self, val): self["texttemplate"] = val @property def texttemplatefallback(self): """ Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. The 'texttemplatefallback' property accepts values of any type Returns ------- Any """ return self["texttemplatefallback"] @texttemplatefallback.setter def texttemplatefallback(self, val): self["texttemplatefallback"] = val @property def texttemplatesrc(self): """ Sets the source reference on Chart Studio Cloud for `texttemplate`. The 'texttemplatesrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["texttemplatesrc"] @texttemplatesrc.setter def texttemplatesrc(self, val): self["texttemplatesrc"] = val @property def uid(self): """ Assign an id to this trace, Use this to provide object constancy between traces during animations and transitions. The 'uid' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str """ return self["uid"] @uid.setter def uid(self, val): self["uid"] = val @property def uirevision(self): """ Controls persistence of some user-driven changes to the trace: `constraintrange` in `parcoords` traces, as well as some `editable: true` modifications such as `name` and `colorbar.title`. Defaults to `layout.uirevision`. Note that other user-driven trace attribute changes are controlled by `layout` attributes: `trace.visible` is controlled by `layout.legend.uirevision`, `selectedpoints` is controlled by `layout.selectionrevision`, and `colorbar.(x|y)` (accessible with `config: {editable: true}`) is controlled by `layout.editrevision`. Trace changes are tracked by `uid`, which only falls back on trace index if no `uid` is provided. So if your app can add/remove traces before the end of the `data` array, such that the same trace has a different index, you can still preserve user-driven changes if you give each trace a `uid` that stays with it as it moves. The 'uirevision' property accepts values of any type Returns ------- Any """ return self["uirevision"] @uirevision.setter def uirevision(self, val): self["uirevision"] = val @property def values(self): """ Sets the values associated with each of the sectors. Use with `branchvalues` to determine how the values are summed. The 'values' property is an array that may be specified as a tuple, list, numpy array, or pandas Series Returns ------- numpy.ndarray """ return self["values"] @values.setter def values(self, val): self["values"] = val @property def valuessrc(self): """ Sets the source reference on Chart Studio Cloud for `values`. The 'valuessrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["valuessrc"] @valuessrc.setter def valuessrc(self, val): self["valuessrc"] = val @property def visible(self): """ Determines whether or not this trace is visible. If "legendonly", the trace is not drawn, but can appear as a legend item (provided that the legend itself is visible). The 'visible' property is an enumeration that may be specified as: - One of the following enumeration values: [True, False, 'legendonly'] Returns ------- Any """ return self["visible"] @visible.setter def visible(self, val): self["visible"] = val @property def type(self): return self._props["type"] @property def _prop_descriptions(self): return """\ branchvalues Determines how the items in `values` are summed. When set to "total", items in `values` are taken to be value of all its descendants. When set to "remainder", items in `values` corresponding to the root and the branches sectors are taken to be the extra part not part of the sum of the values at their leaves. count Determines default for `values` when it is not provided, by inferring a 1 for each of the "leaves" and/or "branches", otherwise 0. customdata Assigns extra data each datum. This may be useful when listening to hover, click and selection events. Note that, "scatter" traces also appends customdata items in the markers DOM elements customdatasrc Sets the source reference on Chart Studio Cloud for `customdata`. domain :class:`plotly.graph_objects.sunburst.Domain` instance or dict with compatible properties hoverinfo Determines which trace information appear on hover. If `none` or `skip` are set, no information is displayed upon hovering. But, if `none` is set, click and hover events are still fired. hoverinfosrc Sets the source reference on Chart Studio Cloud for `hoverinfo`. hoverlabel :class:`plotly.graph_objects.sunburst.Hoverlabel` instance or dict with compatible properties hovertemplate Template string used for rendering the information that appear on hover box. Note that this will override `hoverinfo`. Variables are inserted using %{variable}, for example "y: %{y}" as well as %{xother}, {%_xother}, {%_xother_}, {%xother_}. When showing info for several points, "xother" will be added to those with different x positions from the first point. An underscore before or after "(x|y)other" will add a space on that side, only when this field is shown. Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-format/tree/v1.4.5#d3-format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time-format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-time- format/tree/v2.2.3#locale_format for details on the date formatting syntax. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. The variables available in `hovertemplate` are the ones emitted as event data described at this link https://plotly.com/javascript/plotlyjs-events/#event- data. Additionally, all attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. Finally, the template string has access to variables `currentPath`, `root`, `entry`, `percentRoot`, `percentEntry` and `percentParent`. Anything contained in tag `<extra>` is displayed in the secondary box, for example `<extra>%{fullData.name}</extra>`. To hide the secondary box completely, use an empty tag `<extra></extra>`. hovertemplatefallback Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. hovertemplatesrc Sets the source reference on Chart Studio Cloud for `hovertemplate`. hovertext Sets hover text elements associated with each sector. If a single string, the same string appears for all data points. If an array of string, the items are mapped in order of this trace's sectors. To be seen, trace `hoverinfo` must contain a "text" flag. hovertextsrc Sets the source reference on Chart Studio Cloud for `hovertext`. ids Assigns id labels to each datum. These ids for object constancy of data points during animation. Should be an array of strings, not numbers or any other type. idssrc Sets the source reference on Chart Studio Cloud for `ids`. insidetextfont Sets the font used for `textinfo` lying inside the sector. insidetextorientation Controls the orientation of the text inside chart sectors. When set to "auto", text may be oriented in any direction in order to be as big as possible in the middle of a sector. The "horizontal" option orients text to be parallel with the bottom of the chart, and may make text smaller in order to achieve that goal. The "radial" option orients text along the radius of the sector. The "tangential" option orients text perpendicular to the radius of the sector. labels Sets the labels of each of the sectors. labelssrc Sets the source reference on Chart Studio Cloud for `labels`. leaf :class:`plotly.graph_objects.sunburst.Leaf` instance or dict with compatible properties legend Sets the reference to a legend to show this trace in. References to these legends are "legend", "legend2", "legend3", etc. Settings for these legends are set in the layout, under `layout.legend`, `layout.legend2`, etc. legendgrouptitle :class:`plotly.graph_objects.sunburst.Legendgrouptitle` instance or dict with compatible properties legendrank Sets the legend rank for this trace. Items and groups with smaller ranks are presented on top/left side while with "reversed" `legend.traceorder` they are on bottom/right side. The default legendrank is 1000, so that you can use ranks less than 1000 to place certain items before all unranked items, and ranks greater than 1000 to go after all unranked items. When having unranked or equal rank items shapes would be displayed after traces i.e. according to their order in data and layout. legendwidth Sets the width (in px or fraction) of the legend for this trace. level Sets the level from which this trace hierarchy is rendered. Set `level` to `''` to start from the root node in the hierarchy. Must be an "id" if `ids` is filled in, otherwise plotly attempts to find a matching item in `labels`. marker :class:`plotly.graph_objects.sunburst.Marker` instance or dict with compatible properties maxdepth Sets the number of rendered sectors from any given `level`. Set `maxdepth` to "-1" to render all the levels in the hierarchy. meta Assigns extra meta information associated with this trace that can be used in various text attributes. Attributes such as trace `name`, graph, axis and colorbar `title.text`, annotation `text` `rangeselector`, `updatemenues` and `sliders` `label` text all support `meta`. To access the trace `meta` values in an attribute in the same trace, simply use `%{meta[i]}` where `i` is the index or key of the `meta` item in question. To access trace `meta` in layout attributes, use `%{data[n[.meta[i]}` where `i` is the index or key of the `meta` and `n` is the trace index. metasrc Sets the source reference on Chart Studio Cloud for `meta`. name Sets the trace name. The trace name appears as the legend item and on hover. opacity Sets the opacity of the trace. outsidetextfont Sets the font used for `textinfo` lying outside the sector. This option refers to the root of the hierarchy presented at the center of a sunburst graph. Please note that if a hierarchy has multiple root nodes, this option won't have any effect and `insidetextfont` would be used. parents Sets the parent sectors for each of the sectors. Empty string items '' are understood to reference the root node in the hierarchy. If `ids` is filled, `parents` items are understood to be "ids" themselves. When `ids` is not set, plotly attempts to find matching items in `labels`, but beware they must be unique. parentssrc Sets the source reference on Chart Studio Cloud for `parents`. root :class:`plotly.graph_objects.sunburst.Root` instance or dict with compatible properties rotation Rotates the whole diagram counterclockwise by some angle. By default the first slice starts at 3 o'clock. sort Determines whether or not the sectors are reordered from largest to smallest. stream :class:`plotly.graph_objects.sunburst.Stream` instance or dict with compatible properties text Sets text elements associated with each sector. If trace `textinfo` contains a "text" flag, these elements will be seen on the chart. If trace `hoverinfo` contains a "text" flag and "hovertext" is not set, these elements will be seen in the hover labels. textfont Sets the font used for `textinfo`. textinfo Determines which trace information appear on the graph. textsrc Sets the source reference on Chart Studio Cloud for `text`. texttemplate Template string used for rendering the information text that appears on points. Note that this will override `textinfo`. Variables are inserted using %{variable}, for example "y: %{y}". Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-format/tree/v1.4.5#d3-format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time-format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-time- format/tree/v2.2.3#locale_format for details on the date formatting syntax. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. All attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. Finally, the template string has access to variables `currentPath`, `root`, `entry`, `percentRoot`, `percentEntry`, `percentParent`, `label` and `value`. texttemplatefallback Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. texttemplatesrc Sets the source reference on Chart Studio Cloud for `texttemplate`. uid Assign an id to this trace, Use this to provide object constancy between traces during animations and transitions. uirevision Controls persistence of some user-driven changes to the trace: `constraintrange` in `parcoords` traces, as well as some `editable: true` modifications such as `name` and `colorbar.title`. Defaults to `layout.uirevision`. Note that other user-driven trace attribute changes are controlled by `layout` attributes: `trace.visible` is controlled by `layout.legend.uirevision`, `selectedpoints` is controlled by `layout.selectionrevision`, and `colorbar.(x|y)` (accessible with `config: {editable: true}`) is controlled by `layout.editrevision`. Trace changes are tracked by `uid`, which only falls back on trace index if no `uid` is provided. So if your app can add/remove traces before the end of the `data` array, such that the same trace has a different index, you can still preserve user-driven changes if you give each trace a `uid` that stays with it as it moves. values Sets the values associated with each of the sectors. Use with `branchvalues` to determine how the values are summed. valuessrc Sets the source reference on Chart Studio Cloud for `values`. visible Determines whether or not this trace is visible. If "legendonly", the trace is not drawn, but can appear as a legend item (provided that the legend itself is visible). """ def __init__( self, arg=None, branchvalues=None, count=None, customdata=None, customdatasrc=None, domain=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hovertemplate=None, hovertemplatefallback=None, hovertemplatesrc=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, insidetextfont=None, insidetextorientation=None, labels=None, labelssrc=None, leaf=None, legend=None, legendgrouptitle=None, legendrank=None, legendwidth=None, level=None, marker=None, maxdepth=None, meta=None, metasrc=None, name=None, opacity=None, outsidetextfont=None, parents=None, parentssrc=None, root=None, rotation=None, sort=None, stream=None, text=None, textfont=None, textinfo=None, textsrc=None, texttemplate=None, texttemplatefallback=None, texttemplatesrc=None, uid=None, uirevision=None, values=None, valuessrc=None, visible=None, **kwargs, ): """ Construct a new Sunburst object Visualize hierarchal data spanning outward radially from root to leaves. The sunburst sectors are determined by the entries in "labels" or "ids" and in "parents". Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.Sunburst` branchvalues Determines how the items in `values` are summed. When set to "total", items in `values` are taken to be value of all its descendants. When set to "remainder", items in `values` corresponding to the root and the branches sectors are taken to be the extra part not part of the sum of the values at their leaves. count Determines default for `values` when it is not provided, by inferring a 1 for each of the "leaves" and/or "branches", otherwise 0. customdata Assigns extra data each datum. This may be useful when listening to hover, click and selection events. Note that, "scatter" traces also appends customdata items in the markers DOM elements customdatasrc Sets the source reference on Chart Studio Cloud for `customdata`. domain :class:`plotly.graph_objects.sunburst.Domain` instance or dict with compatible properties hoverinfo Determines which trace information appear on hover. If `none` or `skip` are set, no information is displayed upon hovering. But, if `none` is set, click and hover events are still fired. hoverinfosrc Sets the source reference on Chart Studio Cloud for `hoverinfo`. hoverlabel :class:`plotly.graph_objects.sunburst.Hoverlabel` instance or dict with compatible properties hovertemplate Template string used for rendering the information that appear on hover box. Note that this will override `hoverinfo`. Variables are inserted using %{variable}, for example "y: %{y}" as well as %{xother}, {%_xother}, {%_xother_}, {%xother_}. When showing info for several points, "xother" will be added to those with different x positions from the first point. An underscore before or after "(x|y)other" will add a space on that side, only when this field is shown. Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-format/tree/v1.4.5#d3-format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time-format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-time- format/tree/v2.2.3#locale_format for details on the date formatting syntax. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. The variables available in `hovertemplate` are the ones emitted as event data described at this link https://plotly.com/javascript/plotlyjs-events/#event- data. Additionally, all attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. Finally, the template string has access to variables `currentPath`, `root`, `entry`, `percentRoot`, `percentEntry` and `percentParent`. Anything contained in tag `<extra>` is displayed in the secondary box, for example `<extra>%{fullData.name}</extra>`. To hide the secondary box completely, use an empty tag `<extra></extra>`. hovertemplatefallback Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. hovertemplatesrc Sets the source reference on Chart Studio Cloud for `hovertemplate`. hovertext Sets hover text elements associated with each sector. If a single string, the same string appears for all data points. If an array of string, the items are mapped in order of this trace's sectors. To be seen, trace `hoverinfo` must contain a "text" flag. hovertextsrc Sets the source reference on Chart Studio Cloud for `hovertext`. ids Assigns id labels to each datum. These ids for object constancy of data points during animation. Should be an array of strings, not numbers or any other type. idssrc Sets the source reference on Chart Studio Cloud for `ids`. insidetextfont Sets the font used for `textinfo` lying inside the sector. insidetextorientation Controls the orientation of the text inside chart sectors. When set to "auto", text may be oriented in any direction in order to be as big as possible in the middle of a sector. The "horizontal" option orients text to be parallel with the bottom of the chart, and may make text smaller in order to achieve that goal. The "radial" option orients text along the radius of the sector. The "tangential" option orients text perpendicular to the radius of the sector. labels Sets the labels of each of the sectors. labelssrc Sets the source reference on Chart Studio Cloud for `labels`. leaf :class:`plotly.graph_objects.sunburst.Leaf` instance or dict with compatible properties legend Sets the reference to a legend to show this trace in. References to these legends are "legend", "legend2", "legend3", etc. Settings for these legends are set in the layout, under `layout.legend`, `layout.legend2`, etc. legendgrouptitle :class:`plotly.graph_objects.sunburst.Legendgrouptitle` instance or dict with compatible properties legendrank Sets the legend rank for this trace. Items and groups with smaller ranks are presented on top/left side while with "reversed" `legend.traceorder` they are on bottom/right side. The default legendrank is 1000, so that you can use ranks less than 1000 to place certain items before all unranked items, and ranks greater than 1000 to go after all unranked items. When having unranked or equal rank items shapes would be displayed after traces i.e. according to their order in data and layout. legendwidth Sets the width (in px or fraction) of the legend for this trace. level Sets the level from which this trace hierarchy is rendered. Set `level` to `''` to start from the root node in the hierarchy. Must be an "id" if `ids` is filled in, otherwise plotly attempts to find a matching item in `labels`. marker :class:`plotly.graph_objects.sunburst.Marker` instance or dict with compatible properties maxdepth Sets the number of rendered sectors from any given `level`. Set `maxdepth` to "-1" to render all the levels in the hierarchy. meta Assigns extra meta information associated with this trace that can be used in various text attributes. Attributes such as trace `name`, graph, axis and colorbar `title.text`, annotation `text` `rangeselector`, `updatemenues` and `sliders` `label` text all support `meta`. To access the trace `meta` values in an attribute in the same trace, simply use `%{meta[i]}` where `i` is the index or key of the `meta` item in question. To access trace `meta` in layout attributes, use `%{data[n[.meta[i]}` where `i` is the index or key of the `meta` and `n` is the trace index. metasrc Sets the source reference on Chart Studio Cloud for `meta`. name Sets the trace name. The trace name appears as the legend item and on hover. opacity Sets the opacity of the trace. outsidetextfont Sets the font used for `textinfo` lying outside the sector. This option refers to the root of the hierarchy presented at the center of a sunburst graph. Please note that if a hierarchy has multiple root nodes, this option won't have any effect and `insidetextfont` would be used. parents Sets the parent sectors for each of the sectors. Empty string items '' are understood to reference the root node in the hierarchy. If `ids` is filled, `parents` items are understood to be "ids" themselves. When `ids` is not set, plotly attempts to find matching items in `labels`, but beware they must be unique. parentssrc Sets the source reference on Chart Studio Cloud for `parents`. root :class:`plotly.graph_objects.sunburst.Root` instance or dict with compatible properties rotation Rotates the whole diagram counterclockwise by some angle. By default the first slice starts at 3 o'clock. sort Determines whether or not the sectors are reordered from largest to smallest. stream :class:`plotly.graph_objects.sunburst.Stream` instance or dict with compatible properties text Sets text elements associated with each sector. If trace `textinfo` contains a "text" flag, these elements will be seen on the chart. If trace `hoverinfo` contains a "text" flag and "hovertext" is not set, these elements will be seen in the hover labels. textfont Sets the font used for `textinfo`. textinfo Determines which trace information appear on the graph. textsrc Sets the source reference on Chart Studio Cloud for `text`. texttemplate Template string used for rendering the information text that appears on points. Note that this will override `textinfo`. Variables are inserted using %{variable}, for example "y: %{y}". Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-format/tree/v1.4.5#d3-format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time-format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-time- format/tree/v2.2.3#locale_format for details on the date formatting syntax. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. All attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. Finally, the template string has access to variables `currentPath`, `root`, `entry`, `percentRoot`, `percentEntry`, `percentParent`, `label` and `value`. texttemplatefallback Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. texttemplatesrc Sets the source reference on Chart Studio Cloud for `texttemplate`. uid Assign an id to this trace, Use this to provide object constancy between traces during animations and transitions. uirevision Controls persistence of some user-driven changes to the trace: `constraintrange` in `parcoords` traces, as well as some `editable: true` modifications such as `name` and `colorbar.title`. Defaults to `layout.uirevision`. Note that other user-driven trace attribute changes are controlled by `layout` attributes: `trace.visible` is controlled by `layout.legend.uirevision`, `selectedpoints` is controlled by `layout.selectionrevision`, and `colorbar.(x|y)` (accessible with `config: {editable: true}`) is controlled by `layout.editrevision`. Trace changes are tracked by `uid`, which only falls back on trace index if no `uid` is provided. So if your app can add/remove traces before the end of the `data` array, such that the same trace has a different index, you can still preserve user-driven changes if you give each trace a `uid` that stays with it as it moves. values Sets the values associated with each of the sectors. Use with `branchvalues` to determine how the values are summed. valuessrc Sets the source reference on Chart Studio Cloud for `values`. visible Determines whether or not this trace is visible. If "legendonly", the trace is not drawn, but can appear as a legend item (provided that the legend itself is visible). Returns ------- Sunburst """ super().__init__("sunburst") if "_parent" in kwargs: self._parent = kwargs["_parent"] return if arg is None: arg = {} elif isinstance(arg, self.__class__): arg = arg.to_plotly_json() elif isinstance(arg, dict): arg = _copy.copy(arg) else: raise ValueError("""\ The first argument to the plotly.graph_objs.Sunburst constructor must be a dict or an instance of :class:`plotly.graph_objs.Sunburst`""") self._skip_invalid = kwargs.pop("skip_invalid", False) self._validate = kwargs.pop("_validate", True) self._set_property("branchvalues", arg, branchvalues) self._set_property("count", arg, count) self._set_property("customdata", arg, customdata) self._set_property("customdatasrc", arg, customdatasrc) self._set_property("domain", arg, domain) self._set_property("hoverinfo", arg, hoverinfo) self._set_property("hoverinfosrc", arg, hoverinfosrc) self._set_property("hoverlabel", arg, hoverlabel) self._set_property("hovertemplate", arg, hovertemplate) self._set_property("hovertemplatefallback", arg, hovertemplatefallback) self._set_property("hovertemplatesrc", arg, hovertemplatesrc) self._set_property("hovertext", arg, hovertext) self._set_property("hovertextsrc", arg, hovertextsrc) self._set_property("ids", arg, ids) self._set_property("idssrc", arg, idssrc) self._set_property("insidetextfont", arg, insidetextfont) self._set_property("insidetextorientation", arg, insidetextorientation) self._set_property("labels", arg, labels) self._set_property("labelssrc", arg, labelssrc) self._set_property("leaf", arg, leaf) self._set_property("legend", arg, legend) self._set_property("legendgrouptitle", arg, legendgrouptitle) self._set_property("legendrank", arg, legendrank) self._set_property("legendwidth", arg, legendwidth) self._set_property("level", arg, level) self._set_property("marker", arg, marker) self._set_property("maxdepth", arg, maxdepth) self._set_property("meta", arg, meta) self._set_property("metasrc", arg, metasrc) self._set_property("name", arg, name) self._set_property("opacity", arg, opacity) self._set_property("outsidetextfont", arg, outsidetextfont) self._set_property("parents", arg, parents) self._set_property("parentssrc", arg, parentssrc) self._set_property("root", arg, root) self._set_property("rotation", arg, rotation) self._set_property("sort", arg, sort) self._set_property("stream", arg, stream) self._set_property("text", arg, text) self._set_property("textfont", arg, textfont) self._set_property("textinfo", arg, textinfo) self._set_property("textsrc", arg, textsrc) self._set_property("texttemplate", arg, texttemplate) self._set_property("texttemplatefallback", arg, texttemplatefallback) self._set_property("texttemplatesrc", arg, texttemplatesrc) self._set_property("uid", arg, uid) self._set_property("uirevision", arg, uirevision) self._set_property("values", arg, values) self._set_property("valuessrc", arg, valuessrc) self._set_property("visible", arg, visible) self._props["type"] = "sunburst" arg.pop("type", None) self._process_kwargs(**dict(arg, **kwargs)) self._skip_invalid = False
Sunburst
python
great-expectations__great_expectations
tests/integration/conftest.py
{ "start": 985, "end": 9044 }
class ____: data_source_config: DataSourceTestConfig data: pd.DataFrame extra_data: Mapping[str, pd.DataFrame] secondary_source_config: Union[DataSourceTestConfig, None] = None secondary_data: Union[pd.DataFrame, None] = None @override def __hash__(self) -> int: if self.secondary_data is None and self.secondary_source_config is not None: raise ValueError( "secondary_data cannot be None when secondary_source_config is provided" ) return hash( ( self.__class__, hash_data_frame(self.data), dict_to_tuple( {k: hash_data_frame(self.extra_data[k]) for k in sorted(self.extra_data)} ), hash_data_frame(self.secondary_data) if self.secondary_data is not None else None, ) ) @override def __eq__(self, value: object) -> bool: # We need to implement this ourselves to call `.equals` on dataframes.` if not isinstance(value, TestConfig): return False return all( [ self.data_source_config == value.data_source_config, self.data.equals(value.data), self.extra_data.keys() == value.extra_data.keys(), all(self.extra_data[k].equals(value.extra_data[k]) for k in self.extra_data), self.secondary_source_config == value.secondary_source_config, (self.secondary_data is None and value.secondary_data is None) or ( self.secondary_data is not None and value.secondary_data is not None and self.secondary_data.equals(value.secondary_data) ), ] ) def parameterize_batch_for_data_sources( data_source_configs: Sequence[DataSourceTestConfig], data: pd.DataFrame, extra_data: Optional[Mapping[str, pd.DataFrame]] = None, ) -> Callable[[_F], _F]: """Test decorator that parametrizes a test function with batches for various data sources. This injects a `batch_for_datasource` parameter into the test function for each data source type. Args: data_source_configs: The data source configurations to test. data: Data to load into the asset extra_data: Mapping of {asset_label: data} to load into other assets. Only relevant for SQL multi-table expectations. NOTE: This is NOT the table name. The label is used to correlate the data with the types passed to DataSourceTestConfig.extra_column_types. example use: @parameterize_batch_for_data_sources( data_source_configs=[DataSourceType.FOO, DataSourceType.BAR], data=pd.DataFrame{"col_name": [1, 2]}, # description="test_stuff", ) def test_stuff(batch_for_datasource) -> None: ... """ if len(data_source_configs) == 0: raise ValueError("At least one data source configuration must be provided.") def decorator(func: _F) -> _F: pytest_params = [ pytest.param( TestConfig( data_source_config=config, data=data, extra_data=extra_data or {}, ), id=config.test_id, marks=[config.pytest_mark], ) for config in data_source_configs ] parameterize_decorator = pytest.mark.parametrize( _batch_setup_for_datasource.__name__, pytest_params, indirect=True, ) return parameterize_decorator(func) return decorator # NOTE on performance setup/teardown: # When we get equivalent TestConfigs, we only instantiate one BatchTestSetup for all of them, and # only perform its setup/teardown once. batch_for_datasource instantiate the BatchTestSetup # immediately before the first test that needs it and store it in cached_test_configs. Subsequent # tests that use the same TestConfig will reuse the same BatchTestSetup. At the end of the test # session, _cleanup will clean up all the BatchTestSetups. @pytest.fixture(scope="session") def _cached_test_configs() -> dict[TestConfig, BatchTestSetup]: """Fixture to hold cached test configurations across tests.""" cached_test_configs: dict[TestConfig, BatchTestSetup] = {} return cached_test_configs @pytest.fixture(scope="session") def _cached_secondary_test_configs() -> dict[UUID, BatchTestSetup]: """Fixture to hold secondary test configurations across tests.""" cached_test_configs: dict[UUID, BatchTestSetup] = {} return cached_test_configs @pytest.fixture(scope="session") def _cleanup( _cached_test_configs: Mapping[TestConfig, BatchTestSetup], _cached_secondary_test_configs: Mapping[TestConfig, BatchTestSetup], # While not explicitly used, we want the session_sql_engine_manager to # be torn down after we clean up. Adding it as a dependeny will ensure # this. session_sql_engine_manager: SessionSQLEngineManager, ) -> Generator[None, None, None]: """Fixture to do all teardown at the end of the test session.""" yield for batch_setup in _cached_test_configs.values(): batch_setup.teardown() for batch_setup in _cached_secondary_test_configs.values(): batch_setup.teardown() @pytest.fixture def _batch_setup_for_datasource( request: pytest.FixtureRequest, _cached_test_configs: dict[TestConfig, BatchTestSetup], _cached_secondary_test_configs: dict[UUID, BatchTestSetup], session_sql_engine_manager: SessionSQLEngineManager, # _cleanup is not called directly. It is a session scoped fixture # which will cleanup created db resources such as schemas. _cleanup: Callable[[], None], ) -> Generator[BatchTestSetup, None, None]: """Fixture that yields a BatchSetup for a specific data source type. This must be used in conjunction with `indirect=True` to defer execution """ config = request.param assert isinstance(config, TestConfig) if config not in _cached_test_configs: batch_setup = config.data_source_config.create_batch_setup( request=request, data=config.data, extra_data=config.extra_data, context=gx.get_context(mode="ephemeral"), engine_manager=session_sql_engine_manager, ) _cached_test_configs[config] = batch_setup batch_setup.setup() if config.secondary_source_config: assert config.secondary_data is not None, ( "Secondary data is required when secondary config is provided." ) secondary_batch_setup = config.secondary_source_config.create_batch_setup( request=request, data=config.secondary_data, extra_data={}, context=batch_setup.context, engine_manager=session_sql_engine_manager, ) _cached_secondary_test_configs[batch_setup.id] = secondary_batch_setup secondary_batch_setup.setup() yield _cached_test_configs[config] @pytest.fixture def batch_for_datasource( _batch_setup_for_datasource: BatchTestSetup, ) -> Generator[Batch, None, None]: """Fixture that yields a batch for a specific data source type. This must be used in conjunction with `indirect=True` to defer execution """ set_context(_batch_setup_for_datasource.context) yield _batch_setup_for_datasource.make_batch() @pytest.fixture def asset_for_datasource( _batch_setup_for_datasource: BatchTestSetup, ) -> Generator[DataAsset, None, None]: """Fixture that yields an asset for a specific data source type. This must be used in conjunction with `indirect=True` to defer execution """ set_context(_batch_setup_for_datasource.context) yield _batch_setup_for_datasource.make_asset() @dataclass(frozen=True)
TestConfig
python
google__jax
tests/lru_cache_test.py
{ "start": 846, "end": 1463 }
class ____(jtu.JaxTestCase): name: str | None path: pathlib.Path | None def setUp(self): if importlib.util.find_spec("filelock") is None: self.skipTest("filelock is not installed") super().setUp() tmpdir = tempfile.TemporaryDirectory() self.enter_context(tmpdir) self.name = tmpdir.name self.path = pathlib.Path(self.name) def tearDown(self): self.path = None self.name = None super().tearDown() def assertCacheKeys(self, keys): self.assertEqual(set(self.path.glob(f"*{_CACHE_SUFFIX}")), {self.path / f"{key}{_CACHE_SUFFIX}" for key in keys})
LRUCacheTestCase
python
great-expectations__great_expectations
tests/integration/metrics/column/test_values_not_match_regex_count.py
{ "start": 735, "end": 1756 }
class ____: @parameterize_batch_for_data_sources( data_source_configs=ALL_DATA_SOURCES_EXCEPT_SNOWFLAKE, data=DATA_FRAME, ) def test_partial_match_characters(self, batch_for_datasource: Batch) -> None: metric = ColumnValuesNotMatchRegexCount(column=COLUMN_NAME, regex="ab") metric_result = batch_for_datasource.compute_metrics(metric) assert isinstance(metric_result, ColumnValuesNotMatchRegexCountResult) assert metric_result.value == 2 @parameterize_batch_for_data_sources( data_source_configs=SPARK_DATA_SOURCES + SQL_DATA_SOURCES, data=DATA_FRAME, ) def test_special_characters(self, batch_for_datasource: Batch) -> None: metric = ColumnValuesNotMatchRegexCount(column=COLUMN_NAME, regex="^(a|d).+") metric_result = batch_for_datasource.compute_metrics(metric) assert isinstance(metric_result, ColumnValuesNotMatchRegexCountResult) assert metric_result.value == 3
TestColumnValuesNotMatchRegexCount
python
PrefectHQ__prefect
src/prefect/client/schemas/filters.py
{ "start": 30657, "end": 30869 }
class ____(PrefectBaseModel): """Filter by `Artifact.flow_run_id`.""" any_: Optional[List[UUID]] = Field( default=None, description="A list of flow run IDs to include" )
ArtifactFilterFlowRunId
python
dagster-io__dagster
python_modules/dagster/dagster/_core/execution/plan/handle.py
{ "start": 336, "end": 1704 }
class ____(NamedTuple("_StepHandle", [("node_handle", NodeHandle), ("key", str)])): """A reference to an ExecutionStep that was determined statically.""" def __new__(cls, node_handle: NodeHandle, key: Optional[str] = None): return super().__new__( cls, node_handle=check.inst_param(node_handle, "node_handle", NodeHandle), # mypy can't tell that if default is set, this is guaranteed to be a str key=cast("str", check.opt_str_param(key, "key", default=str(node_handle))), ) def to_key(self) -> str: return self.key @staticmethod def parse_from_key( string: str, ) -> Union["StepHandle", "ResolvedFromDynamicStepHandle", "UnresolvedStepHandle"]: unresolved_match = re.match(r"(.*)\[\?\]", string) if unresolved_match: return UnresolvedStepHandle(NodeHandle.from_string(unresolved_match.group(1))) resolved_match = re.match(r"(.*)\[(.*)\]", string) if resolved_match: return ResolvedFromDynamicStepHandle( NodeHandle.from_string(resolved_match.group(1)), resolved_match.group(2) ) return StepHandle(NodeHandle.from_string(string)) # Serialize node_handle -> solid_handle for backcompat @whitelist_for_serdes(storage_field_names={"node_handle": "solid_handle"})
StepHandle
python
PrefectHQ__prefect
src/integrations/prefect-docker/prefect_docker/worker.py
{ "start": 14775, "end": 37125 }
class ____(BaseWorker[DockerWorkerJobConfiguration, Any, DockerWorkerResult]): """Prefect worker that executes flow runs within Docker containers.""" type = "docker" job_configuration = DockerWorkerJobConfiguration _description = ( "Execute flow runs within Docker containers. Works well for managing flow " "execution environments via Docker images. Requires access to a running " "Docker daemon." ) _display_name = "Docker" _documentation_url = "https://docs.prefect.io/integrations/prefect-docker" _logo_url = "https://images.ctfassets.net/gm98wzqotmnx/2IfXXfMq66mrzJBDFFCHTp/6d8f320d9e4fc4393f045673d61ab612/Moby-logo.png?h=250" # noqa def __init__( self, *args: Any, test_mode: Optional[bool] = None, **kwargs: Any ) -> None: if test_mode is None: self.test_mode = bool(os.getenv("PREFECT_DOCKER_TEST_MODE", False)) else: self.test_mode = test_mode self.__tmp_dir = None super().__init__(*args, **kwargs) @property def _tmp_dir(self) -> str: """Returns a temporary directory for the worker.""" if self.__tmp_dir is None: self.__tmp_dir = tempfile.mkdtemp() return self.__tmp_dir async def setup(self): if not self.test_mode: self._client = get_client() if self._client.server_type == ServerType.EPHEMERAL: raise RuntimeError( "Docker worker cannot be used with an ephemeral server. Please set" " PREFECT_API_URL to the URL for your Prefect API instance. You" " can use a local Prefect API instance by running `prefect server" " start`." ) return await super().setup() async def _initiate_run( self, flow_run: "FlowRun", configuration: DockerWorkerJobConfiguration, ): """ Initiates a flow run within a Docker container. This method does not wait for the flow run to complete. """ await run_sync_in_worker_thread(self._create_and_start_container, configuration) async def run( self, flow_run: "FlowRun", configuration: DockerWorkerJobConfiguration, task_status: Optional[anyio.abc.TaskStatus[str]] = None, ) -> DockerWorkerResult: """ Executes a flow run within a Docker container and waits for the flow run to complete. """ # The `docker` library uses requests instead of an async http library so it must # be run in a thread to avoid blocking the event loop. container, created_event = await run_sync_in_worker_thread( self._create_and_start_container, configuration ) container_pid = self._get_infrastructure_pid(container_id=container.id) # Mark as started and return the infrastructure id if task_status: task_status.started(container_pid) # Monitor the container container = await run_sync_in_worker_thread( self._watch_container_safe, container, configuration, created_event ) exit_code = container.attrs["State"].get("ExitCode") return DockerWorkerResult( status_code=exit_code if exit_code is not None else -1, identifier=container_pid, ) async def _submit_adhoc_run( self, flow: prefect.Flow[..., R], parameters: dict[str, Any] | None = None, job_variables: dict[str, Any] | None = None, task_status: anyio.abc.TaskStatus[FlowRun] | None = None, ): """ Submit a flow to run in a Docker container. """ from prefect._experimental.bundles import ( convert_step_to_command, create_bundle_for_flow_run, ) storage_configured_on_work_pool = ( self.work_pool.storage_configuration.bundle_upload_step is not None and self.work_pool.storage_configuration.bundle_execution_step is not None ) bundle_key = str(uuid.uuid4()) upload_command = None if not storage_configured_on_work_pool: execute_command = convert_step_to_command( {"prefect._experimental.bundles.execute": {"requires": "prefect"}}, f"/tmp/{bundle_key}", ) existing_volumes: list[str] = ( get_from_dict( self.work_pool.base_job_template, "configuration.properties.volumes.default", ) or [] ) job_variable_volumes: list[str] = ( job_variables.get("volumes", []) if job_variables else [] ) job_variables = (job_variables or {}) | { "command": " ".join(execute_command), "volumes": [ *existing_volumes, *job_variable_volumes, # This is a temporary volume for the bundle f"{self._tmp_dir}:/tmp/", ], } else: if TYPE_CHECKING: assert ( self.work_pool.storage_configuration.bundle_upload_step is not None ) assert ( self.work_pool.storage_configuration.bundle_execution_step is not None ) upload_command = convert_step_to_command( self.work_pool.storage_configuration.bundle_upload_step, bundle_key, quiet=True, ) execute_command = convert_step_to_command( self.work_pool.storage_configuration.bundle_execution_step, bundle_key, ) job_variables = (job_variables or {}) | { "command": " ".join(execute_command) } flow_run = await self.client.create_flow_run( flow, parameters=parameters, state=Pending(), job_variables=job_variables, work_pool_name=self.work_pool.name, ) if task_status is not None: # Emit the flow run object to .submit to allow it to return a future as soon as possible task_status.started(flow_run) # Avoid an API call to get the flow api_flow = APIFlow(id=flow_run.flow_id, name=flow.name, labels={}) logger = self.get_flow_run_logger(flow_run) configuration = await self.job_configuration.from_template_and_values( base_job_template=self.work_pool.base_job_template, values=job_variables, client=self._client, ) configuration.prepare_for_flow_run( flow_run=flow_run, flow=api_flow, work_pool=self.work_pool, worker_name=self.name, ) bundle = create_bundle_for_flow_run(flow=flow, flow_run=flow_run) await ( anyio.Path(self._tmp_dir) .joinpath(bundle_key) .write_bytes(json.dumps(bundle).encode("utf-8")) ) if upload_command: try: full_command = upload_command + [bundle_key] logger.debug( "Uploading execution bundle with command: %s", full_command ) await anyio.run_process( full_command, cwd=self._tmp_dir, ) except subprocess.CalledProcessError as e: raise RuntimeError(e.stderr.decode("utf-8")) from e logger.debug("Successfully uploaded execution bundle") try: result = await self.run(flow_run=flow_run, configuration=configuration) if result.status_code != 0: await self._propose_crashed_state( flow_run, ( "Flow run infrastructure exited with non-zero status code" f" {result.status_code}." ), ) except Exception as exc: # This flow run was being submitted and did not start successfully logger.exception( f"Failed to submit flow run '{flow_run.id}' to infrastructure." ) message = f"Flow run could not be submitted to infrastructure:\n{exc!r}" await self._propose_crashed_state(flow_run, message) def _get_client(self): """Returns a docker client.""" try: with warnings.catch_warnings(): # Silence warnings due to use of deprecated methods within dockerpy # See https://github.com/docker/docker-py/pull/2931 warnings.filterwarnings( "ignore", message="distutils Version classes are deprecated.*", category=DeprecationWarning, ) timeout = int( os.environ.get( "DOCKER_CLIENT_TIMEOUT", DEFAULT_DOCKER_TIMEOUT_SECONDS ) ) docker_client = docker.from_env(timeout=timeout) except docker.errors.DockerException as exc: raise RuntimeError("Could not connect to Docker.") from exc return docker_client def _get_infrastructure_pid(self, container_id: str) -> str: """Generates a Docker infrastructure_pid string in the form of `<docker_host_base_url>:<container_id>`. """ docker_client = self._get_client() base_url = docker_client.api.base_url docker_client.close() return f"{base_url}:{container_id}" def _parse_infrastructure_pid(self, infrastructure_pid: str) -> Tuple[str, str]: """Splits a Docker infrastructure_pid into its component parts""" # base_url can contain `:` so we only want the last item of the split base_url, container_id = infrastructure_pid.rsplit(":", 1) return base_url, str(container_id) def _build_container_settings( self, docker_client: "DockerClient", configuration: DockerWorkerJobConfiguration, ) -> dict[str, Any]: """Builds a dictionary of container settings to pass to the Docker API.""" network_mode = configuration.get_network_mode() container_create_kwargs = ( configuration.container_create_kwargs if configuration.container_create_kwargs else {} ) # Check if volumes are being passed through container_create_kwargs if "volumes" in container_create_kwargs: warnings.warn( "volumes should be specified in job_variables rather than container_create_kwargs. " "Use job_variables={'volumes': ['/host/path:/container/path']} instead. " "The volumes in container_create_kwargs will be ignored.", UserWarning, stacklevel=2, ) container_create_kwargs = { k: v for k, v in container_create_kwargs.items() if k not in configuration.__class__.model_fields.keys() } # Get extra_hosts from configuration extra_hosts = configuration.get_extra_hosts(docker_client) # If user provided extra_hosts in container_create_kwargs, merge them if "extra_hosts" in container_create_kwargs: user_extra_hosts = container_create_kwargs.pop("extra_hosts") if extra_hosts: # Merge user's extra_hosts with the auto-generated ones # Convert list format to dict if necessary if isinstance(user_extra_hosts, list): for host_entry in user_extra_hosts: if ":" in host_entry: host, ip = host_entry.split(":", 1) extra_hosts[host] = ip elif isinstance(user_extra_hosts, dict): extra_hosts.update(user_extra_hosts) else: # No auto-generated extra_hosts, use user's directly extra_hosts = user_extra_hosts return dict( image=configuration.image, network=configuration.networks[0] if configuration.networks else None, network_mode=network_mode, command=configuration.command, environment=configuration.env, auto_remove=configuration.auto_remove, labels=configuration.labels, extra_hosts=extra_hosts, name=configuration.name, volumes=configuration.volumes, mem_limit=configuration.mem_limit, memswap_limit=configuration.memswap_limit, privileged=configuration.privileged, **container_create_kwargs, ) def _create_and_start_container( self, configuration: DockerWorkerJobConfiguration ) -> Tuple["Container", Event]: """Creates and starts a Docker container.""" docker_client = self._get_client() if configuration.registry_credentials: self._logger.info("Logging into Docker registry...") docker_client.login( username=configuration.registry_credentials.username, password=configuration.registry_credentials.password.get_secret_value(), registry=configuration.registry_credentials.registry_url, reauth=configuration.registry_credentials.reauth, ) container_settings = self._build_container_settings( docker_client, configuration ) if self._should_pull_image(docker_client, configuration=configuration): self._logger.info(f"Pulling image {configuration.image!r}...") self._pull_image(docker_client, configuration) try: self._logger.info( f"Creating Docker container {container_settings['name']!r}..." ) container = self._create_container(docker_client, **container_settings) self._logger.info( f"Docker container {container.name!r} created successfully." ) except Exception as exc: self._emit_container_creation_failed_event(configuration) raise exc created_event = self._emit_container_status_change_event( container, configuration ) # Add additional networks after the container is created; only one network can # be attached at creation time if len(configuration.networks) > 1: for network_name in configuration.networks[1:]: network = docker_client.networks.get(network_name) network.connect(container) # Start the container container.start() docker_client.close() return container, created_event def _watch_container_safe( self, container: "Container", configuration: DockerWorkerJobConfiguration, created_event: Event, ) -> "Container": """Watches a container for completion, handling any errors that may occur.""" # Monitor the container capturing the latest snapshot while capturing # not found errors docker_client = self._get_client() try: seen_statuses = {container.status} last_event = created_event for latest_container in self._watch_container( docker_client, container.id, configuration ): container = latest_container if container.status not in seen_statuses: seen_statuses.add(container.status) last_event = self._emit_container_status_change_event( container, configuration, last_event=last_event ) except docker.errors.NotFound: # The container was removed during watching self._logger.warning( f"Docker container {container.name} was removed before we could wait " "for its completion." ) finally: docker_client.close() return container def _watch_container( self, docker_client: "DockerClient", container_id: str, configuration: DockerWorkerJobConfiguration, ) -> Generator[None, None, "Container"]: """ Watches a container for completion, yielding the latest container snapshot on each iteration. """ container: "Container" = docker_client.containers.get(container_id) status = container.status self._logger.info( f"Docker container {container.name!r} has status {container.status!r}" ) yield container if configuration.stream_output: try: for log in container.logs(stream=True): log: bytes print(log.decode().rstrip()) except docker.errors.APIError as exc: if "marked for removal" in str(exc): self._logger.warning( f"Docker container {container.name} was marked for removal" " before logs could be retrieved. Output will not be" " streamed. " ) else: self._logger.exception( "An unexpected Docker API error occurred while streaming output " f"from container {container.name}." ) container.reload() if container.status != status: self._logger.info( f"Docker container {container.name!r} has status" f" {container.status!r}" ) yield container container.wait() self._logger.info( f"Docker container {container.name!r} has status {container.status!r}" ) yield container def _should_pull_image( self, docker_client: "DockerClient", configuration: DockerWorkerJobConfiguration ) -> bool: """ Decide whether we need to pull the Docker image. """ image_pull_policy = configuration._determine_image_pull_policy() if image_pull_policy is ImagePullPolicy.ALWAYS: return True elif image_pull_policy is ImagePullPolicy.NEVER: return False elif image_pull_policy is ImagePullPolicy.IF_NOT_PRESENT: try: # NOTE: images.get() wants the tag included with the image # name, while images.pull() wants them split. docker_client.images.get(configuration.image) except docker.errors.ImageNotFound: self._logger.debug( f"Could not find Docker image locally: {configuration.image}" ) return True return False def _pull_image( self, docker_client: "DockerClient", configuration: DockerWorkerJobConfiguration ): """ Pull the image we're going to use to create the container. """ image, tag = parse_image_tag(configuration.image) return docker_client.images.pull(image, tag) def _create_container(self, docker_client: "DockerClient", **kwargs) -> "Container": """ Create a docker container with retries on name conflicts. If the container already exists with the given name, an incremented index is added. """ # Create the container with retries on name conflicts (with an incremented idx) index = 0 container = None name = original_name = kwargs.pop("name") while not container: try: display_name = repr(name) if name else "with auto-generated name" self._logger.info(f"Creating Docker container {display_name}...") container = docker_client.containers.create(name=name, **kwargs) except docker.errors.APIError as exc: if "Conflict" in str(exc) and "container name" in str(exc): self._logger.info( f"Docker container name {display_name} already exists; " "retrying..." ) index += 1 name = f"{original_name}-{index}" else: raise self._logger.info( f"Docker container {container.name!r} has status {container.status!r}" ) return container def _container_as_resource(self, container: "Container") -> dict[str, str]: """Convert a container to a resource dictionary""" return { "prefect.resource.id": f"prefect.docker.container.{container.id}", "prefect.resource.name": container.name, } def _emit_container_creation_failed_event( self, configuration: DockerWorkerJobConfiguration ) -> Event: """Emit a Prefect event when a docker container fails to be created.""" return emit_event( event="prefect.docker.container.creation-failed", resource=self._event_resource(), related=self._event_related_resources(configuration=configuration), ) def _emit_container_status_change_event( self, container: "Container", configuration: DockerWorkerJobConfiguration, last_event: Optional[Event] = None, ) -> Event: """Emit a Prefect event for a Docker container event.""" related = self._event_related_resources(configuration=configuration) worker_resource = self._event_resource() worker_resource["prefect.resource.role"] = "worker" worker_related_resource = RelatedResource(worker_resource) return emit_event( event=f"prefect.docker.container.{container.status.lower()}", resource=self._container_as_resource(container), related=related + [worker_related_resource], follows=last_event, )
DockerWorker
python
graphql-python__graphene
graphene/tests/issues/test_490.py
{ "start": 75, "end": 516 }
class ____(graphene.ObjectType): some_field = graphene.String(from_=graphene.String(name="from")) def resolve_some_field(self, info, from_=None): return from_ def test_issue(): query_string = """ query myQuery { someField(from: "Oh") } """ schema = graphene.Schema(query=Query) result = schema.execute(query_string) assert not result.errors assert result.data["someField"] == "Oh"
Query
python
huggingface__transformers
src/transformers/models/blenderbot/modeling_blenderbot.py
{ "start": 36601, "end": 43547 }
class ____(BlenderbotPreTrainedModel): _tied_weights_keys = { "encoder.embed_tokens.weight": "shared.weight", "decoder.embed_tokens.weight": "shared.weight", } def __init__(self, config: BlenderbotConfig): super().__init__(config) padding_idx, vocab_size = config.pad_token_id, config.vocab_size embed_scale = math.sqrt(config.d_model) if config.scale_embedding else 1.0 self.shared = BlenderbotScaledWordEmbedding(vocab_size, config.d_model, padding_idx, embed_scale=embed_scale) self.encoder = BlenderbotEncoder(config) self.decoder = BlenderbotDecoder(config) # Initialize weights and apply final processing self.post_init() @classmethod def from_pretrained(cls, pretrained_model_name_or_path: Optional[Union[str, os.PathLike]], *model_args, **kwargs): if pretrained_model_name_or_path == "facebook/blenderbot-90M": warnings.warn( "The checkpoint `facebook/blenderbot-90M` is deprecated. In the future, please use the identical" " checkpoint `facebook/small_blenderbot-90M` with" " `BlenderbotSmallModel.from_pretrained('facebook/small_blenderbot-90M')` instead.", FutureWarning, ) return BlenderbotSmallModel.from_pretrained(pretrained_model_name_or_path) return super().from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs) def get_input_embeddings(self): return self.shared def set_input_embeddings(self, value): self.shared = value self.encoder.embed_tokens = self.shared self.decoder.embed_tokens = self.shared @auto_docstring def forward( self, input_ids: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.Tensor] = None, decoder_input_ids: Optional[torch.LongTensor] = None, decoder_attention_mask: Optional[torch.LongTensor] = None, encoder_outputs: Optional[Union[tuple, BaseModelOutput]] = None, past_key_values: Optional[Cache] = None, inputs_embeds: Optional[torch.Tensor] = None, decoder_inputs_embeds: Optional[torch.FloatTensor] = None, use_cache: Optional[bool] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, cache_position: Optional[torch.Tensor] = None, ) -> Union[tuple[torch.FloatTensor], Seq2SeqModelOutput]: r""" decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*): Indices of decoder input sequence tokens in the vocabulary. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are decoder input IDs?](../glossary#decoder-input-ids) Blenderbot uses the `bos_token_id` as the starting token for `decoder_input_ids` generation. If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see `past_key_values`). decoder_attention_mask (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*): Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also be used by default. Example: ```python >>> from transformers import AutoTokenizer, BlenderbotModel >>> model = BlenderbotModel.from_pretrained("facebook/blenderbot-400M-distill") >>> tokenizer = AutoTokenizer.from_pretrained("facebook/blenderbot-400M-distill") >>> inputs = tokenizer("Studies have been shown that owning a dog is good for you", return_tensors="pt") >>> decoder_input_ids = tokenizer("Studies show that", return_tensors="pt").input_ids # Batch size 1 >>> outputs = model(input_ids=inputs.input_ids, decoder_input_ids=decoder_input_ids) >>> last_hidden_states = outputs.last_hidden_state >>> list(last_hidden_states.shape) [1, 6, 1280] ```""" output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) use_cache = use_cache if use_cache is not None else self.config.use_cache return_dict = return_dict if return_dict is not None else self.config.use_return_dict if encoder_outputs is None: encoder_outputs = self.encoder( input_ids=input_ids, attention_mask=attention_mask, inputs_embeds=inputs_embeds, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) # If the user passed a tuple for encoder_outputs, we wrap it in a BaseModelOutput when return_dict=True elif return_dict and not isinstance(encoder_outputs, BaseModelOutput): encoder_outputs = BaseModelOutput( last_hidden_state=encoder_outputs[0], hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None, attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None, ) # decoder outputs consists of (dec_features, past_key_values, dec_hidden, dec_attn) decoder_outputs = self.decoder( input_ids=decoder_input_ids, attention_mask=decoder_attention_mask, encoder_hidden_states=encoder_outputs[0], encoder_attention_mask=attention_mask, past_key_values=past_key_values, inputs_embeds=decoder_inputs_embeds, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, cache_position=cache_position, ) if not return_dict: return decoder_outputs + encoder_outputs return Seq2SeqModelOutput( last_hidden_state=decoder_outputs.last_hidden_state, past_key_values=decoder_outputs.past_key_values, decoder_hidden_states=decoder_outputs.hidden_states, decoder_attentions=decoder_outputs.attentions, cross_attentions=decoder_outputs.cross_attentions, encoder_last_hidden_state=encoder_outputs.last_hidden_state, encoder_hidden_states=encoder_outputs.hidden_states, encoder_attentions=encoder_outputs.attentions, ) @auto_docstring( custom_intro=""" The Blenderbot Model with a language modeling head. Can be used for summarization. """ )
BlenderbotModel
python
matplotlib__matplotlib
lib/matplotlib/figure.py
{ "start": 84737, "end": 91566 }
class ____(FigureBase): """ Logical figure that can be placed inside a figure. See :ref:`figure-api-subfigure` for an index of methods on this class. Typically instantiated using `.Figure.add_subfigure` or `.SubFigure.add_subfigure`, or `.SubFigure.subfigures`. A subfigure has the same methods as a figure except for those particularly tied to the size or dpi of the figure, and is confined to a prescribed region of the figure. For example the following puts two subfigures side-by-side:: fig = plt.figure() sfigs = fig.subfigures(1, 2) axsL = sfigs[0].subplots(1, 2) axsR = sfigs[1].subplots(2, 1) See :doc:`/gallery/subplots_axes_and_figures/subfigures` """ def __init__(self, parent, subplotspec, *, facecolor=None, edgecolor=None, linewidth=0.0, frameon=None, **kwargs): """ Parameters ---------- parent : `.Figure` or `.SubFigure` Figure or subfigure that contains the SubFigure. SubFigures can be nested. subplotspec : `.gridspec.SubplotSpec` Defines the region in a parent gridspec where the subfigure will be placed. facecolor : default: ``"none"`` The figure patch face color; transparent by default. edgecolor : default: :rc:`figure.edgecolor` The figure patch edge color. linewidth : float The linewidth of the frame (i.e. the edge linewidth of the figure patch). frameon : bool, default: :rc:`figure.frameon` If ``False``, suppress drawing the figure background patch. Other Parameters ---------------- **kwargs : `.SubFigure` properties, optional %(SubFigure:kwdoc)s """ super().__init__(**kwargs) if facecolor is None: facecolor = "none" edgecolor = mpl._val_or_rc(edgecolor, 'figure.edgecolor') frameon = mpl._val_or_rc(frameon, 'figure.frameon') self._subplotspec = subplotspec self._parent = parent self._root_figure = parent._root_figure # subfigures use the parent axstack self._axstack = parent._axstack self.subplotpars = parent.subplotpars self.dpi_scale_trans = parent.dpi_scale_trans self._axobservers = parent._axobservers self.transFigure = parent.transFigure self.bbox_relative = Bbox.null() self._redo_transform_rel_fig() self.figbbox = self._parent.figbbox self.bbox = TransformedBbox(self.bbox_relative, self._parent.transSubfigure) self.transSubfigure = BboxTransformTo(self.bbox) self.patch = Rectangle( xy=(0, 0), width=1, height=1, visible=frameon, facecolor=facecolor, edgecolor=edgecolor, linewidth=linewidth, # Don't let the figure patch influence bbox calculation. in_layout=False, transform=self.transSubfigure) self._set_artist_props(self.patch) self.patch.set_antialiased(False) @property def canvas(self): return self._parent.canvas @property def dpi(self): return self._parent.dpi @dpi.setter def dpi(self, value): self._parent.dpi = value def get_dpi(self): """ Return the resolution of the parent figure in dots-per-inch as a float. """ return self._parent.dpi def set_dpi(self, val): """ Set the resolution of parent figure in dots-per-inch. Parameters ---------- val : float """ self._parent.dpi = val self.stale = True def _get_renderer(self): return self._parent._get_renderer() def _redo_transform_rel_fig(self, bbox=None): """ Make the transSubfigure bbox relative to Figure transform. Parameters ---------- bbox : bbox or None If not None, then the bbox is used for relative bounding box. Otherwise, it is calculated from the subplotspec. """ if bbox is not None: self.bbox_relative.p0 = bbox.p0 self.bbox_relative.p1 = bbox.p1 return # need to figure out *where* this subplotspec is. gs = self._subplotspec.get_gridspec() wr = np.asarray(gs.get_width_ratios()) hr = np.asarray(gs.get_height_ratios()) dx = wr[self._subplotspec.colspan].sum() / wr.sum() dy = hr[self._subplotspec.rowspan].sum() / hr.sum() x0 = wr[:self._subplotspec.colspan.start].sum() / wr.sum() y0 = 1 - hr[:self._subplotspec.rowspan.stop].sum() / hr.sum() self.bbox_relative.p0 = (x0, y0) self.bbox_relative.p1 = (x0 + dx, y0 + dy) def get_constrained_layout(self): """ Return whether constrained layout is being used. See :ref:`constrainedlayout_guide`. """ return self._parent.get_constrained_layout() def get_constrained_layout_pads(self, relative=False): """ Get padding for ``constrained_layout``. Returns a list of ``w_pad, h_pad`` in inches and ``wspace`` and ``hspace`` as fractions of the subplot. See :ref:`constrainedlayout_guide`. Parameters ---------- relative : bool If `True`, then convert from inches to figure relative. """ return self._parent.get_constrained_layout_pads(relative=relative) def get_layout_engine(self): return self._parent.get_layout_engine() @property def axes(self): """ List of Axes in the SubFigure. You can access and modify the Axes in the SubFigure through this list. Modifying this list has no effect. Instead, use `~.SubFigure.add_axes`, `~.SubFigure.add_subplot` or `~.SubFigure.delaxes` to add or remove an Axes. Note: The `.SubFigure.axes` property and `~.SubFigure.get_axes` method are equivalent. """ return self._localaxes[:] get_axes = axes.fget def draw(self, renderer): # docstring inherited # draw the figure bounding box, perhaps none for white figure if not self.get_visible(): return artists = self._get_draw_artists(renderer) try: renderer.open_group('subfigure', gid=self.get_gid()) self.patch.draw(renderer) mimage._draw_list_compositing_images( renderer, self, artists, self.get_figure(root=True).suppressComposite) renderer.close_group('subfigure') finally: self.stale = False @_docstring.interpd
SubFigure
python
run-llama__llama_index
llama-index-integrations/tools/llama-index-tools-mcp/llama_index/tools/mcp/tool_spec_mixins.py
{ "start": 3028, "end": 4533 }
class ____: def _create_list_type(self: "McpToolSpec", schema: dict, defs: dict) -> type: """Create a List type from schema.""" item_type = self._resolve_field_type(schema["items"], defs) return List[item_type] def _create_dict_type(self: "McpToolSpec", schema: dict, defs: dict) -> type: """Create a Dict type from schema.""" additional_props = schema.get("additionalProperties") if additional_props is False or additional_props is None: return Dict[str, Any] if isinstance(additional_props, dict): value_type = self._resolve_field_type(additional_props, defs) return Dict[str, value_type] return Dict[str, Any] def _is_simple_array(self: "McpToolSpec", schema: dict) -> bool: """Check if schema is a simple array type.""" return schema.get("type") == "array" and "items" in schema def _is_simple_object(self: "McpToolSpec", schema: dict) -> bool: """Check if schema is a simple object type.""" additional_props = schema.get("additionalProperties") return ( schema.get("type") == "object" and "additionalProperties" in schema and additional_props is not False and isinstance(additional_props, dict) ) def _extract_ref_name(self: "McpToolSpec", ref_path: str) -> str: """Extract reference name from $ref path.""" return ref_path.split("#/$defs/")[-1]
TypeCreationMixin
python
tensorflow__tensorflow
tensorflow/lite/tools/flatbuffer_utils_test.py
{ "start": 9587, "end": 10650 }
class ____(test_util.TensorFlowTestCase): def testXxdOutputToBytes(self): # 1. SETUP # Define the initial model initial_model = test_utils.build_mock_model() initial_bytes = flatbuffer_utils.convert_object_to_bytearray(initial_model) # Define temporary files tmp_dir = self.get_temp_dir() model_filename = os.path.join(tmp_dir, 'model.tflite') # 2. Write model to temporary file (will be used as input for xxd) flatbuffer_utils.write_model(initial_model, model_filename) # 3. DUMP WITH xxd input_cc_file = os.path.join(tmp_dir, 'model.cc') command = 'xxd -i {} > {}'.format(model_filename, input_cc_file) subprocess.call(command, shell=True) # 4. VALIDATE final_bytes = flatbuffer_utils.xxd_output_to_bytes(input_cc_file) if sys.byteorder == 'big': final_bytes = flatbuffer_utils.byte_swap_tflite_buffer( final_bytes, 'little', 'big' ) # Validate that the initial and final bytearray are the same self.assertEqual(initial_bytes, final_bytes)
XxdOutputToBytesTest
python
pytorch__pytorch
torch/_dynamo/variables/lists.py
{ "start": 36232, "end": 42160 }
class ____(CommonListMethodsVariable): def __init__( self, items: list[VariableTracker], maxlen: Optional[VariableTracker] = None, **kwargs: Any, ) -> None: if maxlen is None: maxlen = ConstantVariable.create(None) assert maxlen.is_python_constant(), ( f"maxlen must be a constant, got: {maxlen.debug_repr()}" ) self.maxlen = maxlen items = list(items) if self.maxlen.as_python_constant() is not None: items = items[-maxlen.as_python_constant() :] super().__init__(items, **kwargs) def python_type(self) -> type: return collections.deque def debug_repr(self) -> str: if self.maxlen.as_python_constant() is None: return self.debug_repr_helper( "deque([", "], maxlen=" + self.maxlen.debug_repr() + ")" ) return self.debug_repr_helper("deque([", "])") def as_python_constant(self) -> collections.deque[Any]: return self.python_type()( [x.as_python_constant() for x in self.items], maxlen=self.maxlen.as_python_constant(), ) def reconstruct(self, codegen: "PyCodegen") -> None: codegen.add_push_null( lambda: codegen.append_output( codegen.create_load_python_module(collections.deque) # type: ignore[arg-type] ) ) codegen.foreach(self.items) codegen.extend_output([create_instruction("BUILD_LIST", arg=len(self.items))]) codegen(self.maxlen) codegen.extend_output(codegen.create_call_function_kw(2, ("maxlen",), False)) def var_getattr(self, tx: "InstructionTranslator", name: str) -> VariableTracker: if name == "maxlen": return self.maxlen return super().var_getattr(tx, name) def call_method( self, tx: "InstructionTranslator", name: str, args: list[VariableTracker], kwargs: dict[str, VariableTracker], ) -> VariableTracker: if ( name == "__setitem__" and self.is_mutable() and args and args[0].is_python_constant() ): if kwargs or len(args) != 2: raise_args_mismatch( tx, name, "2 args and 0 kwargs", f"{len(args)} args and {len(kwargs)} kwargs", ) key, value = args assert key.is_python_constant() assert isinstance(key.as_python_constant(), int) tx.output.side_effects.mutation(self) self.items[key.as_python_constant()] = value return ConstantVariable.create(None) maxlen = self.maxlen.as_python_constant() if maxlen is not None: slice_within_maxlen = slice(-maxlen, None) else: slice_within_maxlen = None if ( name == "extendleft" and self.is_mutable() and len(args) > 0 and args[0].has_force_unpack_var_sequence(tx) ): if kwargs or len(args) != 1: raise_args_mismatch( tx, name, "1 args and 0 kwargs", f"{len(args)} args and {len(kwargs)} kwargs", ) # NOTE this is inefficient, but the alternative is to represent self.items # as a deque, which is a more intrusive change. args[0].force_apply_to_var_sequence( tx, lambda item: self.call_method(tx, "appendleft", [item], {}) ) slice_within_maxlen = slice(None, maxlen) result = ConstantVariable.create(None) elif name == "popleft" and self.is_mutable(): if kwargs or len(args) > 0: raise_args_mismatch( tx, name, "0 args and 0 kwargs", f"{len(args)} args and {len(kwargs)} kwargs", ) tx.output.side_effects.mutation(self) result, *self.items[:] = self.items elif name == "appendleft" and len(args) > 0 and self.is_mutable(): if kwargs or len(args) != 1: raise_args_mismatch( tx, name, "1 args and 0 kwargs", f"{len(args)} args and {len(kwargs)} kwargs", ) tx.output.side_effects.mutation(self) self.items[:] = [args[0], *self.items] slice_within_maxlen = slice(None, maxlen) result = ConstantVariable.create(None) elif name == "insert" and len(args) > 0 and self.is_mutable(): if kwargs or len(args) != 2: raise_args_mismatch( tx, name, "2 args and 0 kwargs", f"{len(args)} args and {len(kwargs)} kwargs", ) if maxlen is not None and len(self.items) == maxlen: raise_observed_exception( IndexError, tx, args=["deque already at its maximum size"] ) result = super().call_method(tx, name, args, kwargs) else: result = super().call_method(tx, name, args, kwargs) if ( slice_within_maxlen is not None and maxlen is not None and len(self.items) > maxlen ): self.items[:] = self.items[slice_within_maxlen] return result def call_obj_hasattr( self, tx: "InstructionTranslator", name: str ) -> ConstantVariable: if self.python_type() is collections.deque: return variables.ConstantVariable.create(name in collections.deque.__dict__) return super().call_obj_hasattr(tx, name)
DequeVariable
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/logs/events.py
{ "start": 1349, "end": 1809 }
class ____(graphene.Interface): runId = graphene.NonNull(graphene.String) message = graphene.NonNull(graphene.String) timestamp = graphene.NonNull(graphene.String) level = graphene.NonNull(GrapheneLogLevel) stepKey = graphene.Field(graphene.String) solidHandleID = graphene.Field(graphene.String) eventType = graphene.Field(graphene.Enum.from_enum(DagsterEventType)) class Meta: name = "MessageEvent"
GrapheneMessageEvent
python
kamyu104__LeetCode-Solutions
Python/employee-importance.py
{ "start": 900, "end": 1344 }
class ____(object): def getImportance(self, employees, id): """ :type employees: Employee :type id: int :rtype: int """ result, q = 0, collections.deque([id]) while q: curr = q.popleft() employee = employees[curr-1] result += employee.importance for id in employee.subordinates: q.append(id) return result
Solution2
python
milvus-io__pymilvus
pymilvus/exceptions.py
{ "start": 2591, "end": 2691 }
class ____(MilvusException): """Raise when datatype isn't supported"""
DataTypeNotSupportException
python
PyCQA__pylint
tests/regrtest_data/importing_plugin/importing_plugin.py
{ "start": 121, "end": 749 }
class ____(BaseChecker): options = ( ( "settings-module", { "default": "settings", "type": "string", "metavar": "<settings module>" }, ), ) msgs = { "E9999": ( "Importing checker error message", "importing-checker-error", "Importing checker error message", ), } def open(self) -> None: import_module(self.linter.config.settings_module) def register(linter: "PyLinter") -> None: linter.register_checker(ImportingChecker(linter))
ImportingChecker
python
great-expectations__great_expectations
great_expectations/render/renderer/column_section_renderer.py
{ "start": 15619, "end": 17936 }
class ____(ColumnSectionRenderer): def __init__(self, table_renderer=None) -> None: super().__init__() if table_renderer is None: table_renderer = {"class_name": "ValidationResultsTableContentBlockRenderer"} module_name = table_renderer.get( "module_name", "great_expectations.render.renderer.content_block" ) verify_dynamic_loading_support(module_name=module_name) class_name = table_renderer.get("class_name") self._table_renderer = load_class(class_name=class_name, module_name=module_name) @classmethod def _render_header(cls, validation_results): column = cls._get_column_name(validation_results) new_block = RenderedHeaderContent( **{ "header": RenderedStringTemplateContent( **{ "content_block_type": "string_template", "string_template": { "template": convert_to_string_and_escape(column), "tag": "h5", "styling": {"classes": ["m-0"]}, }, } ), "styling": { "classes": ["col-12", "p-0"], "header": {"classes": ["alert", "alert-secondary"]}, }, } ) return validation_results, new_block def _render_table(self, validation_results, suite_parameters=None): new_block = self._table_renderer.render( validation_results, include_column_name=False, suite_parameters=suite_parameters, ) return [], new_block def render(self, validation_results, suite_parameters=None): # type: ignore[explicit-override] # FIXME column = self._get_column_name(validation_results) content_blocks = [] remaining_evrs, content_block = self._render_header(validation_results) content_blocks.append(content_block) remaining_evrs, content_block = self._render_table(remaining_evrs, suite_parameters) content_blocks.append(content_block) return RenderedSectionContent(**{"section_name": column, "content_blocks": content_blocks})
ValidationResultsColumnSectionRenderer
python
pytorch__pytorch
torch/_dynamo/variables/higher_order_ops.py
{ "start": 117240, "end": 120444 }
class ____(TorchHigherOrderOperatorVariable): """ This hop is not exposed to users but is inserted into the graph after export as a post-processing step. """ def call_function( self, tx: "InstructionTranslator", args: "list[VariableTracker]", kwargs: "dict[str, VariableTracker]", ) -> "VariableTracker": args, kwargs = LazyVariableTracker.realize_all((args, kwargs)) if kwargs: unimplemented( gb_type="wrap_with_autocast: unexpected kwargs", context=f"args: {args}, kwargs: {kwargs}", explanation=f"wrap_with_autocast expects no keyword arguments (got {len(kwargs)}).", hints=[ *graph_break_hints.DYNAMO_BUG, ], ) device_type, dtype, enabled, cache_enabled, fn_var, *rest_args = args for arg in [device_type, dtype, enabled, cache_enabled]: if not isinstance(arg, ConstantVariable): unimplemented( gb_type="wrap_with_autocast: expected constant arg", context=str(args), explanation="wrap_with_autocast expects device_type, dtype, enabled, " "and cache_enabled arguments to be constants.", hints=[ *graph_break_hints.DYNAMO_BUG, ], ) _check_supported_callable_arg(tx, fn_var, "autocast") python_constants = [ arg.as_python_constant() for arg in [device_type, dtype, enabled, cache_enabled] ] with torch.autocast(*python_constants): ( (body_r, treespec), body_graph, body_lifted_freevars, ) = speculate_subgraph( tx, fn_var, [*rest_args], {}, "torch.ops.higher_order.wrap_with_autocast", source_target=self.value, set_subgraph_inputs="manual", should_flatten_outputs=True, ) if len(body_lifted_freevars) > 0: unimplemented( gb_type="wrap_with_autocast: unexpected freevars", context=str(body_lifted_freevars), explanation="wrap_with_autocast expects no freevars.", hints=[], ) body_gmod = torch.fx.GraphModule(tx.output.nn_modules, body_graph) body_name = tx.output.install_subgraph( "wrap_body", body_gmod, ) body_node = make_attr(tx, body_name) proxy_args = tuple( [ *python_constants, body_node, ] + [operand.as_proxy() for operand in rest_args] ) example_value = pytree.tree_map_only( torch.fx.Proxy, lambda a: a.node.meta["example_value"], body_r.as_proxy(), ) return _call_function_and_unflatten_output( tx, self.value, proxy_args, {}, example_value, treespec, body_r )
WrapWithAutocastHigherOrderVariable
python
astropy__astropy
astropy/io/fits/tests/test_checksum.py
{ "start": 267, "end": 1021 }
class ____(FitsTestCase): def setup_method(self): super().setup_method() self._oldfilters = warnings.filters[:] warnings.filterwarnings("error", message="Checksum verification failed") warnings.filterwarnings("error", message="Datasum verification failed") # Monkey-patch the _get_timestamp method so that the checksum # timestamps (and hence the checksum themselves) are always the same self._old_get_timestamp = _ValidHDU._get_timestamp _ValidHDU._get_timestamp = lambda self: "2013-12-20T13:36:10" def teardown_method(self): super().teardown_method() warnings.filters = self._oldfilters _ValidHDU._get_timestamp = self._old_get_timestamp
BaseChecksumTests
python
jazzband__django-formtools
tests/wizard/test_forms.py
{ "start": 11631, "end": 11852 }
class ____(TestCase): def test_init(self): request = get_request() testform = CookieWizardView.as_view([('start', Step1)]) self.assertIsInstance(testform(request), TemplateResponse)
CookieFormTests
python
fastai__fastai
fastai/data/transforms.py
{ "start": 15176, "end": 15309 }
class ____(Transform): "Convert item to appropriate tensor class" order = 5 # %% ../../nbs/05_data.transforms.ipynb 111
ToTensor
python
dagster-io__dagster
python_modules/libraries/dagster-aws/dagster_aws/utils/__init__.py
{ "start": 859, "end": 2657 }
class ____(ConfigurableResource): region_name: Optional[str] = Field( default=None, description="Specifies a custom region for the Boto3 session" ) max_attempts: int = Field( default=5, description=( "This provides Boto3's retry handler with a value of maximum retry attempts, where the" " initial call counts toward the max_attempts value that you provide" ), ) profile_name: Optional[str] = Field( default=None, description="Specifies a profile to connect that session" ) use_ssl: bool = Field( default=True, description="Whether or not to use SSL. By default, SSL is used." ) endpoint_url: Optional[str] = Field( default=None, description="Specifies a custom endpoint for the Boto3 session." ) verify: Optional[bool] = Field( default=True, description=( "Whether or not to verify SSL certificates. By default SSL certificates are verified." ), ) aws_access_key_id: Optional[str] = Field( default=None, description="AWS access key ID to use when creating the boto3 session." ) aws_secret_access_key: Optional[str] = Field( default=None, description="AWS secret access key to use when creating the boto3 session." ) aws_session_token: Optional[str] = Field( default=None, description="AWS session token to use when creating the boto3 session." ) def ensure_dagster_aws_tests_import() -> None: dagster_package_root = (Path(dagster_aws_init_py) / ".." / "..").resolve() assert (dagster_package_root / "dagster_aws_tests").exists(), ( "Could not find dagster_aws_tests where expected" ) sys.path.append(dagster_package_root.as_posix())
ResourceWithBoto3Configuration
python
pallets__werkzeug
src/werkzeug/routing/exceptions.py
{ "start": 430, "end": 598 }
class ____(Exception): """Special exceptions that require the application to redirect, notifying about missing urls, etc. :internal: """
RoutingException
python
doocs__leetcode
solution/0300-0399/0311.Sparse Matrix Multiplication/Solution2.py
{ "start": 0, "end": 659 }
class ____: def multiply(self, mat1: List[List[int]], mat2: List[List[int]]) -> List[List[int]]: def f(mat: List[List[int]]) -> List[List[int]]: g = [[] for _ in range(len(mat))] for i, row in enumerate(mat): for j, x in enumerate(row): if x: g[i].append((j, x)) return g g1 = f(mat1) g2 = f(mat2) m, n = len(mat1), len(mat2[0]) ans = [[0] * n for _ in range(m)] for i in range(m): for k, x in g1[i]: for j, y in g2[k]: ans[i][j] += x * y return ans
Solution