repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
onicagroup/runway
runway/commands/runway/gen_sample.py
generate_sample_stacker_module
def generate_sample_stacker_module(env_root, module_dir=None): """Generate skeleton Stacker sample module.""" if module_dir is None: module_dir = os.path.join(env_root, 'runway-sample-tfstate.cfn') generate_sample_module(module_dir) for i in ['stacks.yaml', 'dev-us-east-1.env']: shutil.copyfile( os.path.join(ROOT, 'templates', 'stacker', i), os.path.join(module_dir, i) ) os.mkdir(os.path.join(module_dir, 'tfstate_blueprints')) for i in ['__init__.py', 'tf_state.py']: shutil.copyfile( os.path.join(ROOT, 'templates', 'stacker', 'tfstate_blueprints', i), os.path.join(module_dir, 'tfstate_blueprints', i) ) os.chmod( # make blueprint executable os.path.join(module_dir, 'tfstate_blueprints', 'tf_state.py'), os.stat(os.path.join(module_dir, 'tfstate_blueprints', 'tf_state.py')).st_mode | 0o0111 ) LOGGER.info("Sample Stacker module created at %s", module_dir)
python
def generate_sample_stacker_module(env_root, module_dir=None): """Generate skeleton Stacker sample module.""" if module_dir is None: module_dir = os.path.join(env_root, 'runway-sample-tfstate.cfn') generate_sample_module(module_dir) for i in ['stacks.yaml', 'dev-us-east-1.env']: shutil.copyfile( os.path.join(ROOT, 'templates', 'stacker', i), os.path.join(module_dir, i) ) os.mkdir(os.path.join(module_dir, 'tfstate_blueprints')) for i in ['__init__.py', 'tf_state.py']: shutil.copyfile( os.path.join(ROOT, 'templates', 'stacker', 'tfstate_blueprints', i), os.path.join(module_dir, 'tfstate_blueprints', i) ) os.chmod( # make blueprint executable os.path.join(module_dir, 'tfstate_blueprints', 'tf_state.py'), os.stat(os.path.join(module_dir, 'tfstate_blueprints', 'tf_state.py')).st_mode | 0o0111 ) LOGGER.info("Sample Stacker module created at %s", module_dir)
[ "def", "generate_sample_stacker_module", "(", "env_root", ",", "module_dir", "=", "None", ")", ":", "if", "module_dir", "is", "None", ":", "module_dir", "=", "os", ".", "path", ".", "join", "(", "env_root", ",", "'runway-sample-tfstate.cfn'", ")", "generate_samp...
Generate skeleton Stacker sample module.
[ "Generate", "skeleton", "Stacker", "sample", "module", "." ]
3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f
https://github.com/onicagroup/runway/blob/3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f/runway/commands/runway/gen_sample.py#L210-L241
train
212,400
onicagroup/runway
runway/commands/runway/gen_sample.py
generate_sample_tf_module
def generate_sample_tf_module(env_root, module_dir=None): """Generate skeleton Terraform sample module.""" if module_dir is None: module_dir = os.path.join(env_root, 'sampleapp.tf') generate_sample_module(module_dir) for i in ['backend-us-east-1.tfvars', 'dev-us-east-1.tfvars', 'main.tf']: shutil.copyfile( os.path.join(ROOT, 'templates', 'terraform', i), os.path.join(module_dir, i), ) tf_ver_template = os.path.join(ROOT, 'templates', 'terraform', '.terraform-version') if os.path.isfile(tf_ver_template): shutil.copyfile( tf_ver_template, os.path.join(module_dir, '.terraform-version'), ) else: # running directly from git latest_tf_ver = get_latest_tf_version() with open(os.path.join(module_dir, '.terraform-version'), 'w') as stream: stream.write(latest_tf_ver) LOGGER.info("Sample Terraform app created at %s", module_dir)
python
def generate_sample_tf_module(env_root, module_dir=None): """Generate skeleton Terraform sample module.""" if module_dir is None: module_dir = os.path.join(env_root, 'sampleapp.tf') generate_sample_module(module_dir) for i in ['backend-us-east-1.tfvars', 'dev-us-east-1.tfvars', 'main.tf']: shutil.copyfile( os.path.join(ROOT, 'templates', 'terraform', i), os.path.join(module_dir, i), ) tf_ver_template = os.path.join(ROOT, 'templates', 'terraform', '.terraform-version') if os.path.isfile(tf_ver_template): shutil.copyfile( tf_ver_template, os.path.join(module_dir, '.terraform-version'), ) else: # running directly from git latest_tf_ver = get_latest_tf_version() with open(os.path.join(module_dir, '.terraform-version'), 'w') as stream: stream.write(latest_tf_ver) LOGGER.info("Sample Terraform app created at %s", module_dir)
[ "def", "generate_sample_tf_module", "(", "env_root", ",", "module_dir", "=", "None", ")", ":", "if", "module_dir", "is", "None", ":", "module_dir", "=", "os", ".", "path", ".", "join", "(", "env_root", ",", "'sampleapp.tf'", ")", "generate_sample_module", "(",...
Generate skeleton Terraform sample module.
[ "Generate", "skeleton", "Terraform", "sample", "module", "." ]
3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f
https://github.com/onicagroup/runway/blob/3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f/runway/commands/runway/gen_sample.py#L244-L273
train
212,401
onicagroup/runway
runway/commands/runway/gen_sample.py
GenSample.execute
def execute(self): """Run selected module generator.""" if self._cli_arguments['cfn']: generate_sample_cfn_module(self.env_root) elif self._cli_arguments['sls']: generate_sample_sls_module(self.env_root) elif self._cli_arguments['sls-tsc']: generate_sample_sls_tsc_module(self.env_root) elif self._cli_arguments['stacker']: generate_sample_stacker_module(self.env_root) elif self._cli_arguments['tf']: generate_sample_tf_module(self.env_root) elif self._cli_arguments['cdk-tsc']: generate_sample_cdk_tsc_module(self.env_root) elif self._cli_arguments['cdk-py']: generate_sample_cdk_py_module(self.env_root) elif self._cli_arguments['cdk-csharp']: generate_sample_cdk_cs_module(self.env_root)
python
def execute(self): """Run selected module generator.""" if self._cli_arguments['cfn']: generate_sample_cfn_module(self.env_root) elif self._cli_arguments['sls']: generate_sample_sls_module(self.env_root) elif self._cli_arguments['sls-tsc']: generate_sample_sls_tsc_module(self.env_root) elif self._cli_arguments['stacker']: generate_sample_stacker_module(self.env_root) elif self._cli_arguments['tf']: generate_sample_tf_module(self.env_root) elif self._cli_arguments['cdk-tsc']: generate_sample_cdk_tsc_module(self.env_root) elif self._cli_arguments['cdk-py']: generate_sample_cdk_py_module(self.env_root) elif self._cli_arguments['cdk-csharp']: generate_sample_cdk_cs_module(self.env_root)
[ "def", "execute", "(", "self", ")", ":", "if", "self", ".", "_cli_arguments", "[", "'cfn'", "]", ":", "generate_sample_cfn_module", "(", "self", ".", "env_root", ")", "elif", "self", ".", "_cli_arguments", "[", "'sls'", "]", ":", "generate_sample_sls_module", ...
Run selected module generator.
[ "Run", "selected", "module", "generator", "." ]
3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f
https://github.com/onicagroup/runway/blob/3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f/runway/commands/runway/gen_sample.py#L279-L296
train
212,402
onicagroup/runway
runway/commands/runway/init.py
Init.execute
def execute(self): # pylint: disable=no-self-use """Generate runway.yml.""" if os.path.isfile('runway.yml'): print('Runway config already present') sys.exit(1) with open('runway.yml', 'w') as stream: stream.write("""--- deployments: - modules: - nameofmyfirstmodulefolder - nameofmysecondmodulefolder # - etc... regions: - us-east-1 """) print('runway.yml generated') print('See additional getting started information at ' 'https://docs.onica.com/projects/runway/en/latest/how_to_use.html')
python
def execute(self): # pylint: disable=no-self-use """Generate runway.yml.""" if os.path.isfile('runway.yml'): print('Runway config already present') sys.exit(1) with open('runway.yml', 'w') as stream: stream.write("""--- deployments: - modules: - nameofmyfirstmodulefolder - nameofmysecondmodulefolder # - etc... regions: - us-east-1 """) print('runway.yml generated') print('See additional getting started information at ' 'https://docs.onica.com/projects/runway/en/latest/how_to_use.html')
[ "def", "execute", "(", "self", ")", ":", "# pylint: disable=no-self-use", "if", "os", ".", "path", ".", "isfile", "(", "'runway.yml'", ")", ":", "print", "(", "'Runway config already present'", ")", "sys", ".", "exit", "(", "1", ")", "with", "open", "(", "...
Generate runway.yml.
[ "Generate", "runway", ".", "yml", "." ]
3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f
https://github.com/onicagroup/runway/blob/3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f/runway/commands/runway/init.py#L13-L30
train
212,403
onicagroup/runway
runway/hooks/staticsite/build_staticsite.py
does_s3_object_exist
def does_s3_object_exist(bucket_name, key, session=None): """Determine if object exists on s3.""" if session: s3_resource = session.resource('s3') else: s3_resource = boto3.resource('s3') try: s3_resource.Object(bucket_name, key).load() except ClientError as exc: if exc.response['Error']['Code'] == '404': return False raise return True
python
def does_s3_object_exist(bucket_name, key, session=None): """Determine if object exists on s3.""" if session: s3_resource = session.resource('s3') else: s3_resource = boto3.resource('s3') try: s3_resource.Object(bucket_name, key).load() except ClientError as exc: if exc.response['Error']['Code'] == '404': return False raise return True
[ "def", "does_s3_object_exist", "(", "bucket_name", ",", "key", ",", "session", "=", "None", ")", ":", "if", "session", ":", "s3_resource", "=", "session", ".", "resource", "(", "'s3'", ")", "else", ":", "s3_resource", "=", "boto3", ".", "resource", "(", ...
Determine if object exists on s3.
[ "Determine", "if", "object", "exists", "on", "s3", "." ]
3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f
https://github.com/onicagroup/runway/blob/3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f/runway/hooks/staticsite/build_staticsite.py#L21-L34
train
212,404
onicagroup/runway
runway/hooks/staticsite/build_staticsite.py
download_and_extract_to_mkdtemp
def download_and_extract_to_mkdtemp(bucket, key, session=None): """Download zip archive and extract it to temporary directory.""" if session: s3_client = session.client('s3') else: s3_client = boto3.client('s3') transfer = S3Transfer(s3_client) filedes, temp_file = tempfile.mkstemp() os.close(filedes) transfer.download_file(bucket, key, temp_file) output_dir = tempfile.mkdtemp() zip_ref = zipfile.ZipFile(temp_file, 'r') zip_ref.extractall(output_dir) zip_ref.close() os.remove(temp_file) return output_dir
python
def download_and_extract_to_mkdtemp(bucket, key, session=None): """Download zip archive and extract it to temporary directory.""" if session: s3_client = session.client('s3') else: s3_client = boto3.client('s3') transfer = S3Transfer(s3_client) filedes, temp_file = tempfile.mkstemp() os.close(filedes) transfer.download_file(bucket, key, temp_file) output_dir = tempfile.mkdtemp() zip_ref = zipfile.ZipFile(temp_file, 'r') zip_ref.extractall(output_dir) zip_ref.close() os.remove(temp_file) return output_dir
[ "def", "download_and_extract_to_mkdtemp", "(", "bucket", ",", "key", ",", "session", "=", "None", ")", ":", "if", "session", ":", "s3_client", "=", "session", ".", "client", "(", "'s3'", ")", "else", ":", "s3_client", "=", "boto3", ".", "client", "(", "'...
Download zip archive and extract it to temporary directory.
[ "Download", "zip", "archive", "and", "extract", "it", "to", "temporary", "directory", "." ]
3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f
https://github.com/onicagroup/runway/blob/3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f/runway/hooks/staticsite/build_staticsite.py#L37-L54
train
212,405
onicagroup/runway
runway/hooks/staticsite/build_staticsite.py
zip_and_upload
def zip_and_upload(app_dir, bucket, key, session=None): """Zip built static site and upload to S3.""" if session: s3_client = session.client('s3') else: s3_client = boto3.client('s3') transfer = S3Transfer(s3_client) filedes, temp_file = tempfile.mkstemp() os.close(filedes) LOGGER.info("staticsite: archiving app at %s to s3://%s/%s", app_dir, bucket, key) with zipfile.ZipFile(temp_file, 'w', zipfile.ZIP_DEFLATED) as filehandle: with change_dir(app_dir): for dirname, _subdirs, files in os.walk('./'): if dirname != './': filehandle.write(dirname) for filename in files: filehandle.write(os.path.join(dirname, filename)) transfer.upload_file(temp_file, bucket, key) os.remove(temp_file)
python
def zip_and_upload(app_dir, bucket, key, session=None): """Zip built static site and upload to S3.""" if session: s3_client = session.client('s3') else: s3_client = boto3.client('s3') transfer = S3Transfer(s3_client) filedes, temp_file = tempfile.mkstemp() os.close(filedes) LOGGER.info("staticsite: archiving app at %s to s3://%s/%s", app_dir, bucket, key) with zipfile.ZipFile(temp_file, 'w', zipfile.ZIP_DEFLATED) as filehandle: with change_dir(app_dir): for dirname, _subdirs, files in os.walk('./'): if dirname != './': filehandle.write(dirname) for filename in files: filehandle.write(os.path.join(dirname, filename)) transfer.upload_file(temp_file, bucket, key) os.remove(temp_file)
[ "def", "zip_and_upload", "(", "app_dir", ",", "bucket", ",", "key", ",", "session", "=", "None", ")", ":", "if", "session", ":", "s3_client", "=", "session", ".", "client", "(", "'s3'", ")", "else", ":", "s3_client", "=", "boto3", ".", "client", "(", ...
Zip built static site and upload to S3.
[ "Zip", "built", "static", "site", "and", "upload", "to", "S3", "." ]
3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f
https://github.com/onicagroup/runway/blob/3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f/runway/hooks/staticsite/build_staticsite.py#L57-L77
train
212,406
onicagroup/runway
runway/hooks/staticsite/build_staticsite.py
build
def build(context, provider, **kwargs): # pylint: disable=unused-argument """Build static site.""" session = get_session(provider.region) options = kwargs.get('options', {}) context_dict = {} context_dict['artifact_key_prefix'] = "%s-%s-" % (options['namespace'], options['name']) # noqa default_param_name = "%shash" % context_dict['artifact_key_prefix'] if options.get('build_output'): build_output = os.path.join( options['path'], options['build_output'] ) else: build_output = options['path'] context_dict['artifact_bucket_name'] = RxrefLookup.handle( kwargs.get('artifact_bucket_rxref_lookup'), provider=provider, context=context ) if options.get('pre_build_steps'): run_commands(options['pre_build_steps'], options['path']) context_dict['hash'] = get_hash_of_files( root_path=options['path'], directories=options.get('source_hashing', {}).get('directories') ) # Now determine if the current staticsite has already been deployed if options.get('source_hashing', {}).get('enabled', True): context_dict['hash_tracking_parameter'] = options.get( 'source_hashing', {}).get('parameter', default_param_name) ssm_client = session.client('ssm') try: old_parameter_value = ssm_client.get_parameter( Name=context_dict['hash_tracking_parameter'] )['Parameter']['Value'] except ssm_client.exceptions.ParameterNotFound: old_parameter_value = None else: context_dict['hash_tracking_disabled'] = True old_parameter_value = None context_dict['current_archive_filename'] = ( context_dict['artifact_key_prefix'] + context_dict['hash'] + '.zip' ) if old_parameter_value: context_dict['old_archive_filename'] = ( context_dict['artifact_key_prefix'] + old_parameter_value + '.zip' ) if old_parameter_value == context_dict['hash']: LOGGER.info("staticsite: skipping build; app hash %s already deployed " "in this environment", context_dict['hash']) context_dict['deploy_is_current'] = True return context_dict if does_s3_object_exist(context_dict['artifact_bucket_name'], context_dict['current_archive_filename'], session): context_dict['app_directory'] = download_and_extract_to_mkdtemp( context_dict['artifact_bucket_name'], context_dict['current_archive_filename'], session ) else: if options.get('build_steps'): LOGGER.info('staticsite: executing build commands') run_commands(options['build_steps'], options['path']) zip_and_upload(build_output, context_dict['artifact_bucket_name'], context_dict['current_archive_filename'], session) context_dict['app_directory'] = build_output context_dict['deploy_is_current'] = False return context_dict
python
def build(context, provider, **kwargs): # pylint: disable=unused-argument """Build static site.""" session = get_session(provider.region) options = kwargs.get('options', {}) context_dict = {} context_dict['artifact_key_prefix'] = "%s-%s-" % (options['namespace'], options['name']) # noqa default_param_name = "%shash" % context_dict['artifact_key_prefix'] if options.get('build_output'): build_output = os.path.join( options['path'], options['build_output'] ) else: build_output = options['path'] context_dict['artifact_bucket_name'] = RxrefLookup.handle( kwargs.get('artifact_bucket_rxref_lookup'), provider=provider, context=context ) if options.get('pre_build_steps'): run_commands(options['pre_build_steps'], options['path']) context_dict['hash'] = get_hash_of_files( root_path=options['path'], directories=options.get('source_hashing', {}).get('directories') ) # Now determine if the current staticsite has already been deployed if options.get('source_hashing', {}).get('enabled', True): context_dict['hash_tracking_parameter'] = options.get( 'source_hashing', {}).get('parameter', default_param_name) ssm_client = session.client('ssm') try: old_parameter_value = ssm_client.get_parameter( Name=context_dict['hash_tracking_parameter'] )['Parameter']['Value'] except ssm_client.exceptions.ParameterNotFound: old_parameter_value = None else: context_dict['hash_tracking_disabled'] = True old_parameter_value = None context_dict['current_archive_filename'] = ( context_dict['artifact_key_prefix'] + context_dict['hash'] + '.zip' ) if old_parameter_value: context_dict['old_archive_filename'] = ( context_dict['artifact_key_prefix'] + old_parameter_value + '.zip' ) if old_parameter_value == context_dict['hash']: LOGGER.info("staticsite: skipping build; app hash %s already deployed " "in this environment", context_dict['hash']) context_dict['deploy_is_current'] = True return context_dict if does_s3_object_exist(context_dict['artifact_bucket_name'], context_dict['current_archive_filename'], session): context_dict['app_directory'] = download_and_extract_to_mkdtemp( context_dict['artifact_bucket_name'], context_dict['current_archive_filename'], session ) else: if options.get('build_steps'): LOGGER.info('staticsite: executing build commands') run_commands(options['build_steps'], options['path']) zip_and_upload(build_output, context_dict['artifact_bucket_name'], context_dict['current_archive_filename'], session) context_dict['app_directory'] = build_output context_dict['deploy_is_current'] = False return context_dict
[ "def", "build", "(", "context", ",", "provider", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=unused-argument", "session", "=", "get_session", "(", "provider", ".", "region", ")", "options", "=", "kwargs", ".", "get", "(", "'options'", ",", "{", "...
Build static site.
[ "Build", "static", "site", "." ]
3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f
https://github.com/onicagroup/runway/blob/3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f/runway/hooks/staticsite/build_staticsite.py#L80-L158
train
212,407
onicagroup/runway
runway/module/staticsite.py
ensure_valid_environment_config
def ensure_valid_environment_config(module_name, config): """Exit if config is invalid.""" if not config.get('namespace'): LOGGER.fatal("staticsite: module %s's environment configuration is " "missing a namespace definition!", module_name) sys.exit(1)
python
def ensure_valid_environment_config(module_name, config): """Exit if config is invalid.""" if not config.get('namespace'): LOGGER.fatal("staticsite: module %s's environment configuration is " "missing a namespace definition!", module_name) sys.exit(1)
[ "def", "ensure_valid_environment_config", "(", "module_name", ",", "config", ")", ":", "if", "not", "config", ".", "get", "(", "'namespace'", ")", ":", "LOGGER", ".", "fatal", "(", "\"staticsite: module %s's environment configuration is \"", "\"missing a namespace definit...
Exit if config is invalid.
[ "Exit", "if", "config", "is", "invalid", "." ]
3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f
https://github.com/onicagroup/runway/blob/3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f/runway/module/staticsite.py#L16-L22
train
212,408
onicagroup/runway
runway/module/staticsite.py
StaticSite.plan
def plan(self): """Create website CFN module and run stacker diff.""" if self.options.get('environments', {}).get(self.context.env_name): self.setup_website_module(command='plan') else: LOGGER.info("Skipping staticsite plan of %s; no environment " "config found for this environment/region", self.options['path'])
python
def plan(self): """Create website CFN module and run stacker diff.""" if self.options.get('environments', {}).get(self.context.env_name): self.setup_website_module(command='plan') else: LOGGER.info("Skipping staticsite plan of %s; no environment " "config found for this environment/region", self.options['path'])
[ "def", "plan", "(", "self", ")", ":", "if", "self", ".", "options", ".", "get", "(", "'environments'", ",", "{", "}", ")", ".", "get", "(", "self", ".", "context", ".", "env_name", ")", ":", "self", ".", "setup_website_module", "(", "command", "=", ...
Create website CFN module and run stacker diff.
[ "Create", "website", "CFN", "module", "and", "run", "stacker", "diff", "." ]
3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f
https://github.com/onicagroup/runway/blob/3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f/runway/module/staticsite.py#L147-L154
train
212,409
onicagroup/runway
runway/module/__init__.py
format_npm_command_for_logging
def format_npm_command_for_logging(command): """Convert npm command list to string for display to user.""" if platform.system().lower() == 'windows': if command[0] == 'npx.cmd' and command[1] == '-c': return "npx.cmd -c \"%s\"" % " ".join(command[2:]) return " ".join(command) # Strip out redundant npx quotes not needed when executing the command # directly return " ".join(command).replace('\'\'', '\'')
python
def format_npm_command_for_logging(command): """Convert npm command list to string for display to user.""" if platform.system().lower() == 'windows': if command[0] == 'npx.cmd' and command[1] == '-c': return "npx.cmd -c \"%s\"" % " ".join(command[2:]) return " ".join(command) # Strip out redundant npx quotes not needed when executing the command # directly return " ".join(command).replace('\'\'', '\'')
[ "def", "format_npm_command_for_logging", "(", "command", ")", ":", "if", "platform", ".", "system", "(", ")", ".", "lower", "(", ")", "==", "'windows'", ":", "if", "command", "[", "0", "]", "==", "'npx.cmd'", "and", "command", "[", "1", "]", "==", "'-c...
Convert npm command list to string for display to user.
[ "Convert", "npm", "command", "list", "to", "string", "for", "display", "to", "user", "." ]
3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f
https://github.com/onicagroup/runway/blob/3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f/runway/module/__init__.py#L17-L25
train
212,410
onicagroup/runway
runway/module/__init__.py
generate_node_command
def generate_node_command(command, command_opts, path): """Return node bin command list for subprocess execution.""" if which(NPX_BIN): # Use npx if available (npm v5.2+) LOGGER.debug("Using npx to invoke %s.", command) if platform.system().lower() == 'windows': cmd_list = [NPX_BIN, '-c', "%s %s" % (command, ' '.join(command_opts))] else: # The nested app-through-npx-via-subprocess command invocation # requires this redundant quoting cmd_list = [NPX_BIN, '-c', "''%s %s''" % (command, ' '.join(command_opts))] else: LOGGER.debug('npx not found; falling back invoking %s shell script ' 'directly.', command) cmd_list = [ os.path.join(path, 'node_modules', '.bin', command) ] + command_opts return cmd_list
python
def generate_node_command(command, command_opts, path): """Return node bin command list for subprocess execution.""" if which(NPX_BIN): # Use npx if available (npm v5.2+) LOGGER.debug("Using npx to invoke %s.", command) if platform.system().lower() == 'windows': cmd_list = [NPX_BIN, '-c', "%s %s" % (command, ' '.join(command_opts))] else: # The nested app-through-npx-via-subprocess command invocation # requires this redundant quoting cmd_list = [NPX_BIN, '-c', "''%s %s''" % (command, ' '.join(command_opts))] else: LOGGER.debug('npx not found; falling back invoking %s shell script ' 'directly.', command) cmd_list = [ os.path.join(path, 'node_modules', '.bin', command) ] + command_opts return cmd_list
[ "def", "generate_node_command", "(", "command", ",", "command_opts", ",", "path", ")", ":", "if", "which", "(", "NPX_BIN", ")", ":", "# Use npx if available (npm v5.2+)", "LOGGER", ".", "debug", "(", "\"Using npx to invoke %s.\"", ",", "command", ")", "if", "platf...
Return node bin command list for subprocess execution.
[ "Return", "node", "bin", "command", "list", "for", "subprocess", "execution", "." ]
3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f
https://github.com/onicagroup/runway/blob/3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f/runway/module/__init__.py#L28-L52
train
212,411
onicagroup/runway
runway/module/__init__.py
run_module_command
def run_module_command(cmd_list, env_vars, exit_on_error=True): """Shell out to provisioner command.""" if exit_on_error: try: subprocess.check_call(cmd_list, env=env_vars) except subprocess.CalledProcessError as shelloutexc: sys.exit(shelloutexc.returncode) else: subprocess.check_call(cmd_list, env=env_vars)
python
def run_module_command(cmd_list, env_vars, exit_on_error=True): """Shell out to provisioner command.""" if exit_on_error: try: subprocess.check_call(cmd_list, env=env_vars) except subprocess.CalledProcessError as shelloutexc: sys.exit(shelloutexc.returncode) else: subprocess.check_call(cmd_list, env=env_vars)
[ "def", "run_module_command", "(", "cmd_list", ",", "env_vars", ",", "exit_on_error", "=", "True", ")", ":", "if", "exit_on_error", ":", "try", ":", "subprocess", ".", "check_call", "(", "cmd_list", ",", "env", "=", "env_vars", ")", "except", "subprocess", "....
Shell out to provisioner command.
[ "Shell", "out", "to", "provisioner", "command", "." ]
3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f
https://github.com/onicagroup/runway/blob/3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f/runway/module/__init__.py#L55-L63
train
212,412
onicagroup/runway
runway/module/__init__.py
use_npm_ci
def use_npm_ci(path): """Return true if npm ci should be used in lieu of npm install.""" # https://docs.npmjs.com/cli/ci#description with open(os.devnull, 'w') as fnull: if ((os.path.isfile(os.path.join(path, 'package-lock.json')) or os.path.isfile(os.path.join(path, 'npm-shrinkwrap.json'))) and subprocess.call( [NPM_BIN, 'ci', '-h'], stdout=fnull, stderr=subprocess.STDOUT ) == 0): return True return False
python
def use_npm_ci(path): """Return true if npm ci should be used in lieu of npm install.""" # https://docs.npmjs.com/cli/ci#description with open(os.devnull, 'w') as fnull: if ((os.path.isfile(os.path.join(path, 'package-lock.json')) or os.path.isfile(os.path.join(path, 'npm-shrinkwrap.json'))) and subprocess.call( [NPM_BIN, 'ci', '-h'], stdout=fnull, stderr=subprocess.STDOUT ) == 0): return True return False
[ "def", "use_npm_ci", "(", "path", ")", ":", "# https://docs.npmjs.com/cli/ci#description", "with", "open", "(", "os", ".", "devnull", ",", "'w'", ")", "as", "fnull", ":", "if", "(", "(", "os", ".", "path", ".", "isfile", "(", "os", ".", "path", ".", "j...
Return true if npm ci should be used in lieu of npm install.
[ "Return", "true", "if", "npm", "ci", "should", "be", "used", "in", "lieu", "of", "npm", "install", "." ]
3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f
https://github.com/onicagroup/runway/blob/3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f/runway/module/__init__.py#L66-L80
train
212,413
onicagroup/runway
runway/module/cdk.py
cdk_module_matches_env
def cdk_module_matches_env(env_name, env_config, env_vars): """Return bool on whether cdk command should continue in current env.""" if env_config.get(env_name): current_env_config = env_config[env_name] if isinstance(current_env_config, type(True)) and current_env_config: return True if isinstance(current_env_config, six.string_types): (account_id, region) = current_env_config.split('/') if region == env_vars['AWS_DEFAULT_REGION']: boto_args = extract_boto_args_from_env(env_vars) sts_client = boto3.client( 'sts', region_name=env_vars['AWS_DEFAULT_REGION'], **boto_args ) if sts_client.get_caller_identity()['Account'] == account_id: return True if isinstance(current_env_config, dict): return True return False
python
def cdk_module_matches_env(env_name, env_config, env_vars): """Return bool on whether cdk command should continue in current env.""" if env_config.get(env_name): current_env_config = env_config[env_name] if isinstance(current_env_config, type(True)) and current_env_config: return True if isinstance(current_env_config, six.string_types): (account_id, region) = current_env_config.split('/') if region == env_vars['AWS_DEFAULT_REGION']: boto_args = extract_boto_args_from_env(env_vars) sts_client = boto3.client( 'sts', region_name=env_vars['AWS_DEFAULT_REGION'], **boto_args ) if sts_client.get_caller_identity()['Account'] == account_id: return True if isinstance(current_env_config, dict): return True return False
[ "def", "cdk_module_matches_env", "(", "env_name", ",", "env_config", ",", "env_vars", ")", ":", "if", "env_config", ".", "get", "(", "env_name", ")", ":", "current_env_config", "=", "env_config", "[", "env_name", "]", "if", "isinstance", "(", "current_env_config...
Return bool on whether cdk command should continue in current env.
[ "Return", "bool", "on", "whether", "cdk", "command", "should", "continue", "in", "current", "env", "." ]
3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f
https://github.com/onicagroup/runway/blob/3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f/runway/module/cdk.py#L22-L41
train
212,414
onicagroup/runway
runway/module/cdk.py
get_cdk_stacks
def get_cdk_stacks(module_path, env_vars, context_opts): """Return list of CDK stacks.""" LOGGER.debug('Listing stacks in the CDK app prior to ' 'diff') return subprocess.check_output( generate_node_command( command='cdk', command_opts=['list'] + context_opts, path=module_path), env=env_vars ).strip().split('\n')
python
def get_cdk_stacks(module_path, env_vars, context_opts): """Return list of CDK stacks.""" LOGGER.debug('Listing stacks in the CDK app prior to ' 'diff') return subprocess.check_output( generate_node_command( command='cdk', command_opts=['list'] + context_opts, path=module_path), env=env_vars ).strip().split('\n')
[ "def", "get_cdk_stacks", "(", "module_path", ",", "env_vars", ",", "context_opts", ")", ":", "LOGGER", ".", "debug", "(", "'Listing stacks in the CDK app prior to '", "'diff'", ")", "return", "subprocess", ".", "check_output", "(", "generate_node_command", "(", "comma...
Return list of CDK stacks.
[ "Return", "list", "of", "CDK", "stacks", "." ]
3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f
https://github.com/onicagroup/runway/blob/3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f/runway/module/cdk.py#L44-L54
train
212,415
onicagroup/runway
runway/commands/modules_command.py
assume_role
def assume_role(role_arn, session_name=None, duration_seconds=None, region='us-east-1', env_vars=None): """Assume IAM role.""" if session_name is None: session_name = 'runway' assume_role_opts = {'RoleArn': role_arn, 'RoleSessionName': session_name} if duration_seconds: assume_role_opts['DurationSeconds'] = int(duration_seconds) boto_args = {} if env_vars: for i in ['aws_access_key_id', 'aws_secret_access_key', 'aws_session_token']: if env_vars.get(i.upper()): boto_args[i] = env_vars[i.upper()] sts_client = boto3.client('sts', region_name=region, **boto_args) LOGGER.info("Assuming role %s...", role_arn) response = sts_client.assume_role(**assume_role_opts) return {'AWS_ACCESS_KEY_ID': response['Credentials']['AccessKeyId'], 'AWS_SECRET_ACCESS_KEY': response['Credentials']['SecretAccessKey'], # noqa 'AWS_SESSION_TOKEN': response['Credentials']['SessionToken']}
python
def assume_role(role_arn, session_name=None, duration_seconds=None, region='us-east-1', env_vars=None): """Assume IAM role.""" if session_name is None: session_name = 'runway' assume_role_opts = {'RoleArn': role_arn, 'RoleSessionName': session_name} if duration_seconds: assume_role_opts['DurationSeconds'] = int(duration_seconds) boto_args = {} if env_vars: for i in ['aws_access_key_id', 'aws_secret_access_key', 'aws_session_token']: if env_vars.get(i.upper()): boto_args[i] = env_vars[i.upper()] sts_client = boto3.client('sts', region_name=region, **boto_args) LOGGER.info("Assuming role %s...", role_arn) response = sts_client.assume_role(**assume_role_opts) return {'AWS_ACCESS_KEY_ID': response['Credentials']['AccessKeyId'], 'AWS_SECRET_ACCESS_KEY': response['Credentials']['SecretAccessKey'], # noqa 'AWS_SESSION_TOKEN': response['Credentials']['SessionToken']}
[ "def", "assume_role", "(", "role_arn", ",", "session_name", "=", "None", ",", "duration_seconds", "=", "None", ",", "region", "=", "'us-east-1'", ",", "env_vars", "=", "None", ")", ":", "if", "session_name", "is", "None", ":", "session_name", "=", "'runway'"...
Assume IAM role.
[ "Assume", "IAM", "role", "." ]
3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f
https://github.com/onicagroup/runway/blob/3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f/runway/commands/modules_command.py#L30-L51
train
212,416
onicagroup/runway
runway/commands/modules_command.py
determine_module_class
def determine_module_class(path, class_path): """Determine type of module and return deployment module class.""" if not class_path: # First check directory name for type-indicating suffix basename = os.path.basename(path) if basename.endswith('.sls'): class_path = 'runway.module.serverless.Serverless' elif basename.endswith('.tf'): class_path = 'runway.module.terraform.Terraform' elif basename.endswith('.cdk'): class_path = 'runway.module.cdk.CloudDevelopmentKit' elif basename.endswith('.cfn'): class_path = 'runway.module.cloudformation.CloudFormation' if not class_path: # Fallback to autodetection if os.path.isfile(os.path.join(path, 'serverless.yml')): class_path = 'runway.module.serverless.Serverless' elif glob.glob(os.path.join(path, '*.tf')): class_path = 'runway.module.terraform.Terraform' elif os.path.isfile(os.path.join(path, 'cdk.json')) \ and os.path.isfile(os.path.join(path, 'package.json')): class_path = 'runway.module.cdk.CloudDevelopmentKit' elif glob.glob(os.path.join(path, '*.env')) or ( glob.glob(os.path.join(path, '*.yaml'))) or ( glob.glob(os.path.join(path, '*.yml'))): class_path = 'runway.module.cloudformation.CloudFormation' if not class_path: LOGGER.error('No module class found for %s', os.path.basename(path)) sys.exit(1) return load_object_from_string(class_path)
python
def determine_module_class(path, class_path): """Determine type of module and return deployment module class.""" if not class_path: # First check directory name for type-indicating suffix basename = os.path.basename(path) if basename.endswith('.sls'): class_path = 'runway.module.serverless.Serverless' elif basename.endswith('.tf'): class_path = 'runway.module.terraform.Terraform' elif basename.endswith('.cdk'): class_path = 'runway.module.cdk.CloudDevelopmentKit' elif basename.endswith('.cfn'): class_path = 'runway.module.cloudformation.CloudFormation' if not class_path: # Fallback to autodetection if os.path.isfile(os.path.join(path, 'serverless.yml')): class_path = 'runway.module.serverless.Serverless' elif glob.glob(os.path.join(path, '*.tf')): class_path = 'runway.module.terraform.Terraform' elif os.path.isfile(os.path.join(path, 'cdk.json')) \ and os.path.isfile(os.path.join(path, 'package.json')): class_path = 'runway.module.cdk.CloudDevelopmentKit' elif glob.glob(os.path.join(path, '*.env')) or ( glob.glob(os.path.join(path, '*.yaml'))) or ( glob.glob(os.path.join(path, '*.yml'))): class_path = 'runway.module.cloudformation.CloudFormation' if not class_path: LOGGER.error('No module class found for %s', os.path.basename(path)) sys.exit(1) return load_object_from_string(class_path)
[ "def", "determine_module_class", "(", "path", ",", "class_path", ")", ":", "if", "not", "class_path", ":", "# First check directory name for type-indicating suffix", "basename", "=", "os", ".", "path", ".", "basename", "(", "path", ")", "if", "basename", ".", "end...
Determine type of module and return deployment module class.
[ "Determine", "type", "of", "module", "and", "return", "deployment", "module", "class", "." ]
3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f
https://github.com/onicagroup/runway/blob/3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f/runway/commands/modules_command.py#L54-L86
train
212,417
onicagroup/runway
runway/commands/modules_command.py
load_module_opts_from_file
def load_module_opts_from_file(path, module_options): """Update module_options with any options defined in module path.""" module_options_file = os.path.join(path, 'runway.module.yml') if os.path.isfile(module_options_file): with open(module_options_file, 'r') as stream: module_options = merge_dicts(module_options, yaml.safe_load(stream)) return module_options
python
def load_module_opts_from_file(path, module_options): """Update module_options with any options defined in module path.""" module_options_file = os.path.join(path, 'runway.module.yml') if os.path.isfile(module_options_file): with open(module_options_file, 'r') as stream: module_options = merge_dicts(module_options, yaml.safe_load(stream)) return module_options
[ "def", "load_module_opts_from_file", "(", "path", ",", "module_options", ")", ":", "module_options_file", "=", "os", ".", "path", ".", "join", "(", "path", ",", "'runway.module.yml'", ")", "if", "os", ".", "path", ".", "isfile", "(", "module_options_file", ")"...
Update module_options with any options defined in module path.
[ "Update", "module_options", "with", "any", "options", "defined", "in", "module", "path", "." ]
3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f
https://github.com/onicagroup/runway/blob/3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f/runway/commands/modules_command.py#L96-L104
train
212,418
onicagroup/runway
runway/commands/modules_command.py
post_deploy_assume_role
def post_deploy_assume_role(assume_role_config, context): """Revert to previous credentials, if necessary.""" if isinstance(assume_role_config, dict): if assume_role_config.get('post_deploy_env_revert'): context.restore_existing_iam_env_vars()
python
def post_deploy_assume_role(assume_role_config, context): """Revert to previous credentials, if necessary.""" if isinstance(assume_role_config, dict): if assume_role_config.get('post_deploy_env_revert'): context.restore_existing_iam_env_vars()
[ "def", "post_deploy_assume_role", "(", "assume_role_config", ",", "context", ")", ":", "if", "isinstance", "(", "assume_role_config", ",", "dict", ")", ":", "if", "assume_role_config", ".", "get", "(", "'post_deploy_env_revert'", ")", ":", "context", ".", "restore...
Revert to previous credentials, if necessary.
[ "Revert", "to", "previous", "credentials", "if", "necessary", "." ]
3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f
https://github.com/onicagroup/runway/blob/3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f/runway/commands/modules_command.py#L107-L111
train
212,419
onicagroup/runway
runway/commands/modules_command.py
validate_account_alias
def validate_account_alias(iam_client, account_alias): """Exit if list_account_aliases doesn't include account_alias.""" # Super overkill here using pagination when an account can only # have a single alias, but at least this implementation should be # future-proof current_account_aliases = [] paginator = iam_client.get_paginator('list_account_aliases') response_iterator = paginator.paginate() for page in response_iterator: current_account_aliases.extend(page.get('AccountAliases', [])) if account_alias in current_account_aliases: LOGGER.info('Verified current AWS account alias matches required ' 'alias %s.', account_alias) else: LOGGER.error('Current AWS account aliases "%s" do not match ' 'required account alias %s in Runway config.', ','.join(current_account_aliases), account_alias) sys.exit(1)
python
def validate_account_alias(iam_client, account_alias): """Exit if list_account_aliases doesn't include account_alias.""" # Super overkill here using pagination when an account can only # have a single alias, but at least this implementation should be # future-proof current_account_aliases = [] paginator = iam_client.get_paginator('list_account_aliases') response_iterator = paginator.paginate() for page in response_iterator: current_account_aliases.extend(page.get('AccountAliases', [])) if account_alias in current_account_aliases: LOGGER.info('Verified current AWS account alias matches required ' 'alias %s.', account_alias) else: LOGGER.error('Current AWS account aliases "%s" do not match ' 'required account alias %s in Runway config.', ','.join(current_account_aliases), account_alias) sys.exit(1)
[ "def", "validate_account_alias", "(", "iam_client", ",", "account_alias", ")", ":", "# Super overkill here using pagination when an account can only", "# have a single alias, but at least this implementation should be", "# future-proof", "current_account_aliases", "=", "[", "]", "pagin...
Exit if list_account_aliases doesn't include account_alias.
[ "Exit", "if", "list_account_aliases", "doesn", "t", "include", "account_alias", "." ]
3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f
https://github.com/onicagroup/runway/blob/3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f/runway/commands/modules_command.py#L155-L174
train
212,420
onicagroup/runway
runway/commands/modules_command.py
validate_account_id
def validate_account_id(sts_client, account_id): """Exit if get_caller_identity doesn't match account_id.""" resp = sts_client.get_caller_identity() if 'Account' in resp: if resp['Account'] == account_id: LOGGER.info('Verified current AWS account matches required ' 'account id %s.', account_id) else: LOGGER.error('Current AWS account %s does not match ' 'required account %s in Runway config.', resp['Account'], account_id) sys.exit(1) else: LOGGER.error('Error checking current account ID') sys.exit(1)
python
def validate_account_id(sts_client, account_id): """Exit if get_caller_identity doesn't match account_id.""" resp = sts_client.get_caller_identity() if 'Account' in resp: if resp['Account'] == account_id: LOGGER.info('Verified current AWS account matches required ' 'account id %s.', account_id) else: LOGGER.error('Current AWS account %s does not match ' 'required account %s in Runway config.', resp['Account'], account_id) sys.exit(1) else: LOGGER.error('Error checking current account ID') sys.exit(1)
[ "def", "validate_account_id", "(", "sts_client", ",", "account_id", ")", ":", "resp", "=", "sts_client", ".", "get_caller_identity", "(", ")", "if", "'Account'", "in", "resp", ":", "if", "resp", "[", "'Account'", "]", "==", "account_id", ":", "LOGGER", ".", ...
Exit if get_caller_identity doesn't match account_id.
[ "Exit", "if", "get_caller_identity", "doesn", "t", "match", "account_id", "." ]
3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f
https://github.com/onicagroup/runway/blob/3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f/runway/commands/modules_command.py#L177-L193
train
212,421
onicagroup/runway
runway/commands/modules_command.py
validate_account_credentials
def validate_account_credentials(deployment, context): """Exit if requested deployment account doesn't match credentials.""" boto_args = {'region_name': context.env_vars['AWS_DEFAULT_REGION']} for i in ['aws_access_key_id', 'aws_secret_access_key', 'aws_session_token']: if context.env_vars.get(i.upper()): boto_args[i] = context.env_vars[i.upper()] if isinstance(deployment.get('account-id'), (int, six.string_types)): account_id = str(deployment['account-id']) elif deployment.get('account-id', {}).get(context.env_name): account_id = str(deployment['account-id'][context.env_name]) else: account_id = None if account_id: validate_account_id(boto3.client('sts', **boto_args), account_id) if isinstance(deployment.get('account-alias'), six.string_types): account_alias = deployment['account-alias'] elif deployment.get('account-alias', {}).get(context.env_name): account_alias = deployment['account-alias'][context.env_name] else: account_alias = None if account_alias: validate_account_alias(boto3.client('iam', **boto_args), account_alias)
python
def validate_account_credentials(deployment, context): """Exit if requested deployment account doesn't match credentials.""" boto_args = {'region_name': context.env_vars['AWS_DEFAULT_REGION']} for i in ['aws_access_key_id', 'aws_secret_access_key', 'aws_session_token']: if context.env_vars.get(i.upper()): boto_args[i] = context.env_vars[i.upper()] if isinstance(deployment.get('account-id'), (int, six.string_types)): account_id = str(deployment['account-id']) elif deployment.get('account-id', {}).get(context.env_name): account_id = str(deployment['account-id'][context.env_name]) else: account_id = None if account_id: validate_account_id(boto3.client('sts', **boto_args), account_id) if isinstance(deployment.get('account-alias'), six.string_types): account_alias = deployment['account-alias'] elif deployment.get('account-alias', {}).get(context.env_name): account_alias = deployment['account-alias'][context.env_name] else: account_alias = None if account_alias: validate_account_alias(boto3.client('iam', **boto_args), account_alias)
[ "def", "validate_account_credentials", "(", "deployment", ",", "context", ")", ":", "boto_args", "=", "{", "'region_name'", ":", "context", ".", "env_vars", "[", "'AWS_DEFAULT_REGION'", "]", "}", "for", "i", "in", "[", "'aws_access_key_id'", ",", "'aws_secret_acce...
Exit if requested deployment account doesn't match credentials.
[ "Exit", "if", "requested", "deployment", "account", "doesn", "t", "match", "credentials", "." ]
3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f
https://github.com/onicagroup/runway/blob/3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f/runway/commands/modules_command.py#L196-L219
train
212,422
onicagroup/runway
runway/commands/modules_command.py
echo_detected_environment
def echo_detected_environment(env_name, env_vars): """Print a helper note about how the environment was determined.""" env_override_name = 'DEPLOY_ENVIRONMENT' LOGGER.info("") if env_override_name in env_vars: LOGGER.info("Environment \"%s\" was determined from the %s environment variable.", env_name, env_override_name) LOGGER.info("If this is not correct, update " "the value (or unset it to fall back to the name of " "the current git branch or parent directory).") else: LOGGER.info("Environment \"%s\" was determined from the current " "git branch or parent directory.", env_name) LOGGER.info("If this is not the environment name, update the branch/folder name or " "set an override value via the %s environment variable", env_override_name) LOGGER.info("")
python
def echo_detected_environment(env_name, env_vars): """Print a helper note about how the environment was determined.""" env_override_name = 'DEPLOY_ENVIRONMENT' LOGGER.info("") if env_override_name in env_vars: LOGGER.info("Environment \"%s\" was determined from the %s environment variable.", env_name, env_override_name) LOGGER.info("If this is not correct, update " "the value (or unset it to fall back to the name of " "the current git branch or parent directory).") else: LOGGER.info("Environment \"%s\" was determined from the current " "git branch or parent directory.", env_name) LOGGER.info("If this is not the environment name, update the branch/folder name or " "set an override value via the %s environment variable", env_override_name) LOGGER.info("")
[ "def", "echo_detected_environment", "(", "env_name", ",", "env_vars", ")", ":", "env_override_name", "=", "'DEPLOY_ENVIRONMENT'", "LOGGER", ".", "info", "(", "\"\"", ")", "if", "env_override_name", "in", "env_vars", ":", "LOGGER", ".", "info", "(", "\"Environment ...
Print a helper note about how the environment was determined.
[ "Print", "a", "helper", "note", "about", "how", "the", "environment", "was", "determined", "." ]
3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f
https://github.com/onicagroup/runway/blob/3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f/runway/commands/modules_command.py#L222-L240
train
212,423
onicagroup/runway
runway/commands/modules_command.py
_module_menu_entry
def _module_menu_entry(module, environment_name): """Build a string to display in the 'select module' menu.""" name = _module_name_for_display(module) if isinstance(module, dict): environment_config = module.get('environments', {}).get(environment_name) if environment_config: return "%s (%s)" % (name, environment_config) return "%s" % (name)
python
def _module_menu_entry(module, environment_name): """Build a string to display in the 'select module' menu.""" name = _module_name_for_display(module) if isinstance(module, dict): environment_config = module.get('environments', {}).get(environment_name) if environment_config: return "%s (%s)" % (name, environment_config) return "%s" % (name)
[ "def", "_module_menu_entry", "(", "module", ",", "environment_name", ")", ":", "name", "=", "_module_name_for_display", "(", "module", ")", "if", "isinstance", "(", "module", ",", "dict", ")", ":", "environment_config", "=", "module", ".", "get", "(", "'enviro...
Build a string to display in the 'select module' menu.
[ "Build", "a", "string", "to", "display", "in", "the", "select", "module", "menu", "." ]
3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f
https://github.com/onicagroup/runway/blob/3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f/runway/commands/modules_command.py#L473-L480
train
212,424
onicagroup/runway
runway/commands/modules_command.py
_deployment_menu_entry
def _deployment_menu_entry(deployment): """Build a string to display in the 'select deployment' menu.""" paths = ", ".join([_module_name_for_display(module) for module in deployment['modules']]) regions = ", ".join(deployment.get('regions', [])) return "%s - %s (%s)" % (deployment.get('name'), paths, regions)
python
def _deployment_menu_entry(deployment): """Build a string to display in the 'select deployment' menu.""" paths = ", ".join([_module_name_for_display(module) for module in deployment['modules']]) regions = ", ".join(deployment.get('regions', [])) return "%s - %s (%s)" % (deployment.get('name'), paths, regions)
[ "def", "_deployment_menu_entry", "(", "deployment", ")", ":", "paths", "=", "\", \"", ".", "join", "(", "[", "_module_name_for_display", "(", "module", ")", "for", "module", "in", "deployment", "[", "'modules'", "]", "]", ")", "regions", "=", "\", \"", ".", ...
Build a string to display in the 'select deployment' menu.
[ "Build", "a", "string", "to", "display", "in", "the", "select", "deployment", "menu", "." ]
3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f
https://github.com/onicagroup/runway/blob/3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f/runway/commands/modules_command.py#L483-L487
train
212,425
onicagroup/runway
runway/commands/modules_command.py
ModulesCommand.select_deployment_to_run
def select_deployment_to_run(env_name, deployments=None, command='build'): # noqa pylint: disable=too-many-branches,too-many-statements,too-many-locals """Query user for deployments to run.""" if deployments is None or not deployments: return [] deployments_to_run = [] num_deployments = len(deployments) if num_deployments == 1: selected_deployment_index = 1 else: print('') print('Configured deployments:') for i, deployment in enumerate(deployments): print(" %d: %s" % (i+1, _deployment_menu_entry(deployment))) print('') print('') if command == 'destroy': print('(Operating in destroy mode -- "all" will destroy all ' 'deployments in reverse order)') selected_deployment_index = input('Enter number of deployment to run (or "all"): ') if selected_deployment_index == 'all': return deployments if selected_deployment_index == '': LOGGER.error('Please select a valid number (or "all")') sys.exit(1) selected_deployment = deployments[int(selected_deployment_index) - 1] if selected_deployment.get('current_dir', False): deployments_to_run.append(selected_deployment) elif not selected_deployment.get('modules', []): LOGGER.error('No modules configured in selected deployment') sys.exit(1) elif len(selected_deployment['modules']) == 1: # No need to select a module in the deployment - there's only one if command == 'destroy': LOGGER.info('(only one deployment detected; all modules ' 'automatically selected for termination)') if not strtobool(input('Proceed?: ')): sys.exit(0) deployments_to_run.append(selected_deployment) else: modules = selected_deployment['modules'] print('') print('Configured modules in deployment \'%s\':' % selected_deployment.get('name')) for i, module in enumerate(modules): print(" %s: %s" % (i+1, _module_menu_entry(module, env_name))) print('') print('') if command == 'destroy': print('(Operating in destroy mode -- "all" will destroy all ' 'deployments in reverse order)') selected_module_index = input('Enter number of module to run (or "all"): ') if selected_module_index == 'all': deployments_to_run.append(selected_deployment) elif selected_module_index == '' or ( not selected_module_index.isdigit() or ( not 0 < int(selected_module_index) <= len(modules))): LOGGER.error('Please select a valid number (or "all")') sys.exit(1) else: selected_deployment['modules'] = [modules[int(selected_module_index) - 1]] deployments_to_run.append(selected_deployment) LOGGER.debug('Selected deployment is %s...', deployments_to_run) return deployments_to_run
python
def select_deployment_to_run(env_name, deployments=None, command='build'): # noqa pylint: disable=too-many-branches,too-many-statements,too-many-locals """Query user for deployments to run.""" if deployments is None or not deployments: return [] deployments_to_run = [] num_deployments = len(deployments) if num_deployments == 1: selected_deployment_index = 1 else: print('') print('Configured deployments:') for i, deployment in enumerate(deployments): print(" %d: %s" % (i+1, _deployment_menu_entry(deployment))) print('') print('') if command == 'destroy': print('(Operating in destroy mode -- "all" will destroy all ' 'deployments in reverse order)') selected_deployment_index = input('Enter number of deployment to run (or "all"): ') if selected_deployment_index == 'all': return deployments if selected_deployment_index == '': LOGGER.error('Please select a valid number (or "all")') sys.exit(1) selected_deployment = deployments[int(selected_deployment_index) - 1] if selected_deployment.get('current_dir', False): deployments_to_run.append(selected_deployment) elif not selected_deployment.get('modules', []): LOGGER.error('No modules configured in selected deployment') sys.exit(1) elif len(selected_deployment['modules']) == 1: # No need to select a module in the deployment - there's only one if command == 'destroy': LOGGER.info('(only one deployment detected; all modules ' 'automatically selected for termination)') if not strtobool(input('Proceed?: ')): sys.exit(0) deployments_to_run.append(selected_deployment) else: modules = selected_deployment['modules'] print('') print('Configured modules in deployment \'%s\':' % selected_deployment.get('name')) for i, module in enumerate(modules): print(" %s: %s" % (i+1, _module_menu_entry(module, env_name))) print('') print('') if command == 'destroy': print('(Operating in destroy mode -- "all" will destroy all ' 'deployments in reverse order)') selected_module_index = input('Enter number of module to run (or "all"): ') if selected_module_index == 'all': deployments_to_run.append(selected_deployment) elif selected_module_index == '' or ( not selected_module_index.isdigit() or ( not 0 < int(selected_module_index) <= len(modules))): LOGGER.error('Please select a valid number (or "all")') sys.exit(1) else: selected_deployment['modules'] = [modules[int(selected_module_index) - 1]] deployments_to_run.append(selected_deployment) LOGGER.debug('Selected deployment is %s...', deployments_to_run) return deployments_to_run
[ "def", "select_deployment_to_run", "(", "env_name", ",", "deployments", "=", "None", ",", "command", "=", "'build'", ")", ":", "# noqa pylint: disable=too-many-branches,too-many-statements,too-many-locals", "if", "deployments", "is", "None", "or", "not", "deployments", ":...
Query user for deployments to run.
[ "Query", "user", "for", "deployments", "to", "run", "." ]
3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f
https://github.com/onicagroup/runway/blob/3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f/runway/commands/modules_command.py#L397-L463
train
212,426
onicagroup/runway
runway/module/serverless.py
gen_sls_config_files
def gen_sls_config_files(stage, region): """Generate possible SLS config files names.""" names = [] for ext in ['yml', 'json']: # Give preference to explicit stage-region files names.append( os.path.join('env', "%s-%s.%s" % (stage, region, ext)) ) names.append("config-%s-%s.%s" % (stage, region, ext)) # Fallback to stage name only names.append( os.path.join('env', "%s.%s" % (stage, ext)) ) names.append("config-%s.%s" % (stage, ext)) return names
python
def gen_sls_config_files(stage, region): """Generate possible SLS config files names.""" names = [] for ext in ['yml', 'json']: # Give preference to explicit stage-region files names.append( os.path.join('env', "%s-%s.%s" % (stage, region, ext)) ) names.append("config-%s-%s.%s" % (stage, region, ext)) # Fallback to stage name only names.append( os.path.join('env', "%s.%s" % (stage, ext)) ) names.append("config-%s.%s" % (stage, ext)) return names
[ "def", "gen_sls_config_files", "(", "stage", ",", "region", ")", ":", "names", "=", "[", "]", "for", "ext", "in", "[", "'yml'", ",", "'json'", "]", ":", "# Give preference to explicit stage-region files", "names", ".", "append", "(", "os", ".", "path", ".", ...
Generate possible SLS config files names.
[ "Generate", "possible", "SLS", "config", "files", "names", "." ]
3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f
https://github.com/onicagroup/runway/blob/3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f/runway/module/serverless.py#L19-L35
train
212,427
onicagroup/runway
runway/module/serverless.py
get_sls_config_file
def get_sls_config_file(path, stage, region): """Determine Serverless config file name.""" for name in gen_sls_config_files(stage, region): if os.path.isfile(os.path.join(path, name)): return name return "config-%s.json" % stage
python
def get_sls_config_file(path, stage, region): """Determine Serverless config file name.""" for name in gen_sls_config_files(stage, region): if os.path.isfile(os.path.join(path, name)): return name return "config-%s.json" % stage
[ "def", "get_sls_config_file", "(", "path", ",", "stage", ",", "region", ")", ":", "for", "name", "in", "gen_sls_config_files", "(", "stage", ",", "region", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "os", ".", "path", ".", "join", "(", "p...
Determine Serverless config file name.
[ "Determine", "Serverless", "config", "file", "name", "." ]
3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f
https://github.com/onicagroup/runway/blob/3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f/runway/module/serverless.py#L38-L43
train
212,428
onicagroup/runway
runway/module/serverless.py
run_sls_remove
def run_sls_remove(sls_cmd, env_vars): """Run sls remove command.""" sls_process = subprocess.Popen(sls_cmd, stdout=subprocess.PIPE, env=env_vars) stdoutdata, _stderrdata = sls_process.communicate() sls_return = sls_process.wait() print(stdoutdata) if sls_return != 0 and (sls_return == 1 and not ( re.search(r"Stack '.*' does not exist", stdoutdata))): sys.exit(sls_return)
python
def run_sls_remove(sls_cmd, env_vars): """Run sls remove command.""" sls_process = subprocess.Popen(sls_cmd, stdout=subprocess.PIPE, env=env_vars) stdoutdata, _stderrdata = sls_process.communicate() sls_return = sls_process.wait() print(stdoutdata) if sls_return != 0 and (sls_return == 1 and not ( re.search(r"Stack '.*' does not exist", stdoutdata))): sys.exit(sls_return)
[ "def", "run_sls_remove", "(", "sls_cmd", ",", "env_vars", ")", ":", "sls_process", "=", "subprocess", ".", "Popen", "(", "sls_cmd", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "env", "=", "env_vars", ")", "stdoutdata", ",", "_stderrdata", "=", "sls...
Run sls remove command.
[ "Run", "sls", "remove", "command", "." ]
3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f
https://github.com/onicagroup/runway/blob/3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f/runway/module/serverless.py#L46-L56
train
212,429
onicagroup/runway
runway/module/serverless.py
Serverless.run_serverless
def run_serverless(self, command='deploy'): """Run Serverless.""" response = {'skipped_configs': False} sls_opts = [command] if not which('npm'): LOGGER.error('"npm" not found in path or is not executable; ' 'please ensure it is installed correctly.') sys.exit(1) if 'CI' in self.context.env_vars and command != 'remove': sls_opts.append('--conceal') # Hide secrets from serverless output if 'DEBUG' in self.context.env_vars: sls_opts.append('-v') # Increase logging if requested warn_on_boto_env_vars(self.context.env_vars) sls_opts.extend(['-r', self.context.env_region]) sls_opts.extend(['--stage', self.context.env_name]) sls_env_file = get_sls_config_file(self.path, self.context.env_name, self.context.env_region) sls_cmd = generate_node_command(command='sls', command_opts=sls_opts, path=self.path) if (not self.options.get('environments') and os.path.isfile(os.path.join(self.path, sls_env_file))) or ( # noqa pylint: disable=line-too-long self.options.get('environments', {}).get(self.context.env_name)): # noqa if os.path.isfile(os.path.join(self.path, 'package.json')): with change_dir(self.path): run_npm_install(self.path, self.options, self.context) LOGGER.info("Running sls %s on %s (\"%s\")", command, os.path.basename(self.path), format_npm_command_for_logging(sls_cmd)) if command == 'remove': # Need to account for exit code 1 on any removals after # the first run_sls_remove(sls_cmd, self.context.env_vars) else: run_module_command(cmd_list=sls_cmd, env_vars=self.context.env_vars) else: LOGGER.warning( "Skipping serverless %s of %s; no \"package.json\" " "file was found (need a package file specifying " "serverless in devDependencies)", command, os.path.basename(self.path)) else: response['skipped_configs'] = True LOGGER.info( "Skipping serverless %s of %s; no config file for " "this stage/region found (looking for one of \"%s\")", command, os.path.basename(self.path), ', '.join(gen_sls_config_files(self.context.env_name, self.context.env_region))) return response
python
def run_serverless(self, command='deploy'): """Run Serverless.""" response = {'skipped_configs': False} sls_opts = [command] if not which('npm'): LOGGER.error('"npm" not found in path or is not executable; ' 'please ensure it is installed correctly.') sys.exit(1) if 'CI' in self.context.env_vars and command != 'remove': sls_opts.append('--conceal') # Hide secrets from serverless output if 'DEBUG' in self.context.env_vars: sls_opts.append('-v') # Increase logging if requested warn_on_boto_env_vars(self.context.env_vars) sls_opts.extend(['-r', self.context.env_region]) sls_opts.extend(['--stage', self.context.env_name]) sls_env_file = get_sls_config_file(self.path, self.context.env_name, self.context.env_region) sls_cmd = generate_node_command(command='sls', command_opts=sls_opts, path=self.path) if (not self.options.get('environments') and os.path.isfile(os.path.join(self.path, sls_env_file))) or ( # noqa pylint: disable=line-too-long self.options.get('environments', {}).get(self.context.env_name)): # noqa if os.path.isfile(os.path.join(self.path, 'package.json')): with change_dir(self.path): run_npm_install(self.path, self.options, self.context) LOGGER.info("Running sls %s on %s (\"%s\")", command, os.path.basename(self.path), format_npm_command_for_logging(sls_cmd)) if command == 'remove': # Need to account for exit code 1 on any removals after # the first run_sls_remove(sls_cmd, self.context.env_vars) else: run_module_command(cmd_list=sls_cmd, env_vars=self.context.env_vars) else: LOGGER.warning( "Skipping serverless %s of %s; no \"package.json\" " "file was found (need a package file specifying " "serverless in devDependencies)", command, os.path.basename(self.path)) else: response['skipped_configs'] = True LOGGER.info( "Skipping serverless %s of %s; no config file for " "this stage/region found (looking for one of \"%s\")", command, os.path.basename(self.path), ', '.join(gen_sls_config_files(self.context.env_name, self.context.env_region))) return response
[ "def", "run_serverless", "(", "self", ",", "command", "=", "'deploy'", ")", ":", "response", "=", "{", "'skipped_configs'", ":", "False", "}", "sls_opts", "=", "[", "command", "]", "if", "not", "which", "(", "'npm'", ")", ":", "LOGGER", ".", "error", "...
Run Serverless.
[ "Run", "Serverless", "." ]
3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f
https://github.com/onicagroup/runway/blob/3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f/runway/module/serverless.py#L62-L122
train
212,430
onicagroup/runway
runway/hooks/staticsite/upload_staticsite.py
aws_cli
def aws_cli(*cmd): """Invoke aws command.""" old_env = dict(os.environ) try: # Environment env = os.environ.copy() env['LC_CTYPE'] = u'en_US.UTF' os.environ.update(env) # Run awscli in the same process exit_code = create_clidriver().main(*cmd) # Deal with problems if exit_code > 0: raise RuntimeError('AWS CLI exited with code {}'.format(exit_code)) finally: os.environ.clear() os.environ.update(old_env)
python
def aws_cli(*cmd): """Invoke aws command.""" old_env = dict(os.environ) try: # Environment env = os.environ.copy() env['LC_CTYPE'] = u'en_US.UTF' os.environ.update(env) # Run awscli in the same process exit_code = create_clidriver().main(*cmd) # Deal with problems if exit_code > 0: raise RuntimeError('AWS CLI exited with code {}'.format(exit_code)) finally: os.environ.clear() os.environ.update(old_env)
[ "def", "aws_cli", "(", "*", "cmd", ")", ":", "old_env", "=", "dict", "(", "os", ".", "environ", ")", "try", ":", "# Environment", "env", "=", "os", ".", "environ", ".", "copy", "(", ")", "env", "[", "'LC_CTYPE'", "]", "=", "u'en_US.UTF'", "os", "."...
Invoke aws command.
[ "Invoke", "aws", "command", "." ]
3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f
https://github.com/onicagroup/runway/blob/3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f/runway/hooks/staticsite/upload_staticsite.py#L17-L35
train
212,431
onicagroup/runway
runway/hooks/staticsite/upload_staticsite.py
get_archives_to_prune
def get_archives_to_prune(archives, hook_data): """Return list of keys to delete.""" files_to_skip = [] for i in ['current_archive_filename', 'old_archive_filename']: if hook_data.get(i): files_to_skip.append(hook_data[i]) archives.sort(key=itemgetter('LastModified'), reverse=False) # sort from oldest to newest # Drop all but last 15 files return [i['Key'] for i in archives[:-15] if i['Key'] not in files_to_skip]
python
def get_archives_to_prune(archives, hook_data): """Return list of keys to delete.""" files_to_skip = [] for i in ['current_archive_filename', 'old_archive_filename']: if hook_data.get(i): files_to_skip.append(hook_data[i]) archives.sort(key=itemgetter('LastModified'), reverse=False) # sort from oldest to newest # Drop all but last 15 files return [i['Key'] for i in archives[:-15] if i['Key'] not in files_to_skip]
[ "def", "get_archives_to_prune", "(", "archives", ",", "hook_data", ")", ":", "files_to_skip", "=", "[", "]", "for", "i", "in", "[", "'current_archive_filename'", ",", "'old_archive_filename'", "]", ":", "if", "hook_data", ".", "get", "(", "i", ")", ":", "fil...
Return list of keys to delete.
[ "Return", "list", "of", "keys", "to", "delete", "." ]
3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f
https://github.com/onicagroup/runway/blob/3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f/runway/hooks/staticsite/upload_staticsite.py#L38-L47
train
212,432
onicagroup/runway
runway/hooks/staticsite/upload_staticsite.py
sync
def sync(context, provider, **kwargs): # pylint: disable=too-many-locals """Sync static website to S3 bucket.""" session = get_session(provider.region) bucket_name = OutputLookup.handle(kwargs.get('bucket_output_lookup'), provider=provider, context=context) if context.hook_data['staticsite']['deploy_is_current']: LOGGER.info('staticsite: skipping upload; latest version already ' 'deployed') else: distribution_id = OutputLookup.handle( kwargs.get('distributionid_output_lookup'), provider=provider, context=context ) distribution_domain = OutputLookup.handle( kwargs.get('distributiondomain_output_lookup'), provider=provider, context=context ) # Using the awscli for s3 syncing is incredibly suboptimal, but on # balance it's probably the most stable/efficient option for syncing # the files until https://github.com/boto/boto3/issues/358 is resolved aws_cli(['s3', 'sync', context.hook_data['staticsite']['app_directory'], "s3://%s/" % bucket_name, '--delete']) cf_client = session.client('cloudfront') cf_client.create_invalidation( DistributionId=distribution_id, InvalidationBatch={'Paths': {'Quantity': 1, 'Items': ['/*']}, 'CallerReference': str(time.time())} ) LOGGER.info("staticsite: sync & CF invalidation of %s (domain %s) " "complete", distribution_id, distribution_domain) if not context.hook_data['staticsite'].get('hash_tracking_disabled'): LOGGER.info("staticsite: updating environment SSM parameter %s " "with hash %s", context.hook_data['staticsite']['hash_tracking_parameter'], # noqa context.hook_data['staticsite']['hash']) ssm_client = session.client('ssm') ssm_client.put_parameter( Name=context.hook_data['staticsite']['hash_tracking_parameter'], # noqa Description='Hash of currently deployed static website source', Value=context.hook_data['staticsite']['hash'], Type='String', Overwrite=True ) LOGGER.info("staticsite: cleaning up old site archives...") archives = [] s3_client = session.client('s3') list_objects_v2_paginator = s3_client.get_paginator('list_objects_v2') response_iterator = list_objects_v2_paginator.paginate( Bucket=context.hook_data['staticsite']['artifact_bucket_name'], Prefix=context.hook_data['staticsite']['artifact_key_prefix'] ) for page in response_iterator: archives.extend(page.get('Contents', [])) archives_to_prune = get_archives_to_prune( archives, context.hook_data['staticsite'] ) # Iterate in chunks of 1000 to match delete_objects limit for objects in [archives_to_prune[i:i + 1000] for i in range(0, len(archives_to_prune), 1000)]: s3_client.delete_objects( Bucket=context.hook_data['staticsite']['artifact_bucket_name'], Delete={'Objects': [{'Key': i} for i in objects]} ) return True
python
def sync(context, provider, **kwargs): # pylint: disable=too-many-locals """Sync static website to S3 bucket.""" session = get_session(provider.region) bucket_name = OutputLookup.handle(kwargs.get('bucket_output_lookup'), provider=provider, context=context) if context.hook_data['staticsite']['deploy_is_current']: LOGGER.info('staticsite: skipping upload; latest version already ' 'deployed') else: distribution_id = OutputLookup.handle( kwargs.get('distributionid_output_lookup'), provider=provider, context=context ) distribution_domain = OutputLookup.handle( kwargs.get('distributiondomain_output_lookup'), provider=provider, context=context ) # Using the awscli for s3 syncing is incredibly suboptimal, but on # balance it's probably the most stable/efficient option for syncing # the files until https://github.com/boto/boto3/issues/358 is resolved aws_cli(['s3', 'sync', context.hook_data['staticsite']['app_directory'], "s3://%s/" % bucket_name, '--delete']) cf_client = session.client('cloudfront') cf_client.create_invalidation( DistributionId=distribution_id, InvalidationBatch={'Paths': {'Quantity': 1, 'Items': ['/*']}, 'CallerReference': str(time.time())} ) LOGGER.info("staticsite: sync & CF invalidation of %s (domain %s) " "complete", distribution_id, distribution_domain) if not context.hook_data['staticsite'].get('hash_tracking_disabled'): LOGGER.info("staticsite: updating environment SSM parameter %s " "with hash %s", context.hook_data['staticsite']['hash_tracking_parameter'], # noqa context.hook_data['staticsite']['hash']) ssm_client = session.client('ssm') ssm_client.put_parameter( Name=context.hook_data['staticsite']['hash_tracking_parameter'], # noqa Description='Hash of currently deployed static website source', Value=context.hook_data['staticsite']['hash'], Type='String', Overwrite=True ) LOGGER.info("staticsite: cleaning up old site archives...") archives = [] s3_client = session.client('s3') list_objects_v2_paginator = s3_client.get_paginator('list_objects_v2') response_iterator = list_objects_v2_paginator.paginate( Bucket=context.hook_data['staticsite']['artifact_bucket_name'], Prefix=context.hook_data['staticsite']['artifact_key_prefix'] ) for page in response_iterator: archives.extend(page.get('Contents', [])) archives_to_prune = get_archives_to_prune( archives, context.hook_data['staticsite'] ) # Iterate in chunks of 1000 to match delete_objects limit for objects in [archives_to_prune[i:i + 1000] for i in range(0, len(archives_to_prune), 1000)]: s3_client.delete_objects( Bucket=context.hook_data['staticsite']['artifact_bucket_name'], Delete={'Objects': [{'Key': i} for i in objects]} ) return True
[ "def", "sync", "(", "context", ",", "provider", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=too-many-locals", "session", "=", "get_session", "(", "provider", ".", "region", ")", "bucket_name", "=", "OutputLookup", ".", "handle", "(", "kwargs", ".", ...
Sync static website to S3 bucket.
[ "Sync", "static", "website", "to", "S3", "bucket", "." ]
3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f
https://github.com/onicagroup/runway/blob/3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f/runway/hooks/staticsite/upload_staticsite.py#L50-L126
train
212,433
onicagroup/runway
runway/module/cloudformation.py
ensure_stacker_compat_config
def ensure_stacker_compat_config(config_filename): """Ensure config file can be loaded by Stacker.""" try: with open(config_filename, 'r') as stream: yaml.safe_load(stream) except yaml.constructor.ConstructorError as yaml_error: if yaml_error.problem.startswith( 'could not determine a constructor for the tag \'!'): LOGGER.error('"%s" appears to be a CloudFormation template, ' 'but is located in the top level of a module ' 'alongside the CloudFormation config files (i.e. ' 'the file or files indicating the stack names & ' 'parameters). Please move the template to a ' 'subdirectory.', config_filename) sys.exit(1)
python
def ensure_stacker_compat_config(config_filename): """Ensure config file can be loaded by Stacker.""" try: with open(config_filename, 'r') as stream: yaml.safe_load(stream) except yaml.constructor.ConstructorError as yaml_error: if yaml_error.problem.startswith( 'could not determine a constructor for the tag \'!'): LOGGER.error('"%s" appears to be a CloudFormation template, ' 'but is located in the top level of a module ' 'alongside the CloudFormation config files (i.e. ' 'the file or files indicating the stack names & ' 'parameters). Please move the template to a ' 'subdirectory.', config_filename) sys.exit(1)
[ "def", "ensure_stacker_compat_config", "(", "config_filename", ")", ":", "try", ":", "with", "open", "(", "config_filename", ",", "'r'", ")", "as", "stream", ":", "yaml", ".", "safe_load", "(", "stream", ")", "except", "yaml", ".", "constructor", ".", "Const...
Ensure config file can be loaded by Stacker.
[ "Ensure", "config", "file", "can", "be", "loaded", "by", "Stacker", "." ]
3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f
https://github.com/onicagroup/runway/blob/3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f/runway/module/cloudformation.py#L17-L32
train
212,434
onicagroup/runway
runway/module/cloudformation.py
get_stacker_env_file
def get_stacker_env_file(path, environment, region): """Determine Stacker environment file name.""" for name in gen_stacker_env_files(environment, region): if os.path.isfile(os.path.join(path, name)): return name return "%s-%s.env" % (environment, region)
python
def get_stacker_env_file(path, environment, region): """Determine Stacker environment file name.""" for name in gen_stacker_env_files(environment, region): if os.path.isfile(os.path.join(path, name)): return name return "%s-%s.env" % (environment, region)
[ "def", "get_stacker_env_file", "(", "path", ",", "environment", ",", "region", ")", ":", "for", "name", "in", "gen_stacker_env_files", "(", "environment", ",", "region", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "os", ".", "path", ".", "join...
Determine Stacker environment file name.
[ "Determine", "Stacker", "environment", "file", "name", "." ]
3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f
https://github.com/onicagroup/runway/blob/3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f/runway/module/cloudformation.py#L45-L50
train
212,435
onicagroup/runway
runway/module/cloudformation.py
make_stacker_cmd_string
def make_stacker_cmd_string(args, lib_path): """Generate stacker invocation script from command line arg list. This is the standard stacker invocation script, with the following changes: * Adding our explicit arguments to parse_args (instead of leaving it empty) * Overriding sys.argv * Adding embedded runway lib directory to sys.path """ if platform.system().lower() == 'windows': # Because this will be run via subprocess, the backslashes on Windows # will cause command errors lib_path = lib_path.replace('\\', '/') return ("import sys;" "sys.argv = ['stacker'] + {args};" "sys.path.insert(1, '{lib_path}');" "from stacker.logger import setup_logging;" "from stacker.commands import Stacker;" "stacker = Stacker(setup_logging=setup_logging);" "args = stacker.parse_args({args});" "stacker.configure(args);args.run(args)".format(args=str(args), lib_path=lib_path))
python
def make_stacker_cmd_string(args, lib_path): """Generate stacker invocation script from command line arg list. This is the standard stacker invocation script, with the following changes: * Adding our explicit arguments to parse_args (instead of leaving it empty) * Overriding sys.argv * Adding embedded runway lib directory to sys.path """ if platform.system().lower() == 'windows': # Because this will be run via subprocess, the backslashes on Windows # will cause command errors lib_path = lib_path.replace('\\', '/') return ("import sys;" "sys.argv = ['stacker'] + {args};" "sys.path.insert(1, '{lib_path}');" "from stacker.logger import setup_logging;" "from stacker.commands import Stacker;" "stacker = Stacker(setup_logging=setup_logging);" "args = stacker.parse_args({args});" "stacker.configure(args);args.run(args)".format(args=str(args), lib_path=lib_path))
[ "def", "make_stacker_cmd_string", "(", "args", ",", "lib_path", ")", ":", "if", "platform", ".", "system", "(", ")", ".", "lower", "(", ")", "==", "'windows'", ":", "# Because this will be run via subprocess, the backslashes on Windows", "# will cause command errors", "...
Generate stacker invocation script from command line arg list. This is the standard stacker invocation script, with the following changes: * Adding our explicit arguments to parse_args (instead of leaving it empty) * Overriding sys.argv * Adding embedded runway lib directory to sys.path
[ "Generate", "stacker", "invocation", "script", "from", "command", "line", "arg", "list", "." ]
3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f
https://github.com/onicagroup/runway/blob/3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f/runway/module/cloudformation.py#L53-L73
train
212,436
onicagroup/runway
runway/module/cloudformation.py
CloudFormation.run_stacker
def run_stacker(self, command='diff'): # pylint: disable=too-many-branches,too-many-locals """Run Stacker.""" response = {'skipped_configs': False} stacker_cmd = [command, "--region=%s" % self.context.env_region] if command == 'destroy': stacker_cmd.append('--force') elif command == 'build': if 'CI' in self.context.env_vars: stacker_cmd.append('--recreate-failed') else: stacker_cmd.append('--interactive') if 'DEBUG' in self.context.env_vars: stacker_cmd.append('--verbose') # Increase logging if requested stacker_env_file = get_stacker_env_file(self.path, self.context.env_name, self.context.env_region) stacker_env_file_present = os.path.isfile( os.path.join(self.path, stacker_env_file) ) if isinstance(self.options.get('environments', {}).get(self.context.env_name), dict): for (key, val) in self.options['environments'][self.context.env_name].items(): # noqa stacker_cmd.extend(['-e', "%s=%s" % (key, val)]) if stacker_env_file_present: stacker_cmd.append(stacker_env_file) if not (stacker_env_file_present or self.options.get( 'environments', {}).get(self.context.env_name)): response['skipped_configs'] = True LOGGER.info( "Skipping stacker %s; no environment " "file found for this environment/region " "(looking for one of \"%s\")", command, ', '.join( gen_stacker_env_files(self.context.env_name, # noqa self.context.env_region)) # noqa ) else: with change_dir(self.path): # Iterate through any stacker yaml configs to deploy them in order # or destroy them in reverse order for _root, _dirs, files in os.walk(self.path): sorted_files = sorted(files) if command == 'destroy': sorted_files = reversed(sorted_files) for name in sorted_files: if re.match(r"runway(\..*)?\.yml", name) or ( name.startswith('.')): # Hidden files (e.g. .gitlab-ci.yml) or runway configs # definitely aren't stacker config files continue if os.path.splitext(name)[1] in ['.yaml', '.yml']: ensure_stacker_compat_config( os.path.join(self.path, name) ) LOGGER.info("Running stacker %s on %s in region %s", command, name, self.context.env_region) stacker_cmd_str = make_stacker_cmd_string( stacker_cmd + [name], get_embedded_lib_path() ) stacker_cmd_list = [sys.executable, '-c'] LOGGER.debug( "Stacker command being executed: %s \"%s\"", ' '.join(stacker_cmd_list), stacker_cmd_str ) run_module_command( cmd_list=stacker_cmd_list + [stacker_cmd_str], env_vars=self.context.env_vars ) break # only need top level files return response
python
def run_stacker(self, command='diff'): # pylint: disable=too-many-branches,too-many-locals """Run Stacker.""" response = {'skipped_configs': False} stacker_cmd = [command, "--region=%s" % self.context.env_region] if command == 'destroy': stacker_cmd.append('--force') elif command == 'build': if 'CI' in self.context.env_vars: stacker_cmd.append('--recreate-failed') else: stacker_cmd.append('--interactive') if 'DEBUG' in self.context.env_vars: stacker_cmd.append('--verbose') # Increase logging if requested stacker_env_file = get_stacker_env_file(self.path, self.context.env_name, self.context.env_region) stacker_env_file_present = os.path.isfile( os.path.join(self.path, stacker_env_file) ) if isinstance(self.options.get('environments', {}).get(self.context.env_name), dict): for (key, val) in self.options['environments'][self.context.env_name].items(): # noqa stacker_cmd.extend(['-e', "%s=%s" % (key, val)]) if stacker_env_file_present: stacker_cmd.append(stacker_env_file) if not (stacker_env_file_present or self.options.get( 'environments', {}).get(self.context.env_name)): response['skipped_configs'] = True LOGGER.info( "Skipping stacker %s; no environment " "file found for this environment/region " "(looking for one of \"%s\")", command, ', '.join( gen_stacker_env_files(self.context.env_name, # noqa self.context.env_region)) # noqa ) else: with change_dir(self.path): # Iterate through any stacker yaml configs to deploy them in order # or destroy them in reverse order for _root, _dirs, files in os.walk(self.path): sorted_files = sorted(files) if command == 'destroy': sorted_files = reversed(sorted_files) for name in sorted_files: if re.match(r"runway(\..*)?\.yml", name) or ( name.startswith('.')): # Hidden files (e.g. .gitlab-ci.yml) or runway configs # definitely aren't stacker config files continue if os.path.splitext(name)[1] in ['.yaml', '.yml']: ensure_stacker_compat_config( os.path.join(self.path, name) ) LOGGER.info("Running stacker %s on %s in region %s", command, name, self.context.env_region) stacker_cmd_str = make_stacker_cmd_string( stacker_cmd + [name], get_embedded_lib_path() ) stacker_cmd_list = [sys.executable, '-c'] LOGGER.debug( "Stacker command being executed: %s \"%s\"", ' '.join(stacker_cmd_list), stacker_cmd_str ) run_module_command( cmd_list=stacker_cmd_list + [stacker_cmd_str], env_vars=self.context.env_vars ) break # only need top level files return response
[ "def", "run_stacker", "(", "self", ",", "command", "=", "'diff'", ")", ":", "# pylint: disable=too-many-branches,too-many-locals", "response", "=", "{", "'skipped_configs'", ":", "False", "}", "stacker_cmd", "=", "[", "command", ",", "\"--region=%s\"", "%", "self", ...
Run Stacker.
[ "Run", "Stacker", "." ]
3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f
https://github.com/onicagroup/runway/blob/3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f/runway/module/cloudformation.py#L79-L159
train
212,437
onicagroup/runway
runway/blueprints/staticsite/staticsite.py
get_cf_distribution_class
def get_cf_distribution_class(): """Return the correct troposphere CF distribution class.""" if LooseVersion(troposphere.__version__) == LooseVersion('2.4.0'): cf_dist = cloudfront.Distribution cf_dist.props['DistributionConfig'] = (DistributionConfig, True) return cf_dist return cloudfront.Distribution
python
def get_cf_distribution_class(): """Return the correct troposphere CF distribution class.""" if LooseVersion(troposphere.__version__) == LooseVersion('2.4.0'): cf_dist = cloudfront.Distribution cf_dist.props['DistributionConfig'] = (DistributionConfig, True) return cf_dist return cloudfront.Distribution
[ "def", "get_cf_distribution_class", "(", ")", ":", "if", "LooseVersion", "(", "troposphere", ".", "__version__", ")", "==", "LooseVersion", "(", "'2.4.0'", ")", ":", "cf_dist", "=", "cloudfront", ".", "Distribution", "cf_dist", ".", "props", "[", "'DistributionC...
Return the correct troposphere CF distribution class.
[ "Return", "the", "correct", "troposphere", "CF", "distribution", "class", "." ]
3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f
https://github.com/onicagroup/runway/blob/3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f/runway/blueprints/staticsite/staticsite.py#L366-L372
train
212,438
onicagroup/runway
runway/blueprints/staticsite/staticsite.py
get_s3_origin_conf_class
def get_s3_origin_conf_class(): """Return the correct S3 Origin Config class for troposphere.""" if LooseVersion(troposphere.__version__) > LooseVersion('2.4.0'): return cloudfront.S3OriginConfig if LooseVersion(troposphere.__version__) == LooseVersion('2.4.0'): return S3OriginConfig return cloudfront.S3Origin
python
def get_s3_origin_conf_class(): """Return the correct S3 Origin Config class for troposphere.""" if LooseVersion(troposphere.__version__) > LooseVersion('2.4.0'): return cloudfront.S3OriginConfig if LooseVersion(troposphere.__version__) == LooseVersion('2.4.0'): return S3OriginConfig return cloudfront.S3Origin
[ "def", "get_s3_origin_conf_class", "(", ")", ":", "if", "LooseVersion", "(", "troposphere", ".", "__version__", ")", ">", "LooseVersion", "(", "'2.4.0'", ")", ":", "return", "cloudfront", ".", "S3OriginConfig", "if", "LooseVersion", "(", "troposphere", ".", "__v...
Return the correct S3 Origin Config class for troposphere.
[ "Return", "the", "correct", "S3", "Origin", "Config", "class", "for", "troposphere", "." ]
3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f
https://github.com/onicagroup/runway/blob/3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f/runway/blueprints/staticsite/staticsite.py#L389-L395
train
212,439
javipalanca/spade
spade/presence.py
PresenceManager.set_available
def set_available(self, show=None): """ Sets the agent availability to True. Args: show (aioxmpp.PresenceShow, optional): the show state of the presence (Default value = None) """ show = self.state.show if show is None else show self.set_presence(PresenceState(available=True, show=show))
python
def set_available(self, show=None): """ Sets the agent availability to True. Args: show (aioxmpp.PresenceShow, optional): the show state of the presence (Default value = None) """ show = self.state.show if show is None else show self.set_presence(PresenceState(available=True, show=show))
[ "def", "set_available", "(", "self", ",", "show", "=", "None", ")", ":", "show", "=", "self", ".", "state", ".", "show", "if", "show", "is", "None", "else", "show", "self", ".", "set_presence", "(", "PresenceState", "(", "available", "=", "True", ",", ...
Sets the agent availability to True. Args: show (aioxmpp.PresenceShow, optional): the show state of the presence (Default value = None)
[ "Sets", "the", "agent", "availability", "to", "True", "." ]
59942bd1a1edae4c807d06cabb178d5630cbf61b
https://github.com/javipalanca/spade/blob/59942bd1a1edae4c807d06cabb178d5630cbf61b/spade/presence.py#L94-L103
train
212,440
javipalanca/spade
spade/presence.py
PresenceManager.set_unavailable
def set_unavailable(self): """Sets the agent availability to False.""" show = PresenceShow.NONE self.set_presence(PresenceState(available=False, show=show))
python
def set_unavailable(self): """Sets the agent availability to False.""" show = PresenceShow.NONE self.set_presence(PresenceState(available=False, show=show))
[ "def", "set_unavailable", "(", "self", ")", ":", "show", "=", "PresenceShow", ".", "NONE", "self", ".", "set_presence", "(", "PresenceState", "(", "available", "=", "False", ",", "show", "=", "show", ")", ")" ]
Sets the agent availability to False.
[ "Sets", "the", "agent", "availability", "to", "False", "." ]
59942bd1a1edae4c807d06cabb178d5630cbf61b
https://github.com/javipalanca/spade/blob/59942bd1a1edae4c807d06cabb178d5630cbf61b/spade/presence.py#L105-L108
train
212,441
javipalanca/spade
spade/presence.py
PresenceManager.set_presence
def set_presence(self, state=None, status=None, priority=None): """ Change the presence broadcast by the client. If the client is currently connected, the new presence is broadcast immediately. Args: state(aioxmpp.PresenceState, optional): New presence state to broadcast (Default value = None) status(dict or str, optional): New status information to broadcast (Default value = None) priority (int, optional): New priority for the resource (Default value = None) """ state = state if state is not None else self.state status = status if status is not None else self.status priority = priority if priority is not None else self.priority self.presenceserver.set_presence(state, status, priority)
python
def set_presence(self, state=None, status=None, priority=None): """ Change the presence broadcast by the client. If the client is currently connected, the new presence is broadcast immediately. Args: state(aioxmpp.PresenceState, optional): New presence state to broadcast (Default value = None) status(dict or str, optional): New status information to broadcast (Default value = None) priority (int, optional): New priority for the resource (Default value = None) """ state = state if state is not None else self.state status = status if status is not None else self.status priority = priority if priority is not None else self.priority self.presenceserver.set_presence(state, status, priority)
[ "def", "set_presence", "(", "self", ",", "state", "=", "None", ",", "status", "=", "None", ",", "priority", "=", "None", ")", ":", "state", "=", "state", "if", "state", "is", "not", "None", "else", "self", ".", "state", "status", "=", "status", "if",...
Change the presence broadcast by the client. If the client is currently connected, the new presence is broadcast immediately. Args: state(aioxmpp.PresenceState, optional): New presence state to broadcast (Default value = None) status(dict or str, optional): New status information to broadcast (Default value = None) priority (int, optional): New priority for the resource (Default value = None)
[ "Change", "the", "presence", "broadcast", "by", "the", "client", ".", "If", "the", "client", "is", "currently", "connected", "the", "new", "presence", "is", "broadcast", "immediately", "." ]
59942bd1a1edae4c807d06cabb178d5630cbf61b
https://github.com/javipalanca/spade/blob/59942bd1a1edae4c807d06cabb178d5630cbf61b/spade/presence.py#L110-L124
train
212,442
javipalanca/spade
spade/presence.py
PresenceManager.get_contacts
def get_contacts(self): """ Returns list of contacts Returns: dict: the roster of contacts """ for jid, item in self.roster.items.items(): try: self._contacts[jid.bare()].update(item.export_as_json()) except KeyError: self._contacts[jid.bare()] = item.export_as_json() return self._contacts
python
def get_contacts(self): """ Returns list of contacts Returns: dict: the roster of contacts """ for jid, item in self.roster.items.items(): try: self._contacts[jid.bare()].update(item.export_as_json()) except KeyError: self._contacts[jid.bare()] = item.export_as_json() return self._contacts
[ "def", "get_contacts", "(", "self", ")", ":", "for", "jid", ",", "item", "in", "self", ".", "roster", ".", "items", ".", "items", "(", ")", ":", "try", ":", "self", ".", "_contacts", "[", "jid", ".", "bare", "(", ")", "]", ".", "update", "(", "...
Returns list of contacts Returns: dict: the roster of contacts
[ "Returns", "list", "of", "contacts" ]
59942bd1a1edae4c807d06cabb178d5630cbf61b
https://github.com/javipalanca/spade/blob/59942bd1a1edae4c807d06cabb178d5630cbf61b/spade/presence.py#L126-L140
train
212,443
javipalanca/spade
spade/presence.py
PresenceManager.get_contact
def get_contact(self, jid): """ Returns a contact Args: jid (aioxmpp.JID): jid of the contact Returns: dict: the roster of contacts """ try: return self.get_contacts()[jid.bare()] except KeyError: raise ContactNotFound except AttributeError: raise AttributeError("jid must be an aioxmpp.JID object")
python
def get_contact(self, jid): """ Returns a contact Args: jid (aioxmpp.JID): jid of the contact Returns: dict: the roster of contacts """ try: return self.get_contacts()[jid.bare()] except KeyError: raise ContactNotFound except AttributeError: raise AttributeError("jid must be an aioxmpp.JID object")
[ "def", "get_contact", "(", "self", ",", "jid", ")", ":", "try", ":", "return", "self", ".", "get_contacts", "(", ")", "[", "jid", ".", "bare", "(", ")", "]", "except", "KeyError", ":", "raise", "ContactNotFound", "except", "AttributeError", ":", "raise",...
Returns a contact Args: jid (aioxmpp.JID): jid of the contact Returns: dict: the roster of contacts
[ "Returns", "a", "contact" ]
59942bd1a1edae4c807d06cabb178d5630cbf61b
https://github.com/javipalanca/spade/blob/59942bd1a1edae4c807d06cabb178d5630cbf61b/spade/presence.py#L142-L158
train
212,444
javipalanca/spade
spade/presence.py
PresenceManager.subscribe
def subscribe(self, peer_jid): """ Asks for subscription Args: peer_jid (str): the JID you ask for subscriptiion """ self.roster.subscribe(aioxmpp.JID.fromstr(peer_jid).bare())
python
def subscribe(self, peer_jid): """ Asks for subscription Args: peer_jid (str): the JID you ask for subscriptiion """ self.roster.subscribe(aioxmpp.JID.fromstr(peer_jid).bare())
[ "def", "subscribe", "(", "self", ",", "peer_jid", ")", ":", "self", ".", "roster", ".", "subscribe", "(", "aioxmpp", ".", "JID", ".", "fromstr", "(", "peer_jid", ")", ".", "bare", "(", ")", ")" ]
Asks for subscription Args: peer_jid (str): the JID you ask for subscriptiion
[ "Asks", "for", "subscription" ]
59942bd1a1edae4c807d06cabb178d5630cbf61b
https://github.com/javipalanca/spade/blob/59942bd1a1edae4c807d06cabb178d5630cbf61b/spade/presence.py#L169-L177
train
212,445
javipalanca/spade
spade/presence.py
PresenceManager.unsubscribe
def unsubscribe(self, peer_jid): """ Asks for unsubscription Args: peer_jid (str): the JID you ask for unsubscriptiion """ self.roster.unsubscribe(aioxmpp.JID.fromstr(peer_jid).bare())
python
def unsubscribe(self, peer_jid): """ Asks for unsubscription Args: peer_jid (str): the JID you ask for unsubscriptiion """ self.roster.unsubscribe(aioxmpp.JID.fromstr(peer_jid).bare())
[ "def", "unsubscribe", "(", "self", ",", "peer_jid", ")", ":", "self", ".", "roster", ".", "unsubscribe", "(", "aioxmpp", ".", "JID", ".", "fromstr", "(", "peer_jid", ")", ".", "bare", "(", ")", ")" ]
Asks for unsubscription Args: peer_jid (str): the JID you ask for unsubscriptiion
[ "Asks", "for", "unsubscription" ]
59942bd1a1edae4c807d06cabb178d5630cbf61b
https://github.com/javipalanca/spade/blob/59942bd1a1edae4c807d06cabb178d5630cbf61b/spade/presence.py#L179-L187
train
212,446
javipalanca/spade
spade/presence.py
PresenceManager.approve
def approve(self, peer_jid): """ Approve a subscription request from jid Args: peer_jid (str): the JID to approve """ self.roster.approve(aioxmpp.JID.fromstr(peer_jid).bare())
python
def approve(self, peer_jid): """ Approve a subscription request from jid Args: peer_jid (str): the JID to approve """ self.roster.approve(aioxmpp.JID.fromstr(peer_jid).bare())
[ "def", "approve", "(", "self", ",", "peer_jid", ")", ":", "self", ".", "roster", ".", "approve", "(", "aioxmpp", ".", "JID", ".", "fromstr", "(", "peer_jid", ")", ".", "bare", "(", ")", ")" ]
Approve a subscription request from jid Args: peer_jid (str): the JID to approve
[ "Approve", "a", "subscription", "request", "from", "jid" ]
59942bd1a1edae4c807d06cabb178d5630cbf61b
https://github.com/javipalanca/spade/blob/59942bd1a1edae4c807d06cabb178d5630cbf61b/spade/presence.py#L189-L197
train
212,447
javipalanca/spade
spade/trace.py
TraceStore.append
def append(self, event, category=None): """ Adds a new event to the trace store. The event may hava a category Args: event (spade.message.Message): the event to be stored category (str, optional): a category to classify the event (Default value = None) """ date = datetime.datetime.now() self.store.insert(0, (date, event, category)) if len(self.store) > self.size: del self.store[-1]
python
def append(self, event, category=None): """ Adds a new event to the trace store. The event may hava a category Args: event (spade.message.Message): the event to be stored category (str, optional): a category to classify the event (Default value = None) """ date = datetime.datetime.now() self.store.insert(0, (date, event, category)) if len(self.store) > self.size: del self.store[-1]
[ "def", "append", "(", "self", ",", "event", ",", "category", "=", "None", ")", ":", "date", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "self", ".", "store", ".", "insert", "(", "0", ",", "(", "date", ",", "event", ",", "category", ")...
Adds a new event to the trace store. The event may hava a category Args: event (spade.message.Message): the event to be stored category (str, optional): a category to classify the event (Default value = None)
[ "Adds", "a", "new", "event", "to", "the", "trace", "store", ".", "The", "event", "may", "hava", "a", "category" ]
59942bd1a1edae4c807d06cabb178d5630cbf61b
https://github.com/javipalanca/spade/blob/59942bd1a1edae4c807d06cabb178d5630cbf61b/spade/trace.py#L22-L35
train
212,448
javipalanca/spade
spade/trace.py
TraceStore.filter
def filter(self, limit=None, to=None, category=None): """ Returns the events that match the filters Args: limit (int, optional): the max length of the events to return (Default value = None) to (str, optional): only events that have been sent or received by 'to' (Default value = None) category (str, optional): only events belonging to the category (Default value = None) Returns: list: a list of filtered events """ if category and not to: msg_slice = itertools.islice((x for x in self.store if x[2] == category), limit) elif to and not category: to = JID.fromstr(to) msg_slice = itertools.islice((x for x in self.store if _agent_in_msg(to, x[1])), limit) elif to and category: to = JID.fromstr(to) msg_slice = itertools.islice((x for x in self.store if _agent_in_msg(to, x[1]) and x[2] == category), limit) else: msg_slice = self.all(limit=limit) return msg_slice return list(msg_slice)[::-1]
python
def filter(self, limit=None, to=None, category=None): """ Returns the events that match the filters Args: limit (int, optional): the max length of the events to return (Default value = None) to (str, optional): only events that have been sent or received by 'to' (Default value = None) category (str, optional): only events belonging to the category (Default value = None) Returns: list: a list of filtered events """ if category and not to: msg_slice = itertools.islice((x for x in self.store if x[2] == category), limit) elif to and not category: to = JID.fromstr(to) msg_slice = itertools.islice((x for x in self.store if _agent_in_msg(to, x[1])), limit) elif to and category: to = JID.fromstr(to) msg_slice = itertools.islice((x for x in self.store if _agent_in_msg(to, x[1]) and x[2] == category), limit) else: msg_slice = self.all(limit=limit) return msg_slice return list(msg_slice)[::-1]
[ "def", "filter", "(", "self", ",", "limit", "=", "None", ",", "to", "=", "None", ",", "category", "=", "None", ")", ":", "if", "category", "and", "not", "to", ":", "msg_slice", "=", "itertools", ".", "islice", "(", "(", "x", "for", "x", "in", "se...
Returns the events that match the filters Args: limit (int, optional): the max length of the events to return (Default value = None) to (str, optional): only events that have been sent or received by 'to' (Default value = None) category (str, optional): only events belonging to the category (Default value = None) Returns: list: a list of filtered events
[ "Returns", "the", "events", "that", "match", "the", "filters" ]
59942bd1a1edae4c807d06cabb178d5630cbf61b
https://github.com/javipalanca/spade/blob/59942bd1a1edae4c807d06cabb178d5630cbf61b/spade/trace.py#L73-L98
train
212,449
javipalanca/spade
spade/agent.py
Agent.start
def start(self, auto_register=True): """ Tells the container to start this agent. It returns a coroutine or a future depending on whether it is called from a coroutine or a synchronous method. Args: auto_register (bool): register the agent in the server (Default value = True) """ return self.container.start_agent(agent=self, auto_register=auto_register)
python
def start(self, auto_register=True): """ Tells the container to start this agent. It returns a coroutine or a future depending on whether it is called from a coroutine or a synchronous method. Args: auto_register (bool): register the agent in the server (Default value = True) """ return self.container.start_agent(agent=self, auto_register=auto_register)
[ "def", "start", "(", "self", ",", "auto_register", "=", "True", ")", ":", "return", "self", ".", "container", ".", "start_agent", "(", "agent", "=", "self", ",", "auto_register", "=", "auto_register", ")" ]
Tells the container to start this agent. It returns a coroutine or a future depending on whether it is called from a coroutine or a synchronous method. Args: auto_register (bool): register the agent in the server (Default value = True)
[ "Tells", "the", "container", "to", "start", "this", "agent", ".", "It", "returns", "a", "coroutine", "or", "a", "future", "depending", "on", "whether", "it", "is", "called", "from", "a", "coroutine", "or", "a", "synchronous", "method", "." ]
59942bd1a1edae4c807d06cabb178d5630cbf61b
https://github.com/javipalanca/spade/blob/59942bd1a1edae4c807d06cabb178d5630cbf61b/spade/agent.py#L76-L84
train
212,450
javipalanca/spade
spade/agent.py
Agent._async_connect
async def _async_connect(self): # pragma: no cover """ connect and authenticate to the XMPP server. Async mode. """ try: self.conn_coro = self.client.connected() aenter = type(self.conn_coro).__aenter__(self.conn_coro) self.stream = await aenter logger.info(f"Agent {str(self.jid)} connected and authenticated.") except aiosasl.AuthenticationFailure: raise AuthenticationFailure( "Could not authenticate the agent. Check user and password or use auto_register=True")
python
async def _async_connect(self): # pragma: no cover """ connect and authenticate to the XMPP server. Async mode. """ try: self.conn_coro = self.client.connected() aenter = type(self.conn_coro).__aenter__(self.conn_coro) self.stream = await aenter logger.info(f"Agent {str(self.jid)} connected and authenticated.") except aiosasl.AuthenticationFailure: raise AuthenticationFailure( "Could not authenticate the agent. Check user and password or use auto_register=True")
[ "async", "def", "_async_connect", "(", "self", ")", ":", "# pragma: no cover", "try", ":", "self", ".", "conn_coro", "=", "self", ".", "client", ".", "connected", "(", ")", "aenter", "=", "type", "(", "self", ".", "conn_coro", ")", ".", "__aenter__", "("...
connect and authenticate to the XMPP server. Async mode.
[ "connect", "and", "authenticate", "to", "the", "XMPP", "server", ".", "Async", "mode", "." ]
59942bd1a1edae4c807d06cabb178d5630cbf61b
https://github.com/javipalanca/spade/blob/59942bd1a1edae4c807d06cabb178d5630cbf61b/spade/agent.py#L128-L137
train
212,451
javipalanca/spade
spade/agent.py
Agent._async_register
async def _async_register(self): # pragma: no cover """ Register the agent in the XMPP server from a coroutine. """ metadata = aioxmpp.make_security_layer(None, no_verify=not self.verify_security) query = ibr.Query(self.jid.localpart, self.password) _, stream, features = await aioxmpp.node.connect_xmlstream(self.jid, metadata, loop=self.loop) await ibr.register(stream, query)
python
async def _async_register(self): # pragma: no cover """ Register the agent in the XMPP server from a coroutine. """ metadata = aioxmpp.make_security_layer(None, no_verify=not self.verify_security) query = ibr.Query(self.jid.localpart, self.password) _, stream, features = await aioxmpp.node.connect_xmlstream(self.jid, metadata, loop=self.loop) await ibr.register(stream, query)
[ "async", "def", "_async_register", "(", "self", ")", ":", "# pragma: no cover", "metadata", "=", "aioxmpp", ".", "make_security_layer", "(", "None", ",", "no_verify", "=", "not", "self", ".", "verify_security", ")", "query", "=", "ibr", ".", "Query", "(", "s...
Register the agent in the XMPP server from a coroutine.
[ "Register", "the", "agent", "in", "the", "XMPP", "server", "from", "a", "coroutine", "." ]
59942bd1a1edae4c807d06cabb178d5630cbf61b
https://github.com/javipalanca/spade/blob/59942bd1a1edae4c807d06cabb178d5630cbf61b/spade/agent.py#L139-L144
train
212,452
javipalanca/spade
spade/agent.py
Agent.build_avatar_url
def build_avatar_url(jid): """ Static method to build a gravatar url with the agent's JID Args: jid (aioxmpp.JID): an XMPP identifier Returns: str: an URL for the gravatar """ digest = md5(str(jid).encode("utf-8")).hexdigest() return "http://www.gravatar.com/avatar/{md5}?d=monsterid".format(md5=digest)
python
def build_avatar_url(jid): """ Static method to build a gravatar url with the agent's JID Args: jid (aioxmpp.JID): an XMPP identifier Returns: str: an URL for the gravatar """ digest = md5(str(jid).encode("utf-8")).hexdigest() return "http://www.gravatar.com/avatar/{md5}?d=monsterid".format(md5=digest)
[ "def", "build_avatar_url", "(", "jid", ")", ":", "digest", "=", "md5", "(", "str", "(", "jid", ")", ".", "encode", "(", "\"utf-8\"", ")", ")", ".", "hexdigest", "(", ")", "return", "\"http://www.gravatar.com/avatar/{md5}?d=monsterid\"", ".", "format", "(", "...
Static method to build a gravatar url with the agent's JID Args: jid (aioxmpp.JID): an XMPP identifier Returns: str: an URL for the gravatar
[ "Static", "method", "to", "build", "a", "gravatar", "url", "with", "the", "agent", "s", "JID" ]
59942bd1a1edae4c807d06cabb178d5630cbf61b
https://github.com/javipalanca/spade/blob/59942bd1a1edae4c807d06cabb178d5630cbf61b/spade/agent.py#L171-L183
train
212,453
javipalanca/spade
spade/agent.py
Agent.add_behaviour
def add_behaviour(self, behaviour, template=None): """ Adds and starts a behaviour to the agent. If template is not None it is used to match new messages and deliver them to the behaviour. Args: behaviour (spade.behaviour.CyclicBehaviour): the behaviour to be started template (spade.template.Template, optional): the template to match messages with (Default value = None) """ behaviour.set_agent(self) if issubclass(type(behaviour), FSMBehaviour): for _, state in behaviour.get_states().items(): state.set_agent(self) behaviour.set_template(template) self.behaviours.append(behaviour) if self.is_alive(): behaviour.start()
python
def add_behaviour(self, behaviour, template=None): """ Adds and starts a behaviour to the agent. If template is not None it is used to match new messages and deliver them to the behaviour. Args: behaviour (spade.behaviour.CyclicBehaviour): the behaviour to be started template (spade.template.Template, optional): the template to match messages with (Default value = None) """ behaviour.set_agent(self) if issubclass(type(behaviour), FSMBehaviour): for _, state in behaviour.get_states().items(): state.set_agent(self) behaviour.set_template(template) self.behaviours.append(behaviour) if self.is_alive(): behaviour.start()
[ "def", "add_behaviour", "(", "self", ",", "behaviour", ",", "template", "=", "None", ")", ":", "behaviour", ".", "set_agent", "(", "self", ")", "if", "issubclass", "(", "type", "(", "behaviour", ")", ",", "FSMBehaviour", ")", ":", "for", "_", ",", "sta...
Adds and starts a behaviour to the agent. If template is not None it is used to match new messages and deliver them to the behaviour. Args: behaviour (spade.behaviour.CyclicBehaviour): the behaviour to be started template (spade.template.Template, optional): the template to match messages with (Default value = None)
[ "Adds", "and", "starts", "a", "behaviour", "to", "the", "agent", ".", "If", "template", "is", "not", "None", "it", "is", "used", "to", "match", "new", "messages", "and", "deliver", "them", "to", "the", "behaviour", "." ]
59942bd1a1edae4c807d06cabb178d5630cbf61b
https://github.com/javipalanca/spade/blob/59942bd1a1edae4c807d06cabb178d5630cbf61b/spade/agent.py#L199-L217
train
212,454
javipalanca/spade
spade/agent.py
Agent.remove_behaviour
def remove_behaviour(self, behaviour): """ Removes a behaviour from the agent. The behaviour is first killed. Args: behaviour (spade.behaviour.CyclicBehaviour): the behaviour instance to be removed """ if not self.has_behaviour(behaviour): raise ValueError("This behaviour is not registered") index = self.behaviours.index(behaviour) self.behaviours[index].kill() self.behaviours.pop(index)
python
def remove_behaviour(self, behaviour): """ Removes a behaviour from the agent. The behaviour is first killed. Args: behaviour (spade.behaviour.CyclicBehaviour): the behaviour instance to be removed """ if not self.has_behaviour(behaviour): raise ValueError("This behaviour is not registered") index = self.behaviours.index(behaviour) self.behaviours[index].kill() self.behaviours.pop(index)
[ "def", "remove_behaviour", "(", "self", ",", "behaviour", ")", ":", "if", "not", "self", ".", "has_behaviour", "(", "behaviour", ")", ":", "raise", "ValueError", "(", "\"This behaviour is not registered\"", ")", "index", "=", "self", ".", "behaviours", ".", "i...
Removes a behaviour from the agent. The behaviour is first killed. Args: behaviour (spade.behaviour.CyclicBehaviour): the behaviour instance to be removed
[ "Removes", "a", "behaviour", "from", "the", "agent", ".", "The", "behaviour", "is", "first", "killed", "." ]
59942bd1a1edae4c807d06cabb178d5630cbf61b
https://github.com/javipalanca/spade/blob/59942bd1a1edae4c807d06cabb178d5630cbf61b/spade/agent.py#L219-L232
train
212,455
javipalanca/spade
spade/agent.py
Agent._async_stop
async def _async_stop(self): """ Stops an agent and kills all its behaviours. """ if self.presence: self.presence.set_unavailable() for behav in self.behaviours: behav.kill() if self.web.is_started(): await self.web.runner.cleanup() """ Discconnect from XMPP server. """ if self.is_alive(): # Disconnect from XMPP server self.client.stop() aexit = self.conn_coro.__aexit__(*sys.exc_info()) await aexit logger.info("Client disconnected.") self._alive.clear()
python
async def _async_stop(self): """ Stops an agent and kills all its behaviours. """ if self.presence: self.presence.set_unavailable() for behav in self.behaviours: behav.kill() if self.web.is_started(): await self.web.runner.cleanup() """ Discconnect from XMPP server. """ if self.is_alive(): # Disconnect from XMPP server self.client.stop() aexit = self.conn_coro.__aexit__(*sys.exc_info()) await aexit logger.info("Client disconnected.") self._alive.clear()
[ "async", "def", "_async_stop", "(", "self", ")", ":", "if", "self", ".", "presence", ":", "self", ".", "presence", ".", "set_unavailable", "(", ")", "for", "behav", "in", "self", ".", "behaviours", ":", "behav", ".", "kill", "(", ")", "if", "self", "...
Stops an agent and kills all its behaviours.
[ "Stops", "an", "agent", "and", "kills", "all", "its", "behaviours", "." ]
59942bd1a1edae4c807d06cabb178d5630cbf61b
https://github.com/javipalanca/spade/blob/59942bd1a1edae4c807d06cabb178d5630cbf61b/spade/agent.py#L254-L271
train
212,456
javipalanca/spade
spade/agent.py
Agent._message_received
def _message_received(self, msg): """ Callback run when an XMPP Message is reveived. This callback delivers the message to every behaviour that is waiting for it. First, the aioxmpp.Message is converted to spade.message.Message Args: msg (aioxmpp.Messagge): the message just received. Returns: list(asyncio.Future): a list of futures of the append of the message at each matched behaviour. """ msg = Message.from_node(msg) return self.dispatch(msg)
python
def _message_received(self, msg): """ Callback run when an XMPP Message is reveived. This callback delivers the message to every behaviour that is waiting for it. First, the aioxmpp.Message is converted to spade.message.Message Args: msg (aioxmpp.Messagge): the message just received. Returns: list(asyncio.Future): a list of futures of the append of the message at each matched behaviour. """ msg = Message.from_node(msg) return self.dispatch(msg)
[ "def", "_message_received", "(", "self", ",", "msg", ")", ":", "msg", "=", "Message", ".", "from_node", "(", "msg", ")", "return", "self", ".", "dispatch", "(", "msg", ")" ]
Callback run when an XMPP Message is reveived. This callback delivers the message to every behaviour that is waiting for it. First, the aioxmpp.Message is converted to spade.message.Message Args: msg (aioxmpp.Messagge): the message just received. Returns: list(asyncio.Future): a list of futures of the append of the message at each matched behaviour.
[ "Callback", "run", "when", "an", "XMPP", "Message", "is", "reveived", ".", "This", "callback", "delivers", "the", "message", "to", "every", "behaviour", "that", "is", "waiting", "for", "it", ".", "First", "the", "aioxmpp", ".", "Message", "is", "converted", ...
59942bd1a1edae4c807d06cabb178d5630cbf61b
https://github.com/javipalanca/spade/blob/59942bd1a1edae4c807d06cabb178d5630cbf61b/spade/agent.py#L310-L326
train
212,457
javipalanca/spade
spade/agent.py
Agent.dispatch
def dispatch(self, msg): """ Dispatch the message to every behaviour that is waiting for it using their templates match. Args: msg (spade.message.Messagge): the message to dispatch. Returns: list(asyncio.Future): a list of futures of the append of the message at each matched behaviour. """ logger.debug(f"Got message: {msg}") futures = [] matched = False for behaviour in (x for x in self.behaviours if x.match(msg)): futures.append(self.submit(behaviour.enqueue(msg))) logger.debug(f"Message enqueued to behaviour: {behaviour}") self.traces.append(msg, category=str(behaviour)) matched = True if not matched: logger.warning(f"No behaviour matched for message: {msg}") self.traces.append(msg) return futures
python
def dispatch(self, msg): """ Dispatch the message to every behaviour that is waiting for it using their templates match. Args: msg (spade.message.Messagge): the message to dispatch. Returns: list(asyncio.Future): a list of futures of the append of the message at each matched behaviour. """ logger.debug(f"Got message: {msg}") futures = [] matched = False for behaviour in (x for x in self.behaviours if x.match(msg)): futures.append(self.submit(behaviour.enqueue(msg))) logger.debug(f"Message enqueued to behaviour: {behaviour}") self.traces.append(msg, category=str(behaviour)) matched = True if not matched: logger.warning(f"No behaviour matched for message: {msg}") self.traces.append(msg) return futures
[ "def", "dispatch", "(", "self", ",", "msg", ")", ":", "logger", ".", "debug", "(", "f\"Got message: {msg}\"", ")", "futures", "=", "[", "]", "matched", "=", "False", "for", "behaviour", "in", "(", "x", "for", "x", "in", "self", ".", "behaviours", "if",...
Dispatch the message to every behaviour that is waiting for it using their templates match. Args: msg (spade.message.Messagge): the message to dispatch. Returns: list(asyncio.Future): a list of futures of the append of the message at each matched behaviour.
[ "Dispatch", "the", "message", "to", "every", "behaviour", "that", "is", "waiting", "for", "it", "using", "their", "templates", "match", "." ]
59942bd1a1edae4c807d06cabb178d5630cbf61b
https://github.com/javipalanca/spade/blob/59942bd1a1edae4c807d06cabb178d5630cbf61b/spade/agent.py#L328-L351
train
212,458
javipalanca/spade
spade/message.py
MessageBase.from_node
def from_node(cls, node): """ Creates a new spade.message.Message from an aixoxmpp.stanza.Message Args: node (aioxmpp.stanza.Message): an aioxmpp Message Returns: spade.message.Message: a new spade Message """ if not isinstance(node, aioxmpp.stanza.Message): raise AttributeError("node must be a aioxmpp.stanza.Message instance") msg = cls() msg._to = node.to msg._sender = node.from_ if None in node.body: msg.body = node.body[None] else: for key in node.body.keys(): msg.body = node.body[key] break for data in node.xep0004_data: if data.title == SPADE_X_METADATA: for field in data.fields: if field.var != "_thread_node": msg.set_metadata(field.var, field.values[0]) else: msg.thread = field.values[0] return msg
python
def from_node(cls, node): """ Creates a new spade.message.Message from an aixoxmpp.stanza.Message Args: node (aioxmpp.stanza.Message): an aioxmpp Message Returns: spade.message.Message: a new spade Message """ if not isinstance(node, aioxmpp.stanza.Message): raise AttributeError("node must be a aioxmpp.stanza.Message instance") msg = cls() msg._to = node.to msg._sender = node.from_ if None in node.body: msg.body = node.body[None] else: for key in node.body.keys(): msg.body = node.body[key] break for data in node.xep0004_data: if data.title == SPADE_X_METADATA: for field in data.fields: if field.var != "_thread_node": msg.set_metadata(field.var, field.values[0]) else: msg.thread = field.values[0] return msg
[ "def", "from_node", "(", "cls", ",", "node", ")", ":", "if", "not", "isinstance", "(", "node", ",", "aioxmpp", ".", "stanza", ".", "Message", ")", ":", "raise", "AttributeError", "(", "\"node must be a aioxmpp.stanza.Message instance\"", ")", "msg", "=", "cls"...
Creates a new spade.message.Message from an aixoxmpp.stanza.Message Args: node (aioxmpp.stanza.Message): an aioxmpp Message Returns: spade.message.Message: a new spade Message
[ "Creates", "a", "new", "spade", ".", "message", ".", "Message", "from", "an", "aixoxmpp", ".", "stanza", ".", "Message" ]
59942bd1a1edae4c807d06cabb178d5630cbf61b
https://github.com/javipalanca/spade/blob/59942bd1a1edae4c807d06cabb178d5630cbf61b/spade/message.py#L31-L62
train
212,459
javipalanca/spade
spade/message.py
MessageBase.to
def to(self, jid: str): """ Set jid of the receiver. Args: jid (str): the jid of the receiver. """ if jid is not None and not isinstance(jid, str): raise TypeError("'to' MUST be a string") self._to = aioxmpp.JID.fromstr(jid) if jid is not None else None
python
def to(self, jid: str): """ Set jid of the receiver. Args: jid (str): the jid of the receiver. """ if jid is not None and not isinstance(jid, str): raise TypeError("'to' MUST be a string") self._to = aioxmpp.JID.fromstr(jid) if jid is not None else None
[ "def", "to", "(", "self", ",", "jid", ":", "str", ")", ":", "if", "jid", "is", "not", "None", "and", "not", "isinstance", "(", "jid", ",", "str", ")", ":", "raise", "TypeError", "(", "\"'to' MUST be a string\"", ")", "self", ".", "_to", "=", "aioxmpp...
Set jid of the receiver. Args: jid (str): the jid of the receiver.
[ "Set", "jid", "of", "the", "receiver", "." ]
59942bd1a1edae4c807d06cabb178d5630cbf61b
https://github.com/javipalanca/spade/blob/59942bd1a1edae4c807d06cabb178d5630cbf61b/spade/message.py#L76-L86
train
212,460
javipalanca/spade
spade/message.py
MessageBase.sender
def sender(self, jid: str): """ Set jid of the sender Args: jid (str): jid of the sender """ if jid is not None and not isinstance(jid, str): raise TypeError("'sender' MUST be a string") self._sender = aioxmpp.JID.fromstr(jid) if jid is not None else None
python
def sender(self, jid: str): """ Set jid of the sender Args: jid (str): jid of the sender """ if jid is not None and not isinstance(jid, str): raise TypeError("'sender' MUST be a string") self._sender = aioxmpp.JID.fromstr(jid) if jid is not None else None
[ "def", "sender", "(", "self", ",", "jid", ":", "str", ")", ":", "if", "jid", "is", "not", "None", "and", "not", "isinstance", "(", "jid", ",", "str", ")", ":", "raise", "TypeError", "(", "\"'sender' MUST be a string\"", ")", "self", ".", "_sender", "="...
Set jid of the sender Args: jid (str): jid of the sender
[ "Set", "jid", "of", "the", "sender" ]
59942bd1a1edae4c807d06cabb178d5630cbf61b
https://github.com/javipalanca/spade/blob/59942bd1a1edae4c807d06cabb178d5630cbf61b/spade/message.py#L100-L110
train
212,461
javipalanca/spade
spade/message.py
MessageBase.thread
def thread(self, value: str): """ Set thread id of the message Args: value (str): the thread id """ if value is not None and not isinstance(value, str): raise TypeError("'thread' MUST be a string") self._thread = value
python
def thread(self, value: str): """ Set thread id of the message Args: value (str): the thread id """ if value is not None and not isinstance(value, str): raise TypeError("'thread' MUST be a string") self._thread = value
[ "def", "thread", "(", "self", ",", "value", ":", "str", ")", ":", "if", "value", "is", "not", "None", "and", "not", "isinstance", "(", "value", ",", "str", ")", ":", "raise", "TypeError", "(", "\"'thread' MUST be a string\"", ")", "self", ".", "_thread",...
Set thread id of the message Args: value (str): the thread id
[ "Set", "thread", "id", "of", "the", "message" ]
59942bd1a1edae4c807d06cabb178d5630cbf61b
https://github.com/javipalanca/spade/blob/59942bd1a1edae4c807d06cabb178d5630cbf61b/spade/message.py#L143-L153
train
212,462
javipalanca/spade
spade/message.py
MessageBase.set_metadata
def set_metadata(self, key: str, value: str): """ Add a new metadata to the message Args: key (str): name of the metadata value (str): value of the metadata """ if not isinstance(key, str) or not isinstance(value, str): raise TypeError("'key' and 'value' of metadata MUST be strings") self.metadata[key] = value
python
def set_metadata(self, key: str, value: str): """ Add a new metadata to the message Args: key (str): name of the metadata value (str): value of the metadata """ if not isinstance(key, str) or not isinstance(value, str): raise TypeError("'key' and 'value' of metadata MUST be strings") self.metadata[key] = value
[ "def", "set_metadata", "(", "self", ",", "key", ":", "str", ",", "value", ":", "str", ")", ":", "if", "not", "isinstance", "(", "key", ",", "str", ")", "or", "not", "isinstance", "(", "value", ",", "str", ")", ":", "raise", "TypeError", "(", "\"'ke...
Add a new metadata to the message Args: key (str): name of the metadata value (str): value of the metadata
[ "Add", "a", "new", "metadata", "to", "the", "message" ]
59942bd1a1edae4c807d06cabb178d5630cbf61b
https://github.com/javipalanca/spade/blob/59942bd1a1edae4c807d06cabb178d5630cbf61b/spade/message.py#L155-L166
train
212,463
javipalanca/spade
spade/message.py
MessageBase.get_metadata
def get_metadata(self, key) -> str: """ Get the value of a metadata. Returns None if metadata does not exist. Args: key (str): name of the metadata Returns: str: the value of the metadata (or None) """ return self.metadata[key] if key in self.metadata else None
python
def get_metadata(self, key) -> str: """ Get the value of a metadata. Returns None if metadata does not exist. Args: key (str): name of the metadata Returns: str: the value of the metadata (or None) """ return self.metadata[key] if key in self.metadata else None
[ "def", "get_metadata", "(", "self", ",", "key", ")", "->", "str", ":", "return", "self", ".", "metadata", "[", "key", "]", "if", "key", "in", "self", ".", "metadata", "else", "None" ]
Get the value of a metadata. Returns None if metadata does not exist. Args: key (str): name of the metadata Returns: str: the value of the metadata (or None)
[ "Get", "the", "value", "of", "a", "metadata", ".", "Returns", "None", "if", "metadata", "does", "not", "exist", "." ]
59942bd1a1edae4c807d06cabb178d5630cbf61b
https://github.com/javipalanca/spade/blob/59942bd1a1edae4c807d06cabb178d5630cbf61b/spade/message.py#L168-L179
train
212,464
javipalanca/spade
spade/message.py
MessageBase.match
def match(self, message) -> bool: """ Returns wether a message matches with this message or not. The message can be a Message object or a Template object. Args: message (spade.message.Message): the message to match to Returns: bool: wether the message matches or not """ if self.to and message.to != self.to: return False if self.sender and message.sender != self.sender: return False if self.body and message.body != self.body: return False if self.thread and message.thread != self.thread: return False for key, value in self.metadata.items(): if message.get_metadata(key) != value: return False logger.debug(f"message matched {self} == {message}") return True
python
def match(self, message) -> bool: """ Returns wether a message matches with this message or not. The message can be a Message object or a Template object. Args: message (spade.message.Message): the message to match to Returns: bool: wether the message matches or not """ if self.to and message.to != self.to: return False if self.sender and message.sender != self.sender: return False if self.body and message.body != self.body: return False if self.thread and message.thread != self.thread: return False for key, value in self.metadata.items(): if message.get_metadata(key) != value: return False logger.debug(f"message matched {self} == {message}") return True
[ "def", "match", "(", "self", ",", "message", ")", "->", "bool", ":", "if", "self", ".", "to", "and", "message", ".", "to", "!=", "self", ".", "to", ":", "return", "False", "if", "self", ".", "sender", "and", "message", ".", "sender", "!=", "self", ...
Returns wether a message matches with this message or not. The message can be a Message object or a Template object. Args: message (spade.message.Message): the message to match to Returns: bool: wether the message matches or not
[ "Returns", "wether", "a", "message", "matches", "with", "this", "message", "or", "not", ".", "The", "message", "can", "be", "a", "Message", "object", "or", "a", "Template", "object", "." ]
59942bd1a1edae4c807d06cabb178d5630cbf61b
https://github.com/javipalanca/spade/blob/59942bd1a1edae4c807d06cabb178d5630cbf61b/spade/message.py#L181-L210
train
212,465
javipalanca/spade
spade/message.py
Message.make_reply
def make_reply(self): """ Creates a copy of the message, exchanging sender and receiver Returns: spade.message.Message: a new message with exchanged sender and receiver """ return Message( to=str(self.sender), sender=str(self.to), body=self.body, thread=self.thread, metadata=self.metadata )
python
def make_reply(self): """ Creates a copy of the message, exchanging sender and receiver Returns: spade.message.Message: a new message with exchanged sender and receiver """ return Message( to=str(self.sender), sender=str(self.to), body=self.body, thread=self.thread, metadata=self.metadata )
[ "def", "make_reply", "(", "self", ")", ":", "return", "Message", "(", "to", "=", "str", "(", "self", ".", "sender", ")", ",", "sender", "=", "str", "(", "self", ".", "to", ")", ",", "body", "=", "self", ".", "body", ",", "thread", "=", "self", ...
Creates a copy of the message, exchanging sender and receiver Returns: spade.message.Message: a new message with exchanged sender and receiver
[ "Creates", "a", "copy", "of", "the", "message", "exchanging", "sender", "and", "receiver" ]
59942bd1a1edae4c807d06cabb178d5630cbf61b
https://github.com/javipalanca/spade/blob/59942bd1a1edae4c807d06cabb178d5630cbf61b/spade/message.py#L224-L238
train
212,466
javipalanca/spade
spade/message.py
Message.prepare
def prepare(self): """ Returns an aioxmpp.stanza.Message built from the Message and prepared to be sent. Returns: aioxmpp.stanza.Message: the message prepared to be sent """ msg = aioxmpp.stanza.Message( to=self.to, from_=self.sender, type_=aioxmpp.MessageType.CHAT, ) msg.body[None] = self.body # Send metadata using xep-0004: Data Forms (https://xmpp.org/extensions/xep-0004.html) if len(self.metadata): data = forms_xso.Data(type_=forms_xso.DataType.FORM) for name, value in self.metadata.items(): data.fields.append( forms_xso.Field( var=name, type_=forms_xso.FieldType.TEXT_SINGLE, values=[value], ) ) if self.thread: data.fields.append(forms_xso.Field(var="_thread_node", type_=forms_xso.FieldType.TEXT_SINGLE, values=[self.thread])) data.title = SPADE_X_METADATA msg.xep0004_data = [data] return msg
python
def prepare(self): """ Returns an aioxmpp.stanza.Message built from the Message and prepared to be sent. Returns: aioxmpp.stanza.Message: the message prepared to be sent """ msg = aioxmpp.stanza.Message( to=self.to, from_=self.sender, type_=aioxmpp.MessageType.CHAT, ) msg.body[None] = self.body # Send metadata using xep-0004: Data Forms (https://xmpp.org/extensions/xep-0004.html) if len(self.metadata): data = forms_xso.Data(type_=forms_xso.DataType.FORM) for name, value in self.metadata.items(): data.fields.append( forms_xso.Field( var=name, type_=forms_xso.FieldType.TEXT_SINGLE, values=[value], ) ) if self.thread: data.fields.append(forms_xso.Field(var="_thread_node", type_=forms_xso.FieldType.TEXT_SINGLE, values=[self.thread])) data.title = SPADE_X_METADATA msg.xep0004_data = [data] return msg
[ "def", "prepare", "(", "self", ")", ":", "msg", "=", "aioxmpp", ".", "stanza", ".", "Message", "(", "to", "=", "self", ".", "to", ",", "from_", "=", "self", ".", "sender", ",", "type_", "=", "aioxmpp", ".", "MessageType", ".", "CHAT", ",", ")", "...
Returns an aioxmpp.stanza.Message built from the Message and prepared to be sent. Returns: aioxmpp.stanza.Message: the message prepared to be sent
[ "Returns", "an", "aioxmpp", ".", "stanza", ".", "Message", "built", "from", "the", "Message", "and", "prepared", "to", "be", "sent", "." ]
59942bd1a1edae4c807d06cabb178d5630cbf61b
https://github.com/javipalanca/spade/blob/59942bd1a1edae4c807d06cabb178d5630cbf61b/spade/message.py#L240-L278
train
212,467
javipalanca/spade
spade/web.py
unused_port
def unused_port(hostname): """Return a port that is unused on the current host.""" with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.bind((hostname, 0)) return s.getsockname()[1]
python
def unused_port(hostname): """Return a port that is unused on the current host.""" with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.bind((hostname, 0)) return s.getsockname()[1]
[ "def", "unused_port", "(", "hostname", ")", ":", "with", "socket", ".", "socket", "(", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_STREAM", ")", "as", "s", ":", "s", ".", "bind", "(", "(", "hostname", ",", "0", ")", ")", "return", "s", ".",...
Return a port that is unused on the current host.
[ "Return", "a", "port", "that", "is", "unused", "on", "the", "current", "host", "." ]
59942bd1a1edae4c807d06cabb178d5630cbf61b
https://github.com/javipalanca/spade/blob/59942bd1a1edae4c807d06cabb178d5630cbf61b/spade/web.py#L15-L19
train
212,468
javipalanca/spade
spade/web.py
start_server_in_loop
async def start_server_in_loop(runner, hostname, port, agent): """ Listens to http requests and sends them to the webapp. Args: runner: AppRunner to process the http requests hostname: host name to listen from. port: port to listen from. agent: agent that owns the web app. """ await runner.setup() agent.web.server = aioweb.TCPSite(runner, hostname, port) await agent.web.server.start() logger.info(f"Serving on http://{hostname}:{port}/")
python
async def start_server_in_loop(runner, hostname, port, agent): """ Listens to http requests and sends them to the webapp. Args: runner: AppRunner to process the http requests hostname: host name to listen from. port: port to listen from. agent: agent that owns the web app. """ await runner.setup() agent.web.server = aioweb.TCPSite(runner, hostname, port) await agent.web.server.start() logger.info(f"Serving on http://{hostname}:{port}/")
[ "async", "def", "start_server_in_loop", "(", "runner", ",", "hostname", ",", "port", ",", "agent", ")", ":", "await", "runner", ".", "setup", "(", ")", "agent", ".", "web", ".", "server", "=", "aioweb", ".", "TCPSite", "(", "runner", ",", "hostname", "...
Listens to http requests and sends them to the webapp. Args: runner: AppRunner to process the http requests hostname: host name to listen from. port: port to listen from. agent: agent that owns the web app.
[ "Listens", "to", "http", "requests", "and", "sends", "them", "to", "the", "webapp", "." ]
59942bd1a1edae4c807d06cabb178d5630cbf61b
https://github.com/javipalanca/spade/blob/59942bd1a1edae4c807d06cabb178d5630cbf61b/spade/web.py#L22-L35
train
212,469
javipalanca/spade
spade/web.py
WebApp.start
def start(self, hostname=None, port=None, templates_path=None): """ Starts the web interface. Args: hostname (str, optional): host name to listen from. (Default value = None) port (int, optional): port to listen from. (Default value = None) templates_path (str, optional): path to look for templates. (Default value = None) """ self.hostname = hostname if hostname else "localhost" if port: self.port = port elif not self.port: self.port = unused_port(self.hostname) if templates_path: self.loaders.insert(0, jinja2.FileSystemLoader(templates_path)) self._set_loaders() self.setup_routes() self.runner = aioweb.AppRunner(self.app) return self.agent.submit(start_server_in_loop(self.runner, self.hostname, self.port, self.agent))
python
def start(self, hostname=None, port=None, templates_path=None): """ Starts the web interface. Args: hostname (str, optional): host name to listen from. (Default value = None) port (int, optional): port to listen from. (Default value = None) templates_path (str, optional): path to look for templates. (Default value = None) """ self.hostname = hostname if hostname else "localhost" if port: self.port = port elif not self.port: self.port = unused_port(self.hostname) if templates_path: self.loaders.insert(0, jinja2.FileSystemLoader(templates_path)) self._set_loaders() self.setup_routes() self.runner = aioweb.AppRunner(self.app) return self.agent.submit(start_server_in_loop(self.runner, self.hostname, self.port, self.agent))
[ "def", "start", "(", "self", ",", "hostname", "=", "None", ",", "port", "=", "None", ",", "templates_path", "=", "None", ")", ":", "self", ".", "hostname", "=", "hostname", "if", "hostname", "else", "\"localhost\"", "if", "port", ":", "self", ".", "por...
Starts the web interface. Args: hostname (str, optional): host name to listen from. (Default value = None) port (int, optional): port to listen from. (Default value = None) templates_path (str, optional): path to look for templates. (Default value = None)
[ "Starts", "the", "web", "interface", "." ]
59942bd1a1edae4c807d06cabb178d5630cbf61b
https://github.com/javipalanca/spade/blob/59942bd1a1edae4c807d06cabb178d5630cbf61b/spade/web.py#L53-L73
train
212,470
javipalanca/spade
spade/web.py
WebApp.add_get
def add_get(self, path, controller, template, raw=False): """ Setup a route of type GET Args: path (str): URL to listen to controller (coroutine): the coroutine to handle the request template (str): the template to render the response or None if it is a JSON response raw (bool): indicates if post-processing (jinja, json, etc) is needed or not """ if raw: fn = controller else: fn = self._prepare_controller(controller, template) self.app.router.add_get(path, fn)
python
def add_get(self, path, controller, template, raw=False): """ Setup a route of type GET Args: path (str): URL to listen to controller (coroutine): the coroutine to handle the request template (str): the template to render the response or None if it is a JSON response raw (bool): indicates if post-processing (jinja, json, etc) is needed or not """ if raw: fn = controller else: fn = self._prepare_controller(controller, template) self.app.router.add_get(path, fn)
[ "def", "add_get", "(", "self", ",", "path", ",", "controller", ",", "template", ",", "raw", "=", "False", ")", ":", "if", "raw", ":", "fn", "=", "controller", "else", ":", "fn", "=", "self", ".", "_prepare_controller", "(", "controller", ",", "template...
Setup a route of type GET Args: path (str): URL to listen to controller (coroutine): the coroutine to handle the request template (str): the template to render the response or None if it is a JSON response raw (bool): indicates if post-processing (jinja, json, etc) is needed or not
[ "Setup", "a", "route", "of", "type", "GET" ]
59942bd1a1edae4c807d06cabb178d5630cbf61b
https://github.com/javipalanca/spade/blob/59942bd1a1edae4c807d06cabb178d5630cbf61b/spade/web.py#L97-L112
train
212,471
javipalanca/spade
spade/behaviour.py
CyclicBehaviour.set_agent
def set_agent(self, agent): """ Links behaviour with its owner agent Args: agent (spade.agent.Agent): the agent who owns the behaviour """ self.agent = agent self.queue = asyncio.Queue(loop=self.agent.loop) self.presence = agent.presence self.web = agent.web
python
def set_agent(self, agent): """ Links behaviour with its owner agent Args: agent (spade.agent.Agent): the agent who owns the behaviour """ self.agent = agent self.queue = asyncio.Queue(loop=self.agent.loop) self.presence = agent.presence self.web = agent.web
[ "def", "set_agent", "(", "self", ",", "agent", ")", ":", "self", ".", "agent", "=", "agent", "self", ".", "queue", "=", "asyncio", ".", "Queue", "(", "loop", "=", "self", ".", "agent", ".", "loop", ")", "self", ".", "presence", "=", "agent", ".", ...
Links behaviour with its owner agent Args: agent (spade.agent.Agent): the agent who owns the behaviour
[ "Links", "behaviour", "with", "its", "owner", "agent" ]
59942bd1a1edae4c807d06cabb178d5630cbf61b
https://github.com/javipalanca/spade/blob/59942bd1a1edae4c807d06cabb178d5630cbf61b/spade/behaviour.py#L50-L61
train
212,472
javipalanca/spade
spade/behaviour.py
CyclicBehaviour.match
def match(self, message: Message) -> bool: """ Matches a message with the behaviour's template Args: message(spade.message.Message): the message to match with Returns: bool: wheter the messaged matches or not """ if self.template: return self.template.match(message) return True
python
def match(self, message: Message) -> bool: """ Matches a message with the behaviour's template Args: message(spade.message.Message): the message to match with Returns: bool: wheter the messaged matches or not """ if self.template: return self.template.match(message) return True
[ "def", "match", "(", "self", ",", "message", ":", "Message", ")", "->", "bool", ":", "if", "self", ".", "template", ":", "return", "self", ".", "template", ".", "match", "(", "message", ")", "return", "True" ]
Matches a message with the behaviour's template Args: message(spade.message.Message): the message to match with Returns: bool: wheter the messaged matches or not
[ "Matches", "a", "message", "with", "the", "behaviour", "s", "template" ]
59942bd1a1edae4c807d06cabb178d5630cbf61b
https://github.com/javipalanca/spade/blob/59942bd1a1edae4c807d06cabb178d5630cbf61b/spade/behaviour.py#L74-L87
train
212,473
javipalanca/spade
spade/behaviour.py
CyclicBehaviour.set
def set(self, name: str, value: Any) -> None: """ Stores a knowledge item in the agent knowledge base. Args: name (str): name of the item value (Any): value of the item """ self.agent.set(name, value)
python
def set(self, name: str, value: Any) -> None: """ Stores a knowledge item in the agent knowledge base. Args: name (str): name of the item value (Any): value of the item """ self.agent.set(name, value)
[ "def", "set", "(", "self", ",", "name", ":", "str", ",", "value", ":", "Any", ")", "->", "None", ":", "self", ".", "agent", ".", "set", "(", "name", ",", "value", ")" ]
Stores a knowledge item in the agent knowledge base. Args: name (str): name of the item value (Any): value of the item
[ "Stores", "a", "knowledge", "item", "in", "the", "agent", "knowledge", "base", "." ]
59942bd1a1edae4c807d06cabb178d5630cbf61b
https://github.com/javipalanca/spade/blob/59942bd1a1edae4c807d06cabb178d5630cbf61b/spade/behaviour.py#L89-L98
train
212,474
javipalanca/spade
spade/behaviour.py
CyclicBehaviour.start
def start(self): """starts behaviour in the event loop""" self.agent.submit(self._start()) self.is_running = True
python
def start(self): """starts behaviour in the event loop""" self.agent.submit(self._start()) self.is_running = True
[ "def", "start", "(", "self", ")", ":", "self", ".", "agent", ".", "submit", "(", "self", ".", "_start", "(", ")", ")", "self", ".", "is_running", "=", "True" ]
starts behaviour in the event loop
[ "starts", "behaviour", "in", "the", "event", "loop" ]
59942bd1a1edae4c807d06cabb178d5630cbf61b
https://github.com/javipalanca/spade/blob/59942bd1a1edae4c807d06cabb178d5630cbf61b/spade/behaviour.py#L113-L116
train
212,475
javipalanca/spade
spade/behaviour.py
CyclicBehaviour._start
async def _start(self): """ Start coroutine. runs on_start coroutine and then runs the _step coroutine where the body of the behaviour is called. """ self.agent._alive.wait() try: await self.on_start() except Exception as e: logger.error("Exception running on_start in behaviour {}: {}".format(self, e)) self.kill(exit_code=e) await self._step() self._is_done.clear()
python
async def _start(self): """ Start coroutine. runs on_start coroutine and then runs the _step coroutine where the body of the behaviour is called. """ self.agent._alive.wait() try: await self.on_start() except Exception as e: logger.error("Exception running on_start in behaviour {}: {}".format(self, e)) self.kill(exit_code=e) await self._step() self._is_done.clear()
[ "async", "def", "_start", "(", "self", ")", ":", "self", ".", "agent", ".", "_alive", ".", "wait", "(", ")", "try", ":", "await", "self", ".", "on_start", "(", ")", "except", "Exception", "as", "e", ":", "logger", ".", "error", "(", "\"Exception runn...
Start coroutine. runs on_start coroutine and then runs the _step coroutine where the body of the behaviour is called.
[ "Start", "coroutine", ".", "runs", "on_start", "coroutine", "and", "then", "runs", "the", "_step", "coroutine", "where", "the", "body", "of", "the", "behaviour", "is", "called", "." ]
59942bd1a1edae4c807d06cabb178d5630cbf61b
https://github.com/javipalanca/spade/blob/59942bd1a1edae4c807d06cabb178d5630cbf61b/spade/behaviour.py#L118-L131
train
212,476
javipalanca/spade
spade/behaviour.py
CyclicBehaviour.kill
def kill(self, exit_code: Any = None): """ Stops the behaviour Args: exit_code (object, optional): the exit code of the behaviour (Default value = None) """ self._force_kill.set() if exit_code is not None: self._exit_code = exit_code logger.info("Killing behavior {0} with exit code: {1}".format(self, exit_code))
python
def kill(self, exit_code: Any = None): """ Stops the behaviour Args: exit_code (object, optional): the exit code of the behaviour (Default value = None) """ self._force_kill.set() if exit_code is not None: self._exit_code = exit_code logger.info("Killing behavior {0} with exit code: {1}".format(self, exit_code))
[ "def", "kill", "(", "self", ",", "exit_code", ":", "Any", "=", "None", ")", ":", "self", ".", "_force_kill", ".", "set", "(", ")", "if", "exit_code", "is", "not", "None", ":", "self", ".", "_exit_code", "=", "exit_code", "logger", ".", "info", "(", ...
Stops the behaviour Args: exit_code (object, optional): the exit code of the behaviour (Default value = None)
[ "Stops", "the", "behaviour" ]
59942bd1a1edae4c807d06cabb178d5630cbf61b
https://github.com/javipalanca/spade/blob/59942bd1a1edae4c807d06cabb178d5630cbf61b/spade/behaviour.py#L133-L144
train
212,477
javipalanca/spade
spade/behaviour.py
CyclicBehaviour.exit_code
def exit_code(self) -> Any: """ Returns the exit_code of the behaviour. It only works when the behaviour is done or killed, otherwise it raises an exception. Returns: object: the exit code of the behaviour """ if self._done() or self.is_killed(): return self._exit_code else: raise BehaviourNotFinishedException
python
def exit_code(self) -> Any: """ Returns the exit_code of the behaviour. It only works when the behaviour is done or killed, otherwise it raises an exception. Returns: object: the exit code of the behaviour """ if self._done() or self.is_killed(): return self._exit_code else: raise BehaviourNotFinishedException
[ "def", "exit_code", "(", "self", ")", "->", "Any", ":", "if", "self", ".", "_done", "(", ")", "or", "self", ".", "is_killed", "(", ")", ":", "return", "self", ".", "_exit_code", "else", ":", "raise", "BehaviourNotFinishedException" ]
Returns the exit_code of the behaviour. It only works when the behaviour is done or killed, otherwise it raises an exception. Returns: object: the exit code of the behaviour
[ "Returns", "the", "exit_code", "of", "the", "behaviour", ".", "It", "only", "works", "when", "the", "behaviour", "is", "done", "or", "killed", "otherwise", "it", "raises", "an", "exception", "." ]
59942bd1a1edae4c807d06cabb178d5630cbf61b
https://github.com/javipalanca/spade/blob/59942bd1a1edae4c807d06cabb178d5630cbf61b/spade/behaviour.py#L157-L170
train
212,478
javipalanca/spade
spade/behaviour.py
CyclicBehaviour.send
async def send(self, msg: Message): """ Sends a message. Args: msg (spade.message.Message): the message to be sent. """ if not msg.sender: msg.sender = str(self.agent.jid) logger.debug(f"Adding agent's jid as sender to message: {msg}") await self.agent.container.send(msg, self) msg.sent = True self.agent.traces.append(msg, category=str(self))
python
async def send(self, msg: Message): """ Sends a message. Args: msg (spade.message.Message): the message to be sent. """ if not msg.sender: msg.sender = str(self.agent.jid) logger.debug(f"Adding agent's jid as sender to message: {msg}") await self.agent.container.send(msg, self) msg.sent = True self.agent.traces.append(msg, category=str(self))
[ "async", "def", "send", "(", "self", ",", "msg", ":", "Message", ")", ":", "if", "not", "msg", ".", "sender", ":", "msg", ".", "sender", "=", "str", "(", "self", ".", "agent", ".", "jid", ")", "logger", ".", "debug", "(", "f\"Adding agent's jid as se...
Sends a message. Args: msg (spade.message.Message): the message to be sent.
[ "Sends", "a", "message", "." ]
59942bd1a1edae4c807d06cabb178d5630cbf61b
https://github.com/javipalanca/spade/blob/59942bd1a1edae4c807d06cabb178d5630cbf61b/spade/behaviour.py#L287-L299
train
212,479
javipalanca/spade
spade/behaviour.py
CyclicBehaviour.receive
async def receive(self, timeout: float = None) -> Union[Message, None]: """ Receives a message for this behaviour. If timeout is not None it returns the message or "None" after timeout is done. Args: timeout (float): number of seconds until return Returns: spade.message.Message: a Message or None """ if timeout: coro = self.queue.get() try: msg = await asyncio.wait_for(coro, timeout=timeout) except asyncio.TimeoutError: msg = None else: try: msg = self.queue.get_nowait() except asyncio.QueueEmpty: msg = None return msg
python
async def receive(self, timeout: float = None) -> Union[Message, None]: """ Receives a message for this behaviour. If timeout is not None it returns the message or "None" after timeout is done. Args: timeout (float): number of seconds until return Returns: spade.message.Message: a Message or None """ if timeout: coro = self.queue.get() try: msg = await asyncio.wait_for(coro, timeout=timeout) except asyncio.TimeoutError: msg = None else: try: msg = self.queue.get_nowait() except asyncio.QueueEmpty: msg = None return msg
[ "async", "def", "receive", "(", "self", ",", "timeout", ":", "float", "=", "None", ")", "->", "Union", "[", "Message", ",", "None", "]", ":", "if", "timeout", ":", "coro", "=", "self", ".", "queue", ".", "get", "(", ")", "try", ":", "msg", "=", ...
Receives a message for this behaviour. If timeout is not None it returns the message or "None" after timeout is done. Args: timeout (float): number of seconds until return Returns: spade.message.Message: a Message or None
[ "Receives", "a", "message", "for", "this", "behaviour", ".", "If", "timeout", "is", "not", "None", "it", "returns", "the", "message", "or", "None", "after", "timeout", "is", "done", "." ]
59942bd1a1edae4c807d06cabb178d5630cbf61b
https://github.com/javipalanca/spade/blob/59942bd1a1edae4c807d06cabb178d5630cbf61b/spade/behaviour.py#L305-L328
train
212,480
javipalanca/spade
spade/behaviour.py
PeriodicBehaviour.period
def period(self, value: float): """ Set the period. Args: value (float): seconds """ if value < 0: raise ValueError("Period must be greater or equal than zero.") self._period = timedelta(seconds=value)
python
def period(self, value: float): """ Set the period. Args: value (float): seconds """ if value < 0: raise ValueError("Period must be greater or equal than zero.") self._period = timedelta(seconds=value)
[ "def", "period", "(", "self", ",", "value", ":", "float", ")", ":", "if", "value", "<", "0", ":", "raise", "ValueError", "(", "\"Period must be greater or equal than zero.\"", ")", "self", ".", "_period", "=", "timedelta", "(", "seconds", "=", "value", ")" ]
Set the period. Args: value (float): seconds
[ "Set", "the", "period", "." ]
59942bd1a1edae4c807d06cabb178d5630cbf61b
https://github.com/javipalanca/spade/blob/59942bd1a1edae4c807d06cabb178d5630cbf61b/spade/behaviour.py#L375-L384
train
212,481
javipalanca/spade
spade/behaviour.py
FSMBehaviour.add_state
def add_state(self, name: str, state: State, initial: bool = False): """ Adds a new state to the FSM. Args: name (str): the name of the state, which is used as its identifier. state (spade.behaviour.State): The state class initial (bool, optional): wether the state is the initial state or not. (Only one initial state is allowed) (Default value = False) """ if not issubclass(state.__class__, State): raise AttributeError("state must be subclass of spade.behaviour.State") self._states[name] = state if initial: self.current_state = name
python
def add_state(self, name: str, state: State, initial: bool = False): """ Adds a new state to the FSM. Args: name (str): the name of the state, which is used as its identifier. state (spade.behaviour.State): The state class initial (bool, optional): wether the state is the initial state or not. (Only one initial state is allowed) (Default value = False) """ if not issubclass(state.__class__, State): raise AttributeError("state must be subclass of spade.behaviour.State") self._states[name] = state if initial: self.current_state = name
[ "def", "add_state", "(", "self", ",", "name", ":", "str", ",", "state", ":", "State", ",", "initial", ":", "bool", "=", "False", ")", ":", "if", "not", "issubclass", "(", "state", ".", "__class__", ",", "State", ")", ":", "raise", "AttributeError", "...
Adds a new state to the FSM. Args: name (str): the name of the state, which is used as its identifier. state (spade.behaviour.State): The state class initial (bool, optional): wether the state is the initial state or not. (Only one initial state is allowed) (Default value = False)
[ "Adds", "a", "new", "state", "to", "the", "FSM", "." ]
59942bd1a1edae4c807d06cabb178d5630cbf61b
https://github.com/javipalanca/spade/blob/59942bd1a1edae4c807d06cabb178d5630cbf61b/spade/behaviour.py#L469-L482
train
212,482
javipalanca/spade
spade/behaviour.py
FSMBehaviour.add_transition
def add_transition(self, source: str, dest: str): """ Adds a transition from one state to another. Args: source (str): the name of the state from where the transition starts dest (str): the name of the state where the transition ends """ self._transitions[source].append(dest)
python
def add_transition(self, source: str, dest: str): """ Adds a transition from one state to another. Args: source (str): the name of the state from where the transition starts dest (str): the name of the state where the transition ends """ self._transitions[source].append(dest)
[ "def", "add_transition", "(", "self", ",", "source", ":", "str", ",", "dest", ":", "str", ")", ":", "self", ".", "_transitions", "[", "source", "]", ".", "append", "(", "dest", ")" ]
Adds a transition from one state to another. Args: source (str): the name of the state from where the transition starts dest (str): the name of the state where the transition ends
[ "Adds", "a", "transition", "from", "one", "state", "to", "another", "." ]
59942bd1a1edae4c807d06cabb178d5630cbf61b
https://github.com/javipalanca/spade/blob/59942bd1a1edae4c807d06cabb178d5630cbf61b/spade/behaviour.py#L490-L498
train
212,483
javipalanca/spade
spade/behaviour.py
FSMBehaviour.is_valid_transition
def is_valid_transition(self, source: str, dest: str) -> bool: """ Checks if a transitions is registered in the FSM Args: source (str): the source state name dest (str): the destination state name Returns: bool: wether the transition is valid or not """ if dest not in self._states or source not in self._states: raise NotValidState elif dest not in self._transitions[source]: raise NotValidTransition return True
python
def is_valid_transition(self, source: str, dest: str) -> bool: """ Checks if a transitions is registered in the FSM Args: source (str): the source state name dest (str): the destination state name Returns: bool: wether the transition is valid or not """ if dest not in self._states or source not in self._states: raise NotValidState elif dest not in self._transitions[source]: raise NotValidTransition return True
[ "def", "is_valid_transition", "(", "self", ",", "source", ":", "str", ",", "dest", ":", "str", ")", "->", "bool", ":", "if", "dest", "not", "in", "self", ".", "_states", "or", "source", "not", "in", "self", ".", "_states", ":", "raise", "NotValidState"...
Checks if a transitions is registered in the FSM Args: source (str): the source state name dest (str): the destination state name Returns: bool: wether the transition is valid or not
[ "Checks", "if", "a", "transitions", "is", "registered", "in", "the", "FSM" ]
59942bd1a1edae4c807d06cabb178d5630cbf61b
https://github.com/javipalanca/spade/blob/59942bd1a1edae4c807d06cabb178d5630cbf61b/spade/behaviour.py#L500-L516
train
212,484
javipalanca/spade
spade/behaviour.py
FSMBehaviour.to_graphviz
def to_graphviz(self) -> str: """ Converts the FSM behaviour structure to Graphviz syntax Returns: str: the graph in Graphviz syntax """ graph = "digraph finite_state_machine { rankdir=LR; node [fixedsize=true];" for origin, dest in self._transitions.items(): origin = origin.replace(" ", "_") for d in dest: d = d.replace(" ", "_") graph += "{0} -> {1};".format(origin, d) graph += "}" return graph
python
def to_graphviz(self) -> str: """ Converts the FSM behaviour structure to Graphviz syntax Returns: str: the graph in Graphviz syntax """ graph = "digraph finite_state_machine { rankdir=LR; node [fixedsize=true];" for origin, dest in self._transitions.items(): origin = origin.replace(" ", "_") for d in dest: d = d.replace(" ", "_") graph += "{0} -> {1};".format(origin, d) graph += "}" return graph
[ "def", "to_graphviz", "(", "self", ")", "->", "str", ":", "graph", "=", "\"digraph finite_state_machine { rankdir=LR; node [fixedsize=true];\"", "for", "origin", ",", "dest", "in", "self", ".", "_transitions", ".", "items", "(", ")", ":", "origin", "=", "origin", ...
Converts the FSM behaviour structure to Graphviz syntax Returns: str: the graph in Graphviz syntax
[ "Converts", "the", "FSM", "behaviour", "structure", "to", "Graphviz", "syntax" ]
59942bd1a1edae4c807d06cabb178d5630cbf61b
https://github.com/javipalanca/spade/blob/59942bd1a1edae4c807d06cabb178d5630cbf61b/spade/behaviour.py#L564-L579
train
212,485
bmcfee/resampy
resampy/core.py
resample
def resample(x, sr_orig, sr_new, axis=-1, filter='kaiser_best', **kwargs): '''Resample a signal x from sr_orig to sr_new along a given axis. Parameters ---------- x : np.ndarray, dtype=np.float* The input signal(s) to resample. sr_orig : int > 0 The sampling rate of x sr_new : int > 0 The target sampling rate of the output signal(s) axis : int The target axis along which to resample `x` filter : optional, str or callable The resampling filter to use. By default, uses the `kaiser_best` (pre-computed filter). kwargs additional keyword arguments provided to the specified filter Returns ------- y : np.ndarray `x` resampled to `sr_new` Raises ------ ValueError if `sr_orig` or `sr_new` is not positive TypeError if the input signal `x` has an unsupported data type. Examples -------- >>> # Generate a sine wave at 440 Hz for 5 seconds >>> sr_orig = 44100.0 >>> x = np.sin(2 * np.pi * 440.0 / sr_orig * np.arange(5 * sr_orig)) >>> x array([ 0. , 0.063, ..., -0.125, -0.063]) >>> # Resample to 22050 with default parameters >>> resampy.resample(x, sr_orig, 22050) array([ 0.011, 0.123, ..., -0.193, -0.103]) >>> # Resample using the fast (low-quality) filter >>> resampy.resample(x, sr_orig, 22050, filter='kaiser_fast') array([ 0.013, 0.121, ..., -0.189, -0.102]) >>> # Resample using a high-quality filter >>> resampy.resample(x, sr_orig, 22050, filter='kaiser_best') array([ 0.011, 0.123, ..., -0.193, -0.103]) >>> # Resample using a Hann-windowed sinc filter >>> resampy.resample(x, sr_orig, 22050, filter='sinc_window', ... window=scipy.signal.hann) array([ 0.011, 0.123, ..., -0.193, -0.103]) >>> # Generate stereo data >>> x_right = np.sin(2 * np.pi * 880.0 / sr_orig * np.arange(len(x)))]) >>> x_stereo = np.stack([x, x_right]) >>> x_stereo.shape (2, 220500) >>> # Resample along the time axis (1) >>> y_stereo = resampy.resample(x, sr_orig, 22050, axis=1) >>> y_stereo.shape (2, 110250) ''' if sr_orig <= 0: raise ValueError('Invalid sample rate: sr_orig={}'.format(sr_orig)) if sr_new <= 0: raise ValueError('Invalid sample rate: sr_new={}'.format(sr_new)) sample_ratio = float(sr_new) / sr_orig # Set up the output shape shape = list(x.shape) shape[axis] = int(shape[axis] * sample_ratio) if shape[axis] < 1: raise ValueError('Input signal length={} is too small to ' 'resample from {}->{}'.format(x.shape[axis], sr_orig, sr_new)) y = np.zeros(shape, dtype=x.dtype) interp_win, precision, _ = get_filter(filter, **kwargs) if sample_ratio < 1: interp_win *= sample_ratio interp_delta = np.zeros_like(interp_win) interp_delta[:-1] = np.diff(interp_win) # Construct 2d views of the data with the resampling axis on the first dimension x_2d = x.swapaxes(0, axis).reshape((x.shape[axis], -1)) y_2d = y.swapaxes(0, axis).reshape((y.shape[axis], -1)) resample_f(x_2d, y_2d, sample_ratio, interp_win, interp_delta, precision) return y
python
def resample(x, sr_orig, sr_new, axis=-1, filter='kaiser_best', **kwargs): '''Resample a signal x from sr_orig to sr_new along a given axis. Parameters ---------- x : np.ndarray, dtype=np.float* The input signal(s) to resample. sr_orig : int > 0 The sampling rate of x sr_new : int > 0 The target sampling rate of the output signal(s) axis : int The target axis along which to resample `x` filter : optional, str or callable The resampling filter to use. By default, uses the `kaiser_best` (pre-computed filter). kwargs additional keyword arguments provided to the specified filter Returns ------- y : np.ndarray `x` resampled to `sr_new` Raises ------ ValueError if `sr_orig` or `sr_new` is not positive TypeError if the input signal `x` has an unsupported data type. Examples -------- >>> # Generate a sine wave at 440 Hz for 5 seconds >>> sr_orig = 44100.0 >>> x = np.sin(2 * np.pi * 440.0 / sr_orig * np.arange(5 * sr_orig)) >>> x array([ 0. , 0.063, ..., -0.125, -0.063]) >>> # Resample to 22050 with default parameters >>> resampy.resample(x, sr_orig, 22050) array([ 0.011, 0.123, ..., -0.193, -0.103]) >>> # Resample using the fast (low-quality) filter >>> resampy.resample(x, sr_orig, 22050, filter='kaiser_fast') array([ 0.013, 0.121, ..., -0.189, -0.102]) >>> # Resample using a high-quality filter >>> resampy.resample(x, sr_orig, 22050, filter='kaiser_best') array([ 0.011, 0.123, ..., -0.193, -0.103]) >>> # Resample using a Hann-windowed sinc filter >>> resampy.resample(x, sr_orig, 22050, filter='sinc_window', ... window=scipy.signal.hann) array([ 0.011, 0.123, ..., -0.193, -0.103]) >>> # Generate stereo data >>> x_right = np.sin(2 * np.pi * 880.0 / sr_orig * np.arange(len(x)))]) >>> x_stereo = np.stack([x, x_right]) >>> x_stereo.shape (2, 220500) >>> # Resample along the time axis (1) >>> y_stereo = resampy.resample(x, sr_orig, 22050, axis=1) >>> y_stereo.shape (2, 110250) ''' if sr_orig <= 0: raise ValueError('Invalid sample rate: sr_orig={}'.format(sr_orig)) if sr_new <= 0: raise ValueError('Invalid sample rate: sr_new={}'.format(sr_new)) sample_ratio = float(sr_new) / sr_orig # Set up the output shape shape = list(x.shape) shape[axis] = int(shape[axis] * sample_ratio) if shape[axis] < 1: raise ValueError('Input signal length={} is too small to ' 'resample from {}->{}'.format(x.shape[axis], sr_orig, sr_new)) y = np.zeros(shape, dtype=x.dtype) interp_win, precision, _ = get_filter(filter, **kwargs) if sample_ratio < 1: interp_win *= sample_ratio interp_delta = np.zeros_like(interp_win) interp_delta[:-1] = np.diff(interp_win) # Construct 2d views of the data with the resampling axis on the first dimension x_2d = x.swapaxes(0, axis).reshape((x.shape[axis], -1)) y_2d = y.swapaxes(0, axis).reshape((y.shape[axis], -1)) resample_f(x_2d, y_2d, sample_ratio, interp_win, interp_delta, precision) return y
[ "def", "resample", "(", "x", ",", "sr_orig", ",", "sr_new", ",", "axis", "=", "-", "1", ",", "filter", "=", "'kaiser_best'", ",", "*", "*", "kwargs", ")", ":", "if", "sr_orig", "<=", "0", ":", "raise", "ValueError", "(", "'Invalid sample rate: sr_orig={}...
Resample a signal x from sr_orig to sr_new along a given axis. Parameters ---------- x : np.ndarray, dtype=np.float* The input signal(s) to resample. sr_orig : int > 0 The sampling rate of x sr_new : int > 0 The target sampling rate of the output signal(s) axis : int The target axis along which to resample `x` filter : optional, str or callable The resampling filter to use. By default, uses the `kaiser_best` (pre-computed filter). kwargs additional keyword arguments provided to the specified filter Returns ------- y : np.ndarray `x` resampled to `sr_new` Raises ------ ValueError if `sr_orig` or `sr_new` is not positive TypeError if the input signal `x` has an unsupported data type. Examples -------- >>> # Generate a sine wave at 440 Hz for 5 seconds >>> sr_orig = 44100.0 >>> x = np.sin(2 * np.pi * 440.0 / sr_orig * np.arange(5 * sr_orig)) >>> x array([ 0. , 0.063, ..., -0.125, -0.063]) >>> # Resample to 22050 with default parameters >>> resampy.resample(x, sr_orig, 22050) array([ 0.011, 0.123, ..., -0.193, -0.103]) >>> # Resample using the fast (low-quality) filter >>> resampy.resample(x, sr_orig, 22050, filter='kaiser_fast') array([ 0.013, 0.121, ..., -0.189, -0.102]) >>> # Resample using a high-quality filter >>> resampy.resample(x, sr_orig, 22050, filter='kaiser_best') array([ 0.011, 0.123, ..., -0.193, -0.103]) >>> # Resample using a Hann-windowed sinc filter >>> resampy.resample(x, sr_orig, 22050, filter='sinc_window', ... window=scipy.signal.hann) array([ 0.011, 0.123, ..., -0.193, -0.103]) >>> # Generate stereo data >>> x_right = np.sin(2 * np.pi * 880.0 / sr_orig * np.arange(len(x)))]) >>> x_stereo = np.stack([x, x_right]) >>> x_stereo.shape (2, 220500) >>> # Resample along the time axis (1) >>> y_stereo = resampy.resample(x, sr_orig, 22050, axis=1) >>> y_stereo.shape (2, 110250)
[ "Resample", "a", "signal", "x", "from", "sr_orig", "to", "sr_new", "along", "a", "given", "axis", "." ]
e5238a7120dcf0d76813bcd3e277998ead8fc308
https://github.com/bmcfee/resampy/blob/e5238a7120dcf0d76813bcd3e277998ead8fc308/resampy/core.py#L14-L115
train
212,486
bmcfee/resampy
resampy/filters.py
sinc_window
def sinc_window(num_zeros=64, precision=9, window=None, rolloff=0.945): '''Construct a windowed sinc interpolation filter Parameters ---------- num_zeros : int > 0 The number of zero-crossings to retain in the sinc filter precision : int > 0 The number of filter coefficients to retain for each zero-crossing window : callable The window function. By default, uses Blackman-Harris. rolloff : float > 0 The roll-off frequency (as a fraction of nyquist) Returns ------- interp_window: np.ndarray [shape=(num_zeros * num_table + 1)] The interpolation window (right-hand side) num_bits: int The number of bits of precision to use in the filter table rolloff : float > 0 The roll-off frequency of the filter, as a fraction of Nyquist Raises ------ TypeError if `window` is not callable or `None` ValueError if `num_zeros < 1`, `precision < 1`, or `rolloff` is outside the range `(0, 1]`. Examples -------- >>> # A filter with 10 zero-crossings, 32 samples per crossing, and a ... # Hann window for tapering. >>> halfwin, prec, rolloff = resampy.filters.sinc_window(num_zeros=10, precision=5, ... window=scipy.signal.hann) >>> halfwin array([ 9.450e-01, 9.436e-01, ..., -7.455e-07, -0.000e+00]) >>> prec 32 >>> rolloff 0.945 >>> # Or using sinc-window filter construction directly in resample >>> y = resampy.resample(x, sr_orig, sr_new, filter='sinc_window', ... num_zeros=10, precision=5, ... window=scipy.signal.hann) ''' if window is None: window = scipy.signal.blackmanharris elif not six.callable(window): raise TypeError('window must be callable, not type(window)={}'.format(type(window))) if not 0 < rolloff <= 1: raise ValueError('Invalid roll-off: rolloff={}'.format(rolloff)) if num_zeros < 1: raise ValueError('Invalid num_zeros: num_zeros={}'.format(num_zeros)) if precision < 0: raise ValueError('Invalid precision: precision={}'.format(precision)) # Generate the right-wing of the sinc num_bits = 2**precision n = num_bits * num_zeros sinc_win = rolloff * np.sinc(rolloff * np.linspace(0, num_zeros, num=n + 1, endpoint=True)) # Build the window function and cut off the left half taper = window(2 * n + 1)[n:] interp_win = (taper * sinc_win) return interp_win, num_bits, rolloff
python
def sinc_window(num_zeros=64, precision=9, window=None, rolloff=0.945): '''Construct a windowed sinc interpolation filter Parameters ---------- num_zeros : int > 0 The number of zero-crossings to retain in the sinc filter precision : int > 0 The number of filter coefficients to retain for each zero-crossing window : callable The window function. By default, uses Blackman-Harris. rolloff : float > 0 The roll-off frequency (as a fraction of nyquist) Returns ------- interp_window: np.ndarray [shape=(num_zeros * num_table + 1)] The interpolation window (right-hand side) num_bits: int The number of bits of precision to use in the filter table rolloff : float > 0 The roll-off frequency of the filter, as a fraction of Nyquist Raises ------ TypeError if `window` is not callable or `None` ValueError if `num_zeros < 1`, `precision < 1`, or `rolloff` is outside the range `(0, 1]`. Examples -------- >>> # A filter with 10 zero-crossings, 32 samples per crossing, and a ... # Hann window for tapering. >>> halfwin, prec, rolloff = resampy.filters.sinc_window(num_zeros=10, precision=5, ... window=scipy.signal.hann) >>> halfwin array([ 9.450e-01, 9.436e-01, ..., -7.455e-07, -0.000e+00]) >>> prec 32 >>> rolloff 0.945 >>> # Or using sinc-window filter construction directly in resample >>> y = resampy.resample(x, sr_orig, sr_new, filter='sinc_window', ... num_zeros=10, precision=5, ... window=scipy.signal.hann) ''' if window is None: window = scipy.signal.blackmanharris elif not six.callable(window): raise TypeError('window must be callable, not type(window)={}'.format(type(window))) if not 0 < rolloff <= 1: raise ValueError('Invalid roll-off: rolloff={}'.format(rolloff)) if num_zeros < 1: raise ValueError('Invalid num_zeros: num_zeros={}'.format(num_zeros)) if precision < 0: raise ValueError('Invalid precision: precision={}'.format(precision)) # Generate the right-wing of the sinc num_bits = 2**precision n = num_bits * num_zeros sinc_win = rolloff * np.sinc(rolloff * np.linspace(0, num_zeros, num=n + 1, endpoint=True)) # Build the window function and cut off the left half taper = window(2 * n + 1)[n:] interp_win = (taper * sinc_win) return interp_win, num_bits, rolloff
[ "def", "sinc_window", "(", "num_zeros", "=", "64", ",", "precision", "=", "9", ",", "window", "=", "None", ",", "rolloff", "=", "0.945", ")", ":", "if", "window", "is", "None", ":", "window", "=", "scipy", ".", "signal", ".", "blackmanharris", "elif", ...
Construct a windowed sinc interpolation filter Parameters ---------- num_zeros : int > 0 The number of zero-crossings to retain in the sinc filter precision : int > 0 The number of filter coefficients to retain for each zero-crossing window : callable The window function. By default, uses Blackman-Harris. rolloff : float > 0 The roll-off frequency (as a fraction of nyquist) Returns ------- interp_window: np.ndarray [shape=(num_zeros * num_table + 1)] The interpolation window (right-hand side) num_bits: int The number of bits of precision to use in the filter table rolloff : float > 0 The roll-off frequency of the filter, as a fraction of Nyquist Raises ------ TypeError if `window` is not callable or `None` ValueError if `num_zeros < 1`, `precision < 1`, or `rolloff` is outside the range `(0, 1]`. Examples -------- >>> # A filter with 10 zero-crossings, 32 samples per crossing, and a ... # Hann window for tapering. >>> halfwin, prec, rolloff = resampy.filters.sinc_window(num_zeros=10, precision=5, ... window=scipy.signal.hann) >>> halfwin array([ 9.450e-01, 9.436e-01, ..., -7.455e-07, -0.000e+00]) >>> prec 32 >>> rolloff 0.945 >>> # Or using sinc-window filter construction directly in resample >>> y = resampy.resample(x, sr_orig, sr_new, filter='sinc_window', ... num_zeros=10, precision=5, ... window=scipy.signal.hann)
[ "Construct", "a", "windowed", "sinc", "interpolation", "filter" ]
e5238a7120dcf0d76813bcd3e277998ead8fc308
https://github.com/bmcfee/resampy/blob/e5238a7120dcf0d76813bcd3e277998ead8fc308/resampy/filters.py#L41-L121
train
212,487
bmcfee/resampy
resampy/filters.py
get_filter
def get_filter(name_or_function, **kwargs): '''Retrieve a window given its name or function handle. Parameters ---------- name_or_function : str or callable If a function, returns `name_or_function(**kwargs)`. If a string, and it matches the name of one of the defined filter functions, the corresponding function is called with `**kwargs`. If a string, and it matches the name of a pre-computed filter, the corresponding filter is retrieved, and kwargs is ignored. Valid pre-computed filter names are: - 'kaiser_fast' - 'kaiser_best' Returns ------- half_window : np.ndarray The right wing of the interpolation filter precision : int > 0 The number of samples between zero-crossings of the filter rolloff : float > 0 The roll-off frequency of the filter as a fraction of Nyquist Raises ------ NotImplementedError If `name_or_function` cannot be found as a filter. ''' if name_or_function in FILTER_FUNCTIONS: return getattr(sys.modules[__name__], name_or_function)(**kwargs) elif six.callable(name_or_function): return name_or_function(**kwargs) else: try: return load_filter(name_or_function) except (IOError, ValueError): raise NotImplementedError('Cannot load filter definition for ' '{}'.format(name_or_function))
python
def get_filter(name_or_function, **kwargs): '''Retrieve a window given its name or function handle. Parameters ---------- name_or_function : str or callable If a function, returns `name_or_function(**kwargs)`. If a string, and it matches the name of one of the defined filter functions, the corresponding function is called with `**kwargs`. If a string, and it matches the name of a pre-computed filter, the corresponding filter is retrieved, and kwargs is ignored. Valid pre-computed filter names are: - 'kaiser_fast' - 'kaiser_best' Returns ------- half_window : np.ndarray The right wing of the interpolation filter precision : int > 0 The number of samples between zero-crossings of the filter rolloff : float > 0 The roll-off frequency of the filter as a fraction of Nyquist Raises ------ NotImplementedError If `name_or_function` cannot be found as a filter. ''' if name_or_function in FILTER_FUNCTIONS: return getattr(sys.modules[__name__], name_or_function)(**kwargs) elif six.callable(name_or_function): return name_or_function(**kwargs) else: try: return load_filter(name_or_function) except (IOError, ValueError): raise NotImplementedError('Cannot load filter definition for ' '{}'.format(name_or_function))
[ "def", "get_filter", "(", "name_or_function", ",", "*", "*", "kwargs", ")", ":", "if", "name_or_function", "in", "FILTER_FUNCTIONS", ":", "return", "getattr", "(", "sys", ".", "modules", "[", "__name__", "]", ",", "name_or_function", ")", "(", "*", "*", "k...
Retrieve a window given its name or function handle. Parameters ---------- name_or_function : str or callable If a function, returns `name_or_function(**kwargs)`. If a string, and it matches the name of one of the defined filter functions, the corresponding function is called with `**kwargs`. If a string, and it matches the name of a pre-computed filter, the corresponding filter is retrieved, and kwargs is ignored. Valid pre-computed filter names are: - 'kaiser_fast' - 'kaiser_best' Returns ------- half_window : np.ndarray The right wing of the interpolation filter precision : int > 0 The number of samples between zero-crossings of the filter rolloff : float > 0 The roll-off frequency of the filter as a fraction of Nyquist Raises ------ NotImplementedError If `name_or_function` cannot be found as a filter.
[ "Retrieve", "a", "window", "given", "its", "name", "or", "function", "handle", "." ]
e5238a7120dcf0d76813bcd3e277998ead8fc308
https://github.com/bmcfee/resampy/blob/e5238a7120dcf0d76813bcd3e277998ead8fc308/resampy/filters.py#L124-L167
train
212,488
bmcfee/resampy
resampy/filters.py
load_filter
def load_filter(filter_name): '''Retrieve a pre-computed filter. Parameters ---------- filter_name : str The key of the filter, e.g., 'kaiser_fast' Returns ------- half_window : np.ndarray The right wing of the interpolation filter precision : int > 0 The number of samples between zero-crossings of the fitler rolloff : float > 0 The roll-off frequency of the filter, as a fraction of Nyquist ''' fname = os.path.join('data', os.path.extsep.join([filter_name, 'npz'])) data = np.load(pkg_resources.resource_filename(__name__, fname)) return data['half_window'], data['precision'], data['rolloff']
python
def load_filter(filter_name): '''Retrieve a pre-computed filter. Parameters ---------- filter_name : str The key of the filter, e.g., 'kaiser_fast' Returns ------- half_window : np.ndarray The right wing of the interpolation filter precision : int > 0 The number of samples between zero-crossings of the fitler rolloff : float > 0 The roll-off frequency of the filter, as a fraction of Nyquist ''' fname = os.path.join('data', os.path.extsep.join([filter_name, 'npz'])) data = np.load(pkg_resources.resource_filename(__name__, fname)) return data['half_window'], data['precision'], data['rolloff']
[ "def", "load_filter", "(", "filter_name", ")", ":", "fname", "=", "os", ".", "path", ".", "join", "(", "'data'", ",", "os", ".", "path", ".", "extsep", ".", "join", "(", "[", "filter_name", ",", "'npz'", "]", ")", ")", "data", "=", "np", ".", "lo...
Retrieve a pre-computed filter. Parameters ---------- filter_name : str The key of the filter, e.g., 'kaiser_fast' Returns ------- half_window : np.ndarray The right wing of the interpolation filter precision : int > 0 The number of samples between zero-crossings of the fitler rolloff : float > 0 The roll-off frequency of the filter, as a fraction of Nyquist
[ "Retrieve", "a", "pre", "-", "computed", "filter", "." ]
e5238a7120dcf0d76813bcd3e277998ead8fc308
https://github.com/bmcfee/resampy/blob/e5238a7120dcf0d76813bcd3e277998ead8fc308/resampy/filters.py#L170-L195
train
212,489
tmbo/questionary
questionary/utils.py
default_values_of
def default_values_of(func): """Return the defaults of the function `func`.""" signature = inspect.signature(func) return [k for k, v in signature.parameters.items() if v.default is not inspect.Parameter.empty or v.kind != inspect.Parameter.POSITIONAL_OR_KEYWORD]
python
def default_values_of(func): """Return the defaults of the function `func`.""" signature = inspect.signature(func) return [k for k, v in signature.parameters.items() if v.default is not inspect.Parameter.empty or v.kind != inspect.Parameter.POSITIONAL_OR_KEYWORD]
[ "def", "default_values_of", "(", "func", ")", ":", "signature", "=", "inspect", ".", "signature", "(", "func", ")", "return", "[", "k", "for", "k", ",", "v", "in", "signature", ".", "parameters", ".", "items", "(", ")", "if", "v", ".", "default", "is...
Return the defaults of the function `func`.
[ "Return", "the", "defaults", "of", "the", "function", "func", "." ]
3dbaa569a0d252404d547360bee495294bbd620d
https://github.com/tmbo/questionary/blob/3dbaa569a0d252404d547360bee495294bbd620d/questionary/utils.py#L7-L14
train
212,490
tmbo/questionary
questionary/utils.py
required_arguments
def required_arguments(func): """Return all arguments of a function that do not have a default value.""" defaults = default_values_of(func) args = arguments_of(func) if defaults: args = args[:-len(defaults)] return args
python
def required_arguments(func): """Return all arguments of a function that do not have a default value.""" defaults = default_values_of(func) args = arguments_of(func) if defaults: args = args[:-len(defaults)] return args
[ "def", "required_arguments", "(", "func", ")", ":", "defaults", "=", "default_values_of", "(", "func", ")", "args", "=", "arguments_of", "(", "func", ")", "if", "defaults", ":", "args", "=", "args", "[", ":", "-", "len", "(", "defaults", ")", "]", "ret...
Return all arguments of a function that do not have a default value.
[ "Return", "all", "arguments", "of", "a", "function", "that", "do", "not", "have", "a", "default", "value", "." ]
3dbaa569a0d252404d547360bee495294bbd620d
https://github.com/tmbo/questionary/blob/3dbaa569a0d252404d547360bee495294bbd620d/questionary/utils.py#L23-L30
train
212,491
tmbo/questionary
questionary/prompts/text.py
text
def text(message: Text, default: Text = "", validate: Union[Type[Validator], Callable[[Text], bool], None] = None, # noqa qmark: Text = DEFAULT_QUESTION_PREFIX, style: Optional[Style] = None, **kwargs: Any) -> Question: """Prompt the user to enter a free text message. This question type can be used to prompt the user for some text input. Args: message: Question text default: Default value will be returned if the user just hits enter. validate: Require the entered value to pass a validation. The value can not be submited until the validator accepts it (e.g. to check minimum password length). This can either be a function accepting the input and returning a boolean, or an class reference to a subclass of the prompt toolkit Validator class. qmark: Question prefix displayed in front of the question. By default this is a `?` style: A custom color and style for the question parts. You can configure colors as well as font types for different elements. Returns: Question: Question instance, ready to be prompted (using `.ask()`). """ merged_style = merge_styles([DEFAULT_STYLE, style]) validator = build_validator(validate) def get_prompt_tokens(): return [("class:qmark", qmark), ("class:question", ' {} '.format(message))] p = PromptSession(get_prompt_tokens, style=merged_style, validator=validator, **kwargs) p.default_buffer.reset(Document(default)) return Question(p.app)
python
def text(message: Text, default: Text = "", validate: Union[Type[Validator], Callable[[Text], bool], None] = None, # noqa qmark: Text = DEFAULT_QUESTION_PREFIX, style: Optional[Style] = None, **kwargs: Any) -> Question: """Prompt the user to enter a free text message. This question type can be used to prompt the user for some text input. Args: message: Question text default: Default value will be returned if the user just hits enter. validate: Require the entered value to pass a validation. The value can not be submited until the validator accepts it (e.g. to check minimum password length). This can either be a function accepting the input and returning a boolean, or an class reference to a subclass of the prompt toolkit Validator class. qmark: Question prefix displayed in front of the question. By default this is a `?` style: A custom color and style for the question parts. You can configure colors as well as font types for different elements. Returns: Question: Question instance, ready to be prompted (using `.ask()`). """ merged_style = merge_styles([DEFAULT_STYLE, style]) validator = build_validator(validate) def get_prompt_tokens(): return [("class:qmark", qmark), ("class:question", ' {} '.format(message))] p = PromptSession(get_prompt_tokens, style=merged_style, validator=validator, **kwargs) p.default_buffer.reset(Document(default)) return Question(p.app)
[ "def", "text", "(", "message", ":", "Text", ",", "default", ":", "Text", "=", "\"\"", ",", "validate", ":", "Union", "[", "Type", "[", "Validator", "]", ",", "Callable", "[", "[", "Text", "]", ",", "bool", "]", ",", "None", "]", "=", "None", ",",...
Prompt the user to enter a free text message. This question type can be used to prompt the user for some text input. Args: message: Question text default: Default value will be returned if the user just hits enter. validate: Require the entered value to pass a validation. The value can not be submited until the validator accepts it (e.g. to check minimum password length). This can either be a function accepting the input and returning a boolean, or an class reference to a subclass of the prompt toolkit Validator class. qmark: Question prefix displayed in front of the question. By default this is a `?` style: A custom color and style for the question parts. You can configure colors as well as font types for different elements. Returns: Question: Question instance, ready to be prompted (using `.ask()`).
[ "Prompt", "the", "user", "to", "enter", "a", "free", "text", "message", "." ]
3dbaa569a0d252404d547360bee495294bbd620d
https://github.com/tmbo/questionary/blob/3dbaa569a0d252404d547360bee495294bbd620d/questionary/prompts/text.py#L15-L65
train
212,492
tmbo/questionary
questionary/question.py
Question.skip_if
def skip_if(self, condition: bool, default: Any = None) -> 'Question': """Skip the question if flag is set and return the default instead.""" self.should_skip_question = condition self.default = default return self
python
def skip_if(self, condition: bool, default: Any = None) -> 'Question': """Skip the question if flag is set and return the default instead.""" self.should_skip_question = condition self.default = default return self
[ "def", "skip_if", "(", "self", ",", "condition", ":", "bool", ",", "default", ":", "Any", "=", "None", ")", "->", "'Question'", ":", "self", ".", "should_skip_question", "=", "condition", "self", ".", "default", "=", "default", "return", "self" ]
Skip the question if flag is set and return the default instead.
[ "Skip", "the", "question", "if", "flag", "is", "set", "and", "return", "the", "default", "instead", "." ]
3dbaa569a0d252404d547360bee495294bbd620d
https://github.com/tmbo/questionary/blob/3dbaa569a0d252404d547360bee495294bbd620d/questionary/question.py#L61-L66
train
212,493
tmbo/questionary
questionary/prompts/common.py
_fix_unecessary_blank_lines
def _fix_unecessary_blank_lines(ps: PromptSession) -> None: """This is a fix for additional empty lines added by prompt toolkit. This assumes the layout of the default session doesn't change, if it does, this needs an update.""" default_container = ps.layout.container default_buffer_window = \ default_container.get_children()[0].content.get_children()[1].content assert isinstance(default_buffer_window, Window) # this forces the main window to stay as small as possible, avoiding # empty lines in selections default_buffer_window.dont_extend_height = Always()
python
def _fix_unecessary_blank_lines(ps: PromptSession) -> None: """This is a fix for additional empty lines added by prompt toolkit. This assumes the layout of the default session doesn't change, if it does, this needs an update.""" default_container = ps.layout.container default_buffer_window = \ default_container.get_children()[0].content.get_children()[1].content assert isinstance(default_buffer_window, Window) # this forces the main window to stay as small as possible, avoiding # empty lines in selections default_buffer_window.dont_extend_height = Always()
[ "def", "_fix_unecessary_blank_lines", "(", "ps", ":", "PromptSession", ")", "->", "None", ":", "default_container", "=", "ps", ".", "layout", ".", "container", "default_buffer_window", "=", "default_container", ".", "get_children", "(", ")", "[", "0", "]", ".", ...
This is a fix for additional empty lines added by prompt toolkit. This assumes the layout of the default session doesn't change, if it does, this needs an update.
[ "This", "is", "a", "fix", "for", "additional", "empty", "lines", "added", "by", "prompt", "toolkit", "." ]
3dbaa569a0d252404d547360bee495294bbd620d
https://github.com/tmbo/questionary/blob/3dbaa569a0d252404d547360bee495294bbd620d/questionary/prompts/common.py#L269-L283
train
212,494
tmbo/questionary
questionary/prompts/common.py
create_inquirer_layout
def create_inquirer_layout( ic: InquirerControl, get_prompt_tokens: Callable[[], List[Tuple[Text, Text]]], **kwargs) -> Layout: """Create a layout combining question and inquirer selection.""" ps = PromptSession(get_prompt_tokens, reserve_space_for_menu=0, **kwargs) _fix_unecessary_blank_lines(ps) return Layout(HSplit([ ps.layout.container, ConditionalContainer( Window(ic), filter=~IsDone() ) ]))
python
def create_inquirer_layout( ic: InquirerControl, get_prompt_tokens: Callable[[], List[Tuple[Text, Text]]], **kwargs) -> Layout: """Create a layout combining question and inquirer selection.""" ps = PromptSession(get_prompt_tokens, reserve_space_for_menu=0, **kwargs) _fix_unecessary_blank_lines(ps) return Layout(HSplit([ ps.layout.container, ConditionalContainer( Window(ic), filter=~IsDone() ) ]))
[ "def", "create_inquirer_layout", "(", "ic", ":", "InquirerControl", ",", "get_prompt_tokens", ":", "Callable", "[", "[", "]", ",", "List", "[", "Tuple", "[", "Text", ",", "Text", "]", "]", "]", ",", "*", "*", "kwargs", ")", "->", "Layout", ":", "ps", ...
Create a layout combining question and inquirer selection.
[ "Create", "a", "layout", "combining", "question", "and", "inquirer", "selection", "." ]
3dbaa569a0d252404d547360bee495294bbd620d
https://github.com/tmbo/questionary/blob/3dbaa569a0d252404d547360bee495294bbd620d/questionary/prompts/common.py#L286-L302
train
212,495
tmbo/questionary
questionary/prompts/common.py
Choice.build
def build(c: Union[Text, 'Choice', Dict[Text, Any]]) -> 'Choice': """Create a choice object from different representations.""" if isinstance(c, Choice): return c elif isinstance(c, str): return Choice(c, c) else: return Choice(c.get('name'), c.get('value'), c.get('disabled', None), c.get('checked'), c.get('key'))
python
def build(c: Union[Text, 'Choice', Dict[Text, Any]]) -> 'Choice': """Create a choice object from different representations.""" if isinstance(c, Choice): return c elif isinstance(c, str): return Choice(c, c) else: return Choice(c.get('name'), c.get('value'), c.get('disabled', None), c.get('checked'), c.get('key'))
[ "def", "build", "(", "c", ":", "Union", "[", "Text", ",", "'Choice'", ",", "Dict", "[", "Text", ",", "Any", "]", "]", ")", "->", "'Choice'", ":", "if", "isinstance", "(", "c", ",", "Choice", ")", ":", "return", "c", "elif", "isinstance", "(", "c"...
Create a choice object from different representations.
[ "Create", "a", "choice", "object", "from", "different", "representations", "." ]
3dbaa569a0d252404d547360bee495294bbd620d
https://github.com/tmbo/questionary/blob/3dbaa569a0d252404d547360bee495294bbd620d/questionary/prompts/common.py#L52-L64
train
212,496
tmbo/questionary
questionary/prompts/password.py
password
def password(message: Text, default: Text = "", validate: Union[Type[Validator], Callable[[Text], bool], None] = None, # noqa qmark: Text = DEFAULT_QUESTION_PREFIX, style: Optional[Style] = None, **kwargs: Any) -> Question: """Question the user to enter a secret text not displayed in the prompt. This question type can be used to prompt the user for information that should not be shown in the command line. The typed text will be replaced with `*`. Args: message: Question text default: Default value will be returned if the user just hits enter. validate: Require the entered value to pass a validation. The value can not be submited until the validator accepts it (e.g. to check minimum password length). This can either be a function accepting the input and returning a boolean, or an class reference to a subclass of the prompt toolkit Validator class. qmark: Question prefix displayed in front of the question. By default this is a `?` style: A custom color and style for the question parts. You can configure colors as well as font types for different elements. Returns: Question: Question instance, ready to be prompted (using `.ask()`). """ return text.text(message, default, validate, qmark, style, is_password=True, **kwargs)
python
def password(message: Text, default: Text = "", validate: Union[Type[Validator], Callable[[Text], bool], None] = None, # noqa qmark: Text = DEFAULT_QUESTION_PREFIX, style: Optional[Style] = None, **kwargs: Any) -> Question: """Question the user to enter a secret text not displayed in the prompt. This question type can be used to prompt the user for information that should not be shown in the command line. The typed text will be replaced with `*`. Args: message: Question text default: Default value will be returned if the user just hits enter. validate: Require the entered value to pass a validation. The value can not be submited until the validator accepts it (e.g. to check minimum password length). This can either be a function accepting the input and returning a boolean, or an class reference to a subclass of the prompt toolkit Validator class. qmark: Question prefix displayed in front of the question. By default this is a `?` style: A custom color and style for the question parts. You can configure colors as well as font types for different elements. Returns: Question: Question instance, ready to be prompted (using `.ask()`). """ return text.text(message, default, validate, qmark, style, is_password=True, **kwargs)
[ "def", "password", "(", "message", ":", "Text", ",", "default", ":", "Text", "=", "\"\"", ",", "validate", ":", "Union", "[", "Type", "[", "Validator", "]", ",", "Callable", "[", "[", "Text", "]", ",", "bool", "]", ",", "None", "]", "=", "None", ...
Question the user to enter a secret text not displayed in the prompt. This question type can be used to prompt the user for information that should not be shown in the command line. The typed text will be replaced with `*`. Args: message: Question text default: Default value will be returned if the user just hits enter. validate: Require the entered value to pass a validation. The value can not be submited until the validator accepts it (e.g. to check minimum password length). This can either be a function accepting the input and returning a boolean, or an class reference to a subclass of the prompt toolkit Validator class. qmark: Question prefix displayed in front of the question. By default this is a `?` style: A custom color and style for the question parts. You can configure colors as well as font types for different elements. Returns: Question: Question instance, ready to be prompted (using `.ask()`).
[ "Question", "the", "user", "to", "enter", "a", "secret", "text", "not", "displayed", "in", "the", "prompt", "." ]
3dbaa569a0d252404d547360bee495294bbd620d
https://github.com/tmbo/questionary/blob/3dbaa569a0d252404d547360bee495294bbd620d/questionary/prompts/password.py#L12-L51
train
212,497
tmbo/questionary
questionary/form.py
form
def form(**kwargs: Question): """Create a form with multiple questions. The parameter name of a question will be the key for the answer in the returned dict.""" return Form(*(FormField(k, q) for k, q in kwargs.items()))
python
def form(**kwargs: Question): """Create a form with multiple questions. The parameter name of a question will be the key for the answer in the returned dict.""" return Form(*(FormField(k, q) for k, q in kwargs.items()))
[ "def", "form", "(", "*", "*", "kwargs", ":", "Question", ")", ":", "return", "Form", "(", "*", "(", "FormField", "(", "k", ",", "q", ")", "for", "k", ",", "q", "in", "kwargs", ".", "items", "(", ")", ")", ")" ]
Create a form with multiple questions. The parameter name of a question will be the key for the answer in the returned dict.
[ "Create", "a", "form", "with", "multiple", "questions", "." ]
3dbaa569a0d252404d547360bee495294bbd620d
https://github.com/tmbo/questionary/blob/3dbaa569a0d252404d547360bee495294bbd620d/questionary/form.py#L9-L14
train
212,498
tmbo/questionary
questionary/prompt.py
prompt
def prompt(questions: List[Dict[Text, Any]], answers: Optional[Dict[Text, Any]] = None, patch_stdout: bool = False, true_color: bool = False, kbi_msg: Text = DEFAULT_KBI_MESSAGE, **kwargs): """Prompt the user for input on all the questions.""" if isinstance(questions, dict): questions = [questions] answers = answers or {} for question_config in questions: # import the question if 'type' not in question_config: raise PromptParameterException('type') if 'name' not in question_config: raise PromptParameterException('name') choices = question_config.get('choices') if choices is not None and callable(choices): question_config['choices'] = choices(answers) _kwargs = kwargs.copy() _kwargs.update(question_config) _type = _kwargs.pop('type') _filter = _kwargs.pop('filter', None) name = _kwargs.pop('name') when = _kwargs.pop('when', None) if true_color: _kwargs["color_depth"] = ColorDepth.TRUE_COLOR try: if when: # at least a little sanity check! if callable(question_config['when']): try: if not question_config['when'](answers): continue except Exception as e: raise ValueError("Problem in 'when' check of {} " "question: {}".format(name, e)) else: raise ValueError("'when' needs to be function that " "accepts a dict argument") if _filter: # at least a little sanity check! if not callable(_filter): raise ValueError("'filter' needs to be function that " "accepts an argument") if callable(question_config.get('default')): _kwargs['default'] = question_config['default'](answers) create_question_func = prompt_by_name(_type) if not create_question_func: raise ValueError("No question type '{}' found. " "Known question types are {}." "".format(_type, ", ".join(AVAILABLE_PROMPTS))) missing_args = list(utils.missing_arguments(create_question_func, _kwargs)) if missing_args: raise PromptParameterException(missing_args[0]) question = create_question_func(**_kwargs) answer = question.unsafe_ask(patch_stdout) if answer is not None: if _filter: try: answer = _filter(answer) except Exception as e: raise ValueError("Problem processing 'filter' of {} " "question: {}".format(name, e)) answers[name] = answer except KeyboardInterrupt: print('') print(kbi_msg) print('') return {} return answers
python
def prompt(questions: List[Dict[Text, Any]], answers: Optional[Dict[Text, Any]] = None, patch_stdout: bool = False, true_color: bool = False, kbi_msg: Text = DEFAULT_KBI_MESSAGE, **kwargs): """Prompt the user for input on all the questions.""" if isinstance(questions, dict): questions = [questions] answers = answers or {} for question_config in questions: # import the question if 'type' not in question_config: raise PromptParameterException('type') if 'name' not in question_config: raise PromptParameterException('name') choices = question_config.get('choices') if choices is not None and callable(choices): question_config['choices'] = choices(answers) _kwargs = kwargs.copy() _kwargs.update(question_config) _type = _kwargs.pop('type') _filter = _kwargs.pop('filter', None) name = _kwargs.pop('name') when = _kwargs.pop('when', None) if true_color: _kwargs["color_depth"] = ColorDepth.TRUE_COLOR try: if when: # at least a little sanity check! if callable(question_config['when']): try: if not question_config['when'](answers): continue except Exception as e: raise ValueError("Problem in 'when' check of {} " "question: {}".format(name, e)) else: raise ValueError("'when' needs to be function that " "accepts a dict argument") if _filter: # at least a little sanity check! if not callable(_filter): raise ValueError("'filter' needs to be function that " "accepts an argument") if callable(question_config.get('default')): _kwargs['default'] = question_config['default'](answers) create_question_func = prompt_by_name(_type) if not create_question_func: raise ValueError("No question type '{}' found. " "Known question types are {}." "".format(_type, ", ".join(AVAILABLE_PROMPTS))) missing_args = list(utils.missing_arguments(create_question_func, _kwargs)) if missing_args: raise PromptParameterException(missing_args[0]) question = create_question_func(**_kwargs) answer = question.unsafe_ask(patch_stdout) if answer is not None: if _filter: try: answer = _filter(answer) except Exception as e: raise ValueError("Problem processing 'filter' of {} " "question: {}".format(name, e)) answers[name] = answer except KeyboardInterrupt: print('') print(kbi_msg) print('') return {} return answers
[ "def", "prompt", "(", "questions", ":", "List", "[", "Dict", "[", "Text", ",", "Any", "]", "]", ",", "answers", ":", "Optional", "[", "Dict", "[", "Text", ",", "Any", "]", "]", "=", "None", ",", "patch_stdout", ":", "bool", "=", "False", ",", "tr...
Prompt the user for input on all the questions.
[ "Prompt", "the", "user", "for", "input", "on", "all", "the", "questions", "." ]
3dbaa569a0d252404d547360bee495294bbd620d
https://github.com/tmbo/questionary/blob/3dbaa569a0d252404d547360bee495294bbd620d/questionary/prompt.py#L18-L104
train
212,499