code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def read_vocab(filename): """Reads vocab file into the memory and adds special-vocab to it. Args: filename: Path to a vocabulary file containg one word per line. Each word is mapped to its line number. Returns: A tuple (vocab, counts, special_vocab) """ tf.logging.info("Reading vocabulary from...
Reads vocab file into the memory and adds special-vocab to it. Args: filename: Path to a vocabulary file containg one word per line. Each word is mapped to its line number. Returns: A tuple (vocab, counts, special_vocab)
read_vocab
python
taoyds/spider
baselines/seq2seq_attention_copy/seq2seq/data/vocab.py
https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/data/vocab.py
Apache-2.0
def create_vocabulary_lookup_table(filename, default_value=None): """Creates a lookup table for a vocabulary file. Args: filename: Path to a vocabulary file containg one word per line. Each word is mapped to its line number. default_value: UNK tokens will be mapped to this id. If None, UNK token...
Creates a lookup table for a vocabulary file. Args: filename: Path to a vocabulary file containg one word per line. Each word is mapped to its line number. default_value: UNK tokens will be mapped to this id. If None, UNK tokens will be mapped to [vocab_size] Returns: A tuple (vocab_to_i...
create_vocabulary_lookup_table
python
taoyds/spider
baselines/seq2seq_attention_copy/seq2seq/data/vocab.py
https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/data/vocab.py
Apache-2.0
def _build(self, query, keys, values, values_length): """Computes attention scores and outputs. Args: query: The query used to calculate attention scores. In seq2seq this is typically the current state of the decoder. A tensor of shape `[B, ...]` keys: The keys used to calculate att...
Computes attention scores and outputs. Args: query: The query used to calculate attention scores. In seq2seq this is typically the current state of the decoder. A tensor of shape `[B, ...]` keys: The keys used to calculate attention scores. In seq2seq, these are typically the ou...
_build
python
taoyds/spider
baselines/seq2seq_attention_copy/seq2seq/decoders/attention.py
https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/decoders/attention.py
Apache-2.0
def att_next_inputs(time, outputs, state, sample_ids, name=None): """Wraps the original decoder helper function to append the attention context. """ finished, next_inputs, next_state = helper.next_inputs( time=time, outputs=outputs, state=state, sample_ids...
Wraps the original decoder helper function to append the attention context.
att_next_inputs
python
taoyds/spider
baselines/seq2seq_attention_copy/seq2seq/decoders/attention_decoder.py
https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/decoders/attention_decoder.py
Apache-2.0
def _setup(self, initial_state, helper): """Sets the initial state and helper for the decoder. """ self.initial_state = initial_state self.helper = helper
Sets the initial state and helper for the decoder.
_setup
python
taoyds/spider
baselines/seq2seq_attention_copy/seq2seq/decoders/rnn_decoder.py
https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/decoders/rnn_decoder.py
Apache-2.0
def finalize(self, outputs, final_state): """Applies final transformation to the decoder output once decoding is finished. """ #pylint: disable=R0201 return (outputs, final_state)
Applies final transformation to the decoder output once decoding is finished.
finalize
python
taoyds/spider
baselines/seq2seq_attention_copy/seq2seq/decoders/rnn_decoder.py
https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/decoders/rnn_decoder.py
Apache-2.0
def position_encoding(sentence_size, embedding_size): """ Position Encoding described in section 4.1 of End-To-End Memory Networks (https://arxiv.org/abs/1503.08895). Args: sentence_size: length of the sentence embedding_size: dimensionality of the embeddings Returns: A numpy array of shape [sen...
Position Encoding described in section 4.1 of End-To-End Memory Networks (https://arxiv.org/abs/1503.08895). Args: sentence_size: length of the sentence embedding_size: dimensionality of the embeddings Returns: A numpy array of shape [sentence_size, embedding_size] containing the fixed positi...
position_encoding
python
taoyds/spider
baselines/seq2seq_attention_copy/seq2seq/encoders/pooling_encoder.py
https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/encoders/pooling_encoder.py
Apache-2.0
def _create_position_embedding(embedding_dim, num_positions, lengths, maxlen): """Creates position embeddings. Args: embedding_dim: Dimensionality of the embeddings. An integer. num_positions: The number of positions to be embedded. For example, if you have inputs of length up to 100, this should be ...
Creates position embeddings. Args: embedding_dim: Dimensionality of the embeddings. An integer. num_positions: The number of positions to be embedded. For example, if you have inputs of length up to 100, this should be 100. An integer. lengths: The lengths of the inputs to create position embedding...
_create_position_embedding
python
taoyds/spider
baselines/seq2seq_attention_copy/seq2seq/encoders/pooling_encoder.py
https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/encoders/pooling_encoder.py
Apache-2.0
def _unpack_cell(cell): """Unpack the cells because the stack_bidirectional_dynamic_rnn expects a list of cells, one per layer.""" if isinstance(cell, tf.contrib.rnn.MultiRNNCell): return cell._cells #pylint: disable=W0212 else: return [cell]
Unpack the cells because the stack_bidirectional_dynamic_rnn expects a list of cells, one per layer.
_unpack_cell
python
taoyds/spider
baselines/seq2seq_attention_copy/seq2seq/encoders/rnn_encoder.py
https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/encoders/rnn_encoder.py
Apache-2.0
def _default_rnn_cell_params(): """Creates default parameters used by multiple RNN encoders. """ return { "cell_class": "BasicLSTMCell", "cell_params": { "num_units": 128 }, "dropout_input_keep_prob": 1.0, "dropout_output_keep_prob": 1.0, "num_layers": 1, "resid...
Creates default parameters used by multiple RNN encoders.
_default_rnn_cell_params
python
taoyds/spider
baselines/seq2seq_attention_copy/seq2seq/encoders/rnn_encoder.py
https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/encoders/rnn_encoder.py
Apache-2.0
def _toggle_dropout(cell_params, mode): """Disables dropout during eval/inference mode """ cell_params = copy.deepcopy(cell_params) if mode != tf.contrib.learn.ModeKeys.TRAIN: cell_params["dropout_input_keep_prob"] = 1.0 cell_params["dropout_output_keep_prob"] = 1.0 return cell_params
Disables dropout during eval/inference mode
_toggle_dropout
python
taoyds/spider
baselines/seq2seq_attention_copy/seq2seq/encoders/rnn_encoder.py
https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/encoders/rnn_encoder.py
Apache-2.0
def gather_tree_py(values, parents): """Gathers path through a tree backwards from the leave nodes. Used to reconstruct beams given their parents.""" beam_length = values.shape[0] num_beams = values.shape[1] res = np.zeros_like(values) res[-1, :] = values[-1, :] for beam_id in range(num_beams): parent...
Gathers path through a tree backwards from the leave nodes. Used to reconstruct beams given their parents.
gather_tree_py
python
taoyds/spider
baselines/seq2seq_attention_copy/seq2seq/inference/beam_search.py
https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/inference/beam_search.py
Apache-2.0
def create_initial_beam_state(config): """Creates an instance of `BeamState` that can be used on the first call to `beam_step`. Args: config: A BeamSearchConfig Returns: An instance of `BeamState`. """ return BeamSearchState( log_probs=tf.zeros([config.beam_width]), finished=tf.zeros( ...
Creates an instance of `BeamState` that can be used on the first call to `beam_step`. Args: config: A BeamSearchConfig Returns: An instance of `BeamState`.
create_initial_beam_state
python
taoyds/spider
baselines/seq2seq_attention_copy/seq2seq/inference/beam_search.py
https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/inference/beam_search.py
Apache-2.0
def hyp_score(log_probs, sequence_lengths, config): """Calculates scores for beam search hypotheses. """ # Calculate the length penality length_penality_ = length_penalty( sequence_lengths=sequence_lengths, penalty_factor=config.length_penalty_weight) score = log_probs / length_penality_ retur...
Calculates scores for beam search hypotheses.
hyp_score
python
taoyds/spider
baselines/seq2seq_attention_copy/seq2seq/inference/beam_search.py
https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/inference/beam_search.py
Apache-2.0
def choose_top_k(scores_flat, config): """Chooses the top-k beams as successors. """ next_beam_scores, word_indices = tf.nn.top_k(scores_flat, k=config.beam_width) return next_beam_scores, word_indices
Chooses the top-k beams as successors.
choose_top_k
python
taoyds/spider
baselines/seq2seq_attention_copy/seq2seq/inference/beam_search.py
https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/inference/beam_search.py
Apache-2.0
def nest_map(inputs, map_fn, name=None): """Applies a function to (possibly nested) tuple of tensors. """ if nest.is_sequence(inputs): inputs_flat = nest.flatten(inputs) y_flat = [map_fn(_) for _ in inputs_flat] outputs = nest.pack_sequence_as(inputs, y_flat) else: outputs = map_fn(inputs) if ...
Applies a function to (possibly nested) tuple of tensors.
nest_map
python
taoyds/spider
baselines/seq2seq_attention_copy/seq2seq/inference/beam_search.py
https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/inference/beam_search.py
Apache-2.0
def mask_probs(probs, eos_token, finished): """Masks log probabilities such that finished beams allocate all probability mass to eos. Unfinished beams remain unchanged. Args: probs: Log probabiltiies of shape `[beam_width, vocab_size]` eos_token: An int32 id corresponding to the EOS token to allocate ...
Masks log probabilities such that finished beams allocate all probability mass to eos. Unfinished beams remain unchanged. Args: probs: Log probabiltiies of shape `[beam_width, vocab_size]` eos_token: An int32 id corresponding to the EOS token to allocate probability to finished: A boolean tensor ...
mask_probs
python
taoyds/spider
baselines/seq2seq_attention_copy/seq2seq/inference/beam_search.py
https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/inference/beam_search.py
Apache-2.0
def beam_search_step(time_, logits, beam_state, config): """Performs a single step of Beam Search Decoding. Args: time_: Beam search time step, should start at 0. At time 0 we assume that all beams are equal and consider only the first beam for continuations. logits: Logits at the current time ...
Performs a single step of Beam Search Decoding. Args: time_: Beam search time step, should start at 0. At time 0 we assume that all beams are equal and consider only the first beam for continuations. logits: Logits at the current time step. A tensor of shape `[B, vocab_size]` beam_state: Curr...
beam_search_step
python
taoyds/spider
baselines/seq2seq_attention_copy/seq2seq/inference/beam_search.py
https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/inference/beam_search.py
Apache-2.0
def create_inference_graph(model, input_pipeline, batch_size=32): """Creates a graph to perform inference. Args: task: An `InferenceTask` instance. input_pipeline: An instance of `InputPipeline` that defines how to read and parse data. batch_size: The batch size used for inference Returns: ...
Creates a graph to perform inference. Args: task: An `InferenceTask` instance. input_pipeline: An instance of `InputPipeline` that defines how to read and parse data. batch_size: The batch size used for inference Returns: The return value of the model function, typically a tuple of (pred...
create_inference_graph
python
taoyds/spider
baselines/seq2seq_attention_copy/seq2seq/inference/inference.py
https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/inference/inference.py
Apache-2.0
def moses_multi_bleu(hypotheses, references, lowercase=False): """Calculate the bleu score for hypotheses and references using the MOSES ulti-bleu.perl script. Args: hypotheses: A numpy array of strings where each string is a single example. references: A numpy array of strings where each string is a sin...
Calculate the bleu score for hypotheses and references using the MOSES ulti-bleu.perl script. Args: hypotheses: A numpy array of strings where each string is a single example. references: A numpy array of strings where each string is a single example. lowercase: If true, pass the "-lc" flag to the mult...
moses_multi_bleu
python
taoyds/spider
baselines/seq2seq_attention_copy/seq2seq/metrics/bleu.py
https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/metrics/bleu.py
Apache-2.0
def accumulate_strings(values, name="strings"): """Accumulates strings into a vector. Args: values: A 1-d string tensor that contains values to add to the accumulator. Returns: A tuple (value_tensor, update_op). """ tf.assert_type(values, tf.string) strings = tf.Variable( name=name, in...
Accumulates strings into a vector. Args: values: A 1-d string tensor that contains values to add to the accumulator. Returns: A tuple (value_tensor, update_op).
accumulate_strings
python
taoyds/spider
baselines/seq2seq_attention_copy/seq2seq/metrics/metric_specs.py
https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/metrics/metric_specs.py
Apache-2.0
def _py_func(self, hypotheses, references): """Wrapper function that converts tensors to unicode and slices them until the EOS token is found. """ # Deal with byte chars if hypotheses.dtype.kind == np.dtype("U"): hypotheses = np.char.encode(hypotheses, "utf-8") if references.dtype.kind =...
Wrapper function that converts tensors to unicode and slices them until the EOS token is found.
_py_func
python
taoyds/spider
baselines/seq2seq_attention_copy/seq2seq/metrics/metric_specs.py
https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/metrics/metric_specs.py
Apache-2.0
def compute_loss(self, decoder_output, _features, labels): """Computes the sequence loss for this model. seq_loss is the cross entropy loss for the output sequence. Returns a tuple `(losses, loss)`, where `losses` are the per-batch losses and loss is a single scalar tensor to minimize. ...
Computes the sequence loss for this model. seq_loss is the cross entropy loss for the output sequence. Returns a tuple `(losses, loss)`, where `losses` are the per-batch losses and loss is a single scalar tensor to minimize.
compute_loss
python
taoyds/spider
baselines/seq2seq_attention_copy/seq2seq/models/attention_copying_seq2seq.py
https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/models/attention_copying_seq2seq.py
Apache-2.0
def _preprocess(self, features, labels): """Model-specific preprocessing for features and labels: - Creates vocabulary lookup tables for source and target vocab - Converts tokens into vocabulary ids - Trims copy indices to target.max_seq_len """ features, labels = super(S...
Model-specific preprocessing for features and labels: - Creates vocabulary lookup tables for source and target vocab - Converts tokens into vocabulary ids - Trims copy indices to target.max_seq_len
_preprocess
python
taoyds/spider
baselines/seq2seq_attention_copy/seq2seq/models/attention_copying_seq2seq.py
https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/models/attention_copying_seq2seq.py
Apache-2.0
def compute_loss(self, decoder_output, _features, labels): """Computes the loss for this model. Loss = seq_loss + schema_copy_loss. seq_loss is the cross entropy loss for the output sequence. schema_copy_loss is zero at any time step where output is not copy_schema, and the cross...
Computes the loss for this model. Loss = seq_loss + schema_copy_loss. seq_loss is the cross entropy loss for the output sequence. schema_copy_loss is zero at any time step where output is not copy_schema, and the cross entropy loss for the schema attention score otherwise. ...
compute_loss
python
taoyds/spider
baselines/seq2seq_attention_copy/seq2seq/models/attention_copying_seq2seq.py
https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/models/attention_copying_seq2seq.py
Apache-2.0
def compute_loss(self, decoder_output, _features, labels): """Computes the loss for this model. Loss = seq_loss + word_copy_loss. seq_loss is the cross entropy loss for the output sequence. word_copy_loss is zero at any time step where output is not copy_word, and the cross entro...
Computes the loss for this model. Loss = seq_loss + word_copy_loss. seq_loss is the cross entropy loss for the output sequence. word_copy_loss is zero at any time step where output is not copy_word, and the cross entropy loss for the input attention score otherwise. Returns a tup...
compute_loss
python
taoyds/spider
baselines/seq2seq_attention_copy/seq2seq/models/attention_copying_seq2seq.py
https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/models/attention_copying_seq2seq.py
Apache-2.0
def compute_loss(self, decoder_output, _features, labels): """Computes the loss for this model. Loss = seq_loss + schema_copy_loss + word_copy_loss. seq_loss is the cross entropy loss for the output sequence. word_copy_loss is zero at any time step where output is not copy_word, ...
Computes the loss for this model. Loss = seq_loss + schema_copy_loss + word_copy_loss. seq_loss is the cross entropy loss for the output sequence. word_copy_loss is zero at any time step where output is not copy_word, and the cross entropy loss for the input attention score otherwise. ...
compute_loss
python
taoyds/spider
baselines/seq2seq_attention_copy/seq2seq/models/attention_copying_seq2seq.py
https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/models/attention_copying_seq2seq.py
Apache-2.0
def _create_bridge(self, encoder_outputs, decoder_state_size): """Creates the bridge to be used between encoder and decoder""" bridge_class = locate(self.params["bridge.class"]) or \ getattr(bridges, self.params["bridge.class"]) return bridge_class( encoder_outputs=encoder_outputs, dec...
Creates the bridge to be used between encoder and decoder
_create_bridge
python
taoyds/spider
baselines/seq2seq_attention_copy/seq2seq/models/basic_seq2seq.py
https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/models/basic_seq2seq.py
Apache-2.0
def _create_decoder(self, _encoder_output, _features, _labels): """Creates a decoder instance based on the passed parameters.""" decoder_mask = _features["decoder_mask"] return self.decoder_class( params=self.params["decoder.params"], mode=self.mode, vocab_size=self.target_vocab...
Creates a decoder instance based on the passed parameters.
_create_decoder
python
taoyds/spider
baselines/seq2seq_attention_copy/seq2seq/models/basic_seq2seq.py
https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/models/basic_seq2seq.py
Apache-2.0
def _preprocess(self, features, labels): """Model-specific preprocessing for features and labels: - Creates vocabulary lookup tables for target vocab - Converts tokens into vocabulary ids - Prepends a speical "SEQUENCE_START" token to the target - Appends a speical "SEQUENCE_END" token to the targe...
Model-specific preprocessing for features and labels: - Creates vocabulary lookup tables for target vocab - Converts tokens into vocabulary ids - Prepends a speical "SEQUENCE_START" token to the target - Appends a speical "SEQUENCE_END" token to the target
_preprocess
python
taoyds/spider
baselines/seq2seq_attention_copy/seq2seq/models/image2seq.py
https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/models/image2seq.py
Apache-2.0
def _flatten_dict(dict_, parent_key="", sep="."): """Flattens a nested dictionary. Namedtuples within the dictionary are converted to dicts. Args: dict_: The dictionary to flatten. parent_key: A prefix to prepend to each key. sep: Separator between parent and child keys, a string. For example {...
Flattens a nested dictionary. Namedtuples within the dictionary are converted to dicts. Args: dict_: The dictionary to flatten. parent_key: A prefix to prepend to each key. sep: Separator between parent and child keys, a string. For example { "a": { "b": 3 } } will become { "a.b": 3 } if the sepa...
_flatten_dict
python
taoyds/spider
baselines/seq2seq_attention_copy/seq2seq/models/model_base.py
https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/models/model_base.py
Apache-2.0
def default_params(): """Returns a dictionary of default parameters for this model.""" return { "optimizer.name": "Adam", "optimizer.learning_rate": 1e-4, "optimizer.params": {}, # Arbitrary parameters for the optimizer "optimizer.lr_decay_type": "", "optimizer.lr_decay_s...
Returns a dictionary of default parameters for this model.
default_params
python
taoyds/spider
baselines/seq2seq_attention_copy/seq2seq/models/model_base.py
https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/models/model_base.py
Apache-2.0
def __call__(self, features, labels, params): """Creates the model graph. See the model_fn documentation in tf.contrib.learn.Estimator class for a more detailed explanation. """ with tf.variable_scope("model"): with tf.variable_scope(self.name): return self._build(features, labels, params)
Creates the model graph. See the model_fn documentation in tf.contrib.learn.Estimator class for a more detailed explanation.
__call__
python
taoyds/spider
baselines/seq2seq_attention_copy/seq2seq/models/model_base.py
https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/models/model_base.py
Apache-2.0
def compute_loss(self, decoder_output, _features, labels): """Computes the loss for this model. Loss = seq_loss + schema_copy_loss. seq_loss is the cross entropy loss for the output sequence. # word_copy_loss is zero at any time step where output is not copy_word, and the cross en...
Computes the loss for this model. Loss = seq_loss + schema_copy_loss. seq_loss is the cross entropy loss for the output sequence. # word_copy_loss is zero at any time step where output is not copy_word, and the cross entropy loss for the input attention score otherwise. schema_cop...
compute_loss
python
taoyds/spider
baselines/seq2seq_attention_copy/seq2seq/models/schema_attention_copying_seq2seq.py
https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/models/schema_attention_copying_seq2seq.py
Apache-2.0
def _clip_gradients(self, grads_and_vars): """In addition to standard gradient clipping, also clips embedding gradients to a specified value.""" grads_and_vars = super(Seq2SeqModel, self)._clip_gradients(grads_and_vars) clipped_gradients = [] variables = [] for gradient, variable in grads_and_v...
In addition to standard gradient clipping, also clips embedding gradients to a specified value.
_clip_gradients
python
taoyds/spider
baselines/seq2seq_attention_copy/seq2seq/models/seq2seq_model.py
https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/models/seq2seq_model.py
Apache-2.0
def _create_predictions(self, decoder_output, features, labels, losses=None): """Creates the dictionary of predictions that is returned by the model. """ predictions = {} # Add features and, if available, labels to predictions predictions.update(_flatten_dict({"features": features})) if labels ...
Creates the dictionary of predictions that is returned by the model.
_create_predictions
python
taoyds/spider
baselines/seq2seq_attention_copy/seq2seq/models/seq2seq_model.py
https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/models/seq2seq_model.py
Apache-2.0
def source_embedding(self): """Returns the embedding used for the source sequence. """ # return tf.get_variable( # name="W", # shape=[self.source_vocab_info.total_size, self.params["embedding.dim"]], # initializer=tf.random_uniform_initializer( # -self.params["embedding.i...
Returns the embedding used for the source sequence.
source_embedding
python
taoyds/spider
baselines/seq2seq_attention_copy/seq2seq/models/seq2seq_model.py
https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/models/seq2seq_model.py
Apache-2.0
def target_embedding(self): """Returns the embedding used for the target sequence. """ # if self.params["embedding.share"]: # return self.source_embedding # return tf.get_variable( # name="W", # shape=[self.target_vocab_info.total_size, self.params["embedding.dim"]], # init...
Returns the embedding used for the target sequence.
target_embedding
python
taoyds/spider
baselines/seq2seq_attention_copy/seq2seq/models/seq2seq_model.py
https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/models/seq2seq_model.py
Apache-2.0
def _get_beam_search_decoder(self, decoder): """Wraps a decoder into a Beam Search decoder. Args: decoder: The original decoder Returns: A BeamSearchDecoder with the same interfaces as the original decoder. """ config = beam_search.BeamSearchConfig( beam_width=self.params["infe...
Wraps a decoder into a Beam Search decoder. Args: decoder: The original decoder Returns: A BeamSearchDecoder with the same interfaces as the original decoder.
_get_beam_search_decoder
python
taoyds/spider
baselines/seq2seq_attention_copy/seq2seq/models/seq2seq_model.py
https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/models/seq2seq_model.py
Apache-2.0
def _preprocess(self, features, labels): """Model-specific preprocessing for features and labels: - Creates vocabulary lookup tables for source and target vocab - Converts tokens into vocabulary ids """ # Create vocabulary lookup for source source_vocab_to_id, source_id_to_vocab, source_word_t...
Model-specific preprocessing for features and labels: - Creates vocabulary lookup tables for source and target vocab - Converts tokens into vocabulary ids
_preprocess
python
taoyds/spider
baselines/seq2seq_attention_copy/seq2seq/models/seq2seq_model.py
https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/models/seq2seq_model.py
Apache-2.0
def compute_loss(self, decoder_output, _features, labels): """Computes the loss for this model. Returns a tuple `(losses, loss)`, where `losses` are the per-batch losses and loss is a single scalar tensor to minimize. """ #pylint: disable=R0201 # Calculate loss per example-timestep of shape [B,...
Computes the loss for this model. Returns a tuple `(losses, loss)`, where `losses` are the per-batch losses and loss is a single scalar tensor to minimize.
compute_loss
python
taoyds/spider
baselines/seq2seq_attention_copy/seq2seq/models/seq2seq_model.py
https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/models/seq2seq_model.py
Apache-2.0
def _get_prediction_length(predictions_dict): """Returns the length of the prediction based on the index of the first SEQUENCE_END token. """ tokens_iter = enumerate(predictions_dict["predicted_tokens"]) return next(((i + 1) for i, _ in tokens_iter if _ == "SEQUENCE_END"), len(predictions_dict["...
Returns the length of the prediction based on the index of the first SEQUENCE_END token.
_get_prediction_length
python
taoyds/spider
baselines/seq2seq_attention_copy/seq2seq/tasks/decode_text.py
https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/tasks/decode_text.py
Apache-2.0
def _get_unk_mapping(filename): """Reads a file that specifies a mapping from source to target tokens. The file must contain lines of the form <source>\t<target>" Args: filename: path to the mapping file Returns: A dictionary that maps from source -> target tokens. """ with gfile.GFile(filename, "...
Reads a file that specifies a mapping from source to target tokens. The file must contain lines of the form <source> <target>" Args: filename: path to the mapping file Returns: A dictionary that maps from source -> target tokens.
_get_unk_mapping
python
taoyds/spider
baselines/seq2seq_attention_copy/seq2seq/tasks/decode_text.py
https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/tasks/decode_text.py
Apache-2.0
def _unk_replace(source_tokens, predicted_tokens, attention_scores, mapping=None): """Replaces UNK tokens with tokens from the source or a provided mapping based on the attention scores. Args: source_tokens: A numpy array of strings. predicted_tokens: A ...
Replaces UNK tokens with tokens from the source or a provided mapping based on the attention scores. Args: source_tokens: A numpy array of strings. predicted_tokens: A numpy array of strings. attention_scores: A numeric numpy array of shape `[prediction_length, source_length]` that contains ...
_unk_replace
python
taoyds/spider
baselines/seq2seq_attention_copy/seq2seq/tasks/decode_text.py
https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/tasks/decode_text.py
Apache-2.0
def _get_scores(predictions_dict): """Returns the attention scores, sliced by source and target length. """ prediction_len = _get_prediction_length(predictions_dict) source_len = predictions_dict["features.source_len"] return predictions_dict["attention_scores"][:prediction_len, :source_len]
Returns the attention scores, sliced by source and target length.
_get_scores
python
taoyds/spider
baselines/seq2seq_attention_copy/seq2seq/tasks/dump_attention.py
https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/tasks/dump_attention.py
Apache-2.0
def _create_figure(predictions_dict): """Creates and returns a new figure that visualizes attention scores for for a single model predictions. """ # Find out how long the predicted sequence is target_words = list(predictions_dict["predicted_tokens"]) prediction_len = _get_prediction_length(predictions_dic...
Creates and returns a new figure that visualizes attention scores for for a single model predictions.
_create_figure
python
taoyds/spider
baselines/seq2seq_attention_copy/seq2seq/tasks/dump_attention.py
https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/tasks/dump_attention.py
Apache-2.0
def unbatch_dict(dict_): """Converts a dictionary of batch items to a batch/list of dictionary items. """ batch_size = list(dict_.values())[0].shape[0] for i in range(batch_size): yield {key: value[i] for key, value in dict_.items()}
Converts a dictionary of batch items to a batch/list of dictionary items.
unbatch_dict
python
taoyds/spider
baselines/seq2seq_attention_copy/seq2seq/tasks/inference_task.py
https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/tasks/inference_task.py
Apache-2.0
def _test_layer(self): """Tests Attention layer with a given score type""" inputs_pl = tf.placeholder(tf.float32, (None, None, self.input_dim)) inputs_length_pl = tf.placeholder(tf.int32, [None]) state_pl = tf.placeholder(tf.float32, (None, self.state_dim)) attention_fn = self._create_layer() s...
Tests Attention layer with a given score type
_test_layer
python
taoyds/spider
baselines/seq2seq_attention_copy/seq2seq/test/attention_test.py
https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/test/attention_test.py
Apache-2.0
def _run(self, scope=None, **kwargs): """Runs the bridge with the given arguments """ with tf.variable_scope(scope or "bridge"): bridge = self._create_bridge(**kwargs) initial_state = bridge() with self.test_session() as sess: sess.run(tf.global_variables_initializer()) initial...
Runs the bridge with the given arguments
_run
python
taoyds/spider
baselines/seq2seq_attention_copy/seq2seq/test/bridges_test.py
https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/test/bridges_test.py
Apache-2.0
def _test_with_params(self, params): """Tests the encoder with a given parameter configuration""" inputs = tf.random_normal( [self.batch_size, self.sequence_length, self.input_depth]) example_length = tf.ones( self.batch_size, dtype=tf.int32) * self.sequence_length encode_fn = ConvEncod...
Tests the encoder with a given parameter configuration
_test_with_params
python
taoyds/spider
baselines/seq2seq_attention_copy/seq2seq/test/conv_encoder_test.py
https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/test/conv_encoder_test.py
Apache-2.0
def _test_pipeline(self, mode, params=None): """Helper function to test the full model pipeline. """ # Create source and target example source_len = self.sequence_length + 5 target_len = self.sequence_length + 10 source = " ".join(np.random.choice(self.vocab_list, source_len)) target = " ".j...
Helper function to test the full model pipeline.
_test_pipeline
python
taoyds/spider
baselines/seq2seq_attention_copy/seq2seq/test/models_test.py
https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/test/models_test.py
Apache-2.0
def _test_constant_shape(self, combiner): """Tests a residual combiner whose shape doesn't change with depth""" inputs = np.random.randn(1, 2) with tf.variable_scope("same_input_size"): res_ = self._test_with_residuals(inputs, residual_combiner=combiner) self.assertEqual(res_[0].shape, (1, 2...
Tests a residual combiner whose shape doesn't change with depth
_test_constant_shape
python
taoyds/spider
baselines/seq2seq_attention_copy/seq2seq/test/rnn_cell_test.py
https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/test/rnn_cell_test.py
Apache-2.0
def _test_encode_with_params(self, params): """Tests the StackBidirectionalRNNEncoder with a specific cell""" inputs = tf.random_normal( [self.batch_size, self.sequence_length, self.input_depth]) example_length = tf.ones( self.batch_size, dtype=tf.int32) * self.sequence_length encode_fn...
Tests the StackBidirectionalRNNEncoder with a specific cell
_test_encode_with_params
python
taoyds/spider
baselines/seq2seq_attention_copy/seq2seq/test/rnn_encoder_test.py
https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/test/rnn_encoder_test.py
Apache-2.0
def _test_with_args(self, **kwargs): """Helper function to test create_input_fn with keyword arguments""" sources_file, targets_file = test_utils.create_temp_parallel_data( sources=["Hello World ."], targets=["Goodbye ."]) pipeline = input_pipeline.ParallelTextInputPipeline( params={ ...
Helper function to test create_input_fn with keyword arguments
_test_with_args
python
taoyds/spider
baselines/seq2seq_attention_copy/seq2seq/test/train_utils_test.py
https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/test/train_utils_test.py
Apache-2.0
def create_temp_parallel_data(sources, targets): """ Creates a temporary TFRecords file. Args: source: List of source sentences target: List of target sentences Returns: A tuple (sources_file, targets_file). """ file_source = tempfile.NamedTemporaryFile() file_target = tempfile.NamedTemporar...
Creates a temporary TFRecords file. Args: source: List of source sentences target: List of target sentences Returns: A tuple (sources_file, targets_file).
create_temp_parallel_data
python
taoyds/spider
baselines/seq2seq_attention_copy/seq2seq/test/utils.py
https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/test/utils.py
Apache-2.0
def create_temporary_vocab_file(words, counts=None): """ Creates a temporary vocabulary file. Args: words: List of words in the vocabulary Returns: A temporary file object with one word per line """ vocab_file = tempfile.NamedTemporaryFile() if counts is None: for token in words: vocab...
Creates a temporary vocabulary file. Args: words: List of words in the vocabulary Returns: A temporary file object with one word per line
create_temporary_vocab_file
python
taoyds/spider
baselines/seq2seq_attention_copy/seq2seq/test/utils.py
https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/test/utils.py
Apache-2.0
def varname_in_checkpoint(name): """Removes the prefix from the variable name. """ prefix_parts = self.params["prefix"].split("/") checkpoint_prefix = "/".join(prefix_parts[:-1]) return name.replace(checkpoint_prefix + "/", "")
Removes the prefix from the variable name.
varname_in_checkpoint
python
taoyds/spider
baselines/seq2seq_attention_copy/seq2seq/training/hooks.py
https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/training/hooks.py
Apache-2.0
def dump(self, model_dir): """Dumps the options to a file in the model directory. Args: model_dir: Path to the model directory. The options will be dumped into a file in this directory. """ gfile.MakeDirs(model_dir) options_dict = { "model_class": self.model_class, "mode...
Dumps the options to a file in the model directory. Args: model_dir: Path to the model directory. The options will be dumped into a file in this directory.
dump
python
taoyds/spider
baselines/seq2seq_attention_copy/seq2seq/training/utils.py
https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/training/utils.py
Apache-2.0
def load(model_dir): """ Loads options from the given model directory. Args: model_dir: Path to the model directory. """ with gfile.GFile(TrainOptions.path(model_dir), "rb") as file: options_dict = json.loads(file.read().decode("utf-8")) options_dict = defaultdict(None, options_dict) ...
Loads options from the given model directory. Args: model_dir: Path to the model directory.
load
python
taoyds/spider
baselines/seq2seq_attention_copy/seq2seq/training/utils.py
https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/training/utils.py
Apache-2.0
def cell_from_spec(cell_classname, cell_params): """Create a RNN Cell instance from a JSON string. Args: cell_classname: Name of the cell class, e.g. "BasicLSTMCell". cell_params: A dictionary of parameters to pass to the cell constructor. Returns: A RNNCell instance. """ cell_params = cell_par...
Create a RNN Cell instance from a JSON string. Args: cell_classname: Name of the cell class, e.g. "BasicLSTMCell". cell_params: A dictionary of parameters to pass to the cell constructor. Returns: A RNNCell instance.
cell_from_spec
python
taoyds/spider
baselines/seq2seq_attention_copy/seq2seq/training/utils.py
https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/training/utils.py
Apache-2.0
def get_rnn_cell(cell_class, cell_params, num_layers=1, dropout_input_keep_prob=1.0, dropout_output_keep_prob=1.0, residual_connections=False, residual_combiner="add", residual_dense=False): """Creat...
Creates a new RNN Cell Args: cell_class: Name of the cell class, e.g. "BasicLSTMCell". cell_params: A dictionary of parameters to pass to the cell constructor. num_layers: Number of layers. The cell will be wrapped with `tf.contrib.rnn.MultiRNNCell` dropout_input_keep_prob: Dropout keep probabi...
get_rnn_cell
python
taoyds/spider
baselines/seq2seq_attention_copy/seq2seq/training/utils.py
https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/training/utils.py
Apache-2.0
def create_learning_rate_decay_fn(decay_type, decay_steps, decay_rate, start_decay_at=0, stop_decay_at=1e9, min_learning_rate=None, ...
Creates a function that decays the learning rate. Args: decay_steps: How often to apply decay. decay_rate: A Python number. The decay rate. start_decay_at: Don't decay before this step stop_decay_at: Don't decay after this step min_learning_rate: Don't decay below this number decay_type: A de...
create_learning_rate_decay_fn
python
taoyds/spider
baselines/seq2seq_attention_copy/seq2seq/training/utils.py
https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/training/utils.py
Apache-2.0
def decay_fn(learning_rate, global_step): """The computed learning rate decay function. """ global_step = tf.to_int32(global_step) decay_type_fn = getattr(tf.train, decay_type) decayed_learning_rate = decay_type_fn( learning_rate=learning_rate, global_step=tf.minimum(global_step, st...
The computed learning rate decay function.
decay_fn
python
taoyds/spider
baselines/seq2seq_attention_copy/seq2seq/training/utils.py
https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/training/utils.py
Apache-2.0
def create_input_fn(pipeline, batch_size, bucket_boundaries=None, allow_smaller_final_batch=False, scope=None): """Creates an input function that can be used with tf.learn estimators. Note that you must pass "factory funcitons" for bo...
Creates an input function that can be used with tf.learn estimators. Note that you must pass "factory funcitons" for both the data provider and featurizer to ensure that everything will be created in the same graph. Args: pipeline: An instance of `seq2seq.data.InputPipeline`. batch_size: Create batc...
create_input_fn
python
taoyds/spider
baselines/seq2seq_attention_copy/seq2seq/training/utils.py
https://github.com/taoyds/spider/blob/master/baselines/seq2seq_attention_copy/seq2seq/training/utils.py
Apache-2.0
def str_list_to_batch(self, str_list): """get a list var of wemb of words in each column name in current bactch""" B = len(str_list) val_embs = [] val_len = np.zeros(B, dtype=np.int64) for i, one_str in enumerate(str_list): if self.trainable: val = [s...
get a list var of wemb of words in each column name in current bactch
str_list_to_batch
python
taoyds/spider
baselines/sqlnet/scripts/model/modules/word_embedding.py
https://github.com/taoyds/spider/blob/master/baselines/sqlnet/scripts/model/modules/word_embedding.py
Apache-2.0
def do_configure(config_path=CONFIG_PATH): """Returns error code :param config_path: path to config.yaml :type config_path: string | CONFIG_PATH (genconf/config.yaml) """ config = Config(config_path) try: gen_out = config_util.onprem_generate(config) except ValidationError as e: ...
Returns error code :param config_path: path to config.yaml :type config_path: string | CONFIG_PATH (genconf/config.yaml)
do_configure
python
dcos/dcos
dcos_installer/backend.py
https://github.com/dcos/dcos/blob/master/dcos_installer/backend.py
Apache-2.0
def do_aws_cf_configure(): """Returns error code Generates AWS templates using a custom config.yaml """ # TODO(cmaloney): Move to Config class introduced in https://github.com/dcos/dcos/pull/623 config = Config(CONFIG_PATH) # This process is usually ran from a docker container where default b...
Returns error code Generates AWS templates using a custom config.yaml
do_aws_cf_configure
python
dcos/dcos
dcos_installer/backend.py
https://github.com/dcos/dcos/blob/master/dcos_installer/backend.py
Apache-2.0
def determine_config_type(config_path=CONFIG_PATH): """Returns the configuration type to the UI. One of either 'minimal' or 'advanced'. 'advanced' blocks UI usage. :param config_path: path to config.yaml :type config_path: str | CONFIG_PATH (genconf/config.yaml) """ # TODO(cmaloney): If the con...
Returns the configuration type to the UI. One of either 'minimal' or 'advanced'. 'advanced' blocks UI usage. :param config_path: path to config.yaml :type config_path: str | CONFIG_PATH (genconf/config.yaml)
determine_config_type
python
dcos/dcos
dcos_installer/backend.py
https://github.com/dcos/dcos/blob/master/dcos_installer/backend.py
Apache-2.0
def success(config: Config): """Returns the data for /success/ endpoint. :param config_path: path to config.yaml :type config_path: str | CONFIG_PATH (genconf/config.yaml) """ master_ips = config.hacky_default_get('master_list', []) agent_ips = config.hacky_default_get('agent_list', []) cod...
Returns the data for /success/ endpoint. :param config_path: path to config.yaml :type config_path: str | CONFIG_PATH (genconf/config.yaml)
success
python
dcos/dcos
dcos_installer/backend.py
https://github.com/dcos/dcos/blob/master/dcos_installer/backend.py
Apache-2.0
def dispatch(args): """ Dispatches the selected mode based on command line args. """ if args.action == 'hash-password': # TODO(cmaloney): Import a function from the auth stuff to do the hashing and guarantee it # always matches byte_str = do_hash_password(args.password).encode('ascii') ...
Dispatches the selected mode based on command line args.
dispatch
python
dcos/dcos
dcos_installer/cli.py
https://github.com/dcos/dcos/blob/master/dcos_installer/cli.py
Apache-2.0
def get_argument_parser(): """ Parse CLI arguments and return a map of options. """ parser = argparse.ArgumentParser( description="DC/OS Install and Configuration Utility") mutual_exc = parser.add_mutually_exclusive_group() mutual_exc.add_argument( '--hash-password', act...
Parse CLI arguments and return a map of options.
get_argument_parser
python
dcos/dcos
dcos_installer/cli.py
https://github.com/dcos/dcos/blob/master/dcos_installer/cli.py
Apache-2.0
def normalize_config_validation(messages): """Accepts Gen error message format and returns a flattened dictionary of validation messages. :param messages: Gen validation messages :type messages: dict | None """ validation = {} if 'errors' in messages: for key, errors in messages['er...
Accepts Gen error message format and returns a flattened dictionary of validation messages. :param messages: Gen validation messages :type messages: dict | None
normalize_config_validation
python
dcos/dcos
dcos_installer/config.py
https://github.com/dcos/dcos/blob/master/dcos_installer/config.py
Apache-2.0
def normalize_config_validation_exception(error: ValidationError) -> dict: """ A ValidationError is transformed to dict and processed by `normalize_config_validation` function. Args: exception: An exception raised during the config validation """ messages = {} messages['errors'] = e...
A ValidationError is transformed to dict and processed by `normalize_config_validation` function. Args: exception: An exception raised during the config validation
normalize_config_validation_exception
python
dcos/dcos
dcos_installer/config.py
https://github.com/dcos/dcos/blob/master/dcos_installer/config.py
Apache-2.0
def test_password_hash(): """Tests that the password hashing method creates de-cryptable hash """ password = 'DcosTestingPassword!@#' # only reads from STDOUT hash_pw = subprocess.check_output(['dcos_installer', '--hash-password', password]) print(hash_pw) hash_pw = hash_pw.decode('ascii').s...
Tests that the password hashing method creates de-cryptable hash
test_password_hash
python
dcos/dcos
dcos_installer/test_backend.py
https://github.com/dcos/dcos/blob/master/dcos_installer/test_backend.py
Apache-2.0
def valid_storage_config(release_config_aws): """ Uses the settings from dcos-release.config.yaml ['testing'] to create a new upload and then deletes it when the test is over """ s3_bucket_name = release_config_aws['bucket'] bucket_path = str(uuid.uuid4()) yield """--- master_list: - 127.0.0.1 ...
Uses the settings from dcos-release.config.yaml ['testing'] to create a new upload and then deletes it when the test is over
valid_storage_config
python
dcos/dcos
dcos_installer/test_backend.py
https://github.com/dcos/dcos/blob/master/dcos_installer/test_backend.py
Apache-2.0
def test_do_configure_valid_config_no_duplicate_logging(tmpdir, monkeypatch, caplog): """ Log messages are logged exactly once. """ monkeypatch.setenv('BOOTSTRAP_VARIANT', 'test_variant') create_config(simple_full_config, tmpdir) create_fake_build_artifacts(tmpdir) with tmpdir.as_cwd(): ...
Log messages are logged exactly once.
test_do_configure_valid_config_no_duplicate_logging
python
dcos/dcos
dcos_installer/test_backend.py
https://github.com/dcos/dcos/blob/master/dcos_installer/test_backend.py
Apache-2.0
def test_do_configure_logs_validation_errors(tmpdir, monkeypatch, caplog): """ Configuration validation errors are logged as `error` messages. """ monkeypatch.setenv('BOOTSTRAP_VARIANT', 'test_variant') invalid_config = textwrap.dedent("""--- cluster_name: DC/OS master_discovery: static ...
Configuration validation errors are logged as `error` messages.
test_do_configure_logs_validation_errors
python
dcos/dcos
dcos_installer/test_backend.py
https://github.com/dcos/dcos/blob/master/dcos_installer/test_backend.py
Apache-2.0
def validate_overlay_networks_not_overlap(dcos_overlay_network, dcos_overlay_enable, calico_network_cidr, calico_enabled): """ checks the subnets used for dcos overlay do not overlap calico ...
checks the subnets used for dcos overlay do not overlap calico network We assume the basic validations, like subnet cidr, have been done.
validate_overlay_networks_not_overlap
python
dcos/dcos
gen/calc.py
https://github.com/dcos/dcos/blob/master/gen/calc.py
Apache-2.0
def validate_adminrouter_x_frame_options(adminrouter_x_frame_options): """ Provide a basic validation that checks that provided value starts with one of the supported options: DENY, SAMEORIGIN, ALLOW-FROM See: https://tools.ietf.org/html/rfc7034#section-2.1 """ msg = 'X-Frame-Options must be set...
Provide a basic validation that checks that provided value starts with one of the supported options: DENY, SAMEORIGIN, ALLOW-FROM See: https://tools.ietf.org/html/rfc7034#section-2.1
validate_adminrouter_x_frame_options
python
dcos/dcos
gen/calc.py
https://github.com/dcos/dcos/blob/master/gen/calc.py
Apache-2.0
def validate_rsa_pubkey(key_pem): """ Check if `key_pem` is a string containing an RSA public key encoded using the X.509 SubjectPublicKeyInfo/OpenSSL PEM public key format. Refs: - https://tools.ietf.org/html/rfc5280.html - http://stackoverflow.com/a/29707204/145...
Check if `key_pem` is a string containing an RSA public key encoded using the X.509 SubjectPublicKeyInfo/OpenSSL PEM public key format. Refs: - https://tools.ietf.org/html/rfc5280.html - http://stackoverflow.com/a/29707204/145400 Args: key_pem (str):...
validate_rsa_pubkey
python
dcos/dcos
gen/calc.py
https://github.com/dcos/dcos/blob/master/gen/calc.py
Apache-2.0
def _check(config: Dict[str, Any]) -> Tuple[List[str], bool]: """ Current constraints are: config.yaml: - exhibitor_tls_enabled == True, - bootstrap_url must not be a local path This is necessary to prevent this orchestration from running when gen ...
Current constraints are: config.yaml: - exhibitor_tls_enabled == True, - bootstrap_url must not be a local path This is necessary to prevent this orchestration from running when gen is not executed on a proper bootstrap node. This is a...
_check
python
dcos/dcos
gen/exhibitor_tls_bootstrap.py
https://github.com/dcos/dcos/blob/master/gen/exhibitor_tls_bootstrap.py
Apache-2.0
def _extract_package(package_path: str) -> None: """ Extracts the dcos-bootstrap-ca package from the local pkgpanda repository """ Path(BINARY_PATH).mkdir(exist_ok=True) with tempfile.TemporaryDirectory() as td: subprocess.run(['tar', '-xJf', package_path, '-C', td]) shutil.move( ...
Extracts the dcos-bootstrap-ca package from the local pkgpanda repository
_extract_package
python
dcos/dcos
gen/exhibitor_tls_bootstrap.py
https://github.com/dcos/dcos/blob/master/gen/exhibitor_tls_bootstrap.py
Apache-2.0
def _init_ca(alt_names: List[str]) -> None: """ Initializes the CA (generates a private key and self signed certificate CA extensions) if the resulting files do not already exist """ root_ca_paths = [ Path(CA_PATH) / 'root-cert.pem', Path(CA_PATH) / 'root-key.pem'] if not all(map(lambda p: p.exi...
Initializes the CA (generates a private key and self signed certificate CA extensions) if the resulting files do not already exist
_init_ca
python
dcos/dcos
gen/exhibitor_tls_bootstrap.py
https://github.com/dcos/dcos/blob/master/gen/exhibitor_tls_bootstrap.py
Apache-2.0
def _get_ca_alt_name(config: Dict[str, Any]) -> str: """ Gets the bootstrap url hostname. Used to populate the CA SAN extension """ url = config['exhibitor_bootstrap_ca_url'] or config['bootstrap_url'] return urlparse(url).hostname or ""
Gets the bootstrap url hostname. Used to populate the CA SAN extension
_get_ca_alt_name
python
dcos/dcos
gen/exhibitor_tls_bootstrap.py
https://github.com/dcos/dcos/blob/master/gen/exhibitor_tls_bootstrap.py
Apache-2.0
def validate_one_of(val: str, valid_values) -> None: """Test if object `val` is a member of container `valid_values`. Raise a AssertionError if it is not a member. The exception message contains both, the representation (__repr__) of `val` as well as the representation of all items in `valid_values`. ...
Test if object `val` is a member of container `valid_values`. Raise a AssertionError if it is not a member. The exception message contains both, the representation (__repr__) of `val` as well as the representation of all items in `valid_values`.
validate_one_of
python
dcos/dcos
gen/internals.py
https://github.com/dcos/dcos/blob/master/gen/internals.py
Apache-2.0
def __init__(self, variables: Set[str]=None, sub_scopes: Dict[str, Scope]=None): """ variables: set of parameters that must be extracted from Source sub_scopes: mapping of variables to be conditionally added """ self.variables = variables if variables is not None else set() ...
variables: set of parameters that must be extracted from Source sub_scopes: mapping of variables to be conditionally added
__init__
python
dcos/dcos
gen/internals.py
https://github.com/dcos/dcos/blob/master/gen/internals.py
Apache-2.0
def __init__(self, entry=None, is_user=False): """ Entry is a dict of the following form: { 'validate': [validate_my_arg_fn], 'default': {arg: value}, # may be overridden by user args 'must': {arg: value}, # may NOT be overridden by user args 'secret': [arg], ...
Entry is a dict of the following form: { 'validate': [validate_my_arg_fn], 'default': {arg: value}, # may be overridden by user args 'must': {arg: value}, # may NOT be overridden by user args 'secret': [arg], 'conditional': {arg: {val_1: add_entry_1, val_2: a...
__init__
python
dcos/dcos
gen/internals.py
https://github.com/dcos/dcos/blob/master/gen/internals.py
Apache-2.0
def validate_single(self, name: str, value: str): """Calls all validate functions which validate the given parameter name The validate functions will raise an AssertionError which should be caught by the caller when validation fails. """ validate_fns = self._validate_by_arg.get(...
Calls all validate functions which validate the given parameter name The validate functions will raise an AssertionError which should be caught by the caller when validation fails.
validate_single
python
dcos/dcos
gen/internals.py
https://github.com/dcos/dcos/blob/master/gen/internals.py
Apache-2.0
def validate_downstream_entry(entry: dict) -> None: """Raise an exception if entry is an invalid downstream gen.internals.Source entry.""" version_key = 'dcos_version' entry_keys = set(entry.get('must', {}).keys()) | set(entry.get('default', {}).keys()) if version_key in entry_keys: raise Except...
Raise an exception if entry is an invalid downstream gen.internals.Source entry.
validate_downstream_entry
python
dcos/dcos
gen/__init__.py
https://github.com/dcos/dcos/blob/master/gen/__init__.py
Apache-2.0
def stringify_configuration(configuration: dict): """Create a stringified version of the complete installer configuration to send to gen.generate()""" gen_config = {} for key, value in configuration.items(): if isinstance(value, list) or isinstance(value, dict): log.debug("Caught %s ...
Create a stringified version of the complete installer configuration to send to gen.generate()
stringify_configuration
python
dcos/dcos
gen/__init__.py
https://github.com/dcos/dcos/blob/master/gen/__init__.py
Apache-2.0
def add_units(cloudconfig, services, cloud_init_implementation='coreos'): ''' Takes a services dict in the format of CoreOS cloud-init 'units' and injects into cloudconfig a transformed version appropriate for the cloud_init_implementation. See: https://coreos.com/os/docs/latest/cloud-config.html f...
Takes a services dict in the format of CoreOS cloud-init 'units' and injects into cloudconfig a transformed version appropriate for the cloud_init_implementation. See: https://coreos.com/os/docs/latest/cloud-config.html for the CoreOS 'units' specification. See: https://cloudinit.readthedocs.io/en...
add_units
python
dcos/dcos
gen/__init__.py
https://github.com/dcos/dcos/blob/master/gen/__init__.py
Apache-2.0
def user_arguments_to_source(user_arguments) -> gen.internals.Source: """Convert all user arguments to be a gen.internals.Source""" # Make sure all user provided arguments are strings. # TODO(cmaloney): Loosen this restriction / allow arbitrary types as long # as they all have a gen specific string fo...
Convert all user arguments to be a gen.internals.Source
user_arguments_to_source
python
dcos/dcos
gen/__init__.py
https://github.com/dcos/dcos/blob/master/gen/__init__.py
Apache-2.0
def get_config_id(argument_dict: dict): """Return a unique ID for the configuration represented by argument_dict.""" # dcos_image_commit and template_filenames should be included in argument_dict, but we reference them explicitly to # ensure that the config ID reflects the current commit and config template...
Return a unique ID for the configuration represented by argument_dict.
get_config_id
python
dcos/dcos
gen/__init__.py
https://github.com/dcos/dcos/blob/master/gen/__init__.py
Apache-2.0
def validate_cloud_config(cc_string): ''' Validate that there aren't any single quotes present since they break the ARM template system. Exit with an error message if any invalid characters are detected. @param cc_string: str, Cloud Configuration ''' if "'" in cc_string: print("ERRO...
Validate that there aren't any single quotes present since they break the ARM template system. Exit with an error message if any invalid characters are detected. @param cc_string: str, Cloud Configuration
validate_cloud_config
python
dcos/dcos
gen/build_deploy/azure.py
https://github.com/dcos/dcos/blob/master/gen/build_deploy/azure.py
Apache-2.0
def transform(cloud_config_yaml_str): ''' Transforms the given yaml into a list of strings which are concatenated together by the ARM template system. We must make it a list of strings so that ARM template parameters appear at the top level of the template and get substituted. ''' cc_json = ...
Transforms the given yaml into a list of strings which are concatenated together by the ARM template system. We must make it a list of strings so that ARM template parameters appear at the top level of the template and get substituted.
transform
python
dcos/dcos
gen/build_deploy/azure.py
https://github.com/dcos/dcos/blob/master/gen/build_deploy/azure.py
Apache-2.0
def gen_templates(gen_arguments, arm_template, extra_sources): ''' Render the cloud_config template given a particular set of options @param user_args: dict, args to pass to the gen library. These are user input arguments which get filled in/prompted for. @param arm_template: strin...
Render the cloud_config template given a particular set of options @param user_args: dict, args to pass to the gen library. These are user input arguments which get filled in/prompted for. @param arm_template: string, path to the source arm template for rendering ...
gen_templates
python
dcos/dcos
gen/build_deploy/azure.py
https://github.com/dcos/dcos/blob/master/gen/build_deploy/azure.py
Apache-2.0
def master_list_arm_json(num_masters, varietal): ''' Return a JSON string containing a list of ARM expressions for the master IP's of the cluster. @param num_masters: int, number of master nodes in the cluster @param varietal: string, indicate template varietal to build for either 'acs' or 'dcos' '...
Return a JSON string containing a list of ARM expressions for the master IP's of the cluster. @param num_masters: int, number of master nodes in the cluster @param varietal: string, indicate template varietal to build for either 'acs' or 'dcos'
master_list_arm_json
python
dcos/dcos
gen/build_deploy/azure.py
https://github.com/dcos/dcos/blob/master/gen/build_deploy/azure.py
Apache-2.0
def make_template(num_masters, gen_arguments, varietal, bootstrap_variant_prefix): ''' Return a tuple: the generated template for num_masters and the artifact dict. @param num_masters: int, number of master nodes to embed in the generated template @param gen_arguments: dict, args to pass to the gen lib...
Return a tuple: the generated template for num_masters and the artifact dict. @param num_masters: int, number of master nodes to embed in the generated template @param gen_arguments: dict, args to pass to the gen library. These are user input arguments which get filled in/prompte...
make_template
python
dcos/dcos
gen/build_deploy/azure.py
https://github.com/dcos/dcos/blob/master/gen/build_deploy/azure.py
Apache-2.0
def gen_buttons(build_name, reproducible_artifact_path, tag, commit, download_url): ''' Generate the button page, that is, "Deploy a cluster to Azure" page ''' dcos_urls = [ encode_url_as_param(DOWNLOAD_URL_TEMPLATE.format( download_url=download_url, reproducible_artifact...
Generate the button page, that is, "Deploy a cluster to Azure" page
gen_buttons
python
dcos/dcos
gen/build_deploy/azure.py
https://github.com/dcos/dcos/blob/master/gen/build_deploy/azure.py
Apache-2.0
def make_bash(gen_out) -> None: """Build bash deployment artifacts and return a list of their filenames.""" # Build custom check bins package if gen_out.arguments['custom_check_bins_provided'] == 'true': package_filename = 'packages/{}/{}.tar.xz'.format( gen_out.arguments['custom_check_b...
Build bash deployment artifacts and return a list of their filenames.
make_bash
python
dcos/dcos
gen/build_deploy/bash.py
https://github.com/dcos/dcos/blob/master/gen/build_deploy/bash.py
Apache-2.0