INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
one iteration of k-means
def _recenter(self): """ one iteration of k-means """ for split_idx in range(len(self._splits)): split = self._splits[split_idx] len_idx = self._split2len_idx[split] if split == self._splits[-1]: continue right_split = self....
Index every sentence into a cluster
def _reindex(self): """ Index every sentence into a cluster """ self._len2split_idx = {} last_split = -1 for split_idx, split in enumerate(self._splits): self._len2split_idx.update( dict(list(zip(list(range(last_split + 1, split)), [split_idx] ...
Build a pair of GNMT encoder/decoder Parameters ---------- cell_type : str or type attention_cell : str or AttentionCell num_layers : int num_bi_layers : int hidden_size : int dropout : float use_residual : bool i2h_weight_initializer : mx.init.Initializer or None h2h_weight...
def get_gnmt_encoder_decoder(cell_type='lstm', attention_cell='scaled_luong', num_layers=2, num_bi_layers=1, hidden_size=128, dropout=0.0, use_residual=False, i2h_weight_initializer=None, h2h_weight_initializer=None, i2h_bias_initial...
Initialize the state from the encoder outputs. Parameters ---------- encoder_outputs : list encoder_valid_length : NDArray or None Returns ------- decoder_states : list The decoder states, includes: - rnn_states : NDArray - a...
def init_state_from_encoder(self, encoder_outputs, encoder_valid_length=None): """Initialize the state from the encoder outputs. Parameters ---------- encoder_outputs : list encoder_valid_length : NDArray or None Returns ------- decoder_states : list ...
Decode the decoder inputs. This function is only used for training. Parameters ---------- inputs : NDArray, Shape (batch_size, length, C_in) states : list of NDArrays or None Initial states. The list of initial decoder states valid_length : NDArray or None ...
def decode_seq(self, inputs, states, valid_length=None): """Decode the decoder inputs. This function is only used for training. Parameters ---------- inputs : NDArray, Shape (batch_size, length, C_in) states : list of NDArrays or None Initial states. The list of init...
Transform instance to inputs for MLM and NSP.
def transform(instance, tokenizer, max_seq_length, max_predictions_per_seq, do_pad=True): """Transform instance to inputs for MLM and NSP.""" pad = tokenizer.convert_tokens_to_ids(['[PAD]'])[0] input_ids = tokenizer.convert_tokens_to_ids(instance.tokens) input_mask = [1] * len(input_ids) segment_ids...
Write to numpy files from `TrainingInstance`s.
def write_to_files_np(features, tokenizer, max_seq_length, max_predictions_per_seq, output_files): # pylint: disable=unused-argument """Write to numpy files from `TrainingInstance`s.""" next_sentence_labels = [] valid_lengths = [] assert len(output_files) == 1, 'numpy format o...
Create IndexedRecordIO files from `TrainingInstance`s.
def write_to_files_rec(instances, tokenizer, max_seq_length, max_predictions_per_seq, output_files): """Create IndexedRecordIO files from `TrainingInstance`s.""" writers = [] for output_file in output_files: writers.append( mx.recordio.MXIndexedRecordIO( ...
Create `TrainingInstance`s from raw text.
def create_training_instances(x): """Create `TrainingInstance`s from raw text.""" (input_files, out, tokenizer, max_seq_length, dupe_factor, short_seq_prob, masked_lm_prob, max_predictions_per_seq, rng) = x time_start = time.time() logging.info('Processing %s', input_files) all_documents = [[]]...
Creates `TrainingInstance`s for a single document.
def create_instances_from_document( all_documents, document_index, max_seq_length, short_seq_prob, masked_lm_prob, max_predictions_per_seq, vocab_words, rng): """Creates `TrainingInstance`s for a single document.""" document = all_documents[document_index] # Account for [CLS], [SEP], [SEP] ...
Creates the predictions for the masked LM objective.
def create_masked_lm_predictions(tokens, masked_lm_prob, max_predictions_per_seq, vocab_words, rng): """Creates the predictions for the masked LM objective.""" cand_indexes = [] for (i, token) in enumerate(tokens): if token in ['[CLS]', '[SEP]']: continu...
Truncates a pair of sequences to a maximum sequence length.
def truncate_seq_pair(tokens_a, tokens_b, max_num_tokens, rng): """Truncates a pair of sequences to a maximum sequence length.""" while True: total_length = len(tokens_a) + len(tokens_b) if total_length <= max_num_tokens: break trunc_tokens = tokens_a if len(tokens_a) > len(...
Main function.
def main(): """Main function.""" time_start = time.time() logging.info('loading vocab file from dataset: %s', args.vocab) vocab_obj = nlp.data.utils._load_pretrained_vocab(args.vocab) tokenizer = BERTTokenizer( vocab=vocab_obj, lower='uncased' in args.vocab) input_files = [] for inp...
GluonNLP specific code to convert the original vocabulary to nlp.vocab.BERTVocab.
def convert_vocab(vocab_file): """GluonNLP specific code to convert the original vocabulary to nlp.vocab.BERTVocab.""" original_vocab = load_vocab(vocab_file) token_to_idx = dict(original_vocab) num_tokens = len(token_to_idx) idx_to_token = [None] * len(original_vocab) for word in original_vocab...
read tensorflow checkpoint
def read_tf_checkpoint(path): """read tensorflow checkpoint""" from tensorflow.python import pywrap_tensorflow tensors = {} reader = pywrap_tensorflow.NewCheckpointReader(path) var_to_shape_map = reader.get_variable_to_shape_map() for key in sorted(var_to_shape_map): tensor = reader.get_...
profile the program between [start_step, end_step).
def profile(curr_step, start_step, end_step, profile_name='profile.json', early_exit=True): """profile the program between [start_step, end_step).""" if curr_step == start_step: mx.nd.waitall() mx.profiler.set_config(profile_memory=False, profile_symbolic=True, ...
Loads a vocabulary file into a dictionary.
def load_vocab(vocab_file): """Loads a vocabulary file into a dictionary.""" vocab = collections.OrderedDict() index = 0 with io.open(vocab_file, 'r') as reader: while True: token = reader.readline() if not token: break token = token.strip() ...
r""" Forward computation for char_encoder Parameters ---------- inputs: NDArray The input tensor is of shape `(seq_len, batch_size, embedding_size)` TNC. mask: NDArray The mask applied to the input of shape `(seq_len, batch_size)`, the mask will ...
def hybrid_forward(self, F, inputs, mask=None): # pylint: disable=arguments-differ r""" Forward computation for char_encoder Parameters ---------- inputs: NDArray The input tensor is of shape `(seq_len, batch_size, embedding_size)` TNC. mask: NDArray ...
Init the sinusoid position encoding table
def _position_encoding_init(max_length, dim): """Init the sinusoid position encoding table """ position_enc = np.arange(max_length).reshape((-1, 1)) \ / (np.power(10000, (2. / dim) * np.arange(dim).reshape((1, -1)))) # Apply the cosine to even columns and sin to odds. position_enc[:, ...
Build a pair of Parallel Transformer encoder/decoder Parameters ---------- num_layers : int num_heads : int scaled : bool units : int hidden_size : int dropout : float use_residual : bool max_src_length : int max_tgt_length : int weight_initializer : mx.init.Initializer ...
def get_transformer_encoder_decoder(num_layers=2, num_heads=8, scaled=True, units=512, hidden_size=2048, dropout=0.0, use_residual=True, max_src_length=50, max_tgt_length=50, w...
r"""Transformer pretrained model. Embedding size is 400, and hidden layer size is 1150. Parameters ---------- dataset_name : str or None, default None src_vocab : gluonnlp.Vocab or None, default None tgt_vocab : gluonnlp.Vocab or None, default None pretrained : bool, default False ...
def transformer_en_de_512(dataset_name=None, src_vocab=None, tgt_vocab=None, pretrained=False, ctx=cpu(), root=os.path.join(get_home_dir(), 'models'), **kwargs): r"""Transformer pretrained model. Embedding size is 400, and hidden layer size is 1150. Parameters ---------- ...
Get activation block based on the name.
def _get_activation(self, act): """Get activation block based on the name. """ if isinstance(act, str): if act.lower() == 'gelu': return GELU() else: return gluon.nn.Activation(act) assert isinstance(act, gluon.Block) return act
Position-wise encoding of the inputs. Parameters ---------- inputs : Symbol or NDArray Input sequence. Shape (batch_size, length, C_in) Returns ------- outputs : Symbol or NDArray Shape (batch_size, length, C_out)
def hybrid_forward(self, F, inputs): # pylint: disable=arguments-differ # pylint: disable=unused-argument """Position-wise encoding of the inputs. Parameters ---------- inputs : Symbol or NDArray Input sequence. Shape (batch_size, length, C_in) Returns ...
Transformer Encoder Attention Cell. Parameters ---------- inputs : Symbol or NDArray Input sequence. Shape (batch_size, length, C_in) mask : Symbol or NDArray or None Mask for inputs. Shape (batch_size, length, length) Returns ------- enc...
def hybrid_forward(self, F, inputs, mask=None): # pylint: disable=arguments-differ # pylint: disable=unused-argument """Transformer Encoder Attention Cell. Parameters ---------- inputs : Symbol or NDArray Input sequence. Shape (batch_size, length, C_in) mask...
Transformer Decoder Attention Cell. Parameters ---------- inputs : Symbol or NDArray Input sequence. Shape (batch_size, length, C_in) mem_value : Symbol or NDArrays Memory value, i.e. output of the encoder. Shape (batch_size, mem_length, C_in) mask : Symb...
def hybrid_forward(self, F, inputs, mem_value, mask=None, mem_mask=None): #pylint: disable=unused-argument # pylint: disable=arguments-differ """Transformer Decoder Attention Cell. Parameters ---------- inputs : Symbol or NDArray Input sequence. Shape (batch_size, ...
Initialize the state from the encoder outputs. Parameters ---------- encoder_outputs : list encoder_valid_length : NDArray or None Returns ------- decoder_states : list The decoder states, includes: - mem_value : NDArray - me...
def init_state_from_encoder(self, encoder_outputs, encoder_valid_length=None): """Initialize the state from the encoder outputs. Parameters ---------- encoder_outputs : list encoder_valid_length : NDArray or None Returns ------- decoder_states : list ...
Decode the decoder inputs. This function is only used for training. Parameters ---------- inputs : NDArray, Shape (batch_size, length, C_in) states : list of NDArrays or None Initial states. The list of decoder states valid_length : NDArray or None Valid ...
def decode_seq(self, inputs, states, valid_length=None): """Decode the decoder inputs. This function is only used for training. Parameters ---------- inputs : NDArray, Shape (batch_size, length, C_in) states : list of NDArrays or None Initial states. The list of deco...
Perform forward and backward computation for a batch of src seq and dst seq
def forward_backward(self, x): """Perform forward and backward computation for a batch of src seq and dst seq""" (src_seq, tgt_seq, src_valid_length, tgt_valid_length), batch_size = x with mx.autograd.record(): out, _ = self._model(src_seq, tgt_seq[:, :-1], ...
Parse arguments.
def parse_args(): """ Parse arguments. """ parser = argparse.ArgumentParser() parser.add_argument('--gpu-id', type=int, default=0, help='GPU id (-1 means CPU)') parser.add_argument('--train-file', default='snli_1.0/snli_1.0_train.txt', help='traini...
Train model and validate/save every epoch.
def train_model(model, train_data_loader, val_data_loader, embedding, ctx, args): """ Train model and validate/save every epoch. """ logger.info(vars(args)) # Initialization model.hybridize() model.collect_params().initialize(mx.init.Normal(0.01), ctx=ctx) model.word_emb.weight.set_data...
Entry point: train or test.
def main(args): """ Entry point: train or test. """ json.dump(vars(args), open(os.path.join(args.output_dir, 'config.json'), 'w')) if args.gpu_id == -1: ctx = mx.cpu() else: ctx = mx.gpu(args.gpu_id) mx.random.seed(args.seed, ctx=ctx) if args.mode == 'train': t...
Draw samples from uniform distribution and return sampled candidates. Parameters ---------- candidates_like: mxnet.nd.NDArray or mxnet.sym.Symbol This input specifies the shape of the to be sampled candidates. # TODO shape selection is not yet supported. Shape must be sp...
def hybrid_forward(self, F, candidates_like, prob, alias): # pylint: disable=unused-argument """Draw samples from uniform distribution and return sampled candidates. Parameters ---------- candidates_like: mxnet.nd.NDArray or mxnet.sym.Symbol This input specifies the ...
r"""Add a handler sending log messages to a sink adequately configured. Parameters ---------- sink : |file-like object|_, |str|, |Path|, |function|_, |Handler| or |class|_ An object in charge of receiving formatted logging messages and propagating them to an appropriate ...
def add( self, sink, *, level=_defaults.LOGURU_LEVEL, format=_defaults.LOGURU_FORMAT, filter=_defaults.LOGURU_FILTER, colorize=_defaults.LOGURU_COLORIZE, serialize=_defaults.LOGURU_SERIALIZE, backtrace=_defaults.LOGURU_BACKTRACE, diagnose=_...
Remove a previously added handler and stop sending logs to its sink. Parameters ---------- handler_id : |int| or ``None`` The id of the sink to remove, as it was returned by the |add| method. If ``None``, all handlers are removed. The pre-configured handler is guaranteed...
def remove(self, handler_id=None): """Remove a previously added handler and stop sending logs to its sink. Parameters ---------- handler_id : |int| or ``None`` The id of the sink to remove, as it was returned by the |add| method. If ``None``, all handlers are rem...
Return a decorator to automatically log possibly caught error in wrapped function. This is useful to ensure unexpected exceptions are logged, the entire program can be wrapped by this method. This is also very useful to decorate |Thread.run| methods while using threads to propagate errors to th...
def catch( self, exception=Exception, *, level="ERROR", reraise=False, message="An error has been caught in function '{record[function]}', " "process '{record[process].name}' ({record[process].id}), " "thread '{record[thread].name}' ({record[thread].id}):"...
r"""Parametrize a logging call to slightly change generated log message. Parameters ---------- exception : |bool|, |tuple| or |Exception|, optional If it does not evaluate as ``False``, the passed exception is formatted and added to the log message. It could be an |Excep...
def opt(self, *, exception=None, record=False, lazy=False, ansi=False, raw=False, depth=0): r"""Parametrize a logging call to slightly change generated log message. Parameters ---------- exception : |bool|, |tuple| or |Exception|, optional If it does not evaluate as ``False`...
Bind attributes to the ``extra`` dict of each logged message record. This is used to add custom context to each logging call. Parameters ---------- **kwargs Mapping between keys and values that will be added to the ``extra`` dict. Returns ------- :c...
def bind(_self, **kwargs): """Bind attributes to the ``extra`` dict of each logged message record. This is used to add custom context to each logging call. Parameters ---------- **kwargs Mapping between keys and values that will be added to the ``extra`` dict. ...
Add, update or retrieve a logging level. Logging levels are defined by their ``name`` to which a severity ``no``, an ansi ``color`` and an ``icon`` are associated and possibly modified at run-time. To |log| to a custom level, you should necessarily use its name, the severity number is not linke...
def level(self, name, no=None, color=None, icon=None): """Add, update or retrieve a logging level. Logging levels are defined by their ``name`` to which a severity ``no``, an ansi ``color`` and an ``icon`` are associated and possibly modified at run-time. To |log| to a custom level, you...
Configure the core logger. It should be noted that ``extra`` values set using this function are available across all modules, so this is the best way to set overall default values. Parameters ---------- handlers : |list| of |dict|, optional A list of each handler to...
def configure(self, *, handlers=None, levels=None, extra=None, activation=None): """Configure the core logger. It should be noted that ``extra`` values set using this function are available across all modules, so this is the best way to set overall default values. Parameters --...
Parse raw logs and extract each entry as a |dict|. The logging format has to be specified as the regex ``pattern``, it will then be used to parse the ``file`` and retrieve each entries based on the named groups present in the regex. Parameters ---------- file : |str|, |...
def parse(file, pattern, *, cast={}, chunk=2 ** 16): """ Parse raw logs and extract each entry as a |dict|. The logging format has to be specified as the regex ``pattern``, it will then be used to parse the ``file`` and retrieve each entries based on the named groups present in ...
r"""Log ``_message.format(*args, **kwargs)`` with severity ``_level``.
def log(_self, _level, _message, *args, **kwargs): r"""Log ``_message.format(*args, **kwargs)`` with severity ``_level``.""" logger = _self.opt( exception=_self._exception, record=_self._record, lazy=_self._lazy, ansi=_self._ansi, raw=_self._ra...
Deprecated function to |add| a new handler. Warnings -------- .. deprecated:: 0.2.2 ``start()`` will be removed in Loguru 1.0.0, it is replaced by ``add()`` which is a less confusing name.
def start(self, *args, **kwargs): """Deprecated function to |add| a new handler. Warnings -------- .. deprecated:: 0.2.2 ``start()`` will be removed in Loguru 1.0.0, it is replaced by ``add()`` which is a less confusing name. """ warnings.warn( ...
Deprecated function to |remove| an existing handler. Warnings -------- .. deprecated:: 0.2.2 ``stop()`` will be removed in Loguru 1.0.0, it is replaced by ``remove()`` which is a less confusing name.
def stop(self, *args, **kwargs): """Deprecated function to |remove| an existing handler. Warnings -------- .. deprecated:: 0.2.2 ``stop()`` will be removed in Loguru 1.0.0, it is replaced by ``remove()`` which is a less confusing name. """ warnings.wa...
Converts a django rest frameworks field to a graphql field and marks the field as required if we are creating an input type and the field itself is required
def convert_serializer_field(field, is_input=True): """ Converts a django rest frameworks field to a graphql field and marks the field as required if we are creating an input type and the field itself is required """ graphql_type = get_graphene_type_from_serializer_field(field) args = [] ...
If the given setting is a string import notation, then perform the necessary import or imports.
def perform_import(val, setting_name): """ If the given setting is a string import notation, then perform the necessary import or imports. """ if val is None: return None elif isinstance(val, six.string_types): return import_from_string(val, setting_name) elif isinstance(val,...
Create a filterset for the given model using the provided meta data
def custom_filterset_factory(model, filterset_base_class=FilterSet, **meta): """ Create a filterset for the given model using the provided meta data """ meta.update({"model": model}) meta_class = type(str("Meta"), (object,), meta) filterset = type( str("%sFilterSet" % model._meta.object_name...
Convert the filter value to a primary key before filtering
def filter(self, qs, value): """ Convert the filter value to a primary key before filtering """ _id = None if value is not None: _, _id = from_global_id(value) return super(GlobalIDFilter, self).filter(qs, _id)
Inspect a FilterSet and produce the arguments to pass to a Graphene Field. These arguments will be available to filter against in the GraphQL
def get_filtering_args_from_filterset(filterset_class, type): """ Inspect a FilterSet and produce the arguments to pass to a Graphene Field. These arguments will be available to filter against in the GraphQL """ from ..forms.converter import convert_form_field args = {} for name, fi...
Map per-topic results to per-topic futures in futmap. The result value of each (successful) future is None.
def _make_topics_result(f, futmap): """ Map per-topic results to per-topic futures in futmap. The result value of each (successful) future is None. """ try: result = f.result() for topic, error in result.items(): fut = futmap.get(topic, Non...
Map per-resource results to per-resource futures in futmap. The result value of each (successful) future is a ConfigResource.
def _make_resource_result(f, futmap): """ Map per-resource results to per-resource futures in futmap. The result value of each (successful) future is a ConfigResource. """ try: result = f.result() for resource, configs in result.items(): fu...
Create futures and a futuremap for the keys in futmap_keys, and create a request-level future to be bassed to the C API.
def _make_futures(futmap_keys, class_check, make_result_fn): """ Create futures and a futuremap for the keys in futmap_keys, and create a request-level future to be bassed to the C API. """ futmap = {} for key in futmap_keys: if class_check is not None and not...
Create new topics in cluster. The future result() value is None. :param list(NewTopic) new_topics: New topics to be created. :param float operation_timeout: Set broker's operation timeout in seconds, controlling how long the CreateTopics request will block o...
def create_topics(self, new_topics, **kwargs): """ Create new topics in cluster. The future result() value is None. :param list(NewTopic) new_topics: New topics to be created. :param float operation_timeout: Set broker's operation timeout in seconds, controlli...
Delete topics. The future result() value is None. :param list(str) topics: Topics to mark for deletion. :param float operation_timeout: Set broker's operation timeout in seconds, controlling how long the DeleteTopics request will block on the broker waiting ...
def delete_topics(self, topics, **kwargs): """ Delete topics. The future result() value is None. :param list(str) topics: Topics to mark for deletion. :param float operation_timeout: Set broker's operation timeout in seconds, controlling how long the DeleteTop...
Create additional partitions for the given topics. The future result() value is None. :param list(NewPartitions) new_partitions: New partitions to be created. :param float operation_timeout: Set broker's operation timeout in seconds, controlling how long the CreatePartitions ...
def create_partitions(self, new_partitions, **kwargs): """ Create additional partitions for the given topics. The future result() value is None. :param list(NewPartitions) new_partitions: New partitions to be created. :param float operation_timeout: Set broker's operation timeo...
Get configuration for the specified resources. The future result() value is a dict(<configname, ConfigEntry>). :warning: Multiple resources and resource types may be requested, but at most one resource of type RESOURCE_BROKER is allowed per call since these resource...
def describe_configs(self, resources, **kwargs): """ Get configuration for the specified resources. The future result() value is a dict(<configname, ConfigEntry>). :warning: Multiple resources and resource types may be requested, but at most one resource of type RESOU...
Parse a schema given a schema string
def loads(schema_str): """ Parse a schema given a schema string """ try: if sys.version_info[0] < 3: return schema.parse(schema_str) else: return schema.Parse(schema_str) except schema.SchemaParseException as e: raise ClientError("Schema parse failed: %s" % (s...
Asynchronously sends message to Kafka by encoding with specified or default avro schema. :param str topic: topic name :param object value: An object to serialize :param str value_schema: Avro schema for value :param object key: An object to serialize :param s...
def produce(self, **kwargs): """ Asynchronously sends message to Kafka by encoding with specified or default avro schema. :param str topic: topic name :param object value: An object to serialize :param str value_schema: Avro schema for value :param ob...
This is an overriden method from confluent_kafka.Consumer class. This handles message deserialization using avro schema :param float timeout: Poll timeout in seconds (default: indefinite) :returns: message object with deserialized key and value as dict objects :rtype: Message
def poll(self, timeout=None): """ This is an overriden method from confluent_kafka.Consumer class. This handles message deserialization using avro schema :param float timeout: Poll timeout in seconds (default: indefinite) :returns: message object with deserialized key and value ...
Given a parsed avro schema, encode a record for the given topic. The record is expected to be a dictionary. The schema is registered with the subject of 'topic-value' :param str topic: Topic name :param schema schema: Avro Schema :param dict record: An object to serialize ...
def encode_record_with_schema(self, topic, schema, record, is_key=False): """ Given a parsed avro schema, encode a record for the given topic. The record is expected to be a dictionary. The schema is registered with the subject of 'topic-value' :param str topic: Topic name ...
Encode a record with a given schema id. The record must be a python dictionary. :param int schema_id: integer ID :param dict record: An object to serialize :param bool is_key: If the record is a key :returns: decoder function :rtype: func
def encode_record_with_schema_id(self, schema_id, record, is_key=False): """ Encode a record with a given schema id. The record must be a python dictionary. :param int schema_id: integer ID :param dict record: An object to serialize :param bool is_key: If the record is a...
Decode a message from kafka that has been encoded for use with the schema registry. :param str|bytes or None message: message key or value to be decoded :returns: Decoded message contents. :rtype dict:
def decode_message(self, message, is_key=False): """ Decode a message from kafka that has been encoded for use with the schema registry. :param str|bytes or None message: message key or value to be decoded :returns: Decoded message contents. :rtype dict: """ ...
Delivery report callback called (from flush()) on successful or failed delivery of the message.
def acked(err, msg): """Delivery report callback called (from flush()) on successful or failed delivery of the message.""" if err is not None: print("failed to deliver message: {}".format(err.str())) else: print("produced to: {} [{}] @ {}".format(msg.topic(), msg.partition(), msg.offset()))
Create topics
def example_create_topics(a, topics): """ Create topics """ new_topics = [NewTopic(topic, num_partitions=3, replication_factor=1) for topic in topics] # Call create_topics to asynchronously create topics, a dict # of <topic,future> is returned. fs = a.create_topics(new_topics) # Wait for opera...
delete topics
def example_delete_topics(a, topics): """ delete topics """ # Call delete_topics to asynchronously delete topics, a future is returned. # By default this operation on the broker returns immediately while # topics are deleted in the background. But here we give it some time (30s) # to propagate in t...
create partitions
def example_create_partitions(a, topics): """ create partitions """ new_parts = [NewPartitions(topic, int(new_total_count)) for topic, new_total_count in zip(topics[0::2], topics[1::2])] # Try switching validate_only to True to only validate the operation # on the broker but not actua...
describe configs
def example_describe_configs(a, args): """ describe configs """ resources = [ConfigResource(restype, resname) for restype, resname in zip(args[0::2], args[1::2])] fs = a.describe_configs(resources) # Wait for operation to finish. for res, f in fs.items(): try: ...
Alter configs atomically, replacing non-specified configuration properties with their default values.
def example_alter_configs(a, args): """ Alter configs atomically, replacing non-specified configuration properties with their default values. """ resources = [] for restype, resname, configs in zip(args[0::3], args[1::3], args[2::3]): resource = ConfigResource(restype, resname) reso...
The AlterConfigs Kafka API requires all configuration to be passed, any left out configuration properties will revert to their default settings. This example shows how to just modify the supplied configuration entries by first reading the configuration from the broker, updating the supplied configurati...
def example_delta_alter_configs(a, args): """ The AlterConfigs Kafka API requires all configuration to be passed, any left out configuration properties will revert to their default settings. This example shows how to just modify the supplied configuration entries by first reading the configuration ...
list topics and cluster metadata
def example_list(a, args): """ list topics and cluster metadata """ if len(args) == 0: what = "all" else: what = args[0] md = a.list_topics(timeout=10) print("Cluster {} metadata (response from broker {}):".format(md.cluster_id, md.orig_broker_name)) if what in ("all", "broke...
Resolve embedded plugins from the wheel's library directory. For internal module use only. :param str plugins: The plugin.library.paths value
def _resolve_plugins(plugins): """ Resolve embedded plugins from the wheel's library directory. For internal module use only. :param str plugins: The plugin.library.paths value """ import os from sys import platform # Location of __init__.py and the embedded library directory ...
Handle delivery reports served from producer.poll. This callback takes an extra argument, obj. This allows the original contents to be included for debugging purposes.
def on_delivery(err, msg, obj): """ Handle delivery reports served from producer.poll. This callback takes an extra argument, obj. This allows the original contents to be included for debugging purposes. """ if err is not None: print('Message {} delivery failed for user {} wi...
Produce User records
def produce(topic, conf): """ Produce User records """ from confluent_kafka.avro import AvroProducer producer = AvroProducer(conf, default_value_schema=record_schema) print("Producing user records to topic {}. ^c to exit.".format(topic)) while True: # Instantiate new User, pop...
Consume User records
def consume(topic, conf): """ Consume User records """ from confluent_kafka.avro import AvroConsumer from confluent_kafka.avro.serializer import SerializerError print("Consuming user records from topic {} with group {}. ^c to exit.".format(topic, conf["group.id"])) c = AvroConsumer(con...
POST /subjects/(string: subject)/versions Register a schema with the registry under the given subject and receive a schema id. avro_schema must be a parsed schema from the python avro library Multiple instances of the same schema will result in cache misses. :param str subject...
def register(self, subject, avro_schema): """ POST /subjects/(string: subject)/versions Register a schema with the registry under the given subject and receive a schema id. avro_schema must be a parsed schema from the python avro library Multiple instances of the same s...
DELETE /subjects/(string: subject) Deletes the specified subject and its associated compatibility level if registered. It is recommended to use this API only when a topic needs to be recycled or in development environments. :param subject: subject name :returns: version of the schema del...
def delete_subject(self, subject): """ DELETE /subjects/(string: subject) Deletes the specified subject and its associated compatibility level if registered. It is recommended to use this API only when a topic needs to be recycled or in development environments. :param subject: s...
GET /schemas/ids/{int: id} Retrieve a parsed avro schema by id or None if not found :param int schema_id: int value :returns: Avro schema :rtype: schema
def get_by_id(self, schema_id): """ GET /schemas/ids/{int: id} Retrieve a parsed avro schema by id or None if not found :param int schema_id: int value :returns: Avro schema :rtype: schema """ if schema_id in self.id_to_schema: return self.id_t...
POST /subjects/(string: subject) Get the version of a schema for a given subject. Returns None if not found. :param str subject: subject name :param: schema avro_schema: Avro schema :returns: version :rtype: int
def get_version(self, subject, avro_schema): """ POST /subjects/(string: subject) Get the version of a schema for a given subject. Returns None if not found. :param str subject: subject name :param: schema avro_schema: Avro schema :returns: version :rtyp...
PUT /config/(string: subject) Update the compatibility level for a subject. Level must be one of: :param str level: ex: 'NONE','FULL','FORWARD', or 'BACKWARD'
def update_compatibility(self, level, subject=None): """ PUT /config/(string: subject) Update the compatibility level for a subject. Level must be one of: :param str level: ex: 'NONE','FULL','FORWARD', or 'BACKWARD' """ if level not in VALID_LEVELS: raise C...
GET /config Get the current compatibility level for a subject. Result will be one of: :param str subject: subject name :raises ClientError: if the request was unsuccessful or an invalid compatibility level was returned :returns: one of 'NONE','FULL','FORWARD', or 'BACKWARD' :rt...
def get_compatibility(self, subject=None): """ GET /config Get the current compatibility level for a subject. Result will be one of: :param str subject: subject name :raises ClientError: if the request was unsuccessful or an invalid compatibility level was returned :ret...
Download artifact from S3 and store in dirpath directory. If the artifact is already downloaded nothing is done.
def download(self, dirpath): """ Download artifact from S3 and store in dirpath directory. If the artifact is already downloaded nothing is done. """ if os.path.isfile(self.lpath) and os.path.getsize(self.lpath) > 0: return print('Downloading %s -> %s' % (self.path, self....
Collect single S3 artifact :param: path string: S3 path
def collect_single_s3(self, path): """ Collect single S3 artifact :param: path string: S3 path """ # The S3 folder contains the tokens needed to perform # matching of project, gitref, etc. folder = os.path.dirname(path) rinfo = re.findall(r'(?P<tag>[^-]+)-(?P<v...
Collect and download build-artifacts from S3 based on git reference
def collect_s3(self): """ Collect and download build-artifacts from S3 based on git reference """ print('Collecting artifacts matching tag/sha %s from S3 bucket %s' % (self.gitref, s3_bucket)) self.s3 = boto3.resource('s3') self.s3_bucket = self.s3.Bucket(s3_bucket) self.s3.meta....
Collect artifacts from a local directory possibly previously collected from s3
def collect_local(self, path): """ Collect artifacts from a local directory possibly previously collected from s3 """ for f in os.listdir(path): lpath = os.path.join(path, f) if not os.path.isfile(lpath): continue Artifact(self, lpath)
Return a value for 'name' from command line args then config file options. Specify 'key' if the config file option is not the same as 'name'.
def _config(name, key=None, **kwargs): ''' Return a value for 'name' from command line args then config file options. Specify 'key' if the config file option is not the same as 'name'. ''' if key is None: key = name if name in kwargs: value = kwargs[name] else: value ...
Add, replace, or update the A and PTR (reverse) records for a host. CLI Example: .. code-block:: bash salt ns1 ddns.add_host example.com host1 60 10.1.1.1
def add_host(zone, name, ttl, ip, nameserver='127.0.0.1', replace=True, timeout=5, port=53, **kwargs): ''' Add, replace, or update the A and PTR (reverse) records for a host. CLI Example: .. code-block:: bash salt ns1 ddns.add_host example.com host1 60 10.1.1.1 ''' res = ...
Delete the forward and reverse records for a host. Returns true if any records are deleted. CLI Example: .. code-block:: bash salt ns1 ddns.delete_host example.com host1
def delete_host(zone, name, nameserver='127.0.0.1', timeout=5, port=53, **kwargs): ''' Delete the forward and reverse records for a host. Returns true if any records are deleted. CLI Example: .. code-block:: bash salt ns1 ddns.delete_host example.com host1 ''' fqd...
Add, replace, or update a DNS record. nameserver must be an IP address and the minion running this module must have update privileges on that server. If replace is true, first deletes all records for this name and type. CLI Example: .. code-block:: bash salt ns1 ddns.update example.com ho...
def update(zone, name, ttl, rdtype, data, nameserver='127.0.0.1', timeout=5, replace=False, port=53, **kwargs): ''' Add, replace, or update a DNS record. nameserver must be an IP address and the minion running this module must have update privileges on that server. If replace is true, fir...
Set all Ansible modules callables :return:
def _set_callables(modules): ''' Set all Ansible modules callables :return: ''' def _set_function(cmd_name, doc): ''' Create a Salt function for the Ansible module. ''' def _cmd(*args, **kw): ''' Call an Ansible module as a function from the Sa...
Display help on Ansible standard module. :param module: :return:
def help(module=None, *args): ''' Display help on Ansible standard module. :param module: :return: ''' if not module: raise CommandExecutionError('Please tell me what module you want to have helped with. ' 'Or call "ansible.list" to know what is avail...
Run Ansible Playbooks :param playbook: Which playbook to run. :param rundir: Directory to run `ansible-playbook` in. (Default: None) :param check: don't make any changes; instead, try to predict some of the changes that may occur (Default: False) :param diff: when changing (small) fil...
def playbooks(playbook, rundir=None, check=False, diff=False, extra_vars=None, flush_cache=False, forks=5, inventory=None, limit=None, list_hosts=False, list_tags=False, list_tasks=False, module_path=None, skip_tags=None, start_at_task=None, syntax_check=False, ta...
Get installed Ansible modules :return:
def _get_modules_map(self, path=None): ''' Get installed Ansible modules :return: ''' paths = {} root = ansible.modules.__path__[0] if not path: path = root for p_el in os.listdir(path): p_el_path = os.path.join(path, p_el) ...
Introspect Ansible module. :param module: :return:
def load_module(self, module): ''' Introspect Ansible module. :param module: :return: ''' m_ref = self._modules_map.get(module) if m_ref is None: raise LoaderError('Module "{0}" was not found'.format(module)) mod = importlib.import_module('ans...
Return module map references. :return:
def get_modules_list(self, pattern=None): ''' Return module map references. :return: ''' if pattern and '*' not in pattern: pattern = '*{0}*'.format(pattern) modules = [] for m_name, m_path in self._modules_map.items(): m_path = m_path.spli...
Call an Ansible module by invoking it. :param module: the name of the module. :param args: Arguments to the module :param kwargs: keywords to the module :return:
def call(self, module, *args, **kwargs): ''' Call an Ansible module by invoking it. :param module: the name of the module. :param args: Arguments to the module :param kwargs: keywords to the module :return: ''' module = self._resolver.load_module(module) ...
Clean out a template temp file
def __clean_tmp(sfn): ''' Clean out a template temp file ''' if sfn.startswith(os.path.join(tempfile.gettempdir(), salt.utils.files.TEMPFILE_PREFIX)): # Don't remove if it exists in file_roots (any saltenv) all_roots = itertools.chain.from_iterable( ...
This function does NOT do any diffing, it just checks the old and new files to see if either is binary, and provides an appropriate string noting the difference between the two files. If neither file is binary, an empty string is returned. This function should only be run AFTER it has been determined t...
def _binary_replace(old, new): ''' This function does NOT do any diffing, it just checks the old and new files to see if either is binary, and provides an appropriate string noting the difference between the two files. If neither file is binary, an empty string is returned. This function should...
Returns a list of the lines in the string, breaking at line boundaries and preserving a trailing newline (if present). Essentially, this works like ``str.striplines(False)`` but preserves an empty line at the end. This is equivalent to the following code: .. code-block:: python lines = str.sp...
def _splitlines_preserving_trailing_newline(str): ''' Returns a list of the lines in the string, breaking at line boundaries and preserving a trailing newline (if present). Essentially, this works like ``str.striplines(False)`` but preserves an empty line at the end. This is equivalent to the follo...
Convert the group id to the group name on this system gid gid to convert to a group name CLI Example: .. code-block:: bash salt '*' file.gid_to_group 0
def gid_to_group(gid): ''' Convert the group id to the group name on this system gid gid to convert to a group name CLI Example: .. code-block:: bash salt '*' file.gid_to_group 0 ''' try: gid = int(gid) except ValueError: # This is not an integer, mayb...
Convert the group to the gid on this system group group to convert to its gid CLI Example: .. code-block:: bash salt '*' file.group_to_gid root
def group_to_gid(group): ''' Convert the group to the gid on this system group group to convert to its gid CLI Example: .. code-block:: bash salt '*' file.group_to_gid root ''' if group is None: return '' try: if isinstance(group, int): ret...
Return the id of the group that owns a given file path file or directory of which to get the gid follow_symlinks indicated if symlinks should be followed CLI Example: .. code-block:: bash salt '*' file.get_gid /etc/passwd .. versionchanged:: 0.16.4 ``follow_sym...
def get_gid(path, follow_symlinks=True): ''' Return the id of the group that owns a given file path file or directory of which to get the gid follow_symlinks indicated if symlinks should be followed CLI Example: .. code-block:: bash salt '*' file.get_gid /etc/passwd...