Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def get(self): '''Get the number of tokens in bucket''' now = time.time() if self.bucket >= self.burst: self.last_update = now return self.bucket bucket = self.rate * (now - self.last_update) self.mutex.acquire(...
[]
Please provide a description of the function:def migrate(pool, from_connection, to_connection): f = connect_database(from_connection) t = connect_database(to_connection) if isinstance(f, ProjectDB): for each in f.get_all(): each = unicode_obj(each) logging.info("project...
[ "\n Migrate tool for pyspider\n " ]
Please provide a description of the function:def encode(data, mime_type='', charset='utf-8', base64=True): if isinstance(data, six.text_type): data = data.encode(charset) else: charset = None if base64: data = utils.text(b64encode(data)) else: data = utils.text(quote...
[ "\n Encode data to DataURL\n " ]
Please provide a description of the function:def decode(data_url): metadata, data = data_url.rsplit(',', 1) _, metadata = metadata.split('data:', 1) parts = metadata.split(';') if parts[-1] == 'base64': data = b64decode(data) else: data = unquote(data) for part in parts: ...
[ "\n Decode DataURL data\n " ]
Please provide a description of the function:def _build_url(url, _params): # Support for unicode domain names and paths. scheme, netloc, path, params, query, fragment = urlparse(url) netloc = netloc.encode('idna').decode('utf-8') if not path: path = '/' if six.PY2: if isinstan...
[ "Build the actual URL to use." ]
Please provide a description of the function:def quote_chinese(url, encodeing="utf-8"): if isinstance(url, six.text_type): return quote_chinese(url.encode(encodeing)) if six.PY3: res = [six.int2byte(b).decode('latin-1') if b < 128 else '%%%02X' % b for b in url] else: res = [b i...
[ "Quote non-ascii characters" ]
Please provide a description of the function:def DownloadResource(url, path): '''Downloads resources from s3 by url and unzips them to the provided path''' import requests from six import BytesIO import zipfile print("Downloading... {} to {}".format(url, path)) r = requests.get(url, stream=True)...
[]
Please provide a description of the function:def AddLeNetModel(model, data): ''' This part is the standard LeNet model: from data to the softmax prediction. For each convolutional layer we specify dim_in - number of input channels and dim_out - number or output channels. Also each Conv and MaxPool laye...
[]
Please provide a description of the function:def AddAccuracy(model, softmax, label): accuracy = brew.accuracy(model, [softmax, label], "accuracy") return accuracy
[ "Adds an accuracy op to the model" ]
Please provide a description of the function:def AddTrainingOperators(model, softmax, label): xent = model.LabelCrossEntropy([softmax, label], 'xent') # compute the expected loss loss = model.AveragedLoss(xent, "loss") # track the accuracy of the model AddAccuracy(model, softmax, label) # u...
[ "Adds training operators to the model." ]
Please provide a description of the function:def AddBookkeepingOperators(model): # Print basically prints out the content of the blob. to_file=1 routes the # printed output to a file. The file is going to be stored under # root_folder/[blob name] model.Print('accuracy', [], to_file=1) model...
[ "This adds a few bookkeeping operators that we can inspect later.\n\n These operators do not affect the training procedure: they only collect\n statistics and prints them to file or to logs.\n " ]
Please provide a description of the function:def get_loss_func(self, C=1.0, k=1): def lf(x): mu, ln_var = self.encode(x) batchsize = len(mu.data) # reconstruction loss rec_loss = 0 for l in six.moves.range(k): z = F.gaussian(mu...
[ "Get loss function of VAE.\n\n The loss value is equal to ELBO (Evidence Lower Bound)\n multiplied by -1.\n\n Args:\n C (int): Usually this is 1.0. Can be changed to control the\n second term of ELBO bound, which works as regularization.\n k (int): Number of...
Please provide a description of the function:def fit(self, env, nb_steps, action_repetition=1, callbacks=None, verbose=1, visualize=False, nb_max_start_steps=0, start_step_policy=None, log_interval=10000, nb_max_episode_steps=None): if not self.compiled: raise Runtim...
[ "Trains the agent on the given environment.\n\n # Arguments\n env: (`Env` instance): Environment that the agent interacts with. See [Env](#env) for details.\n nb_steps (integer): Number of training steps to be performed.\n action_repetition (integer): Number of times the agen...
Please provide a description of the function:def process_step(self, observation, reward, done, info): observation = self.process_observation(observation) reward = self.process_reward(reward) info = self.process_info(info) return observation, reward, done, info
[ "Processes an entire step by applying the processor to the observation, reward, and info arguments.\n\n # Arguments\n observation (object): An observation as obtained by the environment.\n reward (float): A reward as obtained by the environment.\n done (boolean): `True` if th...
Please provide a description of the function:def get_current_value(self): if self.agent.training: # Linear annealed: f(x) = ax + b. a = -float(self.value_max - self.value_min) / float(self.nb_steps) b = float(self.value_max) value = max(self.value_min, a ...
[ "Return current annealing value\n\n # Returns\n Value to use in annealing\n " ]
Please provide a description of the function:def select_action(self, **kwargs): setattr(self.inner_policy, self.attr, self.get_current_value()) return self.inner_policy.select_action(**kwargs)
[ "Choose an action to perform\n\n # Returns\n Action to take (int)\n " ]
Please provide a description of the function:def get_config(self): config = super(LinearAnnealedPolicy, self).get_config() config['attr'] = self.attr config['value_max'] = self.value_max config['value_min'] = self.value_min config['value_test'] = self.value_test ...
[ "Return configurations of LinearAnnealedPolicy\n\n # Returns\n Dict of config\n " ]
Please provide a description of the function:def select_action(self, nb_actions, probs): action = np.random.choice(range(nb_actions), p=probs) return action
[ "Return the selected action\n\n # Arguments\n probs (np.ndarray) : Probabilty for each action\n\n # Returns\n action\n\n " ]
Please provide a description of the function:def select_action(self, q_values): assert q_values.ndim == 1 nb_actions = q_values.shape[0] if np.random.uniform() < self.eps: action = np.random.randint(0, nb_actions) else: action = np.argmax(q_values) ...
[ "Return the selected action\n\n # Arguments\n q_values (np.ndarray): List of the estimations of Q for each action\n\n # Returns\n Selection action\n " ]
Please provide a description of the function:def get_config(self): config = super(EpsGreedyQPolicy, self).get_config() config['eps'] = self.eps return config
[ "Return configurations of EpsGreedyQPolicy\n\n # Returns\n Dict of config\n " ]
Please provide a description of the function:def select_action(self, q_values): assert q_values.ndim == 1 action = np.argmax(q_values) return action
[ "Return the selected action\n\n # Arguments\n q_values (np.ndarray): List of the estimations of Q for each action\n\n # Returns\n Selection action\n " ]
Please provide a description of the function:def get_config(self): config = super(BoltzmannQPolicy, self).get_config() config['tau'] = self.tau config['clip'] = self.clip return config
[ "Return configurations of BoltzmannQPolicy\n\n # Returns\n Dict of config\n " ]
Please provide a description of the function:def select_action(self, q_values): assert q_values.ndim == 1 q_values = q_values.astype('float64') nb_actions = q_values.shape[0] if np.random.uniform() < self.eps: exp_values = np.exp(np.clip(q_values / self.tau, self.cl...
[ "Return the selected action\n The selected action follows the BoltzmannQPolicy with probability epsilon\n or return the Greedy Policy with probability (1 - epsilon)\n\n # Arguments\n q_values (np.ndarray): List of the estimations of Q for each action\n\n # Returns\n ...
Please provide a description of the function:def get_config(self): config = super(MaxBoltzmannQPolicy, self).get_config() config['eps'] = self.eps config['tau'] = self.tau config['clip'] = self.clip return config
[ "Return configurations of MaxBoltzmannQPolicy\n\n # Returns\n Dict of config\n " ]
Please provide a description of the function:def select_action(self, q_values): # We can't use BGE during testing, since we don't have access to the # action_counts at the end of training. assert self.agent.training, "BoltzmannGumbelQPolicy should only be used for training, not testing"...
[ "Return the selected action\n\n # Arguments\n q_values (np.ndarray): List of the estimations of Q for each action\n\n # Returns\n Selection action\n " ]
Please provide a description of the function:def get_config(self): config = super(BoltzmannGumbelQPolicy, self).get_config() config['C'] = self.C return config
[ "Return configurations of BoltzmannGumbelQPolicy\n\n # Returns\n Dict of config\n " ]
Please provide a description of the function:def _set_env(self, env): for callback in self.callbacks: if callable(getattr(callback, '_set_env', None)): callback._set_env(env)
[ " Set environment for each callback in callbackList " ]
Please provide a description of the function:def on_episode_begin(self, episode, logs={}): for callback in self.callbacks: # Check if callback supports the more appropriate `on_episode_begin` callback. # If not, fall back to `on_epoch_begin` to be compatible with built-in Keras ...
[ " Called at beginning of each episode for each callback in callbackList" ]
Please provide a description of the function:def on_episode_end(self, episode, logs={}): for callback in self.callbacks: # Check if callback supports the more appropriate `on_episode_end` callback. # If not, fall back to `on_epoch_end` to be compatible with built-in Keras callba...
[ " Called at end of each episode for each callback in callbackList" ]
Please provide a description of the function:def on_step_begin(self, step, logs={}): for callback in self.callbacks: # Check if callback supports the more appropriate `on_step_begin` callback. # If not, fall back to `on_batch_begin` to be compatible with built-in Keras callbacks...
[ " Called at beginning of each step for each callback in callbackList" ]
Please provide a description of the function:def on_step_end(self, step, logs={}): for callback in self.callbacks: # Check if callback supports the more appropriate `on_step_end` callback. # If not, fall back to `on_batch_end` to be compatible with built-in Keras callbacks. ...
[ " Called at end of each step for each callback in callbackList" ]
Please provide a description of the function:def on_action_begin(self, action, logs={}): for callback in self.callbacks: if callable(getattr(callback, 'on_action_begin', None)): callback.on_action_begin(action, logs=logs)
[ " Called at beginning of each action for each callback in callbackList" ]
Please provide a description of the function:def on_action_end(self, action, logs={}): for callback in self.callbacks: if callable(getattr(callback, 'on_action_end', None)): callback.on_action_end(action, logs=logs)
[ " Called at end of each action for each callback in callbackList" ]
Please provide a description of the function:def on_train_begin(self, logs): self.train_start = timeit.default_timer() self.metrics_names = self.model.metrics_names print('Training for {} steps ...'.format(self.params['nb_steps']))
[ " Print training values at beginning of training " ]
Please provide a description of the function:def on_train_end(self, logs): duration = timeit.default_timer() - self.train_start print('done, took {:.3f} seconds'.format(duration))
[ " Print training time at end of training " ]
Please provide a description of the function:def on_episode_begin(self, episode, logs): self.episode_start[episode] = timeit.default_timer() self.observations[episode] = [] self.rewards[episode] = [] self.actions[episode] = [] self.metrics[episode] = []
[ " Reset environment variables at beginning of each episode " ]
Please provide a description of the function:def on_episode_end(self, episode, logs): duration = timeit.default_timer() - self.episode_start[episode] episode_steps = len(self.observations[episode]) # Format all metrics. metrics = np.array(self.metrics[episode]) metrics_...
[ " Compute and print training statistics of the episode when done " ]
Please provide a description of the function:def on_step_end(self, step, logs): episode = logs['episode'] self.observations[episode].append(logs['observation']) self.rewards[episode].append(logs['reward']) self.actions[episode].append(logs['action']) self.metrics[episode...
[ " Update statistics of episode after each step " ]
Please provide a description of the function:def reset(self): self.interval_start = timeit.default_timer() self.progbar = Progbar(target=self.interval) self.metrics = [] self.infos = [] self.info_names = None self.episode_rewards = []
[ " Reset statistics " ]
Please provide a description of the function:def on_step_begin(self, step, logs): if self.step % self.interval == 0: if len(self.episode_rewards) > 0: metrics = np.array(self.metrics) assert metrics.shape == (self.interval, len(self.metrics_names)) ...
[ " Print metrics if interval is over " ]
Please provide a description of the function:def on_step_end(self, step, logs): if self.info_names is None: self.info_names = logs['info'].keys() values = [('reward', logs['reward'])] if KERAS_VERSION > '2.1.3': self.progbar.update((self.step % self.interval) + 1...
[ " Update progression bar at the end of each step " ]
Please provide a description of the function:def on_episode_begin(self, episode, logs): assert episode not in self.metrics assert episode not in self.starts self.metrics[episode] = [] self.starts[episode] = timeit.default_timer()
[ " Initialize metrics at the beginning of each episode " ]
Please provide a description of the function:def on_episode_end(self, episode, logs): duration = timeit.default_timer() - self.starts[episode] metrics = self.metrics[episode] if np.isnan(metrics).all(): mean_metrics = np.array([np.nan for _ in self.metrics_names]) ...
[ " Compute and print metrics at the end of each episode " ]
Please provide a description of the function:def save_data(self): if len(self.data.keys()) == 0: return # Sort everything by episode. assert 'episode' in self.data sorted_indexes = np.argsort(self.data['episode']) sorted_data = {} for key, values in ...
[ " Save metrics in a json file " ]
Please provide a description of the function:def on_step_end(self, step, logs={}): self.total_steps += 1 if self.total_steps % self.interval != 0: # Nothing to do. return filepath = self.filepath.format(step=self.total_steps, **logs) if self.verbose > 0:...
[ " Save weights at interval steps during training " ]
Please provide a description of the function:def sample_batch_indexes(low, high, size): if high - low >= size: # We have enough data. Draw without replacement, that is each index is unique in the # batch. We cannot use `np.random.choice` here because it is horribly inefficient as # the ...
[ "Return a sample of (size) unique elements between low and high\n\n # Argument\n low (int): The minimum value for our samples\n high (int): The maximum value for our samples\n size (int): The number of samples to pick\n\n # Returns\n A list of samples of len...
Please provide a description of the function:def zeroed_observation(observation): if hasattr(observation, 'shape'): return np.zeros(observation.shape) elif hasattr(observation, '__iter__'): out = [] for x in observation: out.append(zeroed_observation(x)) return o...
[ "Return an array of zeros with same shape as given observation\n\n # Argument\n observation (list): List of observation\n \n # Return\n A np.ndarray of zeros with observation.shape\n " ]
Please provide a description of the function:def get_recent_state(self, current_observation): # This code is slightly complicated by the fact that subsequent observations might be # from different episodes. We ensure that an experience never spans multiple episodes. # This is probably n...
[ "Return list of last observations\n\n # Argument\n current_observation (object): Last observation\n\n # Returns\n A list of the last observations\n " ]
Please provide a description of the function:def sample(self, batch_size, batch_idxs=None): # It is not possible to tell whether the first state in the memory is terminal, because it # would require access to the "terminal" flag associated to the previous state. As a result # we will ne...
[ "Return a randomized batch of experiences\n\n # Argument\n batch_size (int): Size of the all batch\n batch_idxs (int): Indexes to extract\n # Returns\n A list of experiences randomly selected\n " ]
Please provide a description of the function:def append(self, observation, action, reward, terminal, training=True): super(SequentialMemory, self).append(observation, action, reward, terminal, training=training) # This needs to be understood as follows: in `observation`, take `action`...
[ "Append an observation to the memory\n\n # Argument\n observation (dict): Observation returned by environment\n action (int): Action taken to obtain this observation\n reward (float): Reward obtained by taking this action\n terminal (boolean): Is the state terminal...
Please provide a description of the function:def get_config(self): config = super(SequentialMemory, self).get_config() config['limit'] = self.limit return config
[ "Return configurations of SequentialMemory\n\n # Returns\n Dict of config\n " ]
Please provide a description of the function:def sample(self, batch_size, batch_idxs=None): if batch_idxs is None: batch_idxs = sample_batch_indexes(0, self.nb_entries, size=batch_size) assert len(batch_idxs) == batch_size batch_params = [] batch_total_rewards = [] ...
[ "Return a randomized batch of params and rewards\n\n # Argument\n batch_size (int): Size of the all batch\n batch_idxs (int): Indexes to extract\n # Returns\n A list of params randomly selected and a list of associated rewards\n " ]
Please provide a description of the function:def append(self, observation, action, reward, terminal, training=True): super(EpisodeParameterMemory, self).append(observation, action, reward, terminal, training=training) if training: self.intermediate_rewards.append(reward)
[ "Append a reward to the memory\n\n # Argument\n observation (dict): Observation returned by environment\n action (int): Action taken to obtain this observation\n reward (float): Reward obtained by taking this action\n terminal (boolean): Is the state terminal\n ...
Please provide a description of the function:def finalize_episode(self, params): total_reward = sum(self.intermediate_rewards) self.total_rewards.append(total_reward) self.params.append(params) self.intermediate_rewards = []
[ "Closes the current episode, sums up rewards and stores the parameters\n\n # Argument\n params (object): Parameters associated with the episode to be stored and then retrieved back in sample()\n " ]
Please provide a description of the function:def make_gym_env(env_id, num_env=2, seed=123, wrapper_kwargs=None, start_index=0): if wrapper_kwargs is None: wrapper_kwargs = {} def make_env(rank): # pylint: disable=C0111 def _thunk(): env = gym.make(env_id) env.seed(s...
[ "\n Create a wrapped, SubprocVecEnv for Gym Environments.\n " ]
Please provide a description of the function:def invoke_common_options(f): invoke_options = [ template_click_option(), click.option('--env-vars', '-n', type=click.Path(exists=True), help="JSON file containing values for Lambda function's environment v...
[ "\n Common CLI options shared by \"local invoke\" and \"local start-api\" commands\n\n :param f: Callback passed by Click\n " ]
Please provide a description of the function:def get_or_default_template_file_name(ctx, param, provided_value, include_build): search_paths = [ "template.yaml", "template.yml", ] if include_build: search_paths.insert(0, os.path.join(".aws-sam", "build", "template.yaml")) ...
[ "\n Default value for the template file name option is more complex than what Click can handle.\n This method either returns user provided file name or one of the two default options (template.yaml/template.yml)\n depending on the file that exists\n\n :param ctx: Click Context\n :param param: Param n...
Please provide a description of the function:def template_click_option(include_build=True): return click.option('--template', '-t', default=_TEMPLATE_OPTION_DEFAULT_VALUE, type=click.Path(), envvar="SAM_TEMPLATE_FILE", ...
[ "\n Click Option for template option\n " ]
Please provide a description of the function:def create_tarball(tar_paths): tarballfile = TemporaryFile() with tarfile.open(fileobj=tarballfile, mode='w') as archive: for path_on_system, path_in_tarball in tar_paths.items(): archive.add(path_on_system, arcname=path_in_tarball) # F...
[ "\n Context Manger that creates the tarball of the Docker Context to use for building the image\n\n Parameters\n ----------\n tar_paths dict(str, str)\n Key representing a full path to the file or directory and the Value representing the path within the tarball\n\n Yields\n ------\n ...
Please provide a description of the function:def start(self): # We care about passing only stderr to the Service and not stdout because stdout from Docker container # contains the response to the API which is sent out as HTTP response. Only stderr needs to be printed # to the console o...
[ "\n Creates and starts the Local Lambda Invoke service. This method will block until the service is stopped\n manually using an interrupt. After the service is started, callers can make HTTP requests to the endpoint\n to invoke the Lambda function and receive a response.\n\n NOTE: This i...
Please provide a description of the function:def _extract_functions(resources): result = {} for name, resource in resources.items(): resource_type = resource.get("Type") resource_properties = resource.get("Properties", {}) if resource_type == SamFunctionP...
[ "\n Extracts and returns function information from the given dictionary of SAM/CloudFormation resources. This\n method supports functions defined with AWS::Serverless::Function and AWS::Lambda::Function\n\n :param dict resources: Dictionary of SAM/CloudFormation resources\n :return dict(...
Please provide a description of the function:def _convert_sam_function_resource(name, resource_properties, layers): codeuri = SamFunctionProvider._extract_sam_function_codeuri(name, resource_properties, "CodeUri") LOG.debug("Found Serverless function with name='%s' and CodeUri='%s'", name, co...
[ "\n Converts a AWS::Serverless::Function resource to a Function configuration usable by the provider.\n\n :param string name: LogicalID of the resource NOTE: This is *not* the function name because not all functions\n declare a name\n :param dict resource_properties: Properties of th...
Please provide a description of the function:def _extract_sam_function_codeuri(name, resource_properties, code_property_key): codeuri = resource_properties.get(code_property_key, SamFunctionProvider._DEFAULT_CODEURI) # CodeUri can be a dictionary of S3 Bucket/Key or a S3 URI, neither of which a...
[ "\n Extracts the SAM Function CodeUri from the Resource Properties\n\n Parameters\n ----------\n name str\n LogicalId of the resource\n resource_properties dict\n Dictionary representing the Properties of the Resource\n code_property_key str\n ...
Please provide a description of the function:def _convert_lambda_function_resource(name, resource_properties, layers): # pylint: disable=invalid-name # CodeUri is set to "." in order to get code locally from current directory. AWS::Lambda::Function's ``Code`` # property does not support speci...
[ "\n Converts a AWS::Serverless::Function resource to a Function configuration usable by the provider.\n\n :param string name: LogicalID of the resource NOTE: This is *not* the function name because not all functions\n declare a name\n :param dict resource_properties: Properties of th...
Please provide a description of the function:def _extract_lambda_function_code(resource_properties, code_property_key): codeuri = resource_properties.get(code_property_key, SamFunctionProvider._DEFAULT_CODEURI) if isinstance(codeuri, dict): codeuri = SamFunctionProvider._DEFAULT_C...
[ "\n Extracts the Lambda Function Code from the Resource Properties\n\n Parameters\n ----------\n resource_properties dict\n Dictionary representing the Properties of the Resource\n code_property_key str\n Property Key of the code on the Resource\n\n Re...
Please provide a description of the function:def _parse_layer_info(list_of_layers, resources): layers = [] for layer in list_of_layers: # If the layer is a string, assume it is the arn if isinstance(layer, six.string_types): layers.append(LayerVersion(lay...
[ "\n Creates a list of Layer objects that are represented by the resources and the list of layers\n\n Parameters\n ----------\n list_of_layers List(str)\n List of layers that are defined within the Layers Property on a function\n resources dict\n The Resources...
Please provide a description of the function:def resolve(self): # AWS_* variables must always be passed to the function, but user has the choice to override them result = self._get_aws_variables() # Default value for the variable gets lowest priority for name, value in self.va...
[ "\n Resolves the values from different sources and returns a dict of environment variables to use when running\n the function locally.\n\n :return dict: Dict where key is the variable name and value is the value of the variable. Both key and values\n are strings\n " ]
Please provide a description of the function:def _get_aws_variables(self): result = { # Variable that says this function is running in Local Lambda "AWS_SAM_LOCAL": "true", # Function configuration "AWS_LAMBDA_FUNCTION_MEMORY_SIZE": str(self.memory), ...
[ "\n Returns the AWS specific environment variables that should be available in the Lambda runtime.\n They are prefixed it \"AWS_*\".\n\n :return dict: Name and value of AWS environment variable\n " ]
Please provide a description of the function:def _stringify_value(self, value): # List/dict/None values are replaced with a blank if isinstance(value, (dict, list, tuple)) or value is None: result = self._BLANK_VALUE # str(True) will output "True". To maintain backwards co...
[ "\n This method stringifies values of environment variables. If the value of the method is a list or dictionary,\n then this method will replace it with empty string. Values of environment variables in Lambda must be a string.\n List or dictionary usually means they are intrinsic functions whic...
Please provide a description of the function:def create(self): if self.is_created(): raise RuntimeError("This container already exists. Cannot create again.") LOG.info("Mounting %s as %s:ro,delegated inside runtime container", self._host_dir, self._working_dir) kwargs = {...
[ "\n Calls Docker API to creates the Docker container instance. Creating the container does *not* run the container.\n Use ``start`` method to run the container\n\n :return string: ID of the created container\n :raise RuntimeError: If this method is called after a container already has be...
Please provide a description of the function:def delete(self): if not self.is_created(): LOG.debug("Container was not created. Skipping deletion") return try: self.docker_client.containers\ .get(self.id)\ .remove(force=True) ...
[ "\n Removes a container that was created earlier.\n " ]
Please provide a description of the function:def start(self, input_data=None): if input_data: raise ValueError("Passing input through container's stdin is not supported") if not self.is_created(): raise RuntimeError("Container does not exist. Cannot start this containe...
[ "\n Calls Docker API to start the container. The container must be created at the first place to run.\n It waits for the container to complete, fetches both stdout and stderr logs and returns through the\n given streams.\n\n Parameters\n ----------\n input_data\n ...
Please provide a description of the function:def _write_container_output(output_itr, stdout=None, stderr=None): # Iterator returns a tuple of (frame_type, data) where the frame type determines which stream we write output # to for frame_type, data in output_itr: if frame_t...
[ "\n Based on the data returned from the Container output, via the iterator, write it to the appropriate streams\n\n Parameters\n ----------\n output_itr: Iterator\n Iterator returned by the Docker Attach command\n stdout: samcli.lib.utils.stream_writer.StreamWriter, opt...
Please provide a description of the function:def cli(ctx, location, runtime, dependency_manager, output_dir, name, no_input): # All logic must be implemented in the `do_cli` method. This helps ease unit tests do_cli(ctx, location, runtime, dependency_manager, output_dir, name, no_input)
[ " \\b\n Initialize a serverless application with a SAM template, folder\n structure for your Lambda functions, connected to an event source such as APIs,\n S3 Buckets or DynamoDB Tables. This application includes everything you need to\n get started with serverless and eventually grow in...
Please provide a description of the function:def do_cli(ctx, location, runtime, dependency_manager, output_dir, name, no_input): LOG.debug("Init command") click.secho("[+] Initializing project structure...", fg="green") no_build_msg = .format(output_dir=output_dir, name=name) build_msg = .format(...
[ "\n Implementation of the ``cli`` method, just separated out for unit testing purposes\n ", "\nProject generated: {output_dir}/{name}\n\nSteps you can take next within the project folder\n===================================================\n[*] Invoke Function: sam local invoke HelloWorldFunction --event ev...
Please provide a description of the function:def do_cli(function_identifier, # pylint: disable=too-many-locals template, base_dir, build_dir, clean, use_container, manifest_path, docker_network, skip_pull_image, paramete...
[ "\n Implementation of the ``cli`` method\n " ]
Please provide a description of the function:def get_apis(self): result = [] paths_dict = self.swagger.get("paths", {}) binary_media_types = self.get_binary_media_types() for full_path, path_config in paths_dict.items(): for method, method_config in path_config.it...
[ "\n Parses a swagger document and returns a list of APIs configured in the document.\n\n Swagger documents have the following structure\n {\n \"/path1\": { # path\n \"get\": { # method\n \"x-amazon-apigateway-integration\": { # integration\n ...
Please provide a description of the function:def _get_integration_function_name(self, method_config): if not isinstance(method_config, dict) or self._INTEGRATION_KEY not in method_config: return None integration = method_config[self._INTEGRATION_KEY] if integration \ ...
[ "\n Tries to parse the Lambda Function name from the Integration defined in the method configuration.\n Integration configuration is defined under the special \"x-amazon-apigateway-integration\" key. We care only\n about Lambda integrations, which are of type aws_proxy, and ignore the rest. Int...
Please provide a description of the function:def do_cli(ctx, host, port, template, env_vars, debug_port, debug_args, # pylint: disable=R0914 debugger_path, docker_volume_basedir, docker_network, log_file, layer_cache_basedir, skip_pull_image, force_image_build, parameter_overrides): LOG...
[ "\n Implementation of the ``cli`` method, just separated out for unit testing purposes\n " ]
Please provide a description of the function:def do_format(self, event_iterable): for operation in self.formatter_chain: # Make sure the operation has access to certain basic objects like colored partial_op = functools.partial(operation, colored=self.colored) event...
[ "\n Formats the given CloudWatch Logs Event dictionary as necessary and returns an iterable that will\n return the formatted string. This can be used to parse and format the events based on context\n ie. In Lambda Function logs, a formatter may wish to color the \"ERROR\" keywords red,\n ...
Please provide a description of the function:def _pretty_print_event(event, colored): event.timestamp = colored.yellow(event.timestamp) event.log_stream_name = colored.cyan(event.log_stream_name) return ' '.join([event.log_stream_name, event.timestamp, event.message])
[ "\n Basic formatter to convert an event object to string\n " ]
Please provide a description of the function:def colorize_errors(event, colored): nodejs_crash_msg = "Process exited before completing request" timeout_msg = "Task timed out" if nodejs_crash_msg in event.message \ or timeout_msg in event.message: event.mess...
[ "\n Highlights some commonly known Lambda error cases in red:\n - Nodejs process crashes\n - Lambda function timeouts\n " ]
Please provide a description of the function:def highlight_keywords(self, event, colored): if self.keyword: highlight = colored.underline(self.keyword) event.message = event.message.replace(self.keyword, highlight) return event
[ "\n Highlight the keyword in the log statement by drawing an underline\n " ]
Please provide a description of the function:def format_json(event, colored): try: if event.message.startswith("{"): msg_dict = json.loads(event.message) event.message = json.dumps(msg_dict, indent=2) except Exception: # Skip if the event...
[ "\n If the event message is a JSON string, then pretty print the JSON with 2 indents and sort the keys. This makes\n it very easy to visually parse and search JSON data\n " ]
Please provide a description of the function:def get_template_data(template_file): if not pathlib.Path(template_file).exists(): raise ValueError("Template file not found at {}".format(template_file)) with open(template_file, 'r') as fp: try: return yaml_parse(fp.read()) ...
[ "\n Read the template file, parse it as JSON/YAML and return the template as a dictionary.\n\n Parameters\n ----------\n template_file : string\n Path to the template to read\n\n Returns\n -------\n Template data as a dictionary\n " ]
Please provide a description of the function:def move_template(src_template_path, dest_template_path, template_dict): original_root = os.path.dirname(src_template_path) new_root = os.path.dirname(dest_template_path) # Next up, we will be writing the template to a d...
[ "\n Move the SAM/CloudFormation template from ``src_template_path`` to ``dest_template_path``. For convenience, this\n method accepts a dictionary of template data ``template_dict`` that will be written to the destination instead of\n reading from the source file.\n\n SAM/CloudFormation template can con...
Please provide a description of the function:def _update_relative_paths(template_dict, original_root, new_root): for resource_type, properties in template_dict.get("Metadata", {}).items(): if resource_type not in _METADATA_WITH_LOCAL_PATHS: ...
[ "\n SAM/CloudFormation template can contain certain properties whose value is a relative path to a local file/folder.\n This path is usually relative to the template's location. If the template is being moved from original location\n ``original_root`` to new location ``new_root``, use this method to update...
Please provide a description of the function:def _update_aws_include_relative_path(template_dict, original_root, new_root): for key, val in template_dict.items(): if key == "Fn::Transform": if isinstance(val, dict) and val.get("Name") == "AWS::Include": path = val.get("Para...
[ "\n Update relative paths in \"AWS::Include\" directive. This directive can be present at any part of the template,\n and not just within resources.\n " ]
Please provide a description of the function:def _resolve_relative_to(path, original_root, new_root): if not isinstance(path, six.string_types) \ or path.startswith("s3://") \ or os.path.isabs(path): # Value is definitely NOT a relative path. It is either a S3 URi or Absolute p...
[ "\n If the given ``path`` is a relative path, then assume it is relative to ``original_root``. This method will\n update the path to be resolve it relative to ``new_root`` and return.\n\n Examples\n -------\n # Assume a file called template.txt at location /tmp/original/root/template.txt expresse...
Please provide a description of the function:def parse_aws_include_transform(data): if not data: return if _FN_TRANSFORM not in data: return transform_data = data[_FN_TRANSFORM] name = transform_data.get("Name") location = transform_data.get("Parameters", {}).get("Location")...
[ "\n If the input data is an AWS::Include data, then parse and return the location of the included file.\n\n AWS::Include transform data usually has the following format:\n {\n \"Fn::Transform\": {\n \"Name\": \"AWS::Include\",\n \"Parameters\": {\n \"Location\": ...
Please provide a description of the function:def read(self): swagger = None # First check if there is inline swagger if self.definition_body: swagger = self._read_from_definition_body() if not swagger and self.definition_uri: # If not, then try to down...
[ "\n Gets the Swagger document from either of the given locations. If we fail to retrieve or parse the Swagger\n file, this method will return None.\n\n Returns\n -------\n dict:\n Swagger document. None, if we cannot retrieve the document\n " ]
Please provide a description of the function:def _read_from_definition_body(self): # Let's try to parse it as AWS::Include Transform first. If not, then fall back to assuming the Swagger document # was inclined directly into the body location = parse_aws_include_transform(self.definiti...
[ "\n Read the Swagger document from DefinitionBody. It could either be an inline Swagger dictionary or an\n AWS::Include macro that contains location of the included Swagger. In the later case, we will download and\n parse the Swagger document.\n\n Returns\n -------\n dict\n...
Please provide a description of the function:def _download_swagger(self, location): if not location: return bucket, key, version = self._parse_s3_location(location) if bucket and key: LOG.debug("Downloading Swagger document from Bucket=%s, Key=%s, Version=%s", ...
[ "\n Download the file from given local or remote location and return it\n\n Parameters\n ----------\n location : str or dict\n Local path or S3 path to Swagger file to download. Consult the ``__init__.py`` documentation for specifics\n on structure of this property....
Please provide a description of the function:def _download_from_s3(bucket, key, version=None): s3 = boto3.client('s3') extra_args = {} if version: extra_args["VersionId"] = version with tempfile.TemporaryFile() as fp: try: s3.download_f...
[ "\n Download a file from given S3 location, if available.\n\n Parameters\n ----------\n bucket : str\n S3 Bucket name\n\n key : str\n S3 Bucket Key aka file path\n\n version : str\n Optional Version ID of the file\n\n Returns\n ...
Please provide a description of the function:def _parse_s3_location(location): bucket, key, version = None, None, None if isinstance(location, dict): # This is a S3 Location dictionary. Just grab the fields. It is very well possible that # this dictionary has none of th...
[ "\n Parses the given location input as a S3 Location and returns the file's bucket, key and version as separate\n values. Input can be in two different formats:\n\n 1. Dictionary with ``Bucket``, ``Key``, ``Version`` keys\n 2. String of S3 URI in format ``s3://<bucket>/<key>?versionId=<v...
Please provide a description of the function:def debug(self, value): self._debug = value if self._debug: # Turn on debug logging logging.getLogger().setLevel(logging.DEBUG)
[ "\n Turn on debug logging if necessary.\n\n :param value: Value of debug flag\n " ]
Please provide a description of the function:def _refresh_session(self): boto3.setup_default_session(region_name=self._aws_region, profile_name=self._aws_profile)
[ "\n Update boto3's default session by creating a new session based on values set in the context. Some properties of\n the Boto3's session object are read-only. Therefore when Click parses new AWS session related properties (like\n region & profile), it will call this method to create a new sess...
Please provide a description of the function:def generate_project( location=None, runtime="nodejs", dependency_manager=None, output_dir=".", name='sam-sample-app', no_input=False): template = None for mapping in list(itertools.chain(*(RUNTIME_DEP_TEMPLATE_MAPPING.values()))): if r...
[ "Generates project using cookiecutter and options given\n\n Generate project scaffolds a project using default templates if user\n doesn't provide one via location parameter. Default templates are\n automatically chosen depending on runtime given by the user.\n\n Parameters\n ----------\n location...
Please provide a description of the function:def to_utc(some_time): # Convert timezone aware objects to UTC if some_time.tzinfo and some_time.utcoffset(): some_time = some_time.astimezone(tzutc()) # Now that time is UTC, simply remove the timezone component. return some_time.replace(tzinf...
[ "\n Convert the given date to UTC, if the date contains a timezone.\n\n Parameters\n ----------\n some_time : datetime.datetime\n datetime object to convert to UTC\n\n Returns\n -------\n datetime.datetime\n Converted datetime object\n " ]
Please provide a description of the function:def parse_date(date_string): parser_settings = { # Relative times like '10m ago' must subtract from the current UTC time. Without this setting, dateparser # will use current local time as the base for subtraction, but falsely assume it is a UTC time...
[ "\n Parse the given string as datetime object. This parser supports in almost any string formats.\n\n For relative times, like `10min ago`, this parser computes the actual time relative to current UTC time. This\n allows time to always be in UTC if an explicit time zone is not provided.\n\n Parameters\n...