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 session(self) -> tf.compat.v1.Session:
"""Returns the TensorFlow session-like object used by this object.
Returns:
The internal TensorFlow session-like object. If it is `None`, it will
return the current TensorFlow session context manager.
Raises:
AttributeError: When no session-like... | Returns the TensorFlow session-like object used by this object.
Returns:
The internal TensorFlow session-like object. If it is `None`, it will
return the current TensorFlow session context manager.
Raises:
AttributeError: When no session-like object has been set, and no
session conte... | session | python | tensorflow/agents | tf_agents/utils/session_utils.py | https://github.com/tensorflow/agents/blob/master/tf_agents/utils/session_utils.py | Apache-2.0 |
def __init__(self, tensor_spec, scope='normalize_tensor'):
"""Initialize TensorNormalizer.
Args:
tensor_spec: The specs of the tensors to normalize.
scope: Scope for the `tf.Module`.
"""
super(TensorNormalizer, self).__init__(name=scope)
self._scope = scope
self._tensor_spec = tens... | Initialize TensorNormalizer.
Args:
tensor_spec: The specs of the tensors to normalize.
scope: Scope for the `tf.Module`.
| __init__ | python | tensorflow/agents | tf_agents/utils/tensor_normalizer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/utils/tensor_normalizer.py | Apache-2.0 |
def _update_ops(self, tensor, outer_dims):
"""Returns a list of ops which update normalizer variables for tensor.
Args:
tensor: The tensor, whose batch statistics to use for updating
normalization variables.
outer_dims: The dimensions to consider batch dimensions, to reduce over.
""" | Returns a list of ops which update normalizer variables for tensor.
Args:
tensor: The tensor, whose batch statistics to use for updating
normalization variables.
outer_dims: The dimensions to consider batch dimensions, to reduce over.
| _update_ops | python | tensorflow/agents | tf_agents/utils/tensor_normalizer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/utils/tensor_normalizer.py | Apache-2.0 |
def normalize(
self, tensor, clip_value=5.0, center_mean=True, variance_epsilon=1e-3
):
"""Applies normalization to tensor.
Args:
tensor: Tensor to normalize.
clip_value: Clips normalized observations between +/- this value if
clip_value > 0, otherwise does not apply clipping.
... | Applies normalization to tensor.
Args:
tensor: Tensor to normalize.
clip_value: Clips normalized observations between +/- this value if
clip_value > 0, otherwise does not apply clipping.
center_mean: If true, subtracts off mean from normalized tensor.
variance_epsilon: Epsilon to av... | normalize | python | tensorflow/agents | tf_agents/utils/tensor_normalizer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/utils/tensor_normalizer.py | Apache-2.0 |
def _create_variables(self):
"""Creates the variables needed for EMATensorNormalizer."""
self._mean_moving_avg = tf.nest.map_structure(
lambda spec: create_variable('mean', 0, spec.shape, spec.dtype),
self._flat_variable_spec,
)
self._var_moving_avg = tf.nest.map_structure(
lambd... | Creates the variables needed for EMATensorNormalizer. | _create_variables | python | tensorflow/agents | tf_agents/utils/tensor_normalizer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/utils/tensor_normalizer.py | Apache-2.0 |
def variables(self):
"""Returns a tuple of tf variables owned by this EMATensorNormalizer."""
return (
tf.nest.pack_sequence_as(self._tensor_spec, self._mean_moving_avg),
tf.nest.pack_sequence_as(self._tensor_spec, self._var_moving_avg),
) | Returns a tuple of tf variables owned by this EMATensorNormalizer. | variables | python | tensorflow/agents | tf_agents/utils/tensor_normalizer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/utils/tensor_normalizer.py | Apache-2.0 |
def _update_ops(self, tensor, outer_dims):
"""Returns a list of update obs for EMATensorNormalizer mean and var.
This normalizer tracks the mean & variance of the dimensions of the input
tensor using an exponential moving average. The batch mean comes from just
the batch statistics, and the batch varia... | Returns a list of update obs for EMATensorNormalizer mean and var.
This normalizer tracks the mean & variance of the dimensions of the input
tensor using an exponential moving average. The batch mean comes from just
the batch statistics, and the batch variance comes from the squared
difference of tenso... | _update_ops | python | tensorflow/agents | tf_agents/utils/tensor_normalizer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/utils/tensor_normalizer.py | Apache-2.0 |
def _tensor_update_ops(single_tensor, mean_var, var_var):
"""Make update ops for a single non-nested tensor."""
# Take the moments across batch dimension. Calculate variance with
# moving avg mean, so that this works even with batch size 1.
mean = tf.reduce_mean(single_tensor, axis=outer_dims)... | Make update ops for a single non-nested tensor. | _tensor_update_ops | python | tensorflow/agents | tf_agents/utils/tensor_normalizer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/utils/tensor_normalizer.py | Apache-2.0 |
def _create_variables(self):
"""Create all variables needed for the normalizer."""
self._count = [
create_variable(
'count_%d' % i, _EPS, spec.shape, spec.dtype, trainable=False
)
for i, spec in enumerate(self._flat_variable_spec)
]
self._avg = [
create_variab... | Create all variables needed for the normalizer. | _create_variables | python | tensorflow/agents | tf_agents/utils/tensor_normalizer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/utils/tensor_normalizer.py | Apache-2.0 |
def variables(self):
"""Returns a tuple of nested TF Variables owned by this normalizer."""
return (
tf.nest.pack_sequence_as(self._tensor_spec, self._count),
tf.nest.pack_sequence_as(self._tensor_spec, self._avg),
tf.nest.pack_sequence_as(self._tensor_spec, self._m2),
tf.nest.pa... | Returns a tuple of nested TF Variables owned by this normalizer. | variables | python | tensorflow/agents | tf_agents/utils/tensor_normalizer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/utils/tensor_normalizer.py | Apache-2.0 |
def _update_ops(self, tensors, outer_dims):
"""Returns a list of ops which update normalizer variables for tensor.
Args:
tensors: The tensors of values to be normalized.
outer_dims: Ignored. The batch dimensions are extracted by comparing the
associated tensor with the specs.
Returns:... | Returns a list of ops which update normalizer variables for tensor.
Args:
tensors: The tensors of values to be normalized.
outer_dims: Ignored. The batch dimensions are extracted by comparing the
associated tensor with the specs.
Returns:
A list of ops, which when run will update al... | _update_ops | python | tensorflow/agents | tf_agents/utils/tensor_normalizer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/utils/tensor_normalizer.py | Apache-2.0 |
def _get_mean_var_estimates(self):
"""Returns this normalizer's current estimates for mean & var (flat)."""
var = [m2_ab / n_ab for (m2_ab, n_ab) in zip(self._m2, self._count)]
return (self._avg, var) | Returns this normalizer's current estimates for mean & var (flat). | _get_mean_var_estimates | python | tensorflow/agents | tf_agents/utils/tensor_normalizer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/utils/tensor_normalizer.py | Apache-2.0 |
def reset(self):
"""Reset the count, mean and variance to its initial state."""
reset_ops = []
for i in range(len(self._count)):
reset_ops.extend([
self._count[i].assign(_EPS * tf.ones_like(self._count[i])),
self._avg[i].assign(tf.zeros_like(self._avg[i])),
self._m2[i].as... | Reset the count, mean and variance to its initial state. | reset | python | tensorflow/agents | tf_agents/utils/tensor_normalizer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/utils/tensor_normalizer.py | Apache-2.0 |
def parallel_variance_calculation(
n_a: types.Int,
avg_a: types.Float,
m2_a: types.Float,
n_b: types.Int,
avg_b: types.Float,
m2_b: types.Float,
m2_b_c: types.Float,
) -> Tuple[types.Int, types.Float, types.Float, types.Float]:
"""Calculate the sufficient statistics (average & second momen... | Calculate the sufficient statistics (average & second moment) of two sets.
For better precision if sets are of different sizes, `a` should be the smaller
and `b` the bigger.
For more details, see the parallel algorithm of Chan et al. at:
https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Parall... | parallel_variance_calculation | python | tensorflow/agents | tf_agents/utils/tensor_normalizer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/utils/tensor_normalizer.py | Apache-2.0 |
def kahan_summation(
accumulator: types.Float, carry: types.Float, value: types.Float
) -> Tuple[types.Float, types.Float]:
"""Calculate stable acculated sum using compensation for low-bits.
For more details:
https://en.wikipedia.org/wiki/Kahan_summation_algorithm
Args:
accumulator: Accumulator.
... | Calculate stable acculated sum using compensation for low-bits.
For more details:
https://en.wikipedia.org/wiki/Kahan_summation_algorithm
Args:
accumulator: Accumulator.
carry: Carry for lost low-order bits.
value: New value to accumlate.
Returns:
A tuple `(accumulator, carry)` such that `ac... | kahan_summation | python | tensorflow/agents | tf_agents/utils/tensor_normalizer.py | https://github.com/tensorflow/agents/blob/master/tf_agents/utils/tensor_normalizer.py | Apache-2.0 |
def contains(list1, list2):
"""Check if all items in list2 are in list1.
This function handles the case when the parameters are lists of np.arrays
(which wouldn't be handled by something like .issubset(...)
Args:
list1: List which may or may not contain list2.
list2: List to check if included in list ... | Check if all items in list2 are in list1.
This function handles the case when the parameters are lists of np.arrays
(which wouldn't be handled by something like .issubset(...)
Args:
list1: List which may or may not contain list2.
list2: List to check if included in list 1.
Returns:
A boolean indi... | contains | python | tensorflow/agents | tf_agents/utils/test_utils.py | https://github.com/tensorflow/agents/blob/master/tf_agents/utils/test_utils.py | Apache-2.0 |
def test_src_dir_path(relative_path):
"""Returns an absolute test srcdir path given a relative path.
Args:
relative_path: a path relative to tf_agents root. e.g.
"environments/config".
Returns:
An absolute path to the linked in runfiles.
"""
return os.path.join(
FLAGS.test_srcdir, 'tf_ag... | Returns an absolute test srcdir path given a relative path.
Args:
relative_path: a path relative to tf_agents root. e.g.
"environments/config".
Returns:
An absolute path to the linked in runfiles.
| test_src_dir_path | python | tensorflow/agents | tf_agents/utils/test_utils.py | https://github.com/tensorflow/agents/blob/master/tf_agents/utils/test_utils.py | Apache-2.0 |
def discounted_return(
rewards,
discounts,
final_value=None,
time_major=True,
provide_all_returns=True,
):
"""Computes discounted return.
```
Q_n = sum_{n'=n}^N gamma^(n'-n) * r_{n'} + gamma^(N-n+1)*final_value.
```
For details, see
"Reinforcement Learning: An Introduction" Second Edit... | Computes discounted return.
```
Q_n = sum_{n'=n}^N gamma^(n'-n) * r_{n'} + gamma^(N-n+1)*final_value.
```
For details, see
"Reinforcement Learning: An Introduction" Second Edition
by Richard S. Sutton and Andrew G. Barto
Define abbreviations:
`B`: batch size representing number of trajectories.
`T`... | discounted_return | python | tensorflow/agents | tf_agents/utils/value_ops.py | https://github.com/tensorflow/agents/blob/master/tf_agents/utils/value_ops.py | Apache-2.0 |
def generalized_advantage_estimation(
values, final_value, discounts, rewards, td_lambda=1.0, time_major=True
):
"""Computes generalized advantage estimation (GAE).
For theory, see
"High-Dimensional Continuous Control Using Generalized Advantage Estimation"
by John Schulman, Philipp Moritz et al.
See htt... | Computes generalized advantage estimation (GAE).
For theory, see
"High-Dimensional Continuous Control Using Generalized Advantage Estimation"
by John Schulman, Philipp Moritz et al.
See https://arxiv.org/abs/1506.02438 for full paper.
Define abbreviations:
(B) batch size representing number of trajector... | generalized_advantage_estimation | python | tensorflow/agents | tf_agents/utils/value_ops.py | https://github.com/tensorflow/agents/blob/master/tf_agents/utils/value_ops.py | Apache-2.0 |
def _naive_gae_as_ground_truth(
discounts, rewards, values, final_value, td_lambda
):
"""A naive GAE closely resembles equation (16) in the paper.
Slow, for testing purpose only.
For full paper see https://arxiv.org/abs/1506.02438.pdf
Args:
discounts: `np.array` with shape [T, B].
rewards: `np.arra... | A naive GAE closely resembles equation (16) in the paper.
Slow, for testing purpose only.
For full paper see https://arxiv.org/abs/1506.02438.pdf
Args:
discounts: `np.array` with shape [T, B].
rewards: `np.array` with shape [T, B].
values: `np.array` with shape [T, B].
final_value: `np.array` wit... | _naive_gae_as_ground_truth | python | tensorflow/agents | tf_agents/utils/value_ops_test.py | https://github.com/tensorflow/agents/blob/master/tf_agents/utils/value_ops_test.py | Apache-2.0 |
def _numpy_discounted_return(rewards, discounts, final_value):
"""A naive reward to do implemented in python.
Slow, for testing purpose only.
Args:
rewards: `np.array` with shape [T, B].
discounts: `np.array` with shape [T, B].
final_value: `np.array` with shape [B].
Returns:
A `np.array` with... | A naive reward to do implemented in python.
Slow, for testing purpose only.
Args:
rewards: `np.array` with shape [T, B].
discounts: `np.array` with shape [T, B].
final_value: `np.array` with shape [B].
Returns:
A `np.array` with shape[T, B] representing the target values.
| _numpy_discounted_return | python | tensorflow/agents | tf_agents/utils/value_ops_test.py | https://github.com/tensorflow/agents/blob/master/tf_agents/utils/value_ops_test.py | Apache-2.0 |
def is_xla_available():
"""Is XLA compilation available for the current device context?"""
global _IS_XLA_AVAILABLE
# There's unfortunately no cleaner way to get the device other than creating a
# new op and querying it.
with tf.name_scope("is_xla_available"):
device = tf.constant(0.0).device
if device... | Is XLA compilation available for the current device context? | is_xla_available | python | tensorflow/agents | tf_agents/utils/xla.py | https://github.com/tensorflow/agents/blob/master/tf_agents/utils/xla.py | Apache-2.0 |
def compile_method_in_graph_mode(method):
"""Decorator for XLA compilation iff in graph mode and XLA is available.
Example:
```python
class MyClass(object):
@compile_in_graph_mode
def method(self, x, y, z):
return {'a': x + y, 'b': y * z}
@common.function
def calls_fn(inputs):
MyClass a... | Decorator for XLA compilation iff in graph mode and XLA is available.
Example:
```python
class MyClass(object):
@compile_in_graph_mode
def method(self, x, y, z):
return {'a': x + y, 'b': y * z}
@common.function
def calls_fn(inputs):
MyClass a;
return a.method(inputs.x, inputs.y, input... | compile_method_in_graph_mode | python | tensorflow/agents | tf_agents/utils/xla.py | https://github.com/tensorflow/agents/blob/master/tf_agents/utils/xla.py | Apache-2.0 |
def compile_in_graph_mode(fn):
"""Decorator for XLA compilation iff in graph mode and XLA is available.
Example:
```python
@compile_in_graph_mode
def fn(x, y, z):
return {'a': x + y, 'b': y * z}
@common.function
def calls_fn(inputs):
return fn(inputs.x, inputs.y, inputs.z)
# Call calls_fn().... | Decorator for XLA compilation iff in graph mode and XLA is available.
Example:
```python
@compile_in_graph_mode
def fn(x, y, z):
return {'a': x + y, 'b': y * z}
@common.function
def calls_fn(inputs):
return fn(inputs.x, inputs.y, inputs.z)
# Call calls_fn().
Args:
fn: A callable that ac... | compile_in_graph_mode | python | tensorflow/agents | tf_agents/utils/xla.py | https://github.com/tensorflow/agents/blob/master/tf_agents/utils/xla.py | Apache-2.0 |
def _compiled(*args, _fn=None, _self=None, **kwargs):
"""Helper function for optionally XLA compiling `fn`."""
args = tf.nest.map_structure(tf.convert_to_tensor, args)
kwargs = tf.nest.map_structure(tf.convert_to_tensor, kwargs)
if tf.compat.v1.executing_eagerly() or not is_xla_available():
if _self is not ... | Helper function for optionally XLA compiling `fn`. | _compiled | python | tensorflow/agents | tf_agents/utils/xla.py | https://github.com/tensorflow/agents/blob/master/tf_agents/utils/xla.py | Apache-2.0 |
def __init__(
self,
eventlog_dirs: List[str],
event_tag: str,
output_path: str = '.',
title: str = '',
xaxis_title: str = 'steps',
yaxis_title: Optional[str] = None,
graph_agg: GraphAggTypes = GraphAggTypes.MEAN,
output_prefix: str = 'results',
end_step: Optio... | Initializes StatsBuilder class.
Args:
eventlog_dirs: List of paths to event log directories to process.
event_tag: Event to extract from the logs.
output_path: Output path for artifacts, e.g. graphs and cvs files.
title: Title of the graph.
xaxis_title: Title for x-axis of the graph. ... | __init__ | python | tensorflow/agents | tools/graph_builder.py | https://github.com/tensorflow/agents/blob/master/tools/graph_builder.py | Apache-2.0 |
def _gather_data(self) -> Tuple[List[Dict[int, np.generic]], List[float]]:
"""Gather data from all of the logs and add to the data_collector list.
Returns:
Tuple of arrays indexed by log file, e.g. data_collector[0] is all of the
values found in the event log for the given event and walltimes[0] is... | Gather data from all of the logs and add to the data_collector list.
Returns:
Tuple of arrays indexed by log file, e.g. data_collector[0] is all of the
values found in the event log for the given event and walltimes[0] is the
total time in minutes it took to get to the end_step in that event log.... | _gather_data | python | tensorflow/agents | tools/graph_builder.py | https://github.com/tensorflow/agents/blob/master/tools/graph_builder.py | Apache-2.0 |
def _align_and_aggregate(
self, data_collector: List[Dict[int, np.generic]]
) -> List[Sequence[Number]]:
"""Combines data from multipole runs into a pivot table like structure.
Uses the first run as the base and aligns the data for each run by rows
with each row representing a step. If a step is no... | Combines data from multipole runs into a pivot table like structure.
Uses the first run as the base and aligns the data for each run by rows
with each row representing a step. If a step is not found in a run,
the value -1 is used. No error or warning is thrown or logged.
Args:
data_collector: li... | _align_and_aggregate | python | tensorflow/agents | tools/graph_builder.py | https://github.com/tensorflow/agents/blob/master/tools/graph_builder.py | Apache-2.0 |
def _output_csv(self, agg_data: List[Sequence[Number]]):
"""Exports the `agg_data` as a csv.
Args:
agg_data: 2d array of data to export to csv.
"""
# Outputs csv with aggregated data for each step.
csv_path = os.path.join(
self.output_path, self.output_prefix + '_summary.csv'
)
... | Exports the `agg_data` as a csv.
Args:
agg_data: 2d array of data to export to csv.
| _output_csv | python | tensorflow/agents | tools/graph_builder.py | https://github.com/tensorflow/agents/blob/master/tools/graph_builder.py | Apache-2.0 |
def _output_graph(self, agg_data: List[Sequence[Number]], num_runs: int):
"""Builds a graph of the results and outputs to a .png.
Args:
agg_data: 2d array of data to be graphed.
num_runs: Number of columns of runs in the data.
"""
# Build data frames
columns = ['step']
columns.exten... | Builds a graph of the results and outputs to a .png.
Args:
agg_data: 2d array of data to be graphed.
num_runs: Number of columns of runs in the data.
| _output_graph | python | tensorflow/agents | tools/graph_builder.py | https://github.com/tensorflow/agents/blob/master/tools/graph_builder.py | Apache-2.0 |
def build_artifacts(self):
"""Processes the event logs and coordinates creating the artifacts."""
data_collector, _ = self._gather_data()
agg_data = self._align_and_aggregate(data_collector)
self._output_csv(agg_data)
self._output_graph(agg_data, len(data_collector))
if self.show_graph:
p... | Processes the event logs and coordinates creating the artifacts. | build_artifacts | python | tensorflow/agents | tools/graph_builder.py | https://github.com/tensorflow/agents/blob/master/tools/graph_builder.py | Apache-2.0 |
def test_align_and_aggregate(self):
"""Tests combining data from 3 differnet logs into a single result."""
event_log_dirs = [
'event_log_ant_eval00',
'event_log_ant_eval01',
'event_log_ant_eval02',
]
event_log_paths = [
os.path.join(TEST_DATA, log_dir) for log_dir in even... | Tests combining data from 3 differnet logs into a single result. | test_align_and_aggregate | python | tensorflow/agents | tools/graph_builder_test.py | https://github.com/tensorflow/agents/blob/master/tools/graph_builder_test.py | Apache-2.0 |
def test_output_graph(self):
"""Tests outputing a graph to a file does not error out.
There is no validation that the output graph is correct.
"""
output_path = self.create_tempdir()
event_log_dirs = [
'event_log_ant_eval00',
'event_log_ant_eval01',
'event_log_ant_eval02',
... | Tests outputing a graph to a file does not error out.
There is no validation that the output graph is correct.
| test_output_graph | python | tensorflow/agents | tools/graph_builder_test.py | https://github.com/tensorflow/agents/blob/master/tools/graph_builder_test.py | Apache-2.0 |
def __init__(
self, git_repo, version_file, release_number, working_dir, branch_hash
):
"""Initialize ReleaseBuilder class.
Args:
git_repo: Full path to github repo.
version_file: relative path to version file in repo.
release_number: String representing the release number, e.g. 0.1.2... | Initialize ReleaseBuilder class.
Args:
git_repo: Full path to github repo.
version_file: relative path to version file in repo.
release_number: String representing the release number, e.g. 0.1.2 or
0.2.3.rc1.
working_dir: Full path to the directory to check the code out into.
... | __init__ | python | tensorflow/agents | tools/release_builder.py | https://github.com/tensorflow/agents/blob/master/tools/release_builder.py | Apache-2.0 |
def create_release_branch(self):
"""Creates a release branch and optionally an updated version file."""
logging.info('Create release branch %s.', self.branch_name)
logging.info('Starting active branch:%s.', self.repo.active_branch)
self._checkout_or_create_branch()
if self.version_file:
updat... | Creates a release branch and optionally an updated version file. | create_release_branch | python | tensorflow/agents | tools/release_builder.py | https://github.com/tensorflow/agents/blob/master/tools/release_builder.py | Apache-2.0 |
def _parse_version_input(self, release_number):
"""Breaks release_number into major, minor, patch, and release.
Args:
release_number: String representing the release number, e.g. 0.1.2 or
0.2.3.rc1.
Returns:
tuple:
major: Major version number.
minor: Minor version numbe... | Breaks release_number into major, minor, patch, and release.
Args:
release_number: String representing the release number, e.g. 0.1.2 or
0.2.3.rc1.
Returns:
tuple:
major: Major version number.
minor: Minor version number.
patch: Patch version number.
release... | _parse_version_input | python | tensorflow/agents | tools/release_builder.py | https://github.com/tensorflow/agents/blob/master/tools/release_builder.py | Apache-2.0 |
def _update_version_numbers(self, file_path):
"""Updates the version variables in the project's version file.
This assumes that the version file using the following attributes:
_MAJOR_VERSION, _MINOR_VERSION, _PATCH_VERSION, and _REL_SUFFIX.
Args:
file_path: path to the version file.
"""
... | Updates the version variables in the project's version file.
This assumes that the version file using the following attributes:
_MAJOR_VERSION, _MINOR_VERSION, _PATCH_VERSION, and _REL_SUFFIX.
Args:
file_path: path to the version file.
| _update_version_numbers | python | tensorflow/agents | tools/release_builder.py | https://github.com/tensorflow/agents/blob/master/tools/release_builder.py | Apache-2.0 |
def _checkout_or_create_branch(self):
"""Checkout or create branch from branch_hash provided.
If the branch does not exist in the remote (origin) or locally then it is
created at the provided hash point. In all cases the branch is setup with
the upstream set to the origin.
"""
# Checks if alrea... | Checkout or create branch from branch_hash provided.
If the branch does not exist in the remote (origin) or locally then it is
created at the provided hash point. In all cases the branch is setup with
the upstream set to the origin.
| _checkout_or_create_branch | python | tensorflow/agents | tools/release_builder.py | https://github.com/tensorflow/agents/blob/master/tools/release_builder.py | Apache-2.0 |
def _get_repo(self, git_repo, working_dir):
"""Clones repo of points to existing repo.
Args:
git_repo: Full url to git repository.
working_dir: Full path to the directory to check the code out into.
Returns:
Repo object representing the git repository.
"""
os.makedirs(working_dir... | Clones repo of points to existing repo.
Args:
git_repo: Full url to git repository.
working_dir: Full path to the directory to check the code out into.
Returns:
Repo object representing the git repository.
| _get_repo | python | tensorflow/agents | tools/release_builder.py | https://github.com/tensorflow/agents/blob/master/tools/release_builder.py | Apache-2.0 |
def execute_test(file_path, result_path):
"""Executes a single notebook.
Args:
file_path: Path to the notebook to execute.
result_path: Path to store the resulting notebook.
Returns:
bool: True if the notebook does not have any errors, False otherwise.
Raises:
Exception if an unexpected error... | Executes a single notebook.
Args:
file_path: Path to the notebook to execute.
result_path: Path to store the resulting notebook.
Returns:
bool: True if the notebook does not have any errors, False otherwise.
Raises:
Exception if an unexpected error occurs executing the notebook.
| execute_test | python | tensorflow/agents | tools/test_colabs.py | https://github.com/tensorflow/agents/blob/master/tools/test_colabs.py | Apache-2.0 |
def get_test_suite():
"""Returns list of all notebooks to run."""
colab_path = './'
test_notebooks = []
for dirpath, _, filenames in os.walk(colab_path):
for filename in filenames:
if filename.endswith('ipynb'):
if '7_SAC_minitaur_tutorial.ipynb' in filename:
logging.info(
... | Returns list of all notebooks to run. | get_test_suite | python | tensorflow/agents | tools/test_colabs.py | https://github.com/tensorflow/agents/blob/master/tools/test_colabs.py | Apache-2.0 |
def run():
"""Runs all notebooks and reports results."""
os.makedirs(FLAGS.output_dir, exist_ok=True)
if FLAGS.single_colab:
filenames = [FLAGS.single_colab]
else:
filenames = get_test_suite()
passed = []
failed = []
filenames.sort()
for filename in filenames:
logging.info('Testing %s ...',... | Runs all notebooks and reports results. | run | python | tensorflow/agents | tools/test_colabs.py | https://github.com/tensorflow/agents/blob/master/tools/test_colabs.py | Apache-2.0 |
def _find_packages(where='.', exclude=()):
"""Return a list all Python packages found within directory 'where'
'where' should be supplied as a "cross-platform" (i.e. URL-style)
path; it will be converted to the appropriate local path syntax.
'exclude' is a sequence of package names to e... | Return a list all Python packages found within directory 'where'
'where' should be supplied as a "cross-platform" (i.e. URL-style)
path; it will be converted to the appropriate local path syntax.
'exclude' is a sequence of package names to exclude; '*' can be used
as a wildcard in the n... | _find_packages | python | isnowfy/snownlp | setup.py | https://github.com/isnowfy/snownlp/blob/master/setup.py | MIT |
def string_representer(dumper, value):
"""
Customer Yaml representer that will force the scalar to be quoted in a yaml.dump
if it scalar starts with a 0. This is needed to keep account ids a string instead
of turning into on int because yaml thinks it an octal.
Parameters
----------
dumper ... |
Customer Yaml representer that will force the scalar to be quoted in a yaml.dump
if it scalar starts with a 0. This is needed to keep account ids a string instead
of turning into on int because yaml thinks it an octal.
Parameters
----------
dumper yaml.dumper
value str
Value in tem... | string_representer | python | aws/aws-sam-cli | samcli/yamlhelper.py | https://github.com/aws/aws-sam-cli/blob/master/samcli/yamlhelper.py | Apache-2.0 |
def intrinsics_multi_constructor(loader, tag_prefix, node):
"""
YAML constructor to parse CloudFormation intrinsics.
This will return a dictionary with key being the instrinsic name
"""
# Get the actual tag name excluding the first exclamation
tag = node.tag[1:]
# Some intrinsic functions ... |
YAML constructor to parse CloudFormation intrinsics.
This will return a dictionary with key being the instrinsic name
| intrinsics_multi_constructor | python | aws/aws-sam-cli | samcli/yamlhelper.py | https://github.com/aws/aws-sam-cli/blob/master/samcli/yamlhelper.py | Apache-2.0 |
def yaml_dump(dict_to_dump):
"""
Dumps the dictionary as a YAML document
:param dict_to_dump:
:return:
"""
CfnDumper.add_representer(OrderedDict, _dict_representer)
CfnDumper.add_representer(str, string_representer)
CfnDumper.add_representer(Py27Dict, _dict_representer)
CfnDumper.add... |
Dumps the dictionary as a YAML document
:param dict_to_dump:
:return:
| yaml_dump | python | aws/aws-sam-cli | samcli/yamlhelper.py | https://github.com/aws/aws-sam-cli/blob/master/samcli/yamlhelper.py | Apache-2.0 |
def parse_yaml_file(file_path, extra_context: Optional[Dict] = None) -> Dict:
"""
Read the file, do variable substitution, parse it as JSON/YAML
Parameters
----------
file_path : string
Path to the file to read
extra_context : Dict
if the file contains variable in the format of ... |
Read the file, do variable substitution, parse it as JSON/YAML
Parameters
----------
file_path : string
Path to the file to read
extra_context : Dict
if the file contains variable in the format of %(variableName)s i.e. the same format of the string % operator,
this paramete... | parse_yaml_file | python | aws/aws-sam-cli | samcli/yamlhelper.py | https://github.com/aws/aws-sam-cli/blob/master/samcli/yamlhelper.py | Apache-2.0 |
def __init__(self, section=None, cmd_names=None):
"""
The constructor for ConfigProvider class
Parameters
----------
section
The section defined in the configuration file nested within `cmd`
cmd_names
The cmd_name defined in the configuration file... |
The constructor for ConfigProvider class
Parameters
----------
section
The section defined in the configuration file nested within `cmd`
cmd_names
The cmd_name defined in the configuration file
| __init__ | python | aws/aws-sam-cli | samcli/cli/cli_config_file.py | https://github.com/aws/aws-sam-cli/blob/master/samcli/cli/cli_config_file.py | Apache-2.0 |
def __call__(self, config_path: Path, config_env: str, cmd_names: List[str]) -> dict:
"""
Get resolved config based on the `file_path` for the configuration file,
`config_env` targeted inside the config file and corresponding `cmd_name`
as denoted by `click`.
Parameters
... |
Get resolved config based on the `file_path` for the configuration file,
`config_env` targeted inside the config file and corresponding `cmd_name`
as denoted by `click`.
Parameters
----------
config_path: Path
The path of configuration file.
config_e... | __call__ | python | aws/aws-sam-cli | samcli/cli/cli_config_file.py | https://github.com/aws/aws-sam-cli/blob/master/samcli/cli/cli_config_file.py | Apache-2.0 |
def handle_parse_options(resolved_config: dict) -> None:
"""
Click does some handling of options to convert them to the intended types.
When injecting the options to click through a samconfig, we should do a similar
parsing of the options to ensure we pass the intended type.
E.g. if multiple is def... |
Click does some handling of options to convert them to the intended types.
When injecting the options to click through a samconfig, we should do a similar
parsing of the options to ensure we pass the intended type.
E.g. if multiple is defined in the click option but only a single value is passed,
... | handle_parse_options | python | aws/aws-sam-cli | samcli/cli/cli_config_file.py | https://github.com/aws/aws-sam-cli/blob/master/samcli/cli/cli_config_file.py | Apache-2.0 |
def get_options_map() -> dict:
"""
Attempt to get all of the options that exist for a command.
Return a mapping from each option name to that options' properties.
Returns
-------
dict
Dict of command options if successful, None otherwise
"""
try:
command_options = click.... |
Attempt to get all of the options that exist for a command.
Return a mapping from each option name to that options' properties.
Returns
-------
dict
Dict of command options if successful, None otherwise
| get_options_map | python | aws/aws-sam-cli | samcli/cli/cli_config_file.py | https://github.com/aws/aws-sam-cli/blob/master/samcli/cli/cli_config_file.py | Apache-2.0 |
def configuration_callback(
cmd_name: str,
option_name: str,
saved_callback: Optional[Callable],
provider: Callable,
ctx: click.Context,
param: click.Parameter,
value,
):
"""
Callback for reading the config file.
Also takes care of calling user specified custom callback afterwar... |
Callback for reading the config file.
Also takes care of calling user specified custom callback afterwards.
Parameters
----------
cmd_name: str
The `sam` command name derived from click.
option_name: str
The name of the option. This is used for error messages.
saved_callba... | configuration_callback | python | aws/aws-sam-cli | samcli/cli/cli_config_file.py | https://github.com/aws/aws-sam-cli/blob/master/samcli/cli/cli_config_file.py | Apache-2.0 |
def get_ctx_defaults(
cmd_name: str, provider: Callable, ctx: click.Context, config_env_name: str, config_file: Optional[str] = None
) -> Any:
"""
Get the set of the parameters that are needed to be set into the click command.
This function also figures out the command name by looking up current click ... |
Get the set of the parameters that are needed to be set into the click command.
This function also figures out the command name by looking up current click context's parent
and constructing the parsed command name that is used in default configuration file.
If a given cmd_name is start-api, the parsed... | get_ctx_defaults | python | aws/aws-sam-cli | samcli/cli/cli_config_file.py | https://github.com/aws/aws-sam-cli/blob/master/samcli/cli/cli_config_file.py | Apache-2.0 |
def save_command_line_args_to_config(
ctx: click.Context, cmd_names: List[str], config_env_name: str, config_file: SamConfig
):
"""Save the provided command line arguments to the provided config file.
Parameters
----------
ctx: click.Context
Click context of the current session.
cmd_nam... | Save the provided command line arguments to the provided config file.
Parameters
----------
ctx: click.Context
Click context of the current session.
cmd_names: List[str]
List of representing the entire command. Ex: ["local", "generate-event", "s3", "put"]
config_env_name: str
... | save_command_line_args_to_config | python | aws/aws-sam-cli | samcli/cli/cli_config_file.py | https://github.com/aws/aws-sam-cli/blob/master/samcli/cli/cli_config_file.py | Apache-2.0 |
def save_params(func):
"""Decorator for saving provided parameters to a config file, if the flag is set."""
def wrapper(*args, **kwargs):
ctx = click.get_current_context()
cmd_names = get_cmd_names(ctx.info_name, ctx)
save_command_line_args_to_config(
ctx=ctx,
c... | Decorator for saving provided parameters to a config file, if the flag is set. | save_params | python | aws/aws-sam-cli | samcli/cli/cli_config_file.py | https://github.com/aws/aws-sam-cli/blob/master/samcli/cli/cli_config_file.py | Apache-2.0 |
def save_params_option(func):
"""Composite decorator to add --save-params flag to a command.
When used, this command should be placed as the LAST of the click option/argument decorators to preserve the flow
of execution. The decorator itself will add the --save-params option, and, if provided, save the pro... | Composite decorator to add --save-params flag to a command.
When used, this command should be placed as the LAST of the click option/argument decorators to preserve the flow
of execution. The decorator itself will add the --save-params option, and, if provided, save the provided commands
from the terminal ... | save_params_option | python | aws/aws-sam-cli | samcli/cli/cli_config_file.py | https://github.com/aws/aws-sam-cli/blob/master/samcli/cli/cli_config_file.py | Apache-2.0 |
def configuration_option(*param_decls, **attrs):
# pylint does not understand the docstring with the presence of **attrs
# pylint: disable=missing-param-doc,differing-param-doc
"""
Adds configuration file support to a click application.
This will create a hidden click option whose callback function... |
Adds configuration file support to a click application.
This will create a hidden click option whose callback function loads configuration parameters from default
configuration environment [default] in default configuration file [samconfig.toml] in the template file
directory.
Note
----
T... | configuration_option | python | aws/aws-sam-cli | samcli/cli/cli_config_file.py | https://github.com/aws/aws-sam-cli/blob/master/samcli/cli/cli_config_file.py | Apache-2.0 |
def decorator_customize_config_file(f: Callable) -> Callable:
"""
CLI option to customize configuration file name. By default it is 'samconfig.toml' in project directory.
Ex: --config-file samconfig.toml
Parameters
----------
f: Callable
Callback function passed by Click
Returns
... |
CLI option to customize configuration file name. By default it is 'samconfig.toml' in project directory.
Ex: --config-file samconfig.toml
Parameters
----------
f: Callable
Callback function passed by Click
Returns
-------
Callable
A Callback function
| decorator_customize_config_file | python | aws/aws-sam-cli | samcli/cli/cli_config_file.py | https://github.com/aws/aws-sam-cli/blob/master/samcli/cli/cli_config_file.py | Apache-2.0 |
def decorator_customize_config_env(f: Callable) -> Callable:
"""
CLI option to customize configuration environment name. By default it is 'default'.
Ex: --config-env default
Parameters
----------
f: Callable
Callback function passed by Click
Returns
-------
Callable
... |
CLI option to customize configuration environment name. By default it is 'default'.
Ex: --config-env default
Parameters
----------
f: Callable
Callback function passed by Click
Returns
-------
Callable
A Callback function
| decorator_customize_config_env | python | aws/aws-sam-cli | samcli/cli/cli_config_file.py | https://github.com/aws/aws-sam-cli/blob/master/samcli/cli/cli_config_file.py | Apache-2.0 |
def __init__(self, *args, cmd_packages=None, **kwargs):
"""
Initializes the class, optionally with a list of available commands
:param cmd_packages: List of Python packages names of CLI commands
:param args: Other Arguments passed to super class
:param kwargs: Other Arguments pa... |
Initializes the class, optionally with a list of available commands
:param cmd_packages: List of Python packages names of CLI commands
:param args: Other Arguments passed to super class
:param kwargs: Other Arguments passed to super class
| __init__ | python | aws/aws-sam-cli | samcli/cli/command.py | https://github.com/aws/aws-sam-cli/blob/master/samcli/cli/command.py | Apache-2.0 |
def _set_commands(package_names):
"""
Extract the command name from package name. Last part of the module path is the command
ie. if path is foo.bar.baz, then "baz" is the command name.
:param package_names: List of package names
:return: Dictionary with command name as key and ... |
Extract the command name from package name. Last part of the module path is the command
ie. if path is foo.bar.baz, then "baz" is the command name.
:param package_names: List of package names
:return: Dictionary with command name as key and the package name as value.
| _set_commands | python | aws/aws-sam-cli | samcli/cli/command.py | https://github.com/aws/aws-sam-cli/blob/master/samcli/cli/command.py | Apache-2.0 |
def get_command(self, ctx, cmd_name):
"""
Overrides method from ``Group`` that returns Click CLI object for given command name, if found.
:param ctx: Click context
:param cmd_name: Top-level command name
:return: Click object representing the command
"""
if cmd_n... |
Overrides method from ``Group`` that returns Click CLI object for given command name, if found.
:param ctx: Click context
:param cmd_name: Top-level command name
:return: Click object representing the command
| get_command | python | aws/aws-sam-cli | samcli/cli/command.py | https://github.com/aws/aws-sam-cli/blob/master/samcli/cli/command.py | Apache-2.0 |
def __init__(self):
"""
Initialize the context with default values
"""
self._debug = False
self._aws_region = None
self._aws_profile = None
self._session_id = str(uuid.uuid4())
self._experimental = False
self._exception = None
self._console... |
Initialize the context with default values
| __init__ | python | aws/aws-sam-cli | samcli/cli/context.py | https://github.com/aws/aws-sam-cli/blob/master/samcli/cli/context.py | Apache-2.0 |
def debug(self, value):
"""
Turn on debug logging if necessary.
:param value: Value of debug flag
"""
self._debug = value
if self._debug:
# Turn on debug logging and display timestamps
sam_cli_logger = logging.getLogger(SAM_CLI_LOGGER_NAME)
... |
Turn on debug logging if necessary.
:param value: Value of debug flag
| debug | python | aws/aws-sam-cli | samcli/cli/context.py | https://github.com/aws/aws-sam-cli/blob/master/samcli/cli/context.py | Apache-2.0 |
def command_path(self):
"""
Returns the full path of the command as invoked ex: "sam local generate-event s3 put". Wrapper to
https://click.palletsprojects.com/en/7.x/api/#click.Context.command_path
Returns
-------
str
Full path of the command invoked
... |
Returns the full path of the command as invoked ex: "sam local generate-event s3 put". Wrapper to
https://click.palletsprojects.com/en/7.x/api/#click.Context.command_path
Returns
-------
str
Full path of the command invoked
| command_path | python | aws/aws-sam-cli | samcli/cli/context.py | https://github.com/aws/aws-sam-cli/blob/master/samcli/cli/context.py | Apache-2.0 |
def template_dict(self):
"""
Returns the template_dictionary from click context.
Returns
-------
dict
Template as dictionary
"""
click_core_ctx = click.get_current_context()
try:
if click_core_ctx:
return click_core... |
Returns the template_dictionary from click context.
Returns
-------
dict
Template as dictionary
| template_dict | python | aws/aws-sam-cli | samcli/cli/context.py | https://github.com/aws/aws-sam-cli/blob/master/samcli/cli/context.py | Apache-2.0 |
def get_current_context() -> Optional["Context"]:
"""
Get the current Context object from Click's context stacks. This method is safe to run within the
actual command's handler that has a ``@pass_context`` annotation. Outside of the handler, you run
the risk of creating a new Context obj... |
Get the current Context object from Click's context stacks. This method is safe to run within the
actual command's handler that has a ``@pass_context`` annotation. Outside of the handler, you run
the risk of creating a new Context object which is entirely different from the Context object used ... | get_current_context | python | aws/aws-sam-cli | samcli/cli/context.py | https://github.com/aws/aws-sam-cli/blob/master/samcli/cli/context.py | Apache-2.0 |
def _refresh_session(self):
"""
Update boto3's default session by creating a new session based on values set in the context. Some properties of
the Boto3's session object are read-only. Therefore when Click parses new AWS session related properties (like
region & profile), it will call t... |
Update boto3's default session by creating a new session based on values set in the context. Some properties of
the Boto3's session object are read-only. Therefore when Click parses new AWS session related properties (like
region & profile), it will call this method to create a new session with... | _refresh_session | python | aws/aws-sam-cli | samcli/cli/context.py | https://github.com/aws/aws-sam-cli/blob/master/samcli/cli/context.py | Apache-2.0 |
def get_cmd_names(cmd_name, ctx) -> List[str]:
"""
Given the click core context, return a list representing all the subcommands passed to the CLI
Parameters
----------
cmd_name : str
name of current command
ctx : click.Context
click context
Returns
-------
list(str)... |
Given the click core context, return a list representing all the subcommands passed to the CLI
Parameters
----------
cmd_name : str
name of current command
ctx : click.Context
click context
Returns
-------
list(str)
List containing subcommand names. Ex: ["local... | get_cmd_names | python | aws/aws-sam-cli | samcli/cli/context.py | https://github.com/aws/aws-sam-cli/blob/master/samcli/cli/context.py | Apache-2.0 |
def __init__(self):
"""__init__ should only be called once due to Singleton metaclass"""
self._access_lock = threading.RLock()
self._config_dir = None
self._config_filename = None
self._config_data = None
self._persistent_fields = list() | __init__ should only be called once due to Singleton metaclass | __init__ | python | aws/aws-sam-cli | samcli/cli/global_config.py | https://github.com/aws/aws-sam-cli/blob/master/samcli/cli/global_config.py | Apache-2.0 |
def config_dir(self) -> Path:
"""
Returns
-------
Path
Path object for the configuration directory.
"""
if not self._config_dir:
if GlobalConfig._DIR_INJECTION_ENV_VAR in os.environ:
# Set dir to the one specified in _DIR_INJECTION_... |
Returns
-------
Path
Path object for the configuration directory.
| config_dir | python | aws/aws-sam-cli | samcli/cli/global_config.py | https://github.com/aws/aws-sam-cli/blob/master/samcli/cli/global_config.py | Apache-2.0 |
def config_dir(self, dir_path: Path) -> None:
"""
Parameters
----------
dir_path : Path
Directory path object for the configuration.
Raises
------
ValueError
ValueError will be raised if the path is not a directory.
"""
if ... |
Parameters
----------
dir_path : Path
Directory path object for the configuration.
Raises
------
ValueError
ValueError will be raised if the path is not a directory.
| config_dir | python | aws/aws-sam-cli | samcli/cli/global_config.py | https://github.com/aws/aws-sam-cli/blob/master/samcli/cli/global_config.py | Apache-2.0 |
def config_filename(self) -> str:
"""
Returns
-------
str
Filename for the configuration.
"""
if not self._config_filename:
self._config_filename = GlobalConfig.DEFAULT_CONFIG_FILENAME
return self._config_filename |
Returns
-------
str
Filename for the configuration.
| config_filename | python | aws/aws-sam-cli | samcli/cli/global_config.py | https://github.com/aws/aws-sam-cli/blob/master/samcli/cli/global_config.py | Apache-2.0 |
def get_value(
self,
config_entry,
default=None,
value_type=object,
is_flag=False,
reload_config=False,
) -> Any:
"""Get the corresponding value of a configuration entry.
Parameters
----------
config_entry : ConfigEntry
Con... | Get the corresponding value of a configuration entry.
Parameters
----------
config_entry : ConfigEntry
Configuration entry for which the value will be loaded.
default : value_type, optional
The default value to be returned if the configuration does not exist,
... | get_value | python | aws/aws-sam-cli | samcli/cli/global_config.py | https://github.com/aws/aws-sam-cli/blob/master/samcli/cli/global_config.py | Apache-2.0 |
def set_value(self, config_entry: ConfigEntry, value: Any, is_flag: bool = False, flush: bool = True) -> None:
"""Set the value of a configuration. The associated env var will be updated as well.
Parameters
----------
config_entry : ConfigEntry
Configuration entry to be set
... | Set the value of a configuration. The associated env var will be updated as well.
Parameters
----------
config_entry : ConfigEntry
Configuration entry to be set
value : Any
Value of the configuration
is_flag : bool, optional
If is_flag is True... | set_value | python | aws/aws-sam-cli | samcli/cli/global_config.py | https://github.com/aws/aws-sam-cli/blob/master/samcli/cli/global_config.py | Apache-2.0 |
def _load_config(self) -> None:
"""Reload configurations from file and populate self._config_data"""
if not self.config_path.exists():
self._config_data = {}
return
try:
body = self.config_path.read_text()
json_body = json.loads(body)
s... | Reload configurations from file and populate self._config_data | _load_config | python | aws/aws-sam-cli | samcli/cli/global_config.py | https://github.com/aws/aws-sam-cli/blob/master/samcli/cli/global_config.py | Apache-2.0 |
def _write_config(self) -> None:
"""Write configurations in self._config_data to file"""
if not self._config_data:
return
config_data = {key: value for (key, value) in self._config_data.items() if key in self._persistent_fields}
try:
json_str = json.dumps(config_d... | Write configurations in self._config_data to file | _write_config | python | aws/aws-sam-cli | samcli/cli/global_config.py | https://github.com/aws/aws-sam-cli/blob/master/samcli/cli/global_config.py | Apache-2.0 |
def installation_id(self):
"""
Returns the installation UUID for this AWS SAM CLI installation. If the
installation id has not yet been set, it will be set before returning.
Examples
--------
>>> gc = GlobalConfig()
>>> gc.installation_id
"7b7d4db7-2f54-... |
Returns the installation UUID for this AWS SAM CLI installation. If the
installation id has not yet been set, it will be set before returning.
Examples
--------
>>> gc = GlobalConfig()
>>> gc.installation_id
"7b7d4db7-2f54-45ba-bf2f-a2cbc9e74a34"
>>> g... | installation_id | python | aws/aws-sam-cli | samcli/cli/global_config.py | https://github.com/aws/aws-sam-cli/blob/master/samcli/cli/global_config.py | Apache-2.0 |
def is_accelerate_opt_in_stack(self, template_file: str, stack_name: str) -> bool:
"""
Returns True, if current folder with stack name is been accepted to use sam sync before.
Returns False, if this is first time that user runs sam sync with current folder and given stack name.
"""
... |
Returns True, if current folder with stack name is been accepted to use sam sync before.
Returns False, if this is first time that user runs sam sync with current folder and given stack name.
| is_accelerate_opt_in_stack | python | aws/aws-sam-cli | samcli/cli/global_config.py | https://github.com/aws/aws-sam-cli/blob/master/samcli/cli/global_config.py | Apache-2.0 |
def set_accelerate_opt_in_stack(self, template_file: str, stack_name: str) -> None:
"""
Stores current folder and stack name into config, so that next time that user runs sam sync, they don't need
to accept warning message again.
"""
accelerate_opt_in_stacks = (
self.... |
Stores current folder and stack name into config, so that next time that user runs sam sync, they don't need
to accept warning message again.
| set_accelerate_opt_in_stack | python | aws/aws-sam-cli | samcli/cli/global_config.py | https://github.com/aws/aws-sam-cli/blob/master/samcli/cli/global_config.py | Apache-2.0 |
def walk_modules(module: ModuleType, visited: set) -> None:
"""Recursively find all modules from a parent module"""
for pkg in pkgutil.walk_packages(module.__path__, module.__name__ + "."):
if pkg.name in visited:
continue
visited.add(pkg.name)
if pkg.ispkg:
submo... | Recursively find all modules from a parent module | walk_modules | python | aws/aws-sam-cli | samcli/cli/hidden_imports.py | https://github.com/aws/aws-sam-cli/blob/master/samcli/cli/hidden_imports.py | Apache-2.0 |
def _dynamic_import(name, package=None):
"""
Replaces original import_module function and then analyzes all the imports going through this call.
If the package is not defined in hidden imports, then it will raise an error
"""
for hidden_import in hidden_imports.SAM_CLI_HIDDEN_IMPORTS:
# An i... |
Replaces original import_module function and then analyzes all the imports going through this call.
If the package is not defined in hidden imports, then it will raise an error
| _dynamic_import | python | aws/aws-sam-cli | samcli/cli/import_module_proxy.py | https://github.com/aws/aws-sam-cli/blob/master/samcli/cli/import_module_proxy.py | Apache-2.0 |
def common_options(f):
"""
Common CLI options used by all commands. Ex: --debug
:param f: Callback function passed by Click
:return: Callback function
"""
f = debug_option(f)
f = experimental(f)
return f |
Common CLI options used by all commands. Ex: --debug
:param f: Callback function passed by Click
:return: Callback function
| common_options | python | aws/aws-sam-cli | samcli/cli/main.py | https://github.com/aws/aws-sam-cli/blob/master/samcli/cli/main.py | Apache-2.0 |
def aws_creds_options(f):
"""
Common CLI options necessary to interact with AWS services
"""
f = region_option(f)
f = profile_option(f)
return f |
Common CLI options necessary to interact with AWS services
| aws_creds_options | python | aws/aws-sam-cli | samcli/cli/main.py | https://github.com/aws/aws-sam-cli/blob/master/samcli/cli/main.py | Apache-2.0 |
def print_cmdline_args(func):
"""
This function format and print out the command line arguments for debugging.
Parameters
----------
func: Callable
Actual function (command) which will be executed
Returns
-------
function reference:
A wrapped function reference which ex... |
This function format and print out the command line arguments for debugging.
Parameters
----------
func: Callable
Actual function (command) which will be executed
Returns
-------
function reference:
A wrapped function reference which executes original function and checks n... | print_cmdline_args | python | aws/aws-sam-cli | samcli/cli/main.py | https://github.com/aws/aws-sam-cli/blob/master/samcli/cli/main.py | Apache-2.0 |
def cli(ctx):
"""
AWS Serverless Application Model (SAM) CLI
The AWS Serverless Application Model Command Line Interface (AWS SAM CLI) is a command line tool
that you can use with AWS SAM templates and supported third-party integrations to build and run
your serverless applications.
Learn more... |
AWS Serverless Application Model (SAM) CLI
The AWS Serverless Application Model Command Line Interface (AWS SAM CLI) is a command line tool
that you can use with AWS SAM templates and supported third-party integrations to build and run
your serverless applications.
Learn more: https://docs.aws.am... | cli | python | aws/aws-sam-cli | samcli/cli/main.py | https://github.com/aws/aws-sam-cli/blob/master/samcli/cli/main.py | Apache-2.0 |
def debug_option(f):
"""
Configures --debug option for CLI
:param f: Callback Function to be passed to Click
"""
def callback(ctx, param, value):
state = ctx.ensure_object(Context)
state.debug = value
return value
return click.option(
"--debug",
expose_... |
Configures --debug option for CLI
:param f: Callback Function to be passed to Click
| debug_option | python | aws/aws-sam-cli | samcli/cli/options.py | https://github.com/aws/aws-sam-cli/blob/master/samcli/cli/options.py | Apache-2.0 |
def region_option(f):
"""
Configures --region option for CLI
:param f: Callback Function to be passed to Click
"""
def callback(ctx, param, value):
state = ctx.ensure_object(Context)
from botocore import exceptions, utils
from samcli.commands.exceptions import RegionError
... |
Configures --region option for CLI
:param f: Callback Function to be passed to Click
| region_option | python | aws/aws-sam-cli | samcli/cli/options.py | https://github.com/aws/aws-sam-cli/blob/master/samcli/cli/options.py | Apache-2.0 |
def profile_option(f):
"""
Configures --profile option for CLI
:param f: Callback Function to be passed to Click
"""
def callback(ctx, param, value):
state = ctx.ensure_object(Context)
state.profile = value
return value
return click.option(
"--profile",
... |
Configures --profile option for CLI
:param f: Callback Function to be passed to Click
| profile_option | python | aws/aws-sam-cli | samcli/cli/options.py | https://github.com/aws/aws-sam-cli/blob/master/samcli/cli/options.py | Apache-2.0 |
def _unquote_wrapped_quotes(value):
r"""
Removes wrapping single or double quotes and unescapes '\ ', '\"' and '\''.
Parameters
----------
value : str
Input to unquote
Returns
-------
Unquoted string
"""
if value and value[0] == value[-1] and value[0] in ('"', "'") and... |
Removes wrapping single or double quotes and unescapes '\ ', '\"' and '\''.
Parameters
----------
value : str
Input to unquote
Returns
-------
Unquoted string
| _unquote_wrapped_quotes | python | aws/aws-sam-cli | samcli/cli/types.py | https://github.com/aws/aws-sam-cli/blob/master/samcli/cli/types.py | Apache-2.0 |
def _parse_key_value_pair(self, result: dict, key_value_string: str):
"""
This method processes a string in the format "'key1'='value1','key2'='value2'",
where spaces may exist within keys or values.
To optimize performance, the parsing is divided into two stages:
Stage 1: Opti... |
This method processes a string in the format "'key1'='value1','key2'='value2'",
where spaces may exist within keys or values.
To optimize performance, the parsing is divided into two stages:
Stage 1: Optimized Parsing
1. Identify quoted strings containing spaces within values.... | _parse_key_value_pair | python | aws/aws-sam-cli | samcli/cli/types.py | https://github.com/aws/aws-sam-cli/blob/master/samcli/cli/types.py | Apache-2.0 |
def _add_value(self, result: dict, key: str, new_value: str):
"""
Add a given value to a given key in the result map.
"""
if self.multiple_values_per_key:
if not result.get(key):
result[key] = []
result[key].append(new_value)
return
... |
Add a given value to a given key in the result map.
| _add_value | python | aws/aws-sam-cli | samcli/cli/types.py | https://github.com/aws/aws-sam-cli/blob/master/samcli/cli/types.py | Apache-2.0 |
def _standard_key_value_parser(tag_value):
"""
Method to parse simple `Key=Value` type tags without using regex. This is similar to how aws-cli does this.
https://github.com/aws/aws-cli/blob/eff79a263347e8e83c8a2cc07265ab366315a992/awscli/customizations/cloudformation/deploy.py#L361
Para... |
Method to parse simple `Key=Value` type tags without using regex. This is similar to how aws-cli does this.
https://github.com/aws/aws-cli/blob/eff79a263347e8e83c8a2cc07265ab366315a992/awscli/customizations/cloudformation/deploy.py#L361
Parameters
----------
tag_value
R... | _standard_key_value_parser | python | aws/aws-sam-cli | samcli/cli/types.py | https://github.com/aws/aws-sam-cli/blob/master/samcli/cli/types.py | Apache-2.0 |
def _space_separated_key_value_parser(tag_value):
"""
Method to parse space separated `Key1=Value1 Key2=Value2` type tags without using regex.
Parameters
----------
tag_value
"""
tags_dict = {}
for value in tag_value.split(" "):
parsed, parsed_... |
Method to parse space separated `Key1=Value1 Key2=Value2` type tags without using regex.
Parameters
----------
tag_value
| _space_separated_key_value_parser | python | aws/aws-sam-cli | samcli/cli/types.py | https://github.com/aws/aws-sam-cli/blob/master/samcli/cli/types.py | Apache-2.0 |
def _multiple_space_separated_key_value_parser(tag_value):
"""
Method to parse space separated `Key1=Value1 Key2=Value2` type tags without using regex.
Parameters
----------
tag_value
"""
tags_dict = {}
for value in tag_value.split():
parsed, p... |
Method to parse space separated `Key1=Value1 Key2=Value2` type tags without using regex.
Parameters
----------
tag_value
| _multiple_space_separated_key_value_parser | python | aws/aws-sam-cli | samcli/cli/types.py | https://github.com/aws/aws-sam-cli/blob/master/samcli/cli/types.py | Apache-2.0 |
def convert(self, value, param, ctx):
"""
Converts given Signing Profile options to a dictionary where Function or Layer name would be key,
and signing profile details would be the value.
Since this method is also been used when we are reading the config details from samconfig.toml,
... |
Converts given Signing Profile options to a dictionary where Function or Layer name would be key,
and signing profile details would be the value.
Since this method is also been used when we are reading the config details from samconfig.toml,
If value is already a dictionary, don't need... | convert | python | aws/aws-sam-cli | samcli/cli/types.py | https://github.com/aws/aws-sam-cli/blob/master/samcli/cli/types.py | Apache-2.0 |
def __init__(self, converter, transformation):
"""
:param converter: native click Type
:param transformation: callback function for transformation prior to conversion.
"""
self.converter = converter
self.transformer = transformation |
:param converter: native click Type
:param transformation: callback function for transformation prior to conversion.
| __init__ | python | aws/aws-sam-cli | samcli/cli/types.py | https://github.com/aws/aws-sam-cli/blob/master/samcli/cli/types.py | Apache-2.0 |
def convert(self, value, param, ctx):
"""
Attempt a conversion given the stipulations of allowed transformations.
"""
result = self.transformer.transform(value, param, ctx)
if not result:
raise click.BadParameter(f"Invalid Image Repository ECR URI: {value}")
r... |
Attempt a conversion given the stipulations of allowed transformations.
| convert | python | aws/aws-sam-cli | samcli/cli/types.py | https://github.com/aws/aws-sam-cli/blob/master/samcli/cli/types.py | Apache-2.0 |
def convert(self, value, param, ctx):
"""Converts the user provided parameter value with the format "parameter=value" to dict
{"parameter": "value"}
Parameters
------------
value: User provided value for the click option
param: click parameter
ctx: Context
... | Converts the user provided parameter value with the format "parameter=value" to dict
{"parameter": "value"}
Parameters
------------
value: User provided value for the click option
param: click parameter
ctx: Context
| convert | python | aws/aws-sam-cli | samcli/cli/types.py | https://github.com/aws/aws-sam-cli/blob/master/samcli/cli/types.py | Apache-2.0 |
def convert(self, value, param, ctx):
"""Converts the user provided parameters value with the format "host:IP" to dict
{"host": "IP"}
Parameters
------------
value: User provided value for the click option
param: click parameter
ctx: Context
"""
... | Converts the user provided parameters value with the format "host:IP" to dict
{"host": "IP"}
Parameters
------------
value: User provided value for the click option
param: click parameter
ctx: Context
| convert | python | aws/aws-sam-cli | samcli/cli/types.py | https://github.com/aws/aws-sam-cli/blob/master/samcli/cli/types.py | Apache-2.0 |
Subsets and Splits
Django Code with Docstrings
Filters Python code examples from Django repository that contain Django-related code, helping identify relevant code snippets for understanding Django framework usage patterns.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves specific code examples from the Flask repository but doesn't provide meaningful analysis or patterns beyond basic data retrieval.
HTTPX Repo Code and Docstrings
Retrieves specific code examples from the httpx repository, which is useful for understanding how particular libraries are used but doesn't provide broader analytical insights about the dataset.
Requests Repo Docstrings & Code
Retrieves code examples with their docstrings and file paths from the requests repository, providing basic filtering but limited analytical value beyond finding specific code samples.
Quart Repo Docstrings & Code
Retrieves code examples with their docstrings from the Quart repository, providing basic code samples but offering limited analytical value for understanding broader patterns or relationships in the dataset.