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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
openstack/python-saharaclient | saharaclient/api/clusters.py | ClusterManagerV1.get | def get(self, cluster_id, show_progress=False):
"""Get information about a Cluster."""
url = ('/clusters/%(cluster_id)s?%(params)s' %
{"cluster_id": cluster_id,
"params": parse.urlencode({"show_progress": show_progress})})
return self._get(url, 'cluster') | python | def get(self, cluster_id, show_progress=False):
"""Get information about a Cluster."""
url = ('/clusters/%(cluster_id)s?%(params)s' %
{"cluster_id": cluster_id,
"params": parse.urlencode({"show_progress": show_progress})})
return self._get(url, 'cluster') | [
"def",
"get",
"(",
"self",
",",
"cluster_id",
",",
"show_progress",
"=",
"False",
")",
":",
"url",
"=",
"(",
"'/clusters/%(cluster_id)s?%(params)s'",
"%",
"{",
"\"cluster_id\"",
":",
"cluster_id",
",",
"\"params\"",
":",
"parse",
".",
"urlencode",
"(",
"{",
... | Get information about a Cluster. | [
"Get",
"information",
"about",
"a",
"Cluster",
"."
] | c53831d686d9e94187ce5dfdbfa43883b792280e | https://github.com/openstack/python-saharaclient/blob/c53831d686d9e94187ce5dfdbfa43883b792280e/saharaclient/api/clusters.py#L125-L131 | train | 38,600 |
openstack/python-saharaclient | saharaclient/api/clusters.py | ClusterManagerV1.update | def update(self, cluster_id, name=NotUpdated, description=NotUpdated,
is_public=NotUpdated, is_protected=NotUpdated,
shares=NotUpdated):
"""Update a Cluster."""
data = {}
self._copy_if_updated(data, name=name, description=description,
is_public=is_public, is_protected=is_protected,
shares=shares)
return self._patch('/clusters/%s' % cluster_id, data) | python | def update(self, cluster_id, name=NotUpdated, description=NotUpdated,
is_public=NotUpdated, is_protected=NotUpdated,
shares=NotUpdated):
"""Update a Cluster."""
data = {}
self._copy_if_updated(data, name=name, description=description,
is_public=is_public, is_protected=is_protected,
shares=shares)
return self._patch('/clusters/%s' % cluster_id, data) | [
"def",
"update",
"(",
"self",
",",
"cluster_id",
",",
"name",
"=",
"NotUpdated",
",",
"description",
"=",
"NotUpdated",
",",
"is_public",
"=",
"NotUpdated",
",",
"is_protected",
"=",
"NotUpdated",
",",
"shares",
"=",
"NotUpdated",
")",
":",
"data",
"=",
"{... | Update a Cluster. | [
"Update",
"a",
"Cluster",
"."
] | c53831d686d9e94187ce5dfdbfa43883b792280e | https://github.com/openstack/python-saharaclient/blob/c53831d686d9e94187ce5dfdbfa43883b792280e/saharaclient/api/clusters.py#L137-L147 | train | 38,601 |
openstack/python-saharaclient | saharaclient/api/clusters.py | ClusterManagerV1.verification_update | def verification_update(self, cluster_id, status):
"""Start a verification for a Cluster."""
data = {'verification': {'status': status}}
return self._patch("/clusters/%s" % cluster_id, data) | python | def verification_update(self, cluster_id, status):
"""Start a verification for a Cluster."""
data = {'verification': {'status': status}}
return self._patch("/clusters/%s" % cluster_id, data) | [
"def",
"verification_update",
"(",
"self",
",",
"cluster_id",
",",
"status",
")",
":",
"data",
"=",
"{",
"'verification'",
":",
"{",
"'status'",
":",
"status",
"}",
"}",
"return",
"self",
".",
"_patch",
"(",
"\"/clusters/%s\"",
"%",
"cluster_id",
",",
"dat... | Start a verification for a Cluster. | [
"Start",
"a",
"verification",
"for",
"a",
"Cluster",
"."
] | c53831d686d9e94187ce5dfdbfa43883b792280e | https://github.com/openstack/python-saharaclient/blob/c53831d686d9e94187ce5dfdbfa43883b792280e/saharaclient/api/clusters.py#L149-L152 | train | 38,602 |
openstack/python-saharaclient | saharaclient/api/clusters.py | ClusterManagerV2.create | def create(self, name, plugin_name, plugin_version,
cluster_template_id=None, default_image_id=None,
is_transient=None, description=None, cluster_configs=None,
node_groups=None, user_keypair_id=None,
anti_affinity=None, net_id=None, count=None,
use_autoconfig=None, shares=None,
is_public=None, is_protected=None):
"""Launch a Cluster."""
data = {
'name': name,
'plugin_name': plugin_name,
'plugin_version': plugin_version,
}
return self._do_create(data, cluster_template_id, default_image_id,
is_transient, description, cluster_configs,
node_groups, user_keypair_id, anti_affinity,
net_id, count, use_autoconfig, shares,
is_public, is_protected, api_ver=2) | python | def create(self, name, plugin_name, plugin_version,
cluster_template_id=None, default_image_id=None,
is_transient=None, description=None, cluster_configs=None,
node_groups=None, user_keypair_id=None,
anti_affinity=None, net_id=None, count=None,
use_autoconfig=None, shares=None,
is_public=None, is_protected=None):
"""Launch a Cluster."""
data = {
'name': name,
'plugin_name': plugin_name,
'plugin_version': plugin_version,
}
return self._do_create(data, cluster_template_id, default_image_id,
is_transient, description, cluster_configs,
node_groups, user_keypair_id, anti_affinity,
net_id, count, use_autoconfig, shares,
is_public, is_protected, api_ver=2) | [
"def",
"create",
"(",
"self",
",",
"name",
",",
"plugin_name",
",",
"plugin_version",
",",
"cluster_template_id",
"=",
"None",
",",
"default_image_id",
"=",
"None",
",",
"is_transient",
"=",
"None",
",",
"description",
"=",
"None",
",",
"cluster_configs",
"=",... | Launch a Cluster. | [
"Launch",
"a",
"Cluster",
"."
] | c53831d686d9e94187ce5dfdbfa43883b792280e | https://github.com/openstack/python-saharaclient/blob/c53831d686d9e94187ce5dfdbfa43883b792280e/saharaclient/api/clusters.py#L157-L176 | train | 38,603 |
openstack/python-saharaclient | doc/ext/cli.py | _get_command | def _get_command(classes):
"""Associates each command class with command depending on setup.cfg
"""
commands = {}
setup_file = os.path.join(
os.path.abspath(os.path.join(os.path.dirname(__file__), '../..')),
'setup.cfg')
for line in open(setup_file, 'r'):
for cl in classes:
if cl in line:
commands[cl] = line.split(' = ')[0].strip().replace('_', ' ')
return commands | python | def _get_command(classes):
"""Associates each command class with command depending on setup.cfg
"""
commands = {}
setup_file = os.path.join(
os.path.abspath(os.path.join(os.path.dirname(__file__), '../..')),
'setup.cfg')
for line in open(setup_file, 'r'):
for cl in classes:
if cl in line:
commands[cl] = line.split(' = ')[0].strip().replace('_', ' ')
return commands | [
"def",
"_get_command",
"(",
"classes",
")",
":",
"commands",
"=",
"{",
"}",
"setup_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(... | Associates each command class with command depending on setup.cfg | [
"Associates",
"each",
"command",
"class",
"with",
"command",
"depending",
"on",
"setup",
".",
"cfg"
] | c53831d686d9e94187ce5dfdbfa43883b792280e | https://github.com/openstack/python-saharaclient/blob/c53831d686d9e94187ce5dfdbfa43883b792280e/doc/ext/cli.py#L25-L37 | train | 38,604 |
openstack/python-saharaclient | saharaclient/api/base.py | get_json | def get_json(response):
"""Provide backward compatibility with old versions of requests library."""
json_field_or_function = getattr(response, 'json', None)
if callable(json_field_or_function):
return response.json()
else:
return jsonutils.loads(response.content) | python | def get_json(response):
"""Provide backward compatibility with old versions of requests library."""
json_field_or_function = getattr(response, 'json', None)
if callable(json_field_or_function):
return response.json()
else:
return jsonutils.loads(response.content) | [
"def",
"get_json",
"(",
"response",
")",
":",
"json_field_or_function",
"=",
"getattr",
"(",
"response",
",",
"'json'",
",",
"None",
")",
"if",
"callable",
"(",
"json_field_or_function",
")",
":",
"return",
"response",
".",
"json",
"(",
")",
"else",
":",
"... | Provide backward compatibility with old versions of requests library. | [
"Provide",
"backward",
"compatibility",
"with",
"old",
"versions",
"of",
"requests",
"library",
"."
] | c53831d686d9e94187ce5dfdbfa43883b792280e | https://github.com/openstack/python-saharaclient/blob/c53831d686d9e94187ce5dfdbfa43883b792280e/saharaclient/api/base.py#L239-L246 | train | 38,605 |
openstack/python-saharaclient | saharaclient/api/job_binary_internals.py | JobBinaryInternalsManager.create | def create(self, name, data):
"""Create a Job Binary Internal.
:param str data: raw data of script text
"""
return self._update('/job-binary-internals/%s' %
urlparse.quote(name.encode('utf-8')), data,
'job_binary_internal', dump_json=False) | python | def create(self, name, data):
"""Create a Job Binary Internal.
:param str data: raw data of script text
"""
return self._update('/job-binary-internals/%s' %
urlparse.quote(name.encode('utf-8')), data,
'job_binary_internal', dump_json=False) | [
"def",
"create",
"(",
"self",
",",
"name",
",",
"data",
")",
":",
"return",
"self",
".",
"_update",
"(",
"'/job-binary-internals/%s'",
"%",
"urlparse",
".",
"quote",
"(",
"name",
".",
"encode",
"(",
"'utf-8'",
")",
")",
",",
"data",
",",
"'job_binary_int... | Create a Job Binary Internal.
:param str data: raw data of script text | [
"Create",
"a",
"Job",
"Binary",
"Internal",
"."
] | c53831d686d9e94187ce5dfdbfa43883b792280e | https://github.com/openstack/python-saharaclient/blob/c53831d686d9e94187ce5dfdbfa43883b792280e/saharaclient/api/job_binary_internals.py#L29-L36 | train | 38,606 |
openstack/python-saharaclient | saharaclient/api/job_binary_internals.py | JobBinaryInternalsManager.update | def update(self, job_binary_id, name=NotUpdated, is_public=NotUpdated,
is_protected=NotUpdated):
"""Update a Job Binary Internal."""
data = {}
self._copy_if_updated(data, name=name, is_public=is_public,
is_protected=is_protected)
return self._patch('/job-binary-internals/%s' % job_binary_id, data) | python | def update(self, job_binary_id, name=NotUpdated, is_public=NotUpdated,
is_protected=NotUpdated):
"""Update a Job Binary Internal."""
data = {}
self._copy_if_updated(data, name=name, is_public=is_public,
is_protected=is_protected)
return self._patch('/job-binary-internals/%s' % job_binary_id, data) | [
"def",
"update",
"(",
"self",
",",
"job_binary_id",
",",
"name",
"=",
"NotUpdated",
",",
"is_public",
"=",
"NotUpdated",
",",
"is_protected",
"=",
"NotUpdated",
")",
":",
"data",
"=",
"{",
"}",
"self",
".",
"_copy_if_updated",
"(",
"data",
",",
"name",
"... | Update a Job Binary Internal. | [
"Update",
"a",
"Job",
"Binary",
"Internal",
"."
] | c53831d686d9e94187ce5dfdbfa43883b792280e | https://github.com/openstack/python-saharaclient/blob/c53831d686d9e94187ce5dfdbfa43883b792280e/saharaclient/api/job_binary_internals.py#L55-L63 | train | 38,607 |
Enteee/pdml2flow | pdml2flow/utils.py | autoconvert | def autoconvert(string):
"""Try to convert variables into datatypes."""
for fn in (boolify, int, float):
try:
return fn(string)
except ValueError:
pass
return string | python | def autoconvert(string):
"""Try to convert variables into datatypes."""
for fn in (boolify, int, float):
try:
return fn(string)
except ValueError:
pass
return string | [
"def",
"autoconvert",
"(",
"string",
")",
":",
"for",
"fn",
"in",
"(",
"boolify",
",",
"int",
",",
"float",
")",
":",
"try",
":",
"return",
"fn",
"(",
"string",
")",
"except",
"ValueError",
":",
"pass",
"return",
"string"
] | Try to convert variables into datatypes. | [
"Try",
"to",
"convert",
"variables",
"into",
"datatypes",
"."
] | bc9efe379b0b2406bfbbbd8e0f678b1f63805c66 | https://github.com/Enteee/pdml2flow/blob/bc9efe379b0b2406bfbbbd8e0f678b1f63805c66/pdml2flow/utils.py#L11-L18 | train | 38,608 |
Enteee/pdml2flow | pdml2flow/utils.py | call_plugin | def call_plugin(plugin, f, *args, **kwargs):
"""Calls function f from plugin, returns None if plugin does not implement f."""
try:
getattr(plugin, f)
except AttributeError:
return None
if kwargs:
getattr(plugin, f)(
*args,
**kwargs
)
else:
return getattr(plugin, f)(
*args
) | python | def call_plugin(plugin, f, *args, **kwargs):
"""Calls function f from plugin, returns None if plugin does not implement f."""
try:
getattr(plugin, f)
except AttributeError:
return None
if kwargs:
getattr(plugin, f)(
*args,
**kwargs
)
else:
return getattr(plugin, f)(
*args
) | [
"def",
"call_plugin",
"(",
"plugin",
",",
"f",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"getattr",
"(",
"plugin",
",",
"f",
")",
"except",
"AttributeError",
":",
"return",
"None",
"if",
"kwargs",
":",
"getattr",
"(",
"plugin",... | Calls function f from plugin, returns None if plugin does not implement f. | [
"Calls",
"function",
"f",
"from",
"plugin",
"returns",
"None",
"if",
"plugin",
"does",
"not",
"implement",
"f",
"."
] | bc9efe379b0b2406bfbbbd8e0f678b1f63805c66 | https://github.com/Enteee/pdml2flow/blob/bc9efe379b0b2406bfbbbd8e0f678b1f63805c66/pdml2flow/utils.py#L20-L34 | train | 38,609 |
openstack/python-saharaclient | saharaclient/api/job_executions.py | JobExecutionsManager.create | def create(self, job_id, cluster_id, input_id=None,
output_id=None, configs=None, interface=None, is_public=None,
is_protected=None):
"""Launch a Job."""
url = "/jobs/%s/execute" % job_id
data = {
"cluster_id": cluster_id,
}
self._copy_if_defined(data, input_id=input_id, output_id=output_id,
job_configs=configs, interface=interface,
is_public=is_public, is_protected=is_protected)
return self._create(url, data, 'job_execution') | python | def create(self, job_id, cluster_id, input_id=None,
output_id=None, configs=None, interface=None, is_public=None,
is_protected=None):
"""Launch a Job."""
url = "/jobs/%s/execute" % job_id
data = {
"cluster_id": cluster_id,
}
self._copy_if_defined(data, input_id=input_id, output_id=output_id,
job_configs=configs, interface=interface,
is_public=is_public, is_protected=is_protected)
return self._create(url, data, 'job_execution') | [
"def",
"create",
"(",
"self",
",",
"job_id",
",",
"cluster_id",
",",
"input_id",
"=",
"None",
",",
"output_id",
"=",
"None",
",",
"configs",
"=",
"None",
",",
"interface",
"=",
"None",
",",
"is_public",
"=",
"None",
",",
"is_protected",
"=",
"None",
")... | Launch a Job. | [
"Launch",
"a",
"Job",
"."
] | c53831d686d9e94187ce5dfdbfa43883b792280e | https://github.com/openstack/python-saharaclient/blob/c53831d686d9e94187ce5dfdbfa43883b792280e/saharaclient/api/job_executions.py#L43-L57 | train | 38,610 |
openstack/python-saharaclient | saharaclient/api/job_executions.py | JobExecutionsManager.update | def update(self, obj_id, is_public=NotUpdated, is_protected=NotUpdated):
"""Update a Job Execution."""
data = {}
self._copy_if_updated(data, is_public=is_public,
is_protected=is_protected)
return self._patch('/job-executions/%s' % obj_id, data) | python | def update(self, obj_id, is_public=NotUpdated, is_protected=NotUpdated):
"""Update a Job Execution."""
data = {}
self._copy_if_updated(data, is_public=is_public,
is_protected=is_protected)
return self._patch('/job-executions/%s' % obj_id, data) | [
"def",
"update",
"(",
"self",
",",
"obj_id",
",",
"is_public",
"=",
"NotUpdated",
",",
"is_protected",
"=",
"NotUpdated",
")",
":",
"data",
"=",
"{",
"}",
"self",
".",
"_copy_if_updated",
"(",
"data",
",",
"is_public",
"=",
"is_public",
",",
"is_protected"... | Update a Job Execution. | [
"Update",
"a",
"Job",
"Execution",
"."
] | c53831d686d9e94187ce5dfdbfa43883b792280e | https://github.com/openstack/python-saharaclient/blob/c53831d686d9e94187ce5dfdbfa43883b792280e/saharaclient/api/job_executions.py#L59-L65 | train | 38,611 |
datacamp/antlr-tsql | antlr_tsql/ast.py | AstVisitor.visitTerminal | def visitTerminal(self, ctx):
"""Converts case insensitive keywords and identifiers to lowercase
Identifiers in quotes are not lowercased even though there is case sensitivity in quotes for identifiers,
to prevent lowercasing quoted values.
"""
text = str(super().visitTerminal(ctx))
quotes = ["'", '"']
if not (text[0] in quotes and text[-1] in quotes):
text = text.lower()
return Terminal.from_text(text, ctx) | python | def visitTerminal(self, ctx):
"""Converts case insensitive keywords and identifiers to lowercase
Identifiers in quotes are not lowercased even though there is case sensitivity in quotes for identifiers,
to prevent lowercasing quoted values.
"""
text = str(super().visitTerminal(ctx))
quotes = ["'", '"']
if not (text[0] in quotes and text[-1] in quotes):
text = text.lower()
return Terminal.from_text(text, ctx) | [
"def",
"visitTerminal",
"(",
"self",
",",
"ctx",
")",
":",
"text",
"=",
"str",
"(",
"super",
"(",
")",
".",
"visitTerminal",
"(",
"ctx",
")",
")",
"quotes",
"=",
"[",
"\"'\"",
",",
"'\"'",
"]",
"if",
"not",
"(",
"text",
"[",
"0",
"]",
"in",
"qu... | Converts case insensitive keywords and identifiers to lowercase
Identifiers in quotes are not lowercased even though there is case sensitivity in quotes for identifiers,
to prevent lowercasing quoted values. | [
"Converts",
"case",
"insensitive",
"keywords",
"and",
"identifiers",
"to",
"lowercase",
"Identifiers",
"in",
"quotes",
"are",
"not",
"lowercased",
"even",
"though",
"there",
"is",
"case",
"sensitivity",
"in",
"quotes",
"for",
"identifiers",
"to",
"prevent",
"lower... | b048bfb084bad6b8e5f111a9127e38c2b07fd714 | https://github.com/datacamp/antlr-tsql/blob/b048bfb084bad6b8e5f111a9127e38c2b07fd714/antlr_tsql/ast.py#L499-L508 | train | 38,612 |
openstack/python-saharaclient | saharaclient/api/plugins.py | _PluginManager.list | def list(self, search_opts=None):
"""Get a list of Plugins."""
query = base.get_query_string(search_opts)
return self._list('/plugins%s' % query, 'plugins') | python | def list(self, search_opts=None):
"""Get a list of Plugins."""
query = base.get_query_string(search_opts)
return self._list('/plugins%s' % query, 'plugins') | [
"def",
"list",
"(",
"self",
",",
"search_opts",
"=",
"None",
")",
":",
"query",
"=",
"base",
".",
"get_query_string",
"(",
"search_opts",
")",
"return",
"self",
".",
"_list",
"(",
"'/plugins%s'",
"%",
"query",
",",
"'plugins'",
")"
] | Get a list of Plugins. | [
"Get",
"a",
"list",
"of",
"Plugins",
"."
] | c53831d686d9e94187ce5dfdbfa43883b792280e | https://github.com/openstack/python-saharaclient/blob/c53831d686d9e94187ce5dfdbfa43883b792280e/saharaclient/api/plugins.py#L34-L37 | train | 38,613 |
openstack/python-saharaclient | saharaclient/api/plugins.py | PluginManagerV1.convert_to_cluster_template | def convert_to_cluster_template(self, plugin_name, hadoop_version,
template_name, filecontent):
"""Convert to cluster template
Create Cluster Template directly, avoiding Cluster Template
mechanism.
"""
resp = self.api.post('/plugins/%s/%s/convert-config/%s' %
(plugin_name,
hadoop_version,
urlparse.quote(template_name)),
data=filecontent)
if resp.status_code != 202:
raise RuntimeError('Failed to upload template file for plugin "%s"'
' and version "%s"' %
(plugin_name, hadoop_version))
else:
return base.get_json(resp)['cluster_template'] | python | def convert_to_cluster_template(self, plugin_name, hadoop_version,
template_name, filecontent):
"""Convert to cluster template
Create Cluster Template directly, avoiding Cluster Template
mechanism.
"""
resp = self.api.post('/plugins/%s/%s/convert-config/%s' %
(plugin_name,
hadoop_version,
urlparse.quote(template_name)),
data=filecontent)
if resp.status_code != 202:
raise RuntimeError('Failed to upload template file for plugin "%s"'
' and version "%s"' %
(plugin_name, hadoop_version))
else:
return base.get_json(resp)['cluster_template'] | [
"def",
"convert_to_cluster_template",
"(",
"self",
",",
"plugin_name",
",",
"hadoop_version",
",",
"template_name",
",",
"filecontent",
")",
":",
"resp",
"=",
"self",
".",
"api",
".",
"post",
"(",
"'/plugins/%s/%s/convert-config/%s'",
"%",
"(",
"plugin_name",
",",... | Convert to cluster template
Create Cluster Template directly, avoiding Cluster Template
mechanism. | [
"Convert",
"to",
"cluster",
"template"
] | c53831d686d9e94187ce5dfdbfa43883b792280e | https://github.com/openstack/python-saharaclient/blob/c53831d686d9e94187ce5dfdbfa43883b792280e/saharaclient/api/plugins.py#L60-L77 | train | 38,614 |
openstack/python-saharaclient | saharaclient/api/jobs.py | JobsManagerV1.create | def create(self, name, type, mains=None, libs=None, description=None,
interface=None, is_public=None, is_protected=None):
"""Create a Job."""
data = {
'name': name,
'type': type
}
self._copy_if_defined(data, description=description, mains=mains,
libs=libs, interface=interface,
is_public=is_public, is_protected=is_protected)
return self._create('/jobs', data, 'job') | python | def create(self, name, type, mains=None, libs=None, description=None,
interface=None, is_public=None, is_protected=None):
"""Create a Job."""
data = {
'name': name,
'type': type
}
self._copy_if_defined(data, description=description, mains=mains,
libs=libs, interface=interface,
is_public=is_public, is_protected=is_protected)
return self._create('/jobs', data, 'job') | [
"def",
"create",
"(",
"self",
",",
"name",
",",
"type",
",",
"mains",
"=",
"None",
",",
"libs",
"=",
"None",
",",
"description",
"=",
"None",
",",
"interface",
"=",
"None",
",",
"is_public",
"=",
"None",
",",
"is_protected",
"=",
"None",
")",
":",
... | Create a Job. | [
"Create",
"a",
"Job",
"."
] | c53831d686d9e94187ce5dfdbfa43883b792280e | https://github.com/openstack/python-saharaclient/blob/c53831d686d9e94187ce5dfdbfa43883b792280e/saharaclient/api/jobs.py#L27-L39 | train | 38,615 |
openstack/python-saharaclient | saharaclient/api/jobs.py | JobsManagerV1.list | def list(self, search_opts=None, limit=None,
marker=None, sort_by=None, reverse=None):
"""Get a list of Jobs."""
query = base.get_query_string(search_opts, limit=limit, marker=marker,
sort_by=sort_by, reverse=reverse)
url = "/jobs%s" % query
return self._page(url, 'jobs', limit) | python | def list(self, search_opts=None, limit=None,
marker=None, sort_by=None, reverse=None):
"""Get a list of Jobs."""
query = base.get_query_string(search_opts, limit=limit, marker=marker,
sort_by=sort_by, reverse=reverse)
url = "/jobs%s" % query
return self._page(url, 'jobs', limit) | [
"def",
"list",
"(",
"self",
",",
"search_opts",
"=",
"None",
",",
"limit",
"=",
"None",
",",
"marker",
"=",
"None",
",",
"sort_by",
"=",
"None",
",",
"reverse",
"=",
"None",
")",
":",
"query",
"=",
"base",
".",
"get_query_string",
"(",
"search_opts",
... | Get a list of Jobs. | [
"Get",
"a",
"list",
"of",
"Jobs",
"."
] | c53831d686d9e94187ce5dfdbfa43883b792280e | https://github.com/openstack/python-saharaclient/blob/c53831d686d9e94187ce5dfdbfa43883b792280e/saharaclient/api/jobs.py#L41-L47 | train | 38,616 |
openstack/python-saharaclient | saharaclient/api/jobs.py | JobsManagerV1.update | def update(self, job_id, name=NotUpdated, description=NotUpdated,
is_public=NotUpdated, is_protected=NotUpdated):
"""Update a Job."""
data = {}
self._copy_if_updated(data, name=name, description=description,
is_public=is_public, is_protected=is_protected)
return self._patch('/jobs/%s' % job_id, data) | python | def update(self, job_id, name=NotUpdated, description=NotUpdated,
is_public=NotUpdated, is_protected=NotUpdated):
"""Update a Job."""
data = {}
self._copy_if_updated(data, name=name, description=description,
is_public=is_public, is_protected=is_protected)
return self._patch('/jobs/%s' % job_id, data) | [
"def",
"update",
"(",
"self",
",",
"job_id",
",",
"name",
"=",
"NotUpdated",
",",
"description",
"=",
"NotUpdated",
",",
"is_public",
"=",
"NotUpdated",
",",
"is_protected",
"=",
"NotUpdated",
")",
":",
"data",
"=",
"{",
"}",
"self",
".",
"_copy_if_updated... | Update a Job. | [
"Update",
"a",
"Job",
"."
] | c53831d686d9e94187ce5dfdbfa43883b792280e | https://github.com/openstack/python-saharaclient/blob/c53831d686d9e94187ce5dfdbfa43883b792280e/saharaclient/api/jobs.py#L61-L69 | train | 38,617 |
OpenCageData/python-opencage-geocoder | opencage/geocoder.py | _query_for_reverse_geocoding | def _query_for_reverse_geocoding(lat, lng):
"""
Given a lat & lng, what's the string search query.
If the API changes, change this function. Only for internal use.
"""
# have to do some stupid f/Decimal/str stuff to (a) ensure we get as much
# decimal places as the user already specified and (b) to ensure we don't
# get e-5 stuff
return "{0:f},{1:f}".format(Decimal(str(lat)), Decimal(str(lng))) | python | def _query_for_reverse_geocoding(lat, lng):
"""
Given a lat & lng, what's the string search query.
If the API changes, change this function. Only for internal use.
"""
# have to do some stupid f/Decimal/str stuff to (a) ensure we get as much
# decimal places as the user already specified and (b) to ensure we don't
# get e-5 stuff
return "{0:f},{1:f}".format(Decimal(str(lat)), Decimal(str(lng))) | [
"def",
"_query_for_reverse_geocoding",
"(",
"lat",
",",
"lng",
")",
":",
"# have to do some stupid f/Decimal/str stuff to (a) ensure we get as much",
"# decimal places as the user already specified and (b) to ensure we don't",
"# get e-5 stuff",
"return",
"\"{0:f},{1:f}\"",
".",
"format"... | Given a lat & lng, what's the string search query.
If the API changes, change this function. Only for internal use. | [
"Given",
"a",
"lat",
"&",
"lng",
"what",
"s",
"the",
"string",
"search",
"query",
"."
] | 21f102a33a036ed29e08e8375eceaa1bb4ec5009 | https://github.com/OpenCageData/python-opencage-geocoder/blob/21f102a33a036ed29e08e8375eceaa1bb4ec5009/opencage/geocoder.py#L155-L164 | train | 38,618 |
OpenCageData/python-opencage-geocoder | opencage/geocoder.py | OpenCageGeocode.geocode | def geocode(self, query, **kwargs):
"""
Given a string to search for, return the results from OpenCage's Geocoder.
:param string query: String to search for
:returns: Dict results
:raises InvalidInputError: if the query string is not a unicode string
:raises RateLimitExceededError: if you have exceeded the number of queries you can make. Exception says when you can try again
:raises UnknownError: if something goes wrong with the OpenCage API
"""
if six.PY2:
# py3 doesn't have unicode() function, and instead we check the text_type later
try:
query = unicode(query)
except UnicodeDecodeError:
raise InvalidInputError(bad_value=query)
if not isinstance(query, six.text_type):
raise InvalidInputError(bad_value=query)
data = {
'q': query,
'key': self.key
}
# Add user parameters
data.update(kwargs)
url = self.url
response = requests.get(url, params=data)
if (response.status_code == 402 or response.status_code == 429):
# Rate limit exceeded
reset_time = datetime.utcfromtimestamp(response.json()['rate']['reset'])
raise RateLimitExceededError(reset_to=int(response.json()['rate']['limit']), reset_time=reset_time)
elif response.status_code == 500:
raise UnknownError("500 status code from API")
try:
response_json = response.json()
except ValueError:
raise UnknownError("Non-JSON result from server")
if 'results' not in response_json:
raise UnknownError("JSON from API doesn't have a 'results' key")
return floatify_latlng(response_json['results']) | python | def geocode(self, query, **kwargs):
"""
Given a string to search for, return the results from OpenCage's Geocoder.
:param string query: String to search for
:returns: Dict results
:raises InvalidInputError: if the query string is not a unicode string
:raises RateLimitExceededError: if you have exceeded the number of queries you can make. Exception says when you can try again
:raises UnknownError: if something goes wrong with the OpenCage API
"""
if six.PY2:
# py3 doesn't have unicode() function, and instead we check the text_type later
try:
query = unicode(query)
except UnicodeDecodeError:
raise InvalidInputError(bad_value=query)
if not isinstance(query, six.text_type):
raise InvalidInputError(bad_value=query)
data = {
'q': query,
'key': self.key
}
# Add user parameters
data.update(kwargs)
url = self.url
response = requests.get(url, params=data)
if (response.status_code == 402 or response.status_code == 429):
# Rate limit exceeded
reset_time = datetime.utcfromtimestamp(response.json()['rate']['reset'])
raise RateLimitExceededError(reset_to=int(response.json()['rate']['limit']), reset_time=reset_time)
elif response.status_code == 500:
raise UnknownError("500 status code from API")
try:
response_json = response.json()
except ValueError:
raise UnknownError("Non-JSON result from server")
if 'results' not in response_json:
raise UnknownError("JSON from API doesn't have a 'results' key")
return floatify_latlng(response_json['results']) | [
"def",
"geocode",
"(",
"self",
",",
"query",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"six",
".",
"PY2",
":",
"# py3 doesn't have unicode() function, and instead we check the text_type later",
"try",
":",
"query",
"=",
"unicode",
"(",
"query",
")",
"except",
"Un... | Given a string to search for, return the results from OpenCage's Geocoder.
:param string query: String to search for
:returns: Dict results
:raises InvalidInputError: if the query string is not a unicode string
:raises RateLimitExceededError: if you have exceeded the number of queries you can make. Exception says when you can try again
:raises UnknownError: if something goes wrong with the OpenCage API | [
"Given",
"a",
"string",
"to",
"search",
"for",
"return",
"the",
"results",
"from",
"OpenCage",
"s",
"Geocoder",
"."
] | 21f102a33a036ed29e08e8375eceaa1bb4ec5009 | https://github.com/OpenCageData/python-opencage-geocoder/blob/21f102a33a036ed29e08e8375eceaa1bb4ec5009/opencage/geocoder.py#L90-L139 | train | 38,619 |
OpenCageData/python-opencage-geocoder | opencage/geocoder.py | OpenCageGeocode.reverse_geocode | def reverse_geocode(self, lat, lng, **kwargs):
"""
Given a latitude & longitude, return an address for that point from OpenCage's Geocoder.
:param lat: Latitude
:param lng: Longitude
:return: Results from OpenCageData
:rtype: dict
:raises RateLimitExceededError: if you have exceeded the number of queries you can make. Exception says when you can try again
:raises UnknownError: if something goes wrong with the OpenCage API
"""
return self.geocode(_query_for_reverse_geocoding(lat, lng), **kwargs) | python | def reverse_geocode(self, lat, lng, **kwargs):
"""
Given a latitude & longitude, return an address for that point from OpenCage's Geocoder.
:param lat: Latitude
:param lng: Longitude
:return: Results from OpenCageData
:rtype: dict
:raises RateLimitExceededError: if you have exceeded the number of queries you can make. Exception says when you can try again
:raises UnknownError: if something goes wrong with the OpenCage API
"""
return self.geocode(_query_for_reverse_geocoding(lat, lng), **kwargs) | [
"def",
"reverse_geocode",
"(",
"self",
",",
"lat",
",",
"lng",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"geocode",
"(",
"_query_for_reverse_geocoding",
"(",
"lat",
",",
"lng",
")",
",",
"*",
"*",
"kwargs",
")"
] | Given a latitude & longitude, return an address for that point from OpenCage's Geocoder.
:param lat: Latitude
:param lng: Longitude
:return: Results from OpenCageData
:rtype: dict
:raises RateLimitExceededError: if you have exceeded the number of queries you can make. Exception says when you can try again
:raises UnknownError: if something goes wrong with the OpenCage API | [
"Given",
"a",
"latitude",
"&",
"longitude",
"return",
"an",
"address",
"for",
"that",
"point",
"from",
"OpenCage",
"s",
"Geocoder",
"."
] | 21f102a33a036ed29e08e8375eceaa1bb4ec5009 | https://github.com/OpenCageData/python-opencage-geocoder/blob/21f102a33a036ed29e08e8375eceaa1bb4ec5009/opencage/geocoder.py#L141-L152 | train | 38,620 |
zillow/ctds | src/ctds/pool/__init__.py | ConnectionPool.acquire | def acquire(self):
'''
Get a new connection from the pool.
This will return an existing connection, if one is available in the
pool, or create a new connection.
.. warning:: If the pool was created with `maxsize` and `block=True`,
this method may block until a connection is available in the pool.
'''
self._condition.acquire()
try:
# Wait for a connection if there is an upper bound to the pool.
if self._maxsize is not None and self._block:
while not self._pool and self._nconnections == self._maxsize:
self._condition.wait(timeout=None) # block indefinitely
# Check the pool for a non-stale connection.
while self._pool:
pooledconn = self._pool.pop(0) # get least recently used connection
if self._idlettl is not None and (pooledconn.released + self._idlettl) < time.time():
pooledconn.connection.close()
self._nconnections -= 1
else:
return pooledconn.connection
connection = self._dbapi2.connect(*(), **self._connection_args.copy())
self._nconnections += 1
return connection
finally:
self._condition.release() | python | def acquire(self):
'''
Get a new connection from the pool.
This will return an existing connection, if one is available in the
pool, or create a new connection.
.. warning:: If the pool was created with `maxsize` and `block=True`,
this method may block until a connection is available in the pool.
'''
self._condition.acquire()
try:
# Wait for a connection if there is an upper bound to the pool.
if self._maxsize is not None and self._block:
while not self._pool and self._nconnections == self._maxsize:
self._condition.wait(timeout=None) # block indefinitely
# Check the pool for a non-stale connection.
while self._pool:
pooledconn = self._pool.pop(0) # get least recently used connection
if self._idlettl is not None and (pooledconn.released + self._idlettl) < time.time():
pooledconn.connection.close()
self._nconnections -= 1
else:
return pooledconn.connection
connection = self._dbapi2.connect(*(), **self._connection_args.copy())
self._nconnections += 1
return connection
finally:
self._condition.release() | [
"def",
"acquire",
"(",
"self",
")",
":",
"self",
".",
"_condition",
".",
"acquire",
"(",
")",
"try",
":",
"# Wait for a connection if there is an upper bound to the pool.",
"if",
"self",
".",
"_maxsize",
"is",
"not",
"None",
"and",
"self",
".",
"_block",
":",
... | Get a new connection from the pool.
This will return an existing connection, if one is available in the
pool, or create a new connection.
.. warning:: If the pool was created with `maxsize` and `block=True`,
this method may block until a connection is available in the pool. | [
"Get",
"a",
"new",
"connection",
"from",
"the",
"pool",
".",
"This",
"will",
"return",
"an",
"existing",
"connection",
"if",
"one",
"is",
"available",
"in",
"the",
"pool",
"or",
"create",
"a",
"new",
"connection",
"."
] | 03c9d182f63900fe6c792dda2d320392d6e3e759 | https://github.com/zillow/ctds/blob/03c9d182f63900fe6c792dda2d320392d6e3e759/src/ctds/pool/__init__.py#L118-L149 | train | 38,621 |
zillow/ctds | src/ctds/pool/__init__.py | ConnectionPool.release | def release(self, connection):
'''
Return a connection back to the pool.
Prior to release, :py:meth:`ctds.Connection.rollback()` is called to
rollback any pending transaction.
.. note:: This must be called once for every successful call to
:py:meth:`.acquire()`.
:param connection: The connection object returned by
:py:meth:`.acquire()`.
'''
try:
# Rollback the existing connection, closing on failure.
connection.rollback()
except self._dbapi2.Error:
self._close(connection)
return
self._condition.acquire()
try:
if self._maxsize is None or self._maxsize > len(self._pool):
self._pool.append(PooledConnection(connection, time.time()))
self._condition.notify()
else:
self._close(connection)
finally:
self._condition.release() | python | def release(self, connection):
'''
Return a connection back to the pool.
Prior to release, :py:meth:`ctds.Connection.rollback()` is called to
rollback any pending transaction.
.. note:: This must be called once for every successful call to
:py:meth:`.acquire()`.
:param connection: The connection object returned by
:py:meth:`.acquire()`.
'''
try:
# Rollback the existing connection, closing on failure.
connection.rollback()
except self._dbapi2.Error:
self._close(connection)
return
self._condition.acquire()
try:
if self._maxsize is None or self._maxsize > len(self._pool):
self._pool.append(PooledConnection(connection, time.time()))
self._condition.notify()
else:
self._close(connection)
finally:
self._condition.release() | [
"def",
"release",
"(",
"self",
",",
"connection",
")",
":",
"try",
":",
"# Rollback the existing connection, closing on failure.",
"connection",
".",
"rollback",
"(",
")",
"except",
"self",
".",
"_dbapi2",
".",
"Error",
":",
"self",
".",
"_close",
"(",
"connecti... | Return a connection back to the pool.
Prior to release, :py:meth:`ctds.Connection.rollback()` is called to
rollback any pending transaction.
.. note:: This must be called once for every successful call to
:py:meth:`.acquire()`.
:param connection: The connection object returned by
:py:meth:`.acquire()`. | [
"Return",
"a",
"connection",
"back",
"to",
"the",
"pool",
"."
] | 03c9d182f63900fe6c792dda2d320392d6e3e759 | https://github.com/zillow/ctds/blob/03c9d182f63900fe6c792dda2d320392d6e3e759/src/ctds/pool/__init__.py#L151-L179 | train | 38,622 |
zillow/ctds | src/ctds/pool/__init__.py | ConnectionPool.finalize | def finalize(self):
'''
Release all connections contained in the pool.
.. note:: This should be called to cleanly shutdown the pool, i.e.
on process exit.
'''
self._condition.acquire()
try:
if self._nconnections != len(self._pool):
warnings.warn('finalize() called with unreleased connections', RuntimeWarning, 2)
while self._pool:
self._close(self._pool.pop().connection)
self._nconnections = 0
finally:
self._condition.release() | python | def finalize(self):
'''
Release all connections contained in the pool.
.. note:: This should be called to cleanly shutdown the pool, i.e.
on process exit.
'''
self._condition.acquire()
try:
if self._nconnections != len(self._pool):
warnings.warn('finalize() called with unreleased connections', RuntimeWarning, 2)
while self._pool:
self._close(self._pool.pop().connection)
self._nconnections = 0
finally:
self._condition.release() | [
"def",
"finalize",
"(",
"self",
")",
":",
"self",
".",
"_condition",
".",
"acquire",
"(",
")",
"try",
":",
"if",
"self",
".",
"_nconnections",
"!=",
"len",
"(",
"self",
".",
"_pool",
")",
":",
"warnings",
".",
"warn",
"(",
"'finalize() called with unrele... | Release all connections contained in the pool.
.. note:: This should be called to cleanly shutdown the pool, i.e.
on process exit. | [
"Release",
"all",
"connections",
"contained",
"in",
"the",
"pool",
"."
] | 03c9d182f63900fe6c792dda2d320392d6e3e759 | https://github.com/zillow/ctds/blob/03c9d182f63900fe6c792dda2d320392d6e3e759/src/ctds/pool/__init__.py#L181-L197 | train | 38,623 |
sphinx-contrib/openapi | sphinxcontrib/openapi/openapi30.py | _dict_merge | def _dict_merge(dct, merge_dct):
"""Recursive dict merge.
Inspired by :meth:``dict.update()``, instead of updating only top-level
keys, dict_merge recurses down into dicts nested to an arbitrary depth,
updating keys. The ``merge_dct`` is merged into ``dct``.
From https://gist.github.com/angstwad/bf22d1822c38a92ec0a9
Arguments:
dct: dict onto which the merge is executed
merge_dct: dct merged into dct
"""
for k, v in merge_dct.items():
if (k in dct and isinstance(dct[k], dict)
and isinstance(merge_dct[k], collections.Mapping)):
_dict_merge(dct[k], merge_dct[k])
else:
dct[k] = merge_dct[k] | python | def _dict_merge(dct, merge_dct):
"""Recursive dict merge.
Inspired by :meth:``dict.update()``, instead of updating only top-level
keys, dict_merge recurses down into dicts nested to an arbitrary depth,
updating keys. The ``merge_dct`` is merged into ``dct``.
From https://gist.github.com/angstwad/bf22d1822c38a92ec0a9
Arguments:
dct: dict onto which the merge is executed
merge_dct: dct merged into dct
"""
for k, v in merge_dct.items():
if (k in dct and isinstance(dct[k], dict)
and isinstance(merge_dct[k], collections.Mapping)):
_dict_merge(dct[k], merge_dct[k])
else:
dct[k] = merge_dct[k] | [
"def",
"_dict_merge",
"(",
"dct",
",",
"merge_dct",
")",
":",
"for",
"k",
",",
"v",
"in",
"merge_dct",
".",
"items",
"(",
")",
":",
"if",
"(",
"k",
"in",
"dct",
"and",
"isinstance",
"(",
"dct",
"[",
"k",
"]",
",",
"dict",
")",
"and",
"isinstance"... | Recursive dict merge.
Inspired by :meth:``dict.update()``, instead of updating only top-level
keys, dict_merge recurses down into dicts nested to an arbitrary depth,
updating keys. The ``merge_dct`` is merged into ``dct``.
From https://gist.github.com/angstwad/bf22d1822c38a92ec0a9
Arguments:
dct: dict onto which the merge is executed
merge_dct: dct merged into dct | [
"Recursive",
"dict",
"merge",
"."
] | 71ff7af270896db49ff9f9136468b78cc929db19 | https://github.com/sphinx-contrib/openapi/blob/71ff7af270896db49ff9f9136468b78cc929db19/sphinxcontrib/openapi/openapi30.py#L58-L76 | train | 38,624 |
sphinx-contrib/openapi | sphinxcontrib/openapi/openapi30.py | _parse_schema | def _parse_schema(schema, method):
"""
Convert a Schema Object to a Python object.
Args:
schema: An ``OrderedDict`` representing the schema object.
"""
if method and schema.get('readOnly', False):
return _READONLY_PROPERTY
# allOf: Must be valid against all of the subschemas
if 'allOf' in schema:
schema_ = copy.deepcopy(schema['allOf'][0])
for x in schema['allOf'][1:]:
_dict_merge(schema_, x)
return _parse_schema(schema_, method)
# anyOf: Must be valid against any of the subschemas
# TODO(stephenfin): Handle anyOf
# oneOf: Must be valid against exactly one of the subschemas
if 'oneOf' in schema:
# we only show the first one since we can't show everything
return _parse_schema(schema['oneOf'][0], method)
if 'enum' in schema:
# we only show the first one since we can't show everything
return schema['enum'][0]
schema_type = schema.get('type', 'object')
if schema_type == 'array':
# special case oneOf so that we can show examples for all possible
# combinations
if 'oneOf' in schema['items']:
return [
_parse_schema(x, method) for x in schema['items']['oneOf']]
return [_parse_schema(schema['items'], method)]
if schema_type == 'object':
if method and all(v.get('readOnly', False)
for v in schema['properties'].values()):
return _READONLY_PROPERTY
results = []
for name, prop in schema.get('properties', {}).items():
result = _parse_schema(prop, method)
if result != _READONLY_PROPERTY:
results.append((name, result))
return collections.OrderedDict(results)
if (schema_type, schema.get('format')) in _TYPE_MAPPING:
return _TYPE_MAPPING[(schema_type, schema.get('format'))]
return _TYPE_MAPPING[(schema_type, None)] | python | def _parse_schema(schema, method):
"""
Convert a Schema Object to a Python object.
Args:
schema: An ``OrderedDict`` representing the schema object.
"""
if method and schema.get('readOnly', False):
return _READONLY_PROPERTY
# allOf: Must be valid against all of the subschemas
if 'allOf' in schema:
schema_ = copy.deepcopy(schema['allOf'][0])
for x in schema['allOf'][1:]:
_dict_merge(schema_, x)
return _parse_schema(schema_, method)
# anyOf: Must be valid against any of the subschemas
# TODO(stephenfin): Handle anyOf
# oneOf: Must be valid against exactly one of the subschemas
if 'oneOf' in schema:
# we only show the first one since we can't show everything
return _parse_schema(schema['oneOf'][0], method)
if 'enum' in schema:
# we only show the first one since we can't show everything
return schema['enum'][0]
schema_type = schema.get('type', 'object')
if schema_type == 'array':
# special case oneOf so that we can show examples for all possible
# combinations
if 'oneOf' in schema['items']:
return [
_parse_schema(x, method) for x in schema['items']['oneOf']]
return [_parse_schema(schema['items'], method)]
if schema_type == 'object':
if method and all(v.get('readOnly', False)
for v in schema['properties'].values()):
return _READONLY_PROPERTY
results = []
for name, prop in schema.get('properties', {}).items():
result = _parse_schema(prop, method)
if result != _READONLY_PROPERTY:
results.append((name, result))
return collections.OrderedDict(results)
if (schema_type, schema.get('format')) in _TYPE_MAPPING:
return _TYPE_MAPPING[(schema_type, schema.get('format'))]
return _TYPE_MAPPING[(schema_type, None)] | [
"def",
"_parse_schema",
"(",
"schema",
",",
"method",
")",
":",
"if",
"method",
"and",
"schema",
".",
"get",
"(",
"'readOnly'",
",",
"False",
")",
":",
"return",
"_READONLY_PROPERTY",
"# allOf: Must be valid against all of the subschemas",
"if",
"'allOf'",
"in",
"... | Convert a Schema Object to a Python object.
Args:
schema: An ``OrderedDict`` representing the schema object. | [
"Convert",
"a",
"Schema",
"Object",
"to",
"a",
"Python",
"object",
"."
] | 71ff7af270896db49ff9f9136468b78cc929db19 | https://github.com/sphinx-contrib/openapi/blob/71ff7af270896db49ff9f9136468b78cc929db19/sphinxcontrib/openapi/openapi30.py#L79-L136 | train | 38,625 |
sphinx-contrib/openapi | sphinxcontrib/openapi/openapi30.py | _example | def _example(media_type_objects, method=None, endpoint=None, status=None,
nb_indent=0):
"""
Format examples in `Media Type Object` openapi v3 to HTTP request or
HTTP response example.
If method and endpoint is provided, this fonction prints a request example
else status should be provided to print a response example.
Arguments:
media_type_objects (Dict[str, Dict]): Dict containing
Media Type Objects.
method: The HTTP method to use in example.
endpoint: The HTTP route to use in example.
status: The HTTP status to use in example.
"""
indent = ' '
extra_indent = indent * nb_indent
if method is not None:
method = method.upper()
else:
try:
# one of possible values for status might be 'default'.
# in the case, just fallback to '-'
status_text = http_status_codes[int(status)]
except (ValueError, KeyError):
status_text = '-'
for content_type, content in media_type_objects.items():
examples = content.get('examples')
example = content.get('example')
if examples is None:
examples = {}
if not example:
if content_type != 'application/json':
LOG.info('skipping non-JSON example generation.')
continue
example = _parse_schema(content['schema'], method=method)
if method is None:
examples['Example response'] = {
'value': example,
}
else:
examples['Example request'] = {
'value': example,
}
for example in examples.values():
if not isinstance(example['value'], six.string_types):
example['value'] = json.dumps(
example['value'], indent=4, separators=(',', ': '))
for example_name, example in examples.items():
if 'summary' in example:
example_title = '{example_name} - {example[summary]}'.format(
**locals())
else:
example_title = example_name
yield ''
yield '{extra_indent}**{example_title}:**'.format(**locals())
yield ''
yield '{extra_indent}.. sourcecode:: http'.format(**locals())
yield ''
# Print http request example
if method:
yield '{extra_indent}{indent}{method} {endpoint} HTTP/1.1' \
.format(**locals())
yield '{extra_indent}{indent}Host: example.com' \
.format(**locals())
yield '{extra_indent}{indent}Content-Type: {content_type}' \
.format(**locals())
# Print http response example
else:
yield '{extra_indent}{indent}HTTP/1.1 {status} {status_text}' \
.format(**locals())
yield '{extra_indent}{indent}Content-Type: {content_type}' \
.format(**locals())
yield ''
for example_line in example['value'].splitlines():
yield '{extra_indent}{indent}{example_line}'.format(**locals())
yield '' | python | def _example(media_type_objects, method=None, endpoint=None, status=None,
nb_indent=0):
"""
Format examples in `Media Type Object` openapi v3 to HTTP request or
HTTP response example.
If method and endpoint is provided, this fonction prints a request example
else status should be provided to print a response example.
Arguments:
media_type_objects (Dict[str, Dict]): Dict containing
Media Type Objects.
method: The HTTP method to use in example.
endpoint: The HTTP route to use in example.
status: The HTTP status to use in example.
"""
indent = ' '
extra_indent = indent * nb_indent
if method is not None:
method = method.upper()
else:
try:
# one of possible values for status might be 'default'.
# in the case, just fallback to '-'
status_text = http_status_codes[int(status)]
except (ValueError, KeyError):
status_text = '-'
for content_type, content in media_type_objects.items():
examples = content.get('examples')
example = content.get('example')
if examples is None:
examples = {}
if not example:
if content_type != 'application/json':
LOG.info('skipping non-JSON example generation.')
continue
example = _parse_schema(content['schema'], method=method)
if method is None:
examples['Example response'] = {
'value': example,
}
else:
examples['Example request'] = {
'value': example,
}
for example in examples.values():
if not isinstance(example['value'], six.string_types):
example['value'] = json.dumps(
example['value'], indent=4, separators=(',', ': '))
for example_name, example in examples.items():
if 'summary' in example:
example_title = '{example_name} - {example[summary]}'.format(
**locals())
else:
example_title = example_name
yield ''
yield '{extra_indent}**{example_title}:**'.format(**locals())
yield ''
yield '{extra_indent}.. sourcecode:: http'.format(**locals())
yield ''
# Print http request example
if method:
yield '{extra_indent}{indent}{method} {endpoint} HTTP/1.1' \
.format(**locals())
yield '{extra_indent}{indent}Host: example.com' \
.format(**locals())
yield '{extra_indent}{indent}Content-Type: {content_type}' \
.format(**locals())
# Print http response example
else:
yield '{extra_indent}{indent}HTTP/1.1 {status} {status_text}' \
.format(**locals())
yield '{extra_indent}{indent}Content-Type: {content_type}' \
.format(**locals())
yield ''
for example_line in example['value'].splitlines():
yield '{extra_indent}{indent}{example_line}'.format(**locals())
yield '' | [
"def",
"_example",
"(",
"media_type_objects",
",",
"method",
"=",
"None",
",",
"endpoint",
"=",
"None",
",",
"status",
"=",
"None",
",",
"nb_indent",
"=",
"0",
")",
":",
"indent",
"=",
"' '",
"extra_indent",
"=",
"indent",
"*",
"nb_indent",
"if",
"meth... | Format examples in `Media Type Object` openapi v3 to HTTP request or
HTTP response example.
If method and endpoint is provided, this fonction prints a request example
else status should be provided to print a response example.
Arguments:
media_type_objects (Dict[str, Dict]): Dict containing
Media Type Objects.
method: The HTTP method to use in example.
endpoint: The HTTP route to use in example.
status: The HTTP status to use in example. | [
"Format",
"examples",
"in",
"Media",
"Type",
"Object",
"openapi",
"v3",
"to",
"HTTP",
"request",
"or",
"HTTP",
"response",
"example",
".",
"If",
"method",
"and",
"endpoint",
"is",
"provided",
"this",
"fonction",
"prints",
"a",
"request",
"example",
"else",
"... | 71ff7af270896db49ff9f9136468b78cc929db19 | https://github.com/sphinx-contrib/openapi/blob/71ff7af270896db49ff9f9136468b78cc929db19/sphinxcontrib/openapi/openapi30.py#L139-L225 | train | 38,626 |
rossmann-engineering/EasyModbusTCP.PY | easymodbus/modbusClient.py | ModbusClient.connect | def connect(self):
"""
Connects to a Modbus-TCP Server or a Modbus-RTU Slave with the given Parameters
"""
if (self.__ser is not None):
serial = importlib.import_module("serial")
if self.__stopbits == 0:
self.__ser.stopbits = serial.STOPBITS_ONE
elif self.__stopbits == 1:
self.__ser.stopbits = serial.STOPBITS_TWO
elif self.__stopbits == 2:
self.__ser.stopbits = serial.STOPBITS_ONE_POINT_FIVE
if self.__parity == 0:
self.__ser.parity = serial.PARITY_EVEN
elif self.__parity == 1:
self.__ser.parity = serial.PARITY_ODD
elif self.__parity == 2:
self.__ser.parity = serial.PARITY_NONE
self.__ser = serial.Serial(self.serialPort, self.__baudrate, timeout=self.__timeout, parity=self.__ser.parity, stopbits=self.__ser.stopbits, xonxoff=0, rtscts=0)
self.__ser.writeTimeout = self.__timeout
#print (self.ser)
if (self.__tcpClientSocket is not None):
self.__tcpClientSocket.settimeout(5)
self.__tcpClientSocket.connect((self.__ipAddress, self.__port))
self.__connected = True
self.__thread = threading.Thread(target=self.__listen, args=())
self.__thread.start() | python | def connect(self):
"""
Connects to a Modbus-TCP Server or a Modbus-RTU Slave with the given Parameters
"""
if (self.__ser is not None):
serial = importlib.import_module("serial")
if self.__stopbits == 0:
self.__ser.stopbits = serial.STOPBITS_ONE
elif self.__stopbits == 1:
self.__ser.stopbits = serial.STOPBITS_TWO
elif self.__stopbits == 2:
self.__ser.stopbits = serial.STOPBITS_ONE_POINT_FIVE
if self.__parity == 0:
self.__ser.parity = serial.PARITY_EVEN
elif self.__parity == 1:
self.__ser.parity = serial.PARITY_ODD
elif self.__parity == 2:
self.__ser.parity = serial.PARITY_NONE
self.__ser = serial.Serial(self.serialPort, self.__baudrate, timeout=self.__timeout, parity=self.__ser.parity, stopbits=self.__ser.stopbits, xonxoff=0, rtscts=0)
self.__ser.writeTimeout = self.__timeout
#print (self.ser)
if (self.__tcpClientSocket is not None):
self.__tcpClientSocket.settimeout(5)
self.__tcpClientSocket.connect((self.__ipAddress, self.__port))
self.__connected = True
self.__thread = threading.Thread(target=self.__listen, args=())
self.__thread.start() | [
"def",
"connect",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"__ser",
"is",
"not",
"None",
")",
":",
"serial",
"=",
"importlib",
".",
"import_module",
"(",
"\"serial\"",
")",
"if",
"self",
".",
"__stopbits",
"==",
"0",
":",
"self",
".",
"__ser",
... | Connects to a Modbus-TCP Server or a Modbus-RTU Slave with the given Parameters | [
"Connects",
"to",
"a",
"Modbus",
"-",
"TCP",
"Server",
"or",
"a",
"Modbus",
"-",
"RTU",
"Slave",
"with",
"the",
"given",
"Parameters"
] | 3ea417470288619ba63ec0474ed1da6bcf105b70 | https://github.com/rossmann-engineering/EasyModbusTCP.PY/blob/3ea417470288619ba63ec0474ed1da6bcf105b70/easymodbus/modbusClient.py#L52-L80 | train | 38,627 |
rossmann-engineering/EasyModbusTCP.PY | easymodbus/modbusClient.py | ModbusClient.close | def close(self):
"""
Closes Serial port, or TCP-Socket connection
"""
if (self.__ser is not None):
self.__ser.close()
if (self.__tcpClientSocket is not None):
self.__stoplistening = True
self.__tcpClientSocket.shutdown(socket.SHUT_RDWR)
self.__tcpClientSocket.close()
self.__connected = False | python | def close(self):
"""
Closes Serial port, or TCP-Socket connection
"""
if (self.__ser is not None):
self.__ser.close()
if (self.__tcpClientSocket is not None):
self.__stoplistening = True
self.__tcpClientSocket.shutdown(socket.SHUT_RDWR)
self.__tcpClientSocket.close()
self.__connected = False | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"__ser",
"is",
"not",
"None",
")",
":",
"self",
".",
"__ser",
".",
"close",
"(",
")",
"if",
"(",
"self",
".",
"__tcpClientSocket",
"is",
"not",
"None",
")",
":",
"self",
".",
"__stopl... | Closes Serial port, or TCP-Socket connection | [
"Closes",
"Serial",
"port",
"or",
"TCP",
"-",
"Socket",
"connection"
] | 3ea417470288619ba63ec0474ed1da6bcf105b70 | https://github.com/rossmann-engineering/EasyModbusTCP.PY/blob/3ea417470288619ba63ec0474ed1da6bcf105b70/easymodbus/modbusClient.py#L97-L107 | train | 38,628 |
crunchyroll/ef-open | efopen/ef_plugin.py | run_plugins | def run_plugins(context_obj, boto3_clients):
"""
Executes all loaded plugins designated for the service calling the function.
Args:
context_obj (obj:EFContext): The EFContext object created by the service.
boto3_clients (dict): Dictionary of boto3 clients created by ef_utils.create_aws_clients()
"""
def print_if_verbose(message):
if context_obj.verbose:
print(message)
service_name = os.path.basename(sys.argv[0]).replace(".py", "")
try:
import plugins
except ImportError:
print_if_verbose("no plugins detected.")
return
else:
for plugin_importer, plugin_name, plugin_ispkg in pkgutil.iter_modules(plugins.__path__):
if plugin_ispkg:
plugin_package = importlib.import_module("plugins.{}".format(plugin_name))
for importer, modname, ispkg in pkgutil.iter_modules(plugin_package.__path__):
plugin_module = importlib.import_module("plugins.{}.{}".format(plugin_name, modname))
for name, obj in inspect.getmembers(plugin_module):
if inspect.isclass(obj) and obj.__name__ == "EFPlugin":
plugin_class = getattr(plugin_module, name)
plugin_instance = plugin_class(context=context_obj, clients=boto3_clients)
if plugin_instance.service == service_name:
print_if_verbose("plugin '{}' loaded".format(plugin_name))
if not context_obj.commit:
print_if_verbose("dryrun: skipping plugin execution.")
else:
try:
plugin_instance.run()
except AttributeError:
print("error executing plugin '{}'".format(modname)) | python | def run_plugins(context_obj, boto3_clients):
"""
Executes all loaded plugins designated for the service calling the function.
Args:
context_obj (obj:EFContext): The EFContext object created by the service.
boto3_clients (dict): Dictionary of boto3 clients created by ef_utils.create_aws_clients()
"""
def print_if_verbose(message):
if context_obj.verbose:
print(message)
service_name = os.path.basename(sys.argv[0]).replace(".py", "")
try:
import plugins
except ImportError:
print_if_verbose("no plugins detected.")
return
else:
for plugin_importer, plugin_name, plugin_ispkg in pkgutil.iter_modules(plugins.__path__):
if plugin_ispkg:
plugin_package = importlib.import_module("plugins.{}".format(plugin_name))
for importer, modname, ispkg in pkgutil.iter_modules(plugin_package.__path__):
plugin_module = importlib.import_module("plugins.{}.{}".format(plugin_name, modname))
for name, obj in inspect.getmembers(plugin_module):
if inspect.isclass(obj) and obj.__name__ == "EFPlugin":
plugin_class = getattr(plugin_module, name)
plugin_instance = plugin_class(context=context_obj, clients=boto3_clients)
if plugin_instance.service == service_name:
print_if_verbose("plugin '{}' loaded".format(plugin_name))
if not context_obj.commit:
print_if_verbose("dryrun: skipping plugin execution.")
else:
try:
plugin_instance.run()
except AttributeError:
print("error executing plugin '{}'".format(modname)) | [
"def",
"run_plugins",
"(",
"context_obj",
",",
"boto3_clients",
")",
":",
"def",
"print_if_verbose",
"(",
"message",
")",
":",
"if",
"context_obj",
".",
"verbose",
":",
"print",
"(",
"message",
")",
"service_name",
"=",
"os",
".",
"path",
".",
"basename",
... | Executes all loaded plugins designated for the service calling the function.
Args:
context_obj (obj:EFContext): The EFContext object created by the service.
boto3_clients (dict): Dictionary of boto3 clients created by ef_utils.create_aws_clients() | [
"Executes",
"all",
"loaded",
"plugins",
"designated",
"for",
"the",
"service",
"calling",
"the",
"function",
"."
] | 59fff3761af07a59f8f1c1682f2be004bdac15f7 | https://github.com/crunchyroll/ef-open/blob/59fff3761af07a59f8f1c1682f2be004bdac15f7/efopen/ef_plugin.py#L61-L98 | train | 38,629 |
crunchyroll/ef-open | efopen/ef_cf_diff.py | diff_string_templates | def diff_string_templates(string_a, string_b):
"""
Determine the diff of two strings. Return an empty string if the strings
are identical, and the diff output string if they are not.
"""
s1 = string_a.strip().splitlines()
s2 = string_b.strip().splitlines()
diffs = unified_diff(s2, s1, fromfile='deployed', tofile='local', lineterm='')
return '\n'.join(diffs) | python | def diff_string_templates(string_a, string_b):
"""
Determine the diff of two strings. Return an empty string if the strings
are identical, and the diff output string if they are not.
"""
s1 = string_a.strip().splitlines()
s2 = string_b.strip().splitlines()
diffs = unified_diff(s2, s1, fromfile='deployed', tofile='local', lineterm='')
return '\n'.join(diffs) | [
"def",
"diff_string_templates",
"(",
"string_a",
",",
"string_b",
")",
":",
"s1",
"=",
"string_a",
".",
"strip",
"(",
")",
".",
"splitlines",
"(",
")",
"s2",
"=",
"string_b",
".",
"strip",
"(",
")",
".",
"splitlines",
"(",
")",
"diffs",
"=",
"unified_d... | Determine the diff of two strings. Return an empty string if the strings
are identical, and the diff output string if they are not. | [
"Determine",
"the",
"diff",
"of",
"two",
"strings",
".",
"Return",
"an",
"empty",
"string",
"if",
"the",
"strings",
"are",
"identical",
"and",
"the",
"diff",
"output",
"string",
"if",
"they",
"are",
"not",
"."
] | 59fff3761af07a59f8f1c1682f2be004bdac15f7 | https://github.com/crunchyroll/ef-open/blob/59fff3761af07a59f8f1c1682f2be004bdac15f7/efopen/ef_cf_diff.py#L50-L58 | train | 38,630 |
crunchyroll/ef-open | efopen/ef_cf_diff.py | render_local_template | def render_local_template(service_name, environment, repo_root, template_file):
"""
Render a given service's template for a given environment and return it
"""
cmd = 'cd {} && ef-cf {} {} --devel --verbose'.format(repo_root, template_file, environment)
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = p.communicate()
if p.returncode != 0:
stderr = indentify('\n{}'.format(stderr))
stdout = indentify('\n{}'.format(stdout))
raise Exception('Service: `{}`, Env: `{}`, Msg: `{}{}`'
.format(service_name, environment, stderr, stdout))
logger.debug('Rendered template for `%s` in `%s`', template_file, environment)
r = re.match(r".*(^{.*^})$", stdout, re.MULTILINE | re.DOTALL)
return jsonify(json.loads(r.group(1))) | python | def render_local_template(service_name, environment, repo_root, template_file):
"""
Render a given service's template for a given environment and return it
"""
cmd = 'cd {} && ef-cf {} {} --devel --verbose'.format(repo_root, template_file, environment)
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = p.communicate()
if p.returncode != 0:
stderr = indentify('\n{}'.format(stderr))
stdout = indentify('\n{}'.format(stdout))
raise Exception('Service: `{}`, Env: `{}`, Msg: `{}{}`'
.format(service_name, environment, stderr, stdout))
logger.debug('Rendered template for `%s` in `%s`', template_file, environment)
r = re.match(r".*(^{.*^})$", stdout, re.MULTILINE | re.DOTALL)
return jsonify(json.loads(r.group(1))) | [
"def",
"render_local_template",
"(",
"service_name",
",",
"environment",
",",
"repo_root",
",",
"template_file",
")",
":",
"cmd",
"=",
"'cd {} && ef-cf {} {} --devel --verbose'",
".",
"format",
"(",
"repo_root",
",",
"template_file",
",",
"environment",
")",
"p",
"=... | Render a given service's template for a given environment and return it | [
"Render",
"a",
"given",
"service",
"s",
"template",
"for",
"a",
"given",
"environment",
"and",
"return",
"it"
] | 59fff3761af07a59f8f1c1682f2be004bdac15f7 | https://github.com/crunchyroll/ef-open/blob/59fff3761af07a59f8f1c1682f2be004bdac15f7/efopen/ef_cf_diff.py#L61-L78 | train | 38,631 |
crunchyroll/ef-open | efopen/ef_cf_diff.py | fetch_current_cloudformation_template | def fetch_current_cloudformation_template(service_name, environment, cf_client):
"""
Fetch the currently-deployed template for the given service in the given
environment and return it.
"""
stack_name = get_stack_name(environment, service_name)
logger.debug('Fetching template for `%s`', stack_name)
result = cf_client.get_template(StackName=stack_name)
return jsonify(result['TemplateBody']) | python | def fetch_current_cloudformation_template(service_name, environment, cf_client):
"""
Fetch the currently-deployed template for the given service in the given
environment and return it.
"""
stack_name = get_stack_name(environment, service_name)
logger.debug('Fetching template for `%s`', stack_name)
result = cf_client.get_template(StackName=stack_name)
return jsonify(result['TemplateBody']) | [
"def",
"fetch_current_cloudformation_template",
"(",
"service_name",
",",
"environment",
",",
"cf_client",
")",
":",
"stack_name",
"=",
"get_stack_name",
"(",
"environment",
",",
"service_name",
")",
"logger",
".",
"debug",
"(",
"'Fetching template for `%s`'",
",",
"s... | Fetch the currently-deployed template for the given service in the given
environment and return it. | [
"Fetch",
"the",
"currently",
"-",
"deployed",
"template",
"for",
"the",
"given",
"service",
"in",
"the",
"given",
"environment",
"and",
"return",
"it",
"."
] | 59fff3761af07a59f8f1c1682f2be004bdac15f7 | https://github.com/crunchyroll/ef-open/blob/59fff3761af07a59f8f1c1682f2be004bdac15f7/efopen/ef_cf_diff.py#L81-L89 | train | 38,632 |
crunchyroll/ef-open | efopen/ef_cf_diff.py | diff_sevice_by_text | def diff_sevice_by_text(service_name, service, environment, cf_client, repo_root):
"""
Render the local template and compare it to the template that was last
applied in the target environment.
"""
global ret_code
logger.info('Investigating textual diff for `%s`:`%s` in environment `%s`',
service['type'], service_name, environment)
try:
local_template = render_local_template(service_name, environment,
repo_root, service['template_file'])
current_template = fetch_current_cloudformation_template(
service_name, environment, cf_client)
except Exception as e:
ret_code = 2
logger.error(e)
return
ret = diff_string_templates(local_template, current_template)
if not ret:
logger.info('Deployed service `%s` in environment `%s` matches '
'the local template.', service_name, environment)
else:
ret_code = 1
logger.error('Service `%s` in environment `%s` differs from '
'the local template.',
service_name, environment)
logger.info('Change details:\n %s', indentify(ret)) | python | def diff_sevice_by_text(service_name, service, environment, cf_client, repo_root):
"""
Render the local template and compare it to the template that was last
applied in the target environment.
"""
global ret_code
logger.info('Investigating textual diff for `%s`:`%s` in environment `%s`',
service['type'], service_name, environment)
try:
local_template = render_local_template(service_name, environment,
repo_root, service['template_file'])
current_template = fetch_current_cloudformation_template(
service_name, environment, cf_client)
except Exception as e:
ret_code = 2
logger.error(e)
return
ret = diff_string_templates(local_template, current_template)
if not ret:
logger.info('Deployed service `%s` in environment `%s` matches '
'the local template.', service_name, environment)
else:
ret_code = 1
logger.error('Service `%s` in environment `%s` differs from '
'the local template.',
service_name, environment)
logger.info('Change details:\n %s', indentify(ret)) | [
"def",
"diff_sevice_by_text",
"(",
"service_name",
",",
"service",
",",
"environment",
",",
"cf_client",
",",
"repo_root",
")",
":",
"global",
"ret_code",
"logger",
".",
"info",
"(",
"'Investigating textual diff for `%s`:`%s` in environment `%s`'",
",",
"service",
"[",
... | Render the local template and compare it to the template that was last
applied in the target environment. | [
"Render",
"the",
"local",
"template",
"and",
"compare",
"it",
"to",
"the",
"template",
"that",
"was",
"last",
"applied",
"in",
"the",
"target",
"environment",
"."
] | 59fff3761af07a59f8f1c1682f2be004bdac15f7 | https://github.com/crunchyroll/ef-open/blob/59fff3761af07a59f8f1c1682f2be004bdac15f7/efopen/ef_cf_diff.py#L92-L123 | train | 38,633 |
crunchyroll/ef-open | efopen/ef_cf_diff.py | diff_sevice_by_changeset | def diff_sevice_by_changeset(service_name, service, environment, cf_client, repo_root):
"""
If an ef-cf call fails, the error will be logged, the retcode set to 2, but
the function will run to completion and return the list of non-error
results.
"""
global ret_code
logger.info('Investigating changeset for `%s`:`%s` in environment `%s`',
service['type'], service_name, environment)
delete_any_existing_changesets(cf_client, service_name, environment)
try:
changeset = generate_changeset(service_name, environment,
repo_root, service['template_file'])
except Exception as e:
ret_code = 2
logger.error(e)
return
wait_for_changeset_creation(cf_client, changeset['Id'], changeset['StackId'])
logger.info('Created Changeset ID: `%s`', changeset['Id'])
desc = cf_client.describe_change_set(
ChangeSetName=changeset['Id'], StackName=changeset['StackId'])
cf_client.delete_change_set(
ChangeSetName=changeset['Id'], StackName=changeset['StackId'])
if changeset_is_empty(desc):
logger.info('Deployed service `%s` in environment `%s` matches '
'the local template.', service_name, environment)
else:
ret_code = 1
logger.error('Service `%s` in environment `%s` differs from '
'the local template.',
service_name, environment)
details = jsonify(desc['Changes'])
logger.info('Change details:\n %s', indentify(details)) | python | def diff_sevice_by_changeset(service_name, service, environment, cf_client, repo_root):
"""
If an ef-cf call fails, the error will be logged, the retcode set to 2, but
the function will run to completion and return the list of non-error
results.
"""
global ret_code
logger.info('Investigating changeset for `%s`:`%s` in environment `%s`',
service['type'], service_name, environment)
delete_any_existing_changesets(cf_client, service_name, environment)
try:
changeset = generate_changeset(service_name, environment,
repo_root, service['template_file'])
except Exception as e:
ret_code = 2
logger.error(e)
return
wait_for_changeset_creation(cf_client, changeset['Id'], changeset['StackId'])
logger.info('Created Changeset ID: `%s`', changeset['Id'])
desc = cf_client.describe_change_set(
ChangeSetName=changeset['Id'], StackName=changeset['StackId'])
cf_client.delete_change_set(
ChangeSetName=changeset['Id'], StackName=changeset['StackId'])
if changeset_is_empty(desc):
logger.info('Deployed service `%s` in environment `%s` matches '
'the local template.', service_name, environment)
else:
ret_code = 1
logger.error('Service `%s` in environment `%s` differs from '
'the local template.',
service_name, environment)
details = jsonify(desc['Changes'])
logger.info('Change details:\n %s', indentify(details)) | [
"def",
"diff_sevice_by_changeset",
"(",
"service_name",
",",
"service",
",",
"environment",
",",
"cf_client",
",",
"repo_root",
")",
":",
"global",
"ret_code",
"logger",
".",
"info",
"(",
"'Investigating changeset for `%s`:`%s` in environment `%s`'",
",",
"service",
"["... | If an ef-cf call fails, the error will be logged, the retcode set to 2, but
the function will run to completion and return the list of non-error
results. | [
"If",
"an",
"ef",
"-",
"cf",
"call",
"fails",
"the",
"error",
"will",
"be",
"logged",
"the",
"retcode",
"set",
"to",
"2",
"but",
"the",
"function",
"will",
"run",
"to",
"completion",
"and",
"return",
"the",
"list",
"of",
"non",
"-",
"error",
"results",... | 59fff3761af07a59f8f1c1682f2be004bdac15f7 | https://github.com/crunchyroll/ef-open/blob/59fff3761af07a59f8f1c1682f2be004bdac15f7/efopen/ef_cf_diff.py#L198-L238 | train | 38,634 |
crunchyroll/ef-open | efopen/ef_cf_diff.py | get_cloudformation_client | def get_cloudformation_client(service_name, environment_name):
"""
Given a service name and an environment name, return a boto CloudFormation
client object.
"""
region = service_registry.service_region(service_name)
if whereami() == 'ec2':
profile = None
else:
profile = get_account_alias(environment_name)
clients = create_aws_clients(region, profile, 'cloudformation')
return clients['cloudformation'] | python | def get_cloudformation_client(service_name, environment_name):
"""
Given a service name and an environment name, return a boto CloudFormation
client object.
"""
region = service_registry.service_region(service_name)
if whereami() == 'ec2':
profile = None
else:
profile = get_account_alias(environment_name)
clients = create_aws_clients(region, profile, 'cloudformation')
return clients['cloudformation'] | [
"def",
"get_cloudformation_client",
"(",
"service_name",
",",
"environment_name",
")",
":",
"region",
"=",
"service_registry",
".",
"service_region",
"(",
"service_name",
")",
"if",
"whereami",
"(",
")",
"==",
"'ec2'",
":",
"profile",
"=",
"None",
"else",
":",
... | Given a service name and an environment name, return a boto CloudFormation
client object. | [
"Given",
"a",
"service",
"name",
"and",
"an",
"environment",
"name",
"return",
"a",
"boto",
"CloudFormation",
"client",
"object",
"."
] | 59fff3761af07a59f8f1c1682f2be004bdac15f7 | https://github.com/crunchyroll/ef-open/blob/59fff3761af07a59f8f1c1682f2be004bdac15f7/efopen/ef_cf_diff.py#L241-L254 | train | 38,635 |
crunchyroll/ef-open | efopen/ef_cf_diff.py | evaluate_service_changes | def evaluate_service_changes(services, envs, repo_root, func):
"""
Given a dict of services, and a list of environments, apply the diff
function to evaluate the differences between the target environments
and the rendered templates.
Sub-services (names with '.' in them) are skipped.
"""
for service_name, service in services.iteritems():
for env_category in service['environments']:
if env_category not in get_env_categories(envs):
logger.debug('Skipping not-included environment `%s` for service `%s`',
env_category, service_name)
continue
environment = generate_test_environment_name(env_category)
cf_client = get_cloudformation_client(service_name, environment)
func(service_name, service, environment, cf_client, repo_root) | python | def evaluate_service_changes(services, envs, repo_root, func):
"""
Given a dict of services, and a list of environments, apply the diff
function to evaluate the differences between the target environments
and the rendered templates.
Sub-services (names with '.' in them) are skipped.
"""
for service_name, service in services.iteritems():
for env_category in service['environments']:
if env_category not in get_env_categories(envs):
logger.debug('Skipping not-included environment `%s` for service `%s`',
env_category, service_name)
continue
environment = generate_test_environment_name(env_category)
cf_client = get_cloudformation_client(service_name, environment)
func(service_name, service, environment, cf_client, repo_root) | [
"def",
"evaluate_service_changes",
"(",
"services",
",",
"envs",
",",
"repo_root",
",",
"func",
")",
":",
"for",
"service_name",
",",
"service",
"in",
"services",
".",
"iteritems",
"(",
")",
":",
"for",
"env_category",
"in",
"service",
"[",
"'environments'",
... | Given a dict of services, and a list of environments, apply the diff
function to evaluate the differences between the target environments
and the rendered templates.
Sub-services (names with '.' in them) are skipped. | [
"Given",
"a",
"dict",
"of",
"services",
"and",
"a",
"list",
"of",
"environments",
"apply",
"the",
"diff",
"function",
"to",
"evaluate",
"the",
"differences",
"between",
"the",
"target",
"environments",
"and",
"the",
"rendered",
"templates",
"."
] | 59fff3761af07a59f8f1c1682f2be004bdac15f7 | https://github.com/crunchyroll/ef-open/blob/59fff3761af07a59f8f1c1682f2be004bdac15f7/efopen/ef_cf_diff.py#L277-L297 | train | 38,636 |
crunchyroll/ef-open | efopen/ef_cf_diff.py | get_matching_service_template_file | def get_matching_service_template_file(service_name, template_files):
"""
Return the template file that goes with the given service name, or return
None if there's no match. Subservices return the parent service's file.
"""
# If this is a subservice, use the parent service's template
service_name = service_name.split('.')[0]
if service_name in template_files:
return template_files[service_name]
return None | python | def get_matching_service_template_file(service_name, template_files):
"""
Return the template file that goes with the given service name, or return
None if there's no match. Subservices return the parent service's file.
"""
# If this is a subservice, use the parent service's template
service_name = service_name.split('.')[0]
if service_name in template_files:
return template_files[service_name]
return None | [
"def",
"get_matching_service_template_file",
"(",
"service_name",
",",
"template_files",
")",
":",
"# If this is a subservice, use the parent service's template",
"service_name",
"=",
"service_name",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
"if",
"service_name",
"in"... | Return the template file that goes with the given service name, or return
None if there's no match. Subservices return the parent service's file. | [
"Return",
"the",
"template",
"file",
"that",
"goes",
"with",
"the",
"given",
"service",
"name",
"or",
"return",
"None",
"if",
"there",
"s",
"no",
"match",
".",
"Subservices",
"return",
"the",
"parent",
"service",
"s",
"file",
"."
] | 59fff3761af07a59f8f1c1682f2be004bdac15f7 | https://github.com/crunchyroll/ef-open/blob/59fff3761af07a59f8f1c1682f2be004bdac15f7/efopen/ef_cf_diff.py#L316-L325 | train | 38,637 |
penguinmenac3/starttf | starttf/layers/tile_2d.py | inverse_tile_2d | def inverse_tile_2d(input, k_x, k_y, name):
"""
An inverse tiling layer.
An inverse to the tiling layer can be of great use, since you can keep the resolution of your output low,
but harness the benefits of the resolution of a higher level feature layer.
If you insist on a source you can call it very lightly inspired by yolo9000 "passthrough layer".
:param input: Your input tensor. (Assert input.shape[1] % k_y = 0 and input.shape[2] % k_x = 0)
:param k_x: The tiling factor in x direction [int].
:param k_y: The tiling factor in y direction [int].
:param name: The name of the layer.
:return: The output tensor of shape [batch_size, inp.height / k_y, inp.width / k_x, inp.channels * k_x * k_y].
"""
batch_size, h, w, c = input.get_shape().as_list()
if batch_size is None:
batch_size = -1
# Check if tiling is possible and define output shape.
assert w % k_x == 0 and h % k_y == 0
# Actual inverse tilining
with tf.variable_scope(name) as scope:
tmp = input
tmp = tf.reshape(tmp, (batch_size, int(h * k_y), w, int(c * k_x)))
tmp = tf.transpose(tmp, [0, 2, 1, 3])
tmp = tf.reshape(tmp, (batch_size, w, h, int(c * k_y * k_x)))
tmp = tf.transpose(tmp, [0, 2, 1, 3])
return tmp | python | def inverse_tile_2d(input, k_x, k_y, name):
"""
An inverse tiling layer.
An inverse to the tiling layer can be of great use, since you can keep the resolution of your output low,
but harness the benefits of the resolution of a higher level feature layer.
If you insist on a source you can call it very lightly inspired by yolo9000 "passthrough layer".
:param input: Your input tensor. (Assert input.shape[1] % k_y = 0 and input.shape[2] % k_x = 0)
:param k_x: The tiling factor in x direction [int].
:param k_y: The tiling factor in y direction [int].
:param name: The name of the layer.
:return: The output tensor of shape [batch_size, inp.height / k_y, inp.width / k_x, inp.channels * k_x * k_y].
"""
batch_size, h, w, c = input.get_shape().as_list()
if batch_size is None:
batch_size = -1
# Check if tiling is possible and define output shape.
assert w % k_x == 0 and h % k_y == 0
# Actual inverse tilining
with tf.variable_scope(name) as scope:
tmp = input
tmp = tf.reshape(tmp, (batch_size, int(h * k_y), w, int(c * k_x)))
tmp = tf.transpose(tmp, [0, 2, 1, 3])
tmp = tf.reshape(tmp, (batch_size, w, h, int(c * k_y * k_x)))
tmp = tf.transpose(tmp, [0, 2, 1, 3])
return tmp | [
"def",
"inverse_tile_2d",
"(",
"input",
",",
"k_x",
",",
"k_y",
",",
"name",
")",
":",
"batch_size",
",",
"h",
",",
"w",
",",
"c",
"=",
"input",
".",
"get_shape",
"(",
")",
".",
"as_list",
"(",
")",
"if",
"batch_size",
"is",
"None",
":",
"batch_siz... | An inverse tiling layer.
An inverse to the tiling layer can be of great use, since you can keep the resolution of your output low,
but harness the benefits of the resolution of a higher level feature layer.
If you insist on a source you can call it very lightly inspired by yolo9000 "passthrough layer".
:param input: Your input tensor. (Assert input.shape[1] % k_y = 0 and input.shape[2] % k_x = 0)
:param k_x: The tiling factor in x direction [int].
:param k_y: The tiling factor in y direction [int].
:param name: The name of the layer.
:return: The output tensor of shape [batch_size, inp.height / k_y, inp.width / k_x, inp.channels * k_x * k_y]. | [
"An",
"inverse",
"tiling",
"layer",
"."
] | f4086489d169757c0504e822165db2fea534b944 | https://github.com/penguinmenac3/starttf/blob/f4086489d169757c0504e822165db2fea534b944/starttf/layers/tile_2d.py#L69-L99 | train | 38,638 |
penguinmenac3/starttf | starttf/layers/tile_2d.py | feature_passthrough | def feature_passthrough(early_feat, late_feat, filters, name, kernel_size=(1, 1)):
"""
A feature passthrough layer inspired by yolo9000 and the inverse tiling layer.
It can be proven, that this layer does the same as conv(concat(inverse_tile(early_feat), late_feat)).
This layer has no activation function.
:param early_feat: The early feature layer of shape [batch_size, h * s_x, w * s_y, _].
s_x and s_y are integers computed internally describing the scale between the layers.
:param late_feat: The late feature layer of shape [batch_size, h, w, _].
:param filters: The number of convolution filters.
:param name: The name of the layer.
:param kernel_size: The size of the kernel. Default (1x1).
:return: The output tensor of shape [batch_size, h, w, outputs]
"""
_, h_early, w_early, c_early = early_feat.get_shape().as_list()
_, h_late, w_late, c_late = late_feat.get_shape().as_list()
s_x = int(w_early / w_late)
s_y = int(h_early / h_late)
assert h_late * s_y == h_early and w_late * s_x == w_early
with tf.variable_scope(name) as scope:
early_conv = tf.layers.conv2d(early_feat, filters=filters, kernel_size=(s_x * kernel_size[0], s_y * kernel_size[1]), strides=(s_x, s_y), padding="same")
late_conv = tf.layers.conv2d(late_feat, filters=filters, kernel_size=kernel_size, strides=(1, 1), padding="same")
return early_conv + late_conv | python | def feature_passthrough(early_feat, late_feat, filters, name, kernel_size=(1, 1)):
"""
A feature passthrough layer inspired by yolo9000 and the inverse tiling layer.
It can be proven, that this layer does the same as conv(concat(inverse_tile(early_feat), late_feat)).
This layer has no activation function.
:param early_feat: The early feature layer of shape [batch_size, h * s_x, w * s_y, _].
s_x and s_y are integers computed internally describing the scale between the layers.
:param late_feat: The late feature layer of shape [batch_size, h, w, _].
:param filters: The number of convolution filters.
:param name: The name of the layer.
:param kernel_size: The size of the kernel. Default (1x1).
:return: The output tensor of shape [batch_size, h, w, outputs]
"""
_, h_early, w_early, c_early = early_feat.get_shape().as_list()
_, h_late, w_late, c_late = late_feat.get_shape().as_list()
s_x = int(w_early / w_late)
s_y = int(h_early / h_late)
assert h_late * s_y == h_early and w_late * s_x == w_early
with tf.variable_scope(name) as scope:
early_conv = tf.layers.conv2d(early_feat, filters=filters, kernel_size=(s_x * kernel_size[0], s_y * kernel_size[1]), strides=(s_x, s_y), padding="same")
late_conv = tf.layers.conv2d(late_feat, filters=filters, kernel_size=kernel_size, strides=(1, 1), padding="same")
return early_conv + late_conv | [
"def",
"feature_passthrough",
"(",
"early_feat",
",",
"late_feat",
",",
"filters",
",",
"name",
",",
"kernel_size",
"=",
"(",
"1",
",",
"1",
")",
")",
":",
"_",
",",
"h_early",
",",
"w_early",
",",
"c_early",
"=",
"early_feat",
".",
"get_shape",
"(",
"... | A feature passthrough layer inspired by yolo9000 and the inverse tiling layer.
It can be proven, that this layer does the same as conv(concat(inverse_tile(early_feat), late_feat)).
This layer has no activation function.
:param early_feat: The early feature layer of shape [batch_size, h * s_x, w * s_y, _].
s_x and s_y are integers computed internally describing the scale between the layers.
:param late_feat: The late feature layer of shape [batch_size, h, w, _].
:param filters: The number of convolution filters.
:param name: The name of the layer.
:param kernel_size: The size of the kernel. Default (1x1).
:return: The output tensor of shape [batch_size, h, w, outputs] | [
"A",
"feature",
"passthrough",
"layer",
"inspired",
"by",
"yolo9000",
"and",
"the",
"inverse",
"tiling",
"layer",
"."
] | f4086489d169757c0504e822165db2fea534b944 | https://github.com/penguinmenac3/starttf/blob/f4086489d169757c0504e822165db2fea534b944/starttf/layers/tile_2d.py#L102-L128 | train | 38,639 |
penguinmenac3/starttf | starttf/layers/tile_2d.py | upsampling_feature_passthrough | def upsampling_feature_passthrough(early_feat, late_feat, filters, name, kernel_size=(1, 1)):
"""
An upsampling feature passthrough layer inspired by yolo9000 and the tiling layer.
It can be proven, that this layer does the same as conv(concat(early_feat, tile_2d(late_feat))).
This layer has no activation function.
:param early_feat: The early feature layer of shape [batch_size, h * s_x, w * s_y, _].
s_x and s_y are integers computed internally describing the scale between the layers.
:param late_feat: The late feature layer of shape [batch_size, h, w, _].
:param filters: The number of convolution filters.
:param name: The name of the layer.
:param kernel_size: The size of the kernel. Default (1x1).
:return: The output tensor of shape [batch_size, h * s_x, w * s_y, outputs]
"""
_, h_early, w_early, c_early = early_feat.get_shape().as_list()
_, h_late, w_late, c_late = late_feat.get_shape().as_list()
s_x = int(w_early / w_late)
s_y = int(h_early / h_late)
assert h_late * s_y == h_early and w_late * s_x == w_early
with tf.variable_scope(name) as scope:
tiled = tile_2d(late_feat, s_x, s_y, "tile_2d", reorder_required=False)
concated = tf.concat([early_feat, tiled], axis=-1)
return tf.layers.conv2d(concated, filters=filters, kernel_size=kernel_size, strides=(1, 1), padding="same") | python | def upsampling_feature_passthrough(early_feat, late_feat, filters, name, kernel_size=(1, 1)):
"""
An upsampling feature passthrough layer inspired by yolo9000 and the tiling layer.
It can be proven, that this layer does the same as conv(concat(early_feat, tile_2d(late_feat))).
This layer has no activation function.
:param early_feat: The early feature layer of shape [batch_size, h * s_x, w * s_y, _].
s_x and s_y are integers computed internally describing the scale between the layers.
:param late_feat: The late feature layer of shape [batch_size, h, w, _].
:param filters: The number of convolution filters.
:param name: The name of the layer.
:param kernel_size: The size of the kernel. Default (1x1).
:return: The output tensor of shape [batch_size, h * s_x, w * s_y, outputs]
"""
_, h_early, w_early, c_early = early_feat.get_shape().as_list()
_, h_late, w_late, c_late = late_feat.get_shape().as_list()
s_x = int(w_early / w_late)
s_y = int(h_early / h_late)
assert h_late * s_y == h_early and w_late * s_x == w_early
with tf.variable_scope(name) as scope:
tiled = tile_2d(late_feat, s_x, s_y, "tile_2d", reorder_required=False)
concated = tf.concat([early_feat, tiled], axis=-1)
return tf.layers.conv2d(concated, filters=filters, kernel_size=kernel_size, strides=(1, 1), padding="same") | [
"def",
"upsampling_feature_passthrough",
"(",
"early_feat",
",",
"late_feat",
",",
"filters",
",",
"name",
",",
"kernel_size",
"=",
"(",
"1",
",",
"1",
")",
")",
":",
"_",
",",
"h_early",
",",
"w_early",
",",
"c_early",
"=",
"early_feat",
".",
"get_shape",... | An upsampling feature passthrough layer inspired by yolo9000 and the tiling layer.
It can be proven, that this layer does the same as conv(concat(early_feat, tile_2d(late_feat))).
This layer has no activation function.
:param early_feat: The early feature layer of shape [batch_size, h * s_x, w * s_y, _].
s_x and s_y are integers computed internally describing the scale between the layers.
:param late_feat: The late feature layer of shape [batch_size, h, w, _].
:param filters: The number of convolution filters.
:param name: The name of the layer.
:param kernel_size: The size of the kernel. Default (1x1).
:return: The output tensor of shape [batch_size, h * s_x, w * s_y, outputs] | [
"An",
"upsampling",
"feature",
"passthrough",
"layer",
"inspired",
"by",
"yolo9000",
"and",
"the",
"tiling",
"layer",
"."
] | f4086489d169757c0504e822165db2fea534b944 | https://github.com/penguinmenac3/starttf/blob/f4086489d169757c0504e822165db2fea534b944/starttf/layers/tile_2d.py#L131-L157 | train | 38,640 |
crunchyroll/ef-open | efopen/ef_site_config.py | EFSiteConfig.load | def load(self):
"""Loads the config"""
try:
with open(self._ef_site_config, 'r') as yml_file:
return yaml.safe_load(yml_file)
except (IOError, yaml.parser.ParserError) as error:
print("Error: {}".format(error), file=sys.stderr)
sys.exit(1) | python | def load(self):
"""Loads the config"""
try:
with open(self._ef_site_config, 'r') as yml_file:
return yaml.safe_load(yml_file)
except (IOError, yaml.parser.ParserError) as error:
print("Error: {}".format(error), file=sys.stderr)
sys.exit(1) | [
"def",
"load",
"(",
"self",
")",
":",
"try",
":",
"with",
"open",
"(",
"self",
".",
"_ef_site_config",
",",
"'r'",
")",
"as",
"yml_file",
":",
"return",
"yaml",
".",
"safe_load",
"(",
"yml_file",
")",
"except",
"(",
"IOError",
",",
"yaml",
".",
"pars... | Loads the config | [
"Loads",
"the",
"config"
] | 59fff3761af07a59f8f1c1682f2be004bdac15f7 | https://github.com/crunchyroll/ef-open/blob/59fff3761af07a59f8f1c1682f2be004bdac15f7/efopen/ef_site_config.py#L32-L39 | train | 38,641 |
penguinmenac3/starttf | starttf/losses/loss_processors.py | interpolate_loss | def interpolate_loss(labels, loss1, loss2, interpolation_values):
"""
Interpolate two losses linearly.
:param labels: A float tensor of shape [batch_size, ..., num_classes] representing the label class probabilities.
:param loss1: A float tensor of shape [batch_size, ...] representing the loss1 for interpolation.
:param loss2: A float tensor of shape [batch_size, ...] representing the loss2 for interpolation.
:param interpolation_values: The values for each class how much focal loss should be interpolated in.
:return: A tensor representing the weighted cross entropy.
"""
with tf.variable_scope("interpolate_focus_loss"):
# Select the probs or weights with the labels.
t = tf.reduce_sum(labels * interpolation_values, axis=-1)
return (1 - t) * loss1 + t * loss2 | python | def interpolate_loss(labels, loss1, loss2, interpolation_values):
"""
Interpolate two losses linearly.
:param labels: A float tensor of shape [batch_size, ..., num_classes] representing the label class probabilities.
:param loss1: A float tensor of shape [batch_size, ...] representing the loss1 for interpolation.
:param loss2: A float tensor of shape [batch_size, ...] representing the loss2 for interpolation.
:param interpolation_values: The values for each class how much focal loss should be interpolated in.
:return: A tensor representing the weighted cross entropy.
"""
with tf.variable_scope("interpolate_focus_loss"):
# Select the probs or weights with the labels.
t = tf.reduce_sum(labels * interpolation_values, axis=-1)
return (1 - t) * loss1 + t * loss2 | [
"def",
"interpolate_loss",
"(",
"labels",
",",
"loss1",
",",
"loss2",
",",
"interpolation_values",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"\"interpolate_focus_loss\"",
")",
":",
"# Select the probs or weights with the labels.",
"t",
"=",
"tf",
".",
"red... | Interpolate two losses linearly.
:param labels: A float tensor of shape [batch_size, ..., num_classes] representing the label class probabilities.
:param loss1: A float tensor of shape [batch_size, ...] representing the loss1 for interpolation.
:param loss2: A float tensor of shape [batch_size, ...] representing the loss2 for interpolation.
:param interpolation_values: The values for each class how much focal loss should be interpolated in.
:return: A tensor representing the weighted cross entropy. | [
"Interpolate",
"two",
"losses",
"linearly",
"."
] | f4086489d169757c0504e822165db2fea534b944 | https://github.com/penguinmenac3/starttf/blob/f4086489d169757c0504e822165db2fea534b944/starttf/losses/loss_processors.py#L27-L40 | train | 38,642 |
penguinmenac3/starttf | starttf/losses/loss_processors.py | mask_loss | def mask_loss(input_tensor, binary_tensor):
"""
Mask a loss by using a tensor filled with 0 or 1.
:param input_tensor: A float tensor of shape [batch_size, ...] representing the loss/cross_entropy
:param binary_tensor: A float tensor of shape [batch_size, ...] representing the mask.
:return: A float tensor of shape [batch_size, ...] representing the masked loss.
"""
with tf.variable_scope("mask_loss"):
mask = tf.cast(tf.cast(binary_tensor, tf.bool), tf.float32)
return input_tensor * mask | python | def mask_loss(input_tensor, binary_tensor):
"""
Mask a loss by using a tensor filled with 0 or 1.
:param input_tensor: A float tensor of shape [batch_size, ...] representing the loss/cross_entropy
:param binary_tensor: A float tensor of shape [batch_size, ...] representing the mask.
:return: A float tensor of shape [batch_size, ...] representing the masked loss.
"""
with tf.variable_scope("mask_loss"):
mask = tf.cast(tf.cast(binary_tensor, tf.bool), tf.float32)
return input_tensor * mask | [
"def",
"mask_loss",
"(",
"input_tensor",
",",
"binary_tensor",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"\"mask_loss\"",
")",
":",
"mask",
"=",
"tf",
".",
"cast",
"(",
"tf",
".",
"cast",
"(",
"binary_tensor",
",",
"tf",
".",
"bool",
")",
","... | Mask a loss by using a tensor filled with 0 or 1.
:param input_tensor: A float tensor of shape [batch_size, ...] representing the loss/cross_entropy
:param binary_tensor: A float tensor of shape [batch_size, ...] representing the mask.
:return: A float tensor of shape [batch_size, ...] representing the masked loss. | [
"Mask",
"a",
"loss",
"by",
"using",
"a",
"tensor",
"filled",
"with",
"0",
"or",
"1",
"."
] | f4086489d169757c0504e822165db2fea534b944 | https://github.com/penguinmenac3/starttf/blob/f4086489d169757c0504e822165db2fea534b944/starttf/losses/loss_processors.py#L85-L96 | train | 38,643 |
penguinmenac3/starttf | starttf/losses/loss_processors.py | mean_on_masked | def mean_on_masked(loss, mask, epsilon=1e-8, axis=None):
"""
Average a loss correctly when it was masked.
:param loss: A float tensor of shape [batch_size, ...] representing the (already masked) loss to be averaged.
:param mask: A float tensor of shape [batch_size, ...] representing the mask.
:param epsilon: Offset of log for numerical stability.
:param axis: The dimensions to reduce. If None (the default), reduces all dimensions.
Must be in the range [-rank(input_tensor), rank(input_tensor)).
"""
mask = tf.cast(tf.cast(mask, tf.bool), tf.float32)
active_pixels = tf.reduce_sum(mask)
active_pixels = tf_if(tf.equal(active_pixels, 0), epsilon, active_pixels)
return tf.reduce_sum(loss, axis=axis) / active_pixels | python | def mean_on_masked(loss, mask, epsilon=1e-8, axis=None):
"""
Average a loss correctly when it was masked.
:param loss: A float tensor of shape [batch_size, ...] representing the (already masked) loss to be averaged.
:param mask: A float tensor of shape [batch_size, ...] representing the mask.
:param epsilon: Offset of log for numerical stability.
:param axis: The dimensions to reduce. If None (the default), reduces all dimensions.
Must be in the range [-rank(input_tensor), rank(input_tensor)).
"""
mask = tf.cast(tf.cast(mask, tf.bool), tf.float32)
active_pixels = tf.reduce_sum(mask)
active_pixels = tf_if(tf.equal(active_pixels, 0), epsilon, active_pixels)
return tf.reduce_sum(loss, axis=axis) / active_pixels | [
"def",
"mean_on_masked",
"(",
"loss",
",",
"mask",
",",
"epsilon",
"=",
"1e-8",
",",
"axis",
"=",
"None",
")",
":",
"mask",
"=",
"tf",
".",
"cast",
"(",
"tf",
".",
"cast",
"(",
"mask",
",",
"tf",
".",
"bool",
")",
",",
"tf",
".",
"float32",
")"... | Average a loss correctly when it was masked.
:param loss: A float tensor of shape [batch_size, ...] representing the (already masked) loss to be averaged.
:param mask: A float tensor of shape [batch_size, ...] representing the mask.
:param epsilon: Offset of log for numerical stability.
:param axis: The dimensions to reduce. If None (the default), reduces all dimensions.
Must be in the range [-rank(input_tensor), rank(input_tensor)). | [
"Average",
"a",
"loss",
"correctly",
"when",
"it",
"was",
"masked",
"."
] | f4086489d169757c0504e822165db2fea534b944 | https://github.com/penguinmenac3/starttf/blob/f4086489d169757c0504e822165db2fea534b944/starttf/losses/loss_processors.py#L99-L112 | train | 38,644 |
penguinmenac3/starttf | starttf/losses/loss_processors.py | mask_and_mean_loss | def mask_and_mean_loss(input_tensor, binary_tensor, axis=None):
"""
Mask a loss by using a tensor filled with 0 or 1 and average correctly.
:param input_tensor: A float tensor of shape [batch_size, ...] representing the loss/cross_entropy
:param binary_tensor: A float tensor of shape [batch_size, ...] representing the mask.
:return: A float tensor of shape [batch_size, ...] representing the masked loss.
:param axis: The dimensions to reduce. If None (the default), reduces all dimensions.
Must be in the range [-rank(input_tensor), rank(input_tensor)).
"""
return mean_on_masked(mask_loss(input_tensor, binary_tensor), binary_tensor, axis=axis) | python | def mask_and_mean_loss(input_tensor, binary_tensor, axis=None):
"""
Mask a loss by using a tensor filled with 0 or 1 and average correctly.
:param input_tensor: A float tensor of shape [batch_size, ...] representing the loss/cross_entropy
:param binary_tensor: A float tensor of shape [batch_size, ...] representing the mask.
:return: A float tensor of shape [batch_size, ...] representing the masked loss.
:param axis: The dimensions to reduce. If None (the default), reduces all dimensions.
Must be in the range [-rank(input_tensor), rank(input_tensor)).
"""
return mean_on_masked(mask_loss(input_tensor, binary_tensor), binary_tensor, axis=axis) | [
"def",
"mask_and_mean_loss",
"(",
"input_tensor",
",",
"binary_tensor",
",",
"axis",
"=",
"None",
")",
":",
"return",
"mean_on_masked",
"(",
"mask_loss",
"(",
"input_tensor",
",",
"binary_tensor",
")",
",",
"binary_tensor",
",",
"axis",
"=",
"axis",
")"
] | Mask a loss by using a tensor filled with 0 or 1 and average correctly.
:param input_tensor: A float tensor of shape [batch_size, ...] representing the loss/cross_entropy
:param binary_tensor: A float tensor of shape [batch_size, ...] representing the mask.
:return: A float tensor of shape [batch_size, ...] representing the masked loss.
:param axis: The dimensions to reduce. If None (the default), reduces all dimensions.
Must be in the range [-rank(input_tensor), rank(input_tensor)). | [
"Mask",
"a",
"loss",
"by",
"using",
"a",
"tensor",
"filled",
"with",
"0",
"or",
"1",
"and",
"average",
"correctly",
"."
] | f4086489d169757c0504e822165db2fea534b944 | https://github.com/penguinmenac3/starttf/blob/f4086489d169757c0504e822165db2fea534b944/starttf/losses/loss_processors.py#L115-L125 | train | 38,645 |
penguinmenac3/starttf | starttf/losses/loss_processors.py | variance_corrected_loss | def variance_corrected_loss(loss, sigma_2=None):
"""
Create a variance corrected loss.
When summing variance corrected losses you get the same as multiloss.
This is especially usefull for keras where when having multiple losses they are summed by keras.
This multi-loss implementation is inspired by the Paper "Multi-Task Learning Using Uncertainty to Weight Losses
for Scene Geometry and Semantics" by Kendall, Gal and Cipolla.
:param loss: The loss that should be variance corrected.
:param sigma_2: Optional a variance (sigma squared) to use. If none is provided it is learned.
:return: The variance corrected loss.
"""
with tf.variable_scope("variance_corrected_loss"):
sigma_cost = 0
if sigma_2 is None:
# FIXME the paper has been updated Apr 2018, check if implementation is still valid.
sigma = tf.get_variable(name="sigma", dtype=tf.float32, initializer=tf.constant(1.0), trainable=True)
sigma_2 = tf.pow(sigma, 2)
tf.summary.scalar("sigma2", sigma_2)
sigma_cost = tf.log(sigma_2 + 1.0)
return 0.5 / sigma_2 * loss + sigma_cost | python | def variance_corrected_loss(loss, sigma_2=None):
"""
Create a variance corrected loss.
When summing variance corrected losses you get the same as multiloss.
This is especially usefull for keras where when having multiple losses they are summed by keras.
This multi-loss implementation is inspired by the Paper "Multi-Task Learning Using Uncertainty to Weight Losses
for Scene Geometry and Semantics" by Kendall, Gal and Cipolla.
:param loss: The loss that should be variance corrected.
:param sigma_2: Optional a variance (sigma squared) to use. If none is provided it is learned.
:return: The variance corrected loss.
"""
with tf.variable_scope("variance_corrected_loss"):
sigma_cost = 0
if sigma_2 is None:
# FIXME the paper has been updated Apr 2018, check if implementation is still valid.
sigma = tf.get_variable(name="sigma", dtype=tf.float32, initializer=tf.constant(1.0), trainable=True)
sigma_2 = tf.pow(sigma, 2)
tf.summary.scalar("sigma2", sigma_2)
sigma_cost = tf.log(sigma_2 + 1.0)
return 0.5 / sigma_2 * loss + sigma_cost | [
"def",
"variance_corrected_loss",
"(",
"loss",
",",
"sigma_2",
"=",
"None",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"\"variance_corrected_loss\"",
")",
":",
"sigma_cost",
"=",
"0",
"if",
"sigma_2",
"is",
"None",
":",
"# FIXME the paper has been updated... | Create a variance corrected loss.
When summing variance corrected losses you get the same as multiloss.
This is especially usefull for keras where when having multiple losses they are summed by keras.
This multi-loss implementation is inspired by the Paper "Multi-Task Learning Using Uncertainty to Weight Losses
for Scene Geometry and Semantics" by Kendall, Gal and Cipolla.
:param loss: The loss that should be variance corrected.
:param sigma_2: Optional a variance (sigma squared) to use. If none is provided it is learned.
:return: The variance corrected loss. | [
"Create",
"a",
"variance",
"corrected",
"loss",
"."
] | f4086489d169757c0504e822165db2fea534b944 | https://github.com/penguinmenac3/starttf/blob/f4086489d169757c0504e822165db2fea534b944/starttf/losses/loss_processors.py#L128-L148 | train | 38,646 |
penguinmenac3/starttf | starttf/losses/loss_processors.py | focus_loss | def focus_loss(labels, probs, loss, gamma):
"""
Calculate the alpha balanced focal loss.
See the focal loss paper: "Focal Loss for Dense Object Detection" [by Facebook AI Research]
:param labels: A float tensor of shape [batch_size, ..., num_classes] representing the label class probabilities.
:param probs: A float tensor of shape [batch_size, ..., num_classes] representing the probs (after softmax).
:param loss: A float tensor of shape [batch_size, ...] representing the loss that should be focused.
:param gamma: The focus parameter.
:return: A tensor representing the weighted cross entropy.
"""
with tf.variable_scope("focus_loss"):
# Compute p_t that is used in paper.
# FIXME is it possible that the 1-p term does not make any sense?
p_t = tf.reduce_sum(probs * labels, axis=-1)# + tf.reduce_sum((1.0 - probs) * (1.0 - labels), axis=-1)
focal_factor = tf.pow(1.0 - p_t, gamma) if gamma > 0 else 1 # Improve stability for gamma = 0
return tf.stop_gradient(focal_factor) * loss | python | def focus_loss(labels, probs, loss, gamma):
"""
Calculate the alpha balanced focal loss.
See the focal loss paper: "Focal Loss for Dense Object Detection" [by Facebook AI Research]
:param labels: A float tensor of shape [batch_size, ..., num_classes] representing the label class probabilities.
:param probs: A float tensor of shape [batch_size, ..., num_classes] representing the probs (after softmax).
:param loss: A float tensor of shape [batch_size, ...] representing the loss that should be focused.
:param gamma: The focus parameter.
:return: A tensor representing the weighted cross entropy.
"""
with tf.variable_scope("focus_loss"):
# Compute p_t that is used in paper.
# FIXME is it possible that the 1-p term does not make any sense?
p_t = tf.reduce_sum(probs * labels, axis=-1)# + tf.reduce_sum((1.0 - probs) * (1.0 - labels), axis=-1)
focal_factor = tf.pow(1.0 - p_t, gamma) if gamma > 0 else 1 # Improve stability for gamma = 0
return tf.stop_gradient(focal_factor) * loss | [
"def",
"focus_loss",
"(",
"labels",
",",
"probs",
",",
"loss",
",",
"gamma",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"\"focus_loss\"",
")",
":",
"# Compute p_t that is used in paper.",
"# FIXME is it possible that the 1-p term does not make any sense?",
"p_t",... | Calculate the alpha balanced focal loss.
See the focal loss paper: "Focal Loss for Dense Object Detection" [by Facebook AI Research]
:param labels: A float tensor of shape [batch_size, ..., num_classes] representing the label class probabilities.
:param probs: A float tensor of shape [batch_size, ..., num_classes] representing the probs (after softmax).
:param loss: A float tensor of shape [batch_size, ...] representing the loss that should be focused.
:param gamma: The focus parameter.
:return: A tensor representing the weighted cross entropy. | [
"Calculate",
"the",
"alpha",
"balanced",
"focal",
"loss",
"."
] | f4086489d169757c0504e822165db2fea534b944 | https://github.com/penguinmenac3/starttf/blob/f4086489d169757c0504e822165db2fea534b944/starttf/losses/loss_processors.py#L172-L190 | train | 38,647 |
penguinmenac3/starttf | starttf/layers/caffe_tensorflow.py | Network.get_unique_name | def get_unique_name(self, prefix):
'''Returns an index-suffixed unique name for the given prefix.
This is used for auto-generating layer names based on the type-prefix.
'''
ident = sum(t.startswith(prefix) for t, _ in self.layers.items()) + 1
return '%s_%d' % (prefix, ident) | python | def get_unique_name(self, prefix):
'''Returns an index-suffixed unique name for the given prefix.
This is used for auto-generating layer names based on the type-prefix.
'''
ident = sum(t.startswith(prefix) for t, _ in self.layers.items()) + 1
return '%s_%d' % (prefix, ident) | [
"def",
"get_unique_name",
"(",
"self",
",",
"prefix",
")",
":",
"ident",
"=",
"sum",
"(",
"t",
".",
"startswith",
"(",
"prefix",
")",
"for",
"t",
",",
"_",
"in",
"self",
".",
"layers",
".",
"items",
"(",
")",
")",
"+",
"1",
"return",
"'%s_%d'",
"... | Returns an index-suffixed unique name for the given prefix.
This is used for auto-generating layer names based on the type-prefix. | [
"Returns",
"an",
"index",
"-",
"suffixed",
"unique",
"name",
"for",
"the",
"given",
"prefix",
".",
"This",
"is",
"used",
"for",
"auto",
"-",
"generating",
"layer",
"names",
"based",
"on",
"the",
"type",
"-",
"prefix",
"."
] | f4086489d169757c0504e822165db2fea534b944 | https://github.com/penguinmenac3/starttf/blob/f4086489d169757c0504e822165db2fea534b944/starttf/layers/caffe_tensorflow.py#L142-L147 | train | 38,648 |
penguinmenac3/starttf | starttf/layers/caffe_tensorflow.py | Network.make_var | def make_var(self, op_name, name, shape):
'''Creates a new TensorFlow variable.'''
if op_name in self.weights and name in self.weights[op_name]:
if self.verbose:
print("Using: {} {}".format(op_name, name))
initializer = tf.constant(self.weights[op_name][name], shape=shape)
return tf.get_variable(name, initializer=initializer, trainable=self.trainable)
return tf.get_variable(name, shape, trainable=self.trainable) | python | def make_var(self, op_name, name, shape):
'''Creates a new TensorFlow variable.'''
if op_name in self.weights and name in self.weights[op_name]:
if self.verbose:
print("Using: {} {}".format(op_name, name))
initializer = tf.constant(self.weights[op_name][name], shape=shape)
return tf.get_variable(name, initializer=initializer, trainable=self.trainable)
return tf.get_variable(name, shape, trainable=self.trainable) | [
"def",
"make_var",
"(",
"self",
",",
"op_name",
",",
"name",
",",
"shape",
")",
":",
"if",
"op_name",
"in",
"self",
".",
"weights",
"and",
"name",
"in",
"self",
".",
"weights",
"[",
"op_name",
"]",
":",
"if",
"self",
".",
"verbose",
":",
"print",
"... | Creates a new TensorFlow variable. | [
"Creates",
"a",
"new",
"TensorFlow",
"variable",
"."
] | f4086489d169757c0504e822165db2fea534b944 | https://github.com/penguinmenac3/starttf/blob/f4086489d169757c0504e822165db2fea534b944/starttf/layers/caffe_tensorflow.py#L149-L156 | train | 38,649 |
penguinmenac3/starttf | starttf/data/autorecords.py | write_data | def write_data(hyper_params,
mode,
sequence,
num_threads):
"""
Write a tf record containing a feature dict and a label dict.
:param hyper_params: The hyper parameters required for writing {"problem": {"augmentation": {"steps": Int}}}
:param mode: The mode specifies the purpose of the data. Typically it is either "train" or "validation".
:param sequence: A tf.keras.utils.sequence.
:param num_threads: The number of threads. (Recommended: 4 for training and 2 for validation seems to works nice)
:return:
"""
if not isinstance(sequence, Sequence) and not (callable(getattr(sequence, "__getitem__", None)) and callable(getattr(sequence, "__len__", None))):
raise ValueError("sequence must be tf.keras.utils.Sequence or a subtype or implement __len__(self) and __getitem__(self, idx)")
prefix = os.path.join(hyper_params.train.get("tf_records_path", "tfrecords"), mode)
prefix = prefix.replace("\\", "/")
data_tmp_folder = "/".join(prefix.split("/")[:-1])
if not os.path.exists(data_tmp_folder):
os.makedirs(data_tmp_folder)
args = [(hyper_params, sequence, num_threads, i, (prefix + "_%d.tfrecords") % i) for i in range(num_threads)]
# Retrieve a single batch
sample_feature, sample_label = sequence[0]
config = {"num_threads": num_threads}
for k in sample_feature.keys():
config["feature_" + k] = {"shape": sample_feature[k].shape[1:], "dtype": sample_feature[k].dtype.name}
for k in sample_label.keys():
config["label_" + k] = {"shape": sample_label[k].shape[1:], "dtype": sample_label[k].dtype.name}
with open(prefix + '_config.json', 'w') as outfile:
json.dump(config, outfile)
pool = Pool(processes=num_threads)
pool.map(_write_tf_record_pool_helper, args) | python | def write_data(hyper_params,
mode,
sequence,
num_threads):
"""
Write a tf record containing a feature dict and a label dict.
:param hyper_params: The hyper parameters required for writing {"problem": {"augmentation": {"steps": Int}}}
:param mode: The mode specifies the purpose of the data. Typically it is either "train" or "validation".
:param sequence: A tf.keras.utils.sequence.
:param num_threads: The number of threads. (Recommended: 4 for training and 2 for validation seems to works nice)
:return:
"""
if not isinstance(sequence, Sequence) and not (callable(getattr(sequence, "__getitem__", None)) and callable(getattr(sequence, "__len__", None))):
raise ValueError("sequence must be tf.keras.utils.Sequence or a subtype or implement __len__(self) and __getitem__(self, idx)")
prefix = os.path.join(hyper_params.train.get("tf_records_path", "tfrecords"), mode)
prefix = prefix.replace("\\", "/")
data_tmp_folder = "/".join(prefix.split("/")[:-1])
if not os.path.exists(data_tmp_folder):
os.makedirs(data_tmp_folder)
args = [(hyper_params, sequence, num_threads, i, (prefix + "_%d.tfrecords") % i) for i in range(num_threads)]
# Retrieve a single batch
sample_feature, sample_label = sequence[0]
config = {"num_threads": num_threads}
for k in sample_feature.keys():
config["feature_" + k] = {"shape": sample_feature[k].shape[1:], "dtype": sample_feature[k].dtype.name}
for k in sample_label.keys():
config["label_" + k] = {"shape": sample_label[k].shape[1:], "dtype": sample_label[k].dtype.name}
with open(prefix + '_config.json', 'w') as outfile:
json.dump(config, outfile)
pool = Pool(processes=num_threads)
pool.map(_write_tf_record_pool_helper, args) | [
"def",
"write_data",
"(",
"hyper_params",
",",
"mode",
",",
"sequence",
",",
"num_threads",
")",
":",
"if",
"not",
"isinstance",
"(",
"sequence",
",",
"Sequence",
")",
"and",
"not",
"(",
"callable",
"(",
"getattr",
"(",
"sequence",
",",
"\"__getitem__\"",
... | Write a tf record containing a feature dict and a label dict.
:param hyper_params: The hyper parameters required for writing {"problem": {"augmentation": {"steps": Int}}}
:param mode: The mode specifies the purpose of the data. Typically it is either "train" or "validation".
:param sequence: A tf.keras.utils.sequence.
:param num_threads: The number of threads. (Recommended: 4 for training and 2 for validation seems to works nice)
:return: | [
"Write",
"a",
"tf",
"record",
"containing",
"a",
"feature",
"dict",
"and",
"a",
"label",
"dict",
"."
] | f4086489d169757c0504e822165db2fea534b944 | https://github.com/penguinmenac3/starttf/blob/f4086489d169757c0504e822165db2fea534b944/starttf/data/autorecords.py#L264-L300 | train | 38,650 |
crunchyroll/ef-open | efopen/ef_context.py | EFContext.account_id | def account_id(self, value):
"""
Sets the current account id
Args:
value: current account id (string)
Returns:
None
"""
if type(value) is not str:
raise TypeError("commit value must be string")
self._account_id = value | python | def account_id(self, value):
"""
Sets the current account id
Args:
value: current account id (string)
Returns:
None
"""
if type(value) is not str:
raise TypeError("commit value must be string")
self._account_id = value | [
"def",
"account_id",
"(",
"self",
",",
"value",
")",
":",
"if",
"type",
"(",
"value",
")",
"is",
"not",
"str",
":",
"raise",
"TypeError",
"(",
"\"commit value must be string\"",
")",
"self",
".",
"_account_id",
"=",
"value"
] | Sets the current account id
Args:
value: current account id (string)
Returns:
None | [
"Sets",
"the",
"current",
"account",
"id"
] | 59fff3761af07a59f8f1c1682f2be004bdac15f7 | https://github.com/crunchyroll/ef-open/blob/59fff3761af07a59f8f1c1682f2be004bdac15f7/efopen/ef_context.py#L127-L139 | train | 38,651 |
penguinmenac3/starttf | starttf/rl/agents/agent.py | Agent.learn | def learn(self, steps=1, **kwargs):
"""
Train the model using the environment and the agent.
Note that the model might be shared between multiple agents (which most probably are of the same type)
at the same time.
:param steps: The number of steps to train for.
"""
# TODO add some housekeeping
for i in range(steps):
self.step(**kwargs) | python | def learn(self, steps=1, **kwargs):
"""
Train the model using the environment and the agent.
Note that the model might be shared between multiple agents (which most probably are of the same type)
at the same time.
:param steps: The number of steps to train for.
"""
# TODO add some housekeeping
for i in range(steps):
self.step(**kwargs) | [
"def",
"learn",
"(",
"self",
",",
"steps",
"=",
"1",
",",
"*",
"*",
"kwargs",
")",
":",
"# TODO add some housekeeping",
"for",
"i",
"in",
"range",
"(",
"steps",
")",
":",
"self",
".",
"step",
"(",
"*",
"*",
"kwargs",
")"
] | Train the model using the environment and the agent.
Note that the model might be shared between multiple agents (which most probably are of the same type)
at the same time.
:param steps: The number of steps to train for. | [
"Train",
"the",
"model",
"using",
"the",
"environment",
"and",
"the",
"agent",
"."
] | f4086489d169757c0504e822165db2fea534b944 | https://github.com/penguinmenac3/starttf/blob/f4086489d169757c0504e822165db2fea534b944/starttf/rl/agents/agent.py#L63-L73 | train | 38,652 |
crunchyroll/ef-open | efopen/ef_utils.py | fail | def fail(message, exception_data=None):
"""
Print a failure message and exit nonzero
"""
print(message, file=sys.stderr)
if exception_data:
print(repr(exception_data))
sys.exit(1) | python | def fail(message, exception_data=None):
"""
Print a failure message and exit nonzero
"""
print(message, file=sys.stderr)
if exception_data:
print(repr(exception_data))
sys.exit(1) | [
"def",
"fail",
"(",
"message",
",",
"exception_data",
"=",
"None",
")",
":",
"print",
"(",
"message",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"if",
"exception_data",
":",
"print",
"(",
"repr",
"(",
"exception_data",
")",
")",
"sys",
".",
"exit",
... | Print a failure message and exit nonzero | [
"Print",
"a",
"failure",
"message",
"and",
"exit",
"nonzero"
] | 59fff3761af07a59f8f1c1682f2be004bdac15f7 | https://github.com/crunchyroll/ef-open/blob/59fff3761af07a59f8f1c1682f2be004bdac15f7/efopen/ef_utils.py#L47-L54 | train | 38,653 |
crunchyroll/ef-open | efopen/ef_utils.py | is_in_virtualbox | def is_in_virtualbox():
"""
Is the current environment a virtualbox instance?
Returns a boolean
Raises IOError if the necessary tooling isn't available
"""
if not isfile(__VIRT_WHAT) or not access(__VIRT_WHAT, X_OK):
raise IOError("virt-what not available")
try:
return subprocess.check_output(["sudo", "-n", __VIRT_WHAT]).split('\n')[0:2] == __VIRT_WHAT_VIRTUALBOX_WITH_KVM
except subprocess.CalledProcessError as e:
raise IOError("virt-what failed execution with {}".format(e)) | python | def is_in_virtualbox():
"""
Is the current environment a virtualbox instance?
Returns a boolean
Raises IOError if the necessary tooling isn't available
"""
if not isfile(__VIRT_WHAT) or not access(__VIRT_WHAT, X_OK):
raise IOError("virt-what not available")
try:
return subprocess.check_output(["sudo", "-n", __VIRT_WHAT]).split('\n')[0:2] == __VIRT_WHAT_VIRTUALBOX_WITH_KVM
except subprocess.CalledProcessError as e:
raise IOError("virt-what failed execution with {}".format(e)) | [
"def",
"is_in_virtualbox",
"(",
")",
":",
"if",
"not",
"isfile",
"(",
"__VIRT_WHAT",
")",
"or",
"not",
"access",
"(",
"__VIRT_WHAT",
",",
"X_OK",
")",
":",
"raise",
"IOError",
"(",
"\"virt-what not available\"",
")",
"try",
":",
"return",
"subprocess",
".",
... | Is the current environment a virtualbox instance?
Returns a boolean
Raises IOError if the necessary tooling isn't available | [
"Is",
"the",
"current",
"environment",
"a",
"virtualbox",
"instance?",
"Returns",
"a",
"boolean",
"Raises",
"IOError",
"if",
"the",
"necessary",
"tooling",
"isn",
"t",
"available"
] | 59fff3761af07a59f8f1c1682f2be004bdac15f7 | https://github.com/crunchyroll/ef-open/blob/59fff3761af07a59f8f1c1682f2be004bdac15f7/efopen/ef_utils.py#L75-L86 | train | 38,654 |
penguinmenac3/starttf | starttf/losses/basic_losses.py | sum_abs_distance | def sum_abs_distance(labels, preds):
"""
Compute the sum of abs distances.
:param labels: A float tensor of shape [batch_size, ..., X] representing the labels.
:param preds: A float tensor of shape [batch_size, ..., X] representing the predictions.
:return: A float tensor of shape [batch_size, ...] representing the summed absolute distance.
"""
with tf.variable_scope("sum_abs_distance"):
return tf.reduce_sum(tf.abs(preds - labels), axis=-1) | python | def sum_abs_distance(labels, preds):
"""
Compute the sum of abs distances.
:param labels: A float tensor of shape [batch_size, ..., X] representing the labels.
:param preds: A float tensor of shape [batch_size, ..., X] representing the predictions.
:return: A float tensor of shape [batch_size, ...] representing the summed absolute distance.
"""
with tf.variable_scope("sum_abs_distance"):
return tf.reduce_sum(tf.abs(preds - labels), axis=-1) | [
"def",
"sum_abs_distance",
"(",
"labels",
",",
"preds",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"\"sum_abs_distance\"",
")",
":",
"return",
"tf",
".",
"reduce_sum",
"(",
"tf",
".",
"abs",
"(",
"preds",
"-",
"labels",
")",
",",
"axis",
"=",
... | Compute the sum of abs distances.
:param labels: A float tensor of shape [batch_size, ..., X] representing the labels.
:param preds: A float tensor of shape [batch_size, ..., X] representing the predictions.
:return: A float tensor of shape [batch_size, ...] representing the summed absolute distance. | [
"Compute",
"the",
"sum",
"of",
"abs",
"distances",
"."
] | f4086489d169757c0504e822165db2fea534b944 | https://github.com/penguinmenac3/starttf/blob/f4086489d169757c0504e822165db2fea534b944/starttf/losses/basic_losses.py#L26-L35 | train | 38,655 |
penguinmenac3/starttf | starttf/losses/basic_losses.py | l1_distance | def l1_distance(labels, preds):
"""
Compute the l1_distance.
:param labels: A float tensor of shape [batch_size, ..., X] representing the labels.
:param preds: A float tensor of shape [batch_size, ..., X] representing the predictions.
:return: A float tensor of shape [batch_size, ...] representing the l1 distance.
"""
with tf.variable_scope("l1_distance"):
return tf.norm(preds - labels, ord=1) | python | def l1_distance(labels, preds):
"""
Compute the l1_distance.
:param labels: A float tensor of shape [batch_size, ..., X] representing the labels.
:param preds: A float tensor of shape [batch_size, ..., X] representing the predictions.
:return: A float tensor of shape [batch_size, ...] representing the l1 distance.
"""
with tf.variable_scope("l1_distance"):
return tf.norm(preds - labels, ord=1) | [
"def",
"l1_distance",
"(",
"labels",
",",
"preds",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"\"l1_distance\"",
")",
":",
"return",
"tf",
".",
"norm",
"(",
"preds",
"-",
"labels",
",",
"ord",
"=",
"1",
")"
] | Compute the l1_distance.
:param labels: A float tensor of shape [batch_size, ..., X] representing the labels.
:param preds: A float tensor of shape [batch_size, ..., X] representing the predictions.
:return: A float tensor of shape [batch_size, ...] representing the l1 distance. | [
"Compute",
"the",
"l1_distance",
"."
] | f4086489d169757c0504e822165db2fea534b944 | https://github.com/penguinmenac3/starttf/blob/f4086489d169757c0504e822165db2fea534b944/starttf/losses/basic_losses.py#L38-L47 | train | 38,656 |
penguinmenac3/starttf | starttf/losses/basic_losses.py | smooth_l1_distance | def smooth_l1_distance(labels, preds, delta=1.0):
"""
Compute the smooth l1_distance.
:param labels: A float tensor of shape [batch_size, ..., X] representing the labels.
:param preds: A float tensor of shape [batch_size, ..., X] representing the predictions.
:param delta: `float`, the point where the huber loss function changes from a quadratic to linear.
:return: A float tensor of shape [batch_size, ...] representing the smooth l1 distance.
"""
with tf.variable_scope("smooth_l1"):
return tf.reduce_sum(tf.losses.huber_loss(
labels=labels,
predictions=preds,
delta=delta,
loss_collection=None,
reduction=tf.losses.Reduction.NONE
), axis=-1) | python | def smooth_l1_distance(labels, preds, delta=1.0):
"""
Compute the smooth l1_distance.
:param labels: A float tensor of shape [batch_size, ..., X] representing the labels.
:param preds: A float tensor of shape [batch_size, ..., X] representing the predictions.
:param delta: `float`, the point where the huber loss function changes from a quadratic to linear.
:return: A float tensor of shape [batch_size, ...] representing the smooth l1 distance.
"""
with tf.variable_scope("smooth_l1"):
return tf.reduce_sum(tf.losses.huber_loss(
labels=labels,
predictions=preds,
delta=delta,
loss_collection=None,
reduction=tf.losses.Reduction.NONE
), axis=-1) | [
"def",
"smooth_l1_distance",
"(",
"labels",
",",
"preds",
",",
"delta",
"=",
"1.0",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"\"smooth_l1\"",
")",
":",
"return",
"tf",
".",
"reduce_sum",
"(",
"tf",
".",
"losses",
".",
"huber_loss",
"(",
"label... | Compute the smooth l1_distance.
:param labels: A float tensor of shape [batch_size, ..., X] representing the labels.
:param preds: A float tensor of shape [batch_size, ..., X] representing the predictions.
:param delta: `float`, the point where the huber loss function changes from a quadratic to linear.
:return: A float tensor of shape [batch_size, ...] representing the smooth l1 distance. | [
"Compute",
"the",
"smooth",
"l1_distance",
"."
] | f4086489d169757c0504e822165db2fea534b944 | https://github.com/penguinmenac3/starttf/blob/f4086489d169757c0504e822165db2fea534b944/starttf/losses/basic_losses.py#L50-L66 | train | 38,657 |
penguinmenac3/starttf | starttf/losses/basic_losses.py | l2_distance | def l2_distance(labels, preds):
"""
Compute the l2_distance.
:param labels: A float tensor of shape [batch_size, ..., X] representing the labels.
:param preds: A float tensor of shape [batch_size, ..., X] representing the predictions.
:return: A float tensor of shape [batch_size, ...] representing the l2 distance.
"""
with tf.variable_scope("l2_distance"):
return tf.norm(preds - labels, ord=2) | python | def l2_distance(labels, preds):
"""
Compute the l2_distance.
:param labels: A float tensor of shape [batch_size, ..., X] representing the labels.
:param preds: A float tensor of shape [batch_size, ..., X] representing the predictions.
:return: A float tensor of shape [batch_size, ...] representing the l2 distance.
"""
with tf.variable_scope("l2_distance"):
return tf.norm(preds - labels, ord=2) | [
"def",
"l2_distance",
"(",
"labels",
",",
"preds",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"\"l2_distance\"",
")",
":",
"return",
"tf",
".",
"norm",
"(",
"preds",
"-",
"labels",
",",
"ord",
"=",
"2",
")"
] | Compute the l2_distance.
:param labels: A float tensor of shape [batch_size, ..., X] representing the labels.
:param preds: A float tensor of shape [batch_size, ..., X] representing the predictions.
:return: A float tensor of shape [batch_size, ...] representing the l2 distance. | [
"Compute",
"the",
"l2_distance",
"."
] | f4086489d169757c0504e822165db2fea534b944 | https://github.com/penguinmenac3/starttf/blob/f4086489d169757c0504e822165db2fea534b944/starttf/losses/basic_losses.py#L69-L78 | train | 38,658 |
penguinmenac3/starttf | starttf/losses/basic_losses.py | cross_entropy | def cross_entropy(labels, logits):
"""
Calculate the cross_entropy.
:param labels: A float tensor of shape [batch_size, ..., num_classes] representing the label class probabilities.
:param logits: A float tensor of shape [batch_size, ..., num_classes] representing the logits.
:return: A tensor representing the cross entropy.
"""
with tf.variable_scope("cross_entropy"):
return tf.nn.softmax_cross_entropy_with_logits(labels=labels, logits=logits) | python | def cross_entropy(labels, logits):
"""
Calculate the cross_entropy.
:param labels: A float tensor of shape [batch_size, ..., num_classes] representing the label class probabilities.
:param logits: A float tensor of shape [batch_size, ..., num_classes] representing the logits.
:return: A tensor representing the cross entropy.
"""
with tf.variable_scope("cross_entropy"):
return tf.nn.softmax_cross_entropy_with_logits(labels=labels, logits=logits) | [
"def",
"cross_entropy",
"(",
"labels",
",",
"logits",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"\"cross_entropy\"",
")",
":",
"return",
"tf",
".",
"nn",
".",
"softmax_cross_entropy_with_logits",
"(",
"labels",
"=",
"labels",
",",
"logits",
"=",
"l... | Calculate the cross_entropy.
:param labels: A float tensor of shape [batch_size, ..., num_classes] representing the label class probabilities.
:param logits: A float tensor of shape [batch_size, ..., num_classes] representing the logits.
:return: A tensor representing the cross entropy. | [
"Calculate",
"the",
"cross_entropy",
"."
] | f4086489d169757c0504e822165db2fea534b944 | https://github.com/penguinmenac3/starttf/blob/f4086489d169757c0504e822165db2fea534b944/starttf/losses/basic_losses.py#L81-L90 | train | 38,659 |
crunchyroll/ef-open | plugins_available/newrelic/interface.py | NewRelic.alert_policy_exists | def alert_policy_exists(self, policy_name):
"""Check to see if an alert policy exists in NewRelic. Return True if so, False if not"""
if next((policy for policy in self.all_alerts if policy['name'] == policy_name), False):
return True | python | def alert_policy_exists(self, policy_name):
"""Check to see if an alert policy exists in NewRelic. Return True if so, False if not"""
if next((policy for policy in self.all_alerts if policy['name'] == policy_name), False):
return True | [
"def",
"alert_policy_exists",
"(",
"self",
",",
"policy_name",
")",
":",
"if",
"next",
"(",
"(",
"policy",
"for",
"policy",
"in",
"self",
".",
"all_alerts",
"if",
"policy",
"[",
"'name'",
"]",
"==",
"policy_name",
")",
",",
"False",
")",
":",
"return",
... | Check to see if an alert policy exists in NewRelic. Return True if so, False if not | [
"Check",
"to",
"see",
"if",
"an",
"alert",
"policy",
"exists",
"in",
"NewRelic",
".",
"Return",
"True",
"if",
"so",
"False",
"if",
"not"
] | 59fff3761af07a59f8f1c1682f2be004bdac15f7 | https://github.com/crunchyroll/ef-open/blob/59fff3761af07a59f8f1c1682f2be004bdac15f7/plugins_available/newrelic/interface.py#L111-L114 | train | 38,660 |
crunchyroll/ef-open | plugins_available/newrelic/interface.py | NewRelic.create_alert_policy | def create_alert_policy(self, policy_name):
"""Creates an alert policy in NewRelic"""
policy_data = { 'policy': { 'incident_preference': 'PER_POLICY', 'name': policy_name } }
create_policy = requests.post(
'https://api.newrelic.com/v2/alerts_policies.json',
headers=self.auth_header,
data=json.dumps(policy_data))
create_policy.raise_for_status()
policy_id = create_policy.json()['policy']['id']
self.refresh_all_alerts()
return policy_id | python | def create_alert_policy(self, policy_name):
"""Creates an alert policy in NewRelic"""
policy_data = { 'policy': { 'incident_preference': 'PER_POLICY', 'name': policy_name } }
create_policy = requests.post(
'https://api.newrelic.com/v2/alerts_policies.json',
headers=self.auth_header,
data=json.dumps(policy_data))
create_policy.raise_for_status()
policy_id = create_policy.json()['policy']['id']
self.refresh_all_alerts()
return policy_id | [
"def",
"create_alert_policy",
"(",
"self",
",",
"policy_name",
")",
":",
"policy_data",
"=",
"{",
"'policy'",
":",
"{",
"'incident_preference'",
":",
"'PER_POLICY'",
",",
"'name'",
":",
"policy_name",
"}",
"}",
"create_policy",
"=",
"requests",
".",
"post",
"(... | Creates an alert policy in NewRelic | [
"Creates",
"an",
"alert",
"policy",
"in",
"NewRelic"
] | 59fff3761af07a59f8f1c1682f2be004bdac15f7 | https://github.com/crunchyroll/ef-open/blob/59fff3761af07a59f8f1c1682f2be004bdac15f7/plugins_available/newrelic/interface.py#L116-L126 | train | 38,661 |
gabstopper/smc-python | smc/actions/_search.py | element_href | def element_href(name):
""" Get specified element href by element name
:param name: name of element
:return: string href location of object, else None
"""
if name:
element = fetch_meta_by_name(name)
if element.href:
return element.href | python | def element_href(name):
""" Get specified element href by element name
:param name: name of element
:return: string href location of object, else None
"""
if name:
element = fetch_meta_by_name(name)
if element.href:
return element.href | [
"def",
"element_href",
"(",
"name",
")",
":",
"if",
"name",
":",
"element",
"=",
"fetch_meta_by_name",
"(",
"name",
")",
"if",
"element",
".",
"href",
":",
"return",
"element",
".",
"href"
] | Get specified element href by element name
:param name: name of element
:return: string href location of object, else None | [
"Get",
"specified",
"element",
"href",
"by",
"element",
"name"
] | e027b8a5dcfaf884eada32d113d41c1e56b32457 | https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/actions/_search.py#L44-L53 | train | 38,662 |
gabstopper/smc-python | smc/actions/_search.py | element_as_json | def element_as_json(name):
""" Get specified element json data by name
:param name: name of element
:return: json data representing element, else None
"""
if name:
element = fetch_json_by_name(name)
if element.json:
return element.json | python | def element_as_json(name):
""" Get specified element json data by name
:param name: name of element
:return: json data representing element, else None
"""
if name:
element = fetch_json_by_name(name)
if element.json:
return element.json | [
"def",
"element_as_json",
"(",
"name",
")",
":",
"if",
"name",
":",
"element",
"=",
"fetch_json_by_name",
"(",
"name",
")",
"if",
"element",
".",
"json",
":",
"return",
"element",
".",
"json"
] | Get specified element json data by name
:param name: name of element
:return: json data representing element, else None | [
"Get",
"specified",
"element",
"json",
"data",
"by",
"name"
] | e027b8a5dcfaf884eada32d113d41c1e56b32457 | https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/actions/_search.py#L56-L65 | train | 38,663 |
gabstopper/smc-python | smc/actions/_search.py | element_as_json_with_filter | def element_as_json_with_filter(name, _filter):
"""
Get specified element json data by name with filter.
Filter can be any valid element type.
:param name: name of element
:param _filter: element filter, host, network, tcp_service,
network_elements, services, services_and_applications, etc
:return: json data representing element, else None
"""
if name:
element_href = element_href_use_filter(name, _filter)
if element_href:
return element_by_href_as_json(element_href) | python | def element_as_json_with_filter(name, _filter):
"""
Get specified element json data by name with filter.
Filter can be any valid element type.
:param name: name of element
:param _filter: element filter, host, network, tcp_service,
network_elements, services, services_and_applications, etc
:return: json data representing element, else None
"""
if name:
element_href = element_href_use_filter(name, _filter)
if element_href:
return element_by_href_as_json(element_href) | [
"def",
"element_as_json_with_filter",
"(",
"name",
",",
"_filter",
")",
":",
"if",
"name",
":",
"element_href",
"=",
"element_href_use_filter",
"(",
"name",
",",
"_filter",
")",
"if",
"element_href",
":",
"return",
"element_by_href_as_json",
"(",
"element_href",
"... | Get specified element json data by name with filter.
Filter can be any valid element type.
:param name: name of element
:param _filter: element filter, host, network, tcp_service,
network_elements, services, services_and_applications, etc
:return: json data representing element, else None | [
"Get",
"specified",
"element",
"json",
"data",
"by",
"name",
"with",
"filter",
".",
"Filter",
"can",
"be",
"any",
"valid",
"element",
"type",
"."
] | e027b8a5dcfaf884eada32d113d41c1e56b32457 | https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/actions/_search.py#L68-L81 | train | 38,664 |
gabstopper/smc-python | smc/actions/_search.py | element_href_use_wildcard | def element_href_use_wildcard(name):
""" Get element href using a wildcard rather than matching only on the name
field. This will likely return multiple results.
:param name: name of element
:return: list of matched elements
"""
if name:
element = fetch_meta_by_name(name, exact_match=False)
return element.json | python | def element_href_use_wildcard(name):
""" Get element href using a wildcard rather than matching only on the name
field. This will likely return multiple results.
:param name: name of element
:return: list of matched elements
"""
if name:
element = fetch_meta_by_name(name, exact_match=False)
return element.json | [
"def",
"element_href_use_wildcard",
"(",
"name",
")",
":",
"if",
"name",
":",
"element",
"=",
"fetch_meta_by_name",
"(",
"name",
",",
"exact_match",
"=",
"False",
")",
"return",
"element",
".",
"json"
] | Get element href using a wildcard rather than matching only on the name
field. This will likely return multiple results.
:param name: name of element
:return: list of matched elements | [
"Get",
"element",
"href",
"using",
"a",
"wildcard",
"rather",
"than",
"matching",
"only",
"on",
"the",
"name",
"field",
".",
"This",
"will",
"likely",
"return",
"multiple",
"results",
"."
] | e027b8a5dcfaf884eada32d113d41c1e56b32457 | https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/actions/_search.py#L127-L136 | train | 38,665 |
gabstopper/smc-python | smc/actions/_search.py | element_href_use_filter | def element_href_use_filter(name, _filter):
""" Get element href using filter
Filter should be a valid entry point value, ie host, router, network,
single_fw, etc
:param name: name of element
:param _filter: filter type, unknown filter will result in no matches
:return: element href (if found), else None
"""
if name and _filter:
element = fetch_meta_by_name(name, filter_context=_filter)
if element.json:
return element.json.pop().get('href') | python | def element_href_use_filter(name, _filter):
""" Get element href using filter
Filter should be a valid entry point value, ie host, router, network,
single_fw, etc
:param name: name of element
:param _filter: filter type, unknown filter will result in no matches
:return: element href (if found), else None
"""
if name and _filter:
element = fetch_meta_by_name(name, filter_context=_filter)
if element.json:
return element.json.pop().get('href') | [
"def",
"element_href_use_filter",
"(",
"name",
",",
"_filter",
")",
":",
"if",
"name",
"and",
"_filter",
":",
"element",
"=",
"fetch_meta_by_name",
"(",
"name",
",",
"filter_context",
"=",
"_filter",
")",
"if",
"element",
".",
"json",
":",
"return",
"element... | Get element href using filter
Filter should be a valid entry point value, ie host, router, network,
single_fw, etc
:param name: name of element
:param _filter: filter type, unknown filter will result in no matches
:return: element href (if found), else None | [
"Get",
"element",
"href",
"using",
"filter"
] | e027b8a5dcfaf884eada32d113d41c1e56b32457 | https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/actions/_search.py#L139-L152 | train | 38,666 |
gabstopper/smc-python | smc/actions/_search.py | element_by_href_as_json | def element_by_href_as_json(href, params=None):
""" Get specified element by href
:param href: link to object
:param params: optional search query parameters
:return: json data representing element, else None
"""
if href:
element = fetch_json_by_href(href, params=params)
if element:
return element.json | python | def element_by_href_as_json(href, params=None):
""" Get specified element by href
:param href: link to object
:param params: optional search query parameters
:return: json data representing element, else None
"""
if href:
element = fetch_json_by_href(href, params=params)
if element:
return element.json | [
"def",
"element_by_href_as_json",
"(",
"href",
",",
"params",
"=",
"None",
")",
":",
"if",
"href",
":",
"element",
"=",
"fetch_json_by_href",
"(",
"href",
",",
"params",
"=",
"params",
")",
"if",
"element",
":",
"return",
"element",
".",
"json"
] | Get specified element by href
:param href: link to object
:param params: optional search query parameters
:return: json data representing element, else None | [
"Get",
"specified",
"element",
"by",
"href"
] | e027b8a5dcfaf884eada32d113d41c1e56b32457 | https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/actions/_search.py#L155-L165 | train | 38,667 |
gabstopper/smc-python | smc/actions/_search.py | element_name_by_href | def element_name_by_href(href):
"""
The element href is known, possibly from a reference in an
elements json. You want to retrieve the name of this element.
:param str href: href of element
:return: str name of element, or None
"""
if href:
element = fetch_json_by_href(href)
if element.json:
return element.json.get('name') | python | def element_name_by_href(href):
"""
The element href is known, possibly from a reference in an
elements json. You want to retrieve the name of this element.
:param str href: href of element
:return: str name of element, or None
"""
if href:
element = fetch_json_by_href(href)
if element.json:
return element.json.get('name') | [
"def",
"element_name_by_href",
"(",
"href",
")",
":",
"if",
"href",
":",
"element",
"=",
"fetch_json_by_href",
"(",
"href",
")",
"if",
"element",
".",
"json",
":",
"return",
"element",
".",
"json",
".",
"get",
"(",
"'name'",
")"
] | The element href is known, possibly from a reference in an
elements json. You want to retrieve the name of this element.
:param str href: href of element
:return: str name of element, or None | [
"The",
"element",
"href",
"is",
"known",
"possibly",
"from",
"a",
"reference",
"in",
"an",
"elements",
"json",
".",
"You",
"want",
"to",
"retrieve",
"the",
"name",
"of",
"this",
"element",
"."
] | e027b8a5dcfaf884eada32d113d41c1e56b32457 | https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/actions/_search.py#L168-L179 | train | 38,668 |
gabstopper/smc-python | smc/actions/_search.py | element_name_and_type_by_href | def element_name_and_type_by_href(href):
"""
Retrieve the element name and type of element based on the href.
You may have a href that is within another element reference and
want more information on that reference.
:param str href: href of element
:return: tuple (name, type)
"""
if href:
element = fetch_json_by_href(href)
if element.json:
for entries in element.json.get('link'):
if entries.get('rel') == 'self':
typeof = entries.get('type')
return (element.json.get('name'),
typeof) | python | def element_name_and_type_by_href(href):
"""
Retrieve the element name and type of element based on the href.
You may have a href that is within another element reference and
want more information on that reference.
:param str href: href of element
:return: tuple (name, type)
"""
if href:
element = fetch_json_by_href(href)
if element.json:
for entries in element.json.get('link'):
if entries.get('rel') == 'self':
typeof = entries.get('type')
return (element.json.get('name'),
typeof) | [
"def",
"element_name_and_type_by_href",
"(",
"href",
")",
":",
"if",
"href",
":",
"element",
"=",
"fetch_json_by_href",
"(",
"href",
")",
"if",
"element",
".",
"json",
":",
"for",
"entries",
"in",
"element",
".",
"json",
".",
"get",
"(",
"'link'",
")",
"... | Retrieve the element name and type of element based on the href.
You may have a href that is within another element reference and
want more information on that reference.
:param str href: href of element
:return: tuple (name, type) | [
"Retrieve",
"the",
"element",
"name",
"and",
"type",
"of",
"element",
"based",
"on",
"the",
"href",
".",
"You",
"may",
"have",
"a",
"href",
"that",
"is",
"within",
"another",
"element",
"reference",
"and",
"want",
"more",
"information",
"on",
"that",
"refe... | e027b8a5dcfaf884eada32d113d41c1e56b32457 | https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/actions/_search.py#L182-L199 | train | 38,669 |
gabstopper/smc-python | smc/actions/_search.py | element_attribute_by_href | def element_attribute_by_href(href, attr_name):
"""
The element href is known and you want to retrieve a specific
attribute from that element.
For example, if you want a specific attribute by it's name::
search.element_attribute_by_href(href_to_resource, 'name')
:param str href: href of element
:param str attr_name: name of attribute
:return: str value of attribute
"""
if href:
element = fetch_json_by_href(href)
if element.json:
return element.json.get(attr_name) | python | def element_attribute_by_href(href, attr_name):
"""
The element href is known and you want to retrieve a specific
attribute from that element.
For example, if you want a specific attribute by it's name::
search.element_attribute_by_href(href_to_resource, 'name')
:param str href: href of element
:param str attr_name: name of attribute
:return: str value of attribute
"""
if href:
element = fetch_json_by_href(href)
if element.json:
return element.json.get(attr_name) | [
"def",
"element_attribute_by_href",
"(",
"href",
",",
"attr_name",
")",
":",
"if",
"href",
":",
"element",
"=",
"fetch_json_by_href",
"(",
"href",
")",
"if",
"element",
".",
"json",
":",
"return",
"element",
".",
"json",
".",
"get",
"(",
"attr_name",
")"
] | The element href is known and you want to retrieve a specific
attribute from that element.
For example, if you want a specific attribute by it's name::
search.element_attribute_by_href(href_to_resource, 'name')
:param str href: href of element
:param str attr_name: name of attribute
:return: str value of attribute | [
"The",
"element",
"href",
"is",
"known",
"and",
"you",
"want",
"to",
"retrieve",
"a",
"specific",
"attribute",
"from",
"that",
"element",
"."
] | e027b8a5dcfaf884eada32d113d41c1e56b32457 | https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/actions/_search.py#L202-L218 | train | 38,670 |
gabstopper/smc-python | smc/actions/_search.py | element_by_href_as_smcresult | def element_by_href_as_smcresult(href, params=None):
""" Get specified element returned as an SMCResult object
:param href: href direct link to object
:return: :py:class:`smc.api.web.SMCResult` with etag, href and
element field holding json, else None
"""
if href:
element = fetch_json_by_href(href, params=params)
if element:
return element | python | def element_by_href_as_smcresult(href, params=None):
""" Get specified element returned as an SMCResult object
:param href: href direct link to object
:return: :py:class:`smc.api.web.SMCResult` with etag, href and
element field holding json, else None
"""
if href:
element = fetch_json_by_href(href, params=params)
if element:
return element | [
"def",
"element_by_href_as_smcresult",
"(",
"href",
",",
"params",
"=",
"None",
")",
":",
"if",
"href",
":",
"element",
"=",
"fetch_json_by_href",
"(",
"href",
",",
"params",
"=",
"params",
")",
"if",
"element",
":",
"return",
"element"
] | Get specified element returned as an SMCResult object
:param href: href direct link to object
:return: :py:class:`smc.api.web.SMCResult` with etag, href and
element field holding json, else None | [
"Get",
"specified",
"element",
"returned",
"as",
"an",
"SMCResult",
"object"
] | e027b8a5dcfaf884eada32d113d41c1e56b32457 | https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/actions/_search.py#L221-L231 | train | 38,671 |
gabstopper/smc-python | smc/actions/_search.py | element_as_smcresult_use_filter | def element_as_smcresult_use_filter(name, _filter):
""" Return SMCResult object and use search filter to
find object
:param name: name of element to find
:param _filter: filter to use, i.e. tcp_service, host, etc
:return: :py:class:`smc.api.web.SMCResult`
"""
if name:
element = fetch_meta_by_name(name, filter_context=_filter)
if element.msg:
return element
if element.json:
return element_by_href_as_smcresult(element.json.pop().get('href')) | python | def element_as_smcresult_use_filter(name, _filter):
""" Return SMCResult object and use search filter to
find object
:param name: name of element to find
:param _filter: filter to use, i.e. tcp_service, host, etc
:return: :py:class:`smc.api.web.SMCResult`
"""
if name:
element = fetch_meta_by_name(name, filter_context=_filter)
if element.msg:
return element
if element.json:
return element_by_href_as_smcresult(element.json.pop().get('href')) | [
"def",
"element_as_smcresult_use_filter",
"(",
"name",
",",
"_filter",
")",
":",
"if",
"name",
":",
"element",
"=",
"fetch_meta_by_name",
"(",
"name",
",",
"filter_context",
"=",
"_filter",
")",
"if",
"element",
".",
"msg",
":",
"return",
"element",
"if",
"e... | Return SMCResult object and use search filter to
find object
:param name: name of element to find
:param _filter: filter to use, i.e. tcp_service, host, etc
:return: :py:class:`smc.api.web.SMCResult` | [
"Return",
"SMCResult",
"object",
"and",
"use",
"search",
"filter",
"to",
"find",
"object"
] | e027b8a5dcfaf884eada32d113d41c1e56b32457 | https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/actions/_search.py#L246-L259 | train | 38,672 |
gabstopper/smc-python | smc/actions/_search.py | element_href_by_batch | def element_href_by_batch(list_to_find, filter=None): # @ReservedAssignment
""" Find batch of entries by name. Reduces number of find calls from
calling class.
:param list list_to_find: list of names to find
:param filter: optional filter, i.e. 'tcp_service', 'host', etc
:return: list: {name: href, name: href}, href may be None if not found
"""
try:
if filter:
return [{k: element_href_use_filter(k, filter)
for k in list_to_find}]
return [{k: element_href(k) for k in list_to_find}]
except TypeError:
logger.error("{} is not iterable".format(list_to_find)) | python | def element_href_by_batch(list_to_find, filter=None): # @ReservedAssignment
""" Find batch of entries by name. Reduces number of find calls from
calling class.
:param list list_to_find: list of names to find
:param filter: optional filter, i.e. 'tcp_service', 'host', etc
:return: list: {name: href, name: href}, href may be None if not found
"""
try:
if filter:
return [{k: element_href_use_filter(k, filter)
for k in list_to_find}]
return [{k: element_href(k) for k in list_to_find}]
except TypeError:
logger.error("{} is not iterable".format(list_to_find)) | [
"def",
"element_href_by_batch",
"(",
"list_to_find",
",",
"filter",
"=",
"None",
")",
":",
"# @ReservedAssignment",
"try",
":",
"if",
"filter",
":",
"return",
"[",
"{",
"k",
":",
"element_href_use_filter",
"(",
"k",
",",
"filter",
")",
"for",
"k",
"in",
"l... | Find batch of entries by name. Reduces number of find calls from
calling class.
:param list list_to_find: list of names to find
:param filter: optional filter, i.e. 'tcp_service', 'host', etc
:return: list: {name: href, name: href}, href may be None if not found | [
"Find",
"batch",
"of",
"entries",
"by",
"name",
".",
"Reduces",
"number",
"of",
"find",
"calls",
"from",
"calling",
"class",
"."
] | e027b8a5dcfaf884eada32d113d41c1e56b32457 | https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/actions/_search.py#L262-L276 | train | 38,673 |
gabstopper/smc-python | smc/actions/_search.py | fetch_json_by_name | def fetch_json_by_name(name):
"""
Fetch json based on the element name
First gets the href based on a search by name, then makes a
second query to obtain the element json
:method: GET
:param str name: element name
:return: :py:class:`smc.api.web.SMCResult`
"""
result = fetch_meta_by_name(name)
if result.href:
result = fetch_json_by_href(result.href)
return result | python | def fetch_json_by_name(name):
"""
Fetch json based on the element name
First gets the href based on a search by name, then makes a
second query to obtain the element json
:method: GET
:param str name: element name
:return: :py:class:`smc.api.web.SMCResult`
"""
result = fetch_meta_by_name(name)
if result.href:
result = fetch_json_by_href(result.href)
return result | [
"def",
"fetch_json_by_name",
"(",
"name",
")",
":",
"result",
"=",
"fetch_meta_by_name",
"(",
"name",
")",
"if",
"result",
".",
"href",
":",
"result",
"=",
"fetch_json_by_href",
"(",
"result",
".",
"href",
")",
"return",
"result"
] | Fetch json based on the element name
First gets the href based on a search by name, then makes a
second query to obtain the element json
:method: GET
:param str name: element name
:return: :py:class:`smc.api.web.SMCResult` | [
"Fetch",
"json",
"based",
"on",
"the",
"element",
"name",
"First",
"gets",
"the",
"href",
"based",
"on",
"a",
"search",
"by",
"name",
"then",
"makes",
"a",
"second",
"query",
"to",
"obtain",
"the",
"element",
"json"
] | e027b8a5dcfaf884eada32d113d41c1e56b32457 | https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/actions/_search.py#L342-L355 | train | 38,674 |
gabstopper/smc-python | smc/vpn/elements.py | GatewaySettings.create | def create(cls, name, negotiation_expiration=200000,
negotiation_retry_timer=500,
negotiation_retry_max_number=32,
negotiation_retry_timer_max=7000,
certificate_cache_crl_validity=90000,
mobike_after_sa_update=False,
mobike_before_sa_update=False,
mobike_no_rrc=True):
"""
Create a new gateway setting profile.
:param str name: name of profile
:param int negotiation_expiration: expire after (ms)
:param int negotiation_retry_timer: retry time length (ms)
:param int negotiation_retry_max_num: max number of retries allowed
:param int negotiation_retry_timer_max: maximum length for retry (ms)
:param int certificate_cache_crl_validity: cert cache validity (seconds)
:param boolean mobike_after_sa_update: Whether the After SA flag is set
for Mobike Policy
:param boolean mobike_before_sa_update: Whether the Before SA flag is
set for Mobike Policy
:param boolean mobike_no_rrc: Whether the No RRC flag is set for
Mobike Policy
:raises CreateElementFailed: failed creating profile
:return: instance with meta
:rtype: GatewaySettings
"""
json = {'name': name,
'negotiation_expiration': negotiation_expiration,
'negotiation_retry_timer': negotiation_retry_timer,
'negotiation_retry_max_number': negotiation_retry_max_number,
'negotiation_retry_timer_max': negotiation_retry_timer_max,
'certificate_cache_crl_validity': certificate_cache_crl_validity,
'mobike_after_sa_update': mobike_after_sa_update,
'mobike_before_sa_update': mobike_before_sa_update,
'mobike_no_rrc': mobike_no_rrc}
return ElementCreator(cls, json) | python | def create(cls, name, negotiation_expiration=200000,
negotiation_retry_timer=500,
negotiation_retry_max_number=32,
negotiation_retry_timer_max=7000,
certificate_cache_crl_validity=90000,
mobike_after_sa_update=False,
mobike_before_sa_update=False,
mobike_no_rrc=True):
"""
Create a new gateway setting profile.
:param str name: name of profile
:param int negotiation_expiration: expire after (ms)
:param int negotiation_retry_timer: retry time length (ms)
:param int negotiation_retry_max_num: max number of retries allowed
:param int negotiation_retry_timer_max: maximum length for retry (ms)
:param int certificate_cache_crl_validity: cert cache validity (seconds)
:param boolean mobike_after_sa_update: Whether the After SA flag is set
for Mobike Policy
:param boolean mobike_before_sa_update: Whether the Before SA flag is
set for Mobike Policy
:param boolean mobike_no_rrc: Whether the No RRC flag is set for
Mobike Policy
:raises CreateElementFailed: failed creating profile
:return: instance with meta
:rtype: GatewaySettings
"""
json = {'name': name,
'negotiation_expiration': negotiation_expiration,
'negotiation_retry_timer': negotiation_retry_timer,
'negotiation_retry_max_number': negotiation_retry_max_number,
'negotiation_retry_timer_max': negotiation_retry_timer_max,
'certificate_cache_crl_validity': certificate_cache_crl_validity,
'mobike_after_sa_update': mobike_after_sa_update,
'mobike_before_sa_update': mobike_before_sa_update,
'mobike_no_rrc': mobike_no_rrc}
return ElementCreator(cls, json) | [
"def",
"create",
"(",
"cls",
",",
"name",
",",
"negotiation_expiration",
"=",
"200000",
",",
"negotiation_retry_timer",
"=",
"500",
",",
"negotiation_retry_max_number",
"=",
"32",
",",
"negotiation_retry_timer_max",
"=",
"7000",
",",
"certificate_cache_crl_validity",
... | Create a new gateway setting profile.
:param str name: name of profile
:param int negotiation_expiration: expire after (ms)
:param int negotiation_retry_timer: retry time length (ms)
:param int negotiation_retry_max_num: max number of retries allowed
:param int negotiation_retry_timer_max: maximum length for retry (ms)
:param int certificate_cache_crl_validity: cert cache validity (seconds)
:param boolean mobike_after_sa_update: Whether the After SA flag is set
for Mobike Policy
:param boolean mobike_before_sa_update: Whether the Before SA flag is
set for Mobike Policy
:param boolean mobike_no_rrc: Whether the No RRC flag is set for
Mobike Policy
:raises CreateElementFailed: failed creating profile
:return: instance with meta
:rtype: GatewaySettings | [
"Create",
"a",
"new",
"gateway",
"setting",
"profile",
"."
] | e027b8a5dcfaf884eada32d113d41c1e56b32457 | https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/vpn/elements.py#L65-L102 | train | 38,675 |
gabstopper/smc-python | smc/vpn/elements.py | ExternalGateway.create | def create(cls, name, trust_all_cas=True):
"""
Create new External Gateway
:param str name: name of test_external gateway
:param bool trust_all_cas: whether to trust all internal CA's
(default: True)
:return: instance with meta
:rtype: ExternalGateway
"""
json = {'name': name,
'trust_all_cas': trust_all_cas}
return ElementCreator(cls, json) | python | def create(cls, name, trust_all_cas=True):
"""
Create new External Gateway
:param str name: name of test_external gateway
:param bool trust_all_cas: whether to trust all internal CA's
(default: True)
:return: instance with meta
:rtype: ExternalGateway
"""
json = {'name': name,
'trust_all_cas': trust_all_cas}
return ElementCreator(cls, json) | [
"def",
"create",
"(",
"cls",
",",
"name",
",",
"trust_all_cas",
"=",
"True",
")",
":",
"json",
"=",
"{",
"'name'",
":",
"name",
",",
"'trust_all_cas'",
":",
"trust_all_cas",
"}",
"return",
"ElementCreator",
"(",
"cls",
",",
"json",
")"
] | Create new External Gateway
:param str name: name of test_external gateway
:param bool trust_all_cas: whether to trust all internal CA's
(default: True)
:return: instance with meta
:rtype: ExternalGateway | [
"Create",
"new",
"External",
"Gateway"
] | e027b8a5dcfaf884eada32d113d41c1e56b32457 | https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/vpn/elements.py#L136-L149 | train | 38,676 |
gabstopper/smc-python | smc/vpn/elements.py | ExternalEndpoint.create | def create(self, name, address=None, enabled=True, balancing_mode='active',
ipsec_vpn=True, nat_t=False, force_nat_t=False, dynamic=False,
ike_phase1_id_type=None, ike_phase1_id_value=None):
"""
Create an test_external endpoint. Define common settings for that
specify the address, enabled, nat_t, name, etc. You can also omit
the IP address if the endpoint is dynamic. In that case, you must
also specify the ike_phase1 settings.
:param str name: name of test_external endpoint
:param str address: address of remote host
:param bool enabled: True|False (default: True)
:param str balancing_mode: active
:param bool ipsec_vpn: True|False (default: True)
:param bool nat_t: True|False (default: False)
:param bool force_nat_t: True|False (default: False)
:param bool dynamic: is a dynamic VPN (default: False)
:param int ike_phase1_id_type: If using a dynamic endpoint, you must
set this value. Valid options: 0=DNS name, 1=Email, 2=DN, 3=IP Address
:param str ike_phase1_id_value: value of ike_phase1_id. Required if
ike_phase1_id_type and dynamic set.
:raises CreateElementFailed: create element with reason
:return: newly created element
:rtype: ExternalEndpoint
"""
json = {'name': name,
'address': address,
'balancing_mode': balancing_mode,
'dynamic': dynamic,
'enabled': enabled,
'nat_t': nat_t,
'force_nat_t': force_nat_t,
'ipsec_vpn': ipsec_vpn}
if dynamic:
json.pop('address')
json.update(
ike_phase1_id_type=ike_phase1_id_type,
ike_phase1_id_value=ike_phase1_id_value)
return ElementCreator(
self.__class__,
href=self.href,
json=json) | python | def create(self, name, address=None, enabled=True, balancing_mode='active',
ipsec_vpn=True, nat_t=False, force_nat_t=False, dynamic=False,
ike_phase1_id_type=None, ike_phase1_id_value=None):
"""
Create an test_external endpoint. Define common settings for that
specify the address, enabled, nat_t, name, etc. You can also omit
the IP address if the endpoint is dynamic. In that case, you must
also specify the ike_phase1 settings.
:param str name: name of test_external endpoint
:param str address: address of remote host
:param bool enabled: True|False (default: True)
:param str balancing_mode: active
:param bool ipsec_vpn: True|False (default: True)
:param bool nat_t: True|False (default: False)
:param bool force_nat_t: True|False (default: False)
:param bool dynamic: is a dynamic VPN (default: False)
:param int ike_phase1_id_type: If using a dynamic endpoint, you must
set this value. Valid options: 0=DNS name, 1=Email, 2=DN, 3=IP Address
:param str ike_phase1_id_value: value of ike_phase1_id. Required if
ike_phase1_id_type and dynamic set.
:raises CreateElementFailed: create element with reason
:return: newly created element
:rtype: ExternalEndpoint
"""
json = {'name': name,
'address': address,
'balancing_mode': balancing_mode,
'dynamic': dynamic,
'enabled': enabled,
'nat_t': nat_t,
'force_nat_t': force_nat_t,
'ipsec_vpn': ipsec_vpn}
if dynamic:
json.pop('address')
json.update(
ike_phase1_id_type=ike_phase1_id_type,
ike_phase1_id_value=ike_phase1_id_value)
return ElementCreator(
self.__class__,
href=self.href,
json=json) | [
"def",
"create",
"(",
"self",
",",
"name",
",",
"address",
"=",
"None",
",",
"enabled",
"=",
"True",
",",
"balancing_mode",
"=",
"'active'",
",",
"ipsec_vpn",
"=",
"True",
",",
"nat_t",
"=",
"False",
",",
"force_nat_t",
"=",
"False",
",",
"dynamic",
"=... | Create an test_external endpoint. Define common settings for that
specify the address, enabled, nat_t, name, etc. You can also omit
the IP address if the endpoint is dynamic. In that case, you must
also specify the ike_phase1 settings.
:param str name: name of test_external endpoint
:param str address: address of remote host
:param bool enabled: True|False (default: True)
:param str balancing_mode: active
:param bool ipsec_vpn: True|False (default: True)
:param bool nat_t: True|False (default: False)
:param bool force_nat_t: True|False (default: False)
:param bool dynamic: is a dynamic VPN (default: False)
:param int ike_phase1_id_type: If using a dynamic endpoint, you must
set this value. Valid options: 0=DNS name, 1=Email, 2=DN, 3=IP Address
:param str ike_phase1_id_value: value of ike_phase1_id. Required if
ike_phase1_id_type and dynamic set.
:raises CreateElementFailed: create element with reason
:return: newly created element
:rtype: ExternalEndpoint | [
"Create",
"an",
"test_external",
"endpoint",
".",
"Define",
"common",
"settings",
"for",
"that",
"specify",
"the",
"address",
"enabled",
"nat_t",
"name",
"etc",
".",
"You",
"can",
"also",
"omit",
"the",
"IP",
"address",
"if",
"the",
"endpoint",
"is",
"dynami... | e027b8a5dcfaf884eada32d113d41c1e56b32457 | https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/vpn/elements.py#L273-L316 | train | 38,677 |
gabstopper/smc-python | smc/vpn/elements.py | ExternalEndpoint.enable_disable | def enable_disable(self):
"""
Enable or disable this endpoint. If enabled, it will be disabled
and vice versa.
:return: None
"""
if self.enabled:
self.data['enabled'] = False
else:
self.data['enabled'] = True
self.update() | python | def enable_disable(self):
"""
Enable or disable this endpoint. If enabled, it will be disabled
and vice versa.
:return: None
"""
if self.enabled:
self.data['enabled'] = False
else:
self.data['enabled'] = True
self.update() | [
"def",
"enable_disable",
"(",
"self",
")",
":",
"if",
"self",
".",
"enabled",
":",
"self",
".",
"data",
"[",
"'enabled'",
"]",
"=",
"False",
"else",
":",
"self",
".",
"data",
"[",
"'enabled'",
"]",
"=",
"True",
"self",
".",
"update",
"(",
")"
] | Enable or disable this endpoint. If enabled, it will be disabled
and vice versa.
:return: None | [
"Enable",
"or",
"disable",
"this",
"endpoint",
".",
"If",
"enabled",
"it",
"will",
"be",
"disabled",
"and",
"vice",
"versa",
"."
] | e027b8a5dcfaf884eada32d113d41c1e56b32457 | https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/vpn/elements.py#L383-L394 | train | 38,678 |
gabstopper/smc-python | smc/vpn/elements.py | ExternalEndpoint.enable_disable_force_nat_t | def enable_disable_force_nat_t(self):
"""
Enable or disable NAT-T on this endpoint. If enabled, it will be
disabled and vice versa.
:return: None
"""
if self.force_nat_t:
self.data['force_nat_t'] = False
else:
self.data['force_nat_t'] = True
self.update() | python | def enable_disable_force_nat_t(self):
"""
Enable or disable NAT-T on this endpoint. If enabled, it will be
disabled and vice versa.
:return: None
"""
if self.force_nat_t:
self.data['force_nat_t'] = False
else:
self.data['force_nat_t'] = True
self.update() | [
"def",
"enable_disable_force_nat_t",
"(",
"self",
")",
":",
"if",
"self",
".",
"force_nat_t",
":",
"self",
".",
"data",
"[",
"'force_nat_t'",
"]",
"=",
"False",
"else",
":",
"self",
".",
"data",
"[",
"'force_nat_t'",
"]",
"=",
"True",
"self",
".",
"updat... | Enable or disable NAT-T on this endpoint. If enabled, it will be
disabled and vice versa.
:return: None | [
"Enable",
"or",
"disable",
"NAT",
"-",
"T",
"on",
"this",
"endpoint",
".",
"If",
"enabled",
"it",
"will",
"be",
"disabled",
"and",
"vice",
"versa",
"."
] | e027b8a5dcfaf884eada32d113d41c1e56b32457 | https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/vpn/elements.py#L396-L407 | train | 38,679 |
gabstopper/smc-python | smc/vpn/elements.py | VPNSite.create | def create(self, name, site_element):
"""
Create a VPN site for an internal or external gateway
:param str name: name of site
:param list site_element: list of protected networks/hosts
:type site_element: list[str,Element]
:raises CreateElementFailed: create element failed with reason
:return: href of new element
:rtype: str
"""
site_element = element_resolver(site_element)
json = {
'name': name,
'site_element': site_element}
return ElementCreator(
self.__class__,
href=self.href,
json=json) | python | def create(self, name, site_element):
"""
Create a VPN site for an internal or external gateway
:param str name: name of site
:param list site_element: list of protected networks/hosts
:type site_element: list[str,Element]
:raises CreateElementFailed: create element failed with reason
:return: href of new element
:rtype: str
"""
site_element = element_resolver(site_element)
json = {
'name': name,
'site_element': site_element}
return ElementCreator(
self.__class__,
href=self.href,
json=json) | [
"def",
"create",
"(",
"self",
",",
"name",
",",
"site_element",
")",
":",
"site_element",
"=",
"element_resolver",
"(",
"site_element",
")",
"json",
"=",
"{",
"'name'",
":",
"name",
",",
"'site_element'",
":",
"site_element",
"}",
"return",
"ElementCreator",
... | Create a VPN site for an internal or external gateway
:param str name: name of site
:param list site_element: list of protected networks/hosts
:type site_element: list[str,Element]
:raises CreateElementFailed: create element failed with reason
:return: href of new element
:rtype: str | [
"Create",
"a",
"VPN",
"site",
"for",
"an",
"internal",
"or",
"external",
"gateway"
] | e027b8a5dcfaf884eada32d113d41c1e56b32457 | https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/vpn/elements.py#L436-L455 | train | 38,680 |
gabstopper/smc-python | smc/vpn/elements.py | VPNSite.add_site_element | def add_site_element(self, element):
"""
Add a site element or list of elements to this VPN.
:param list element: list of Elements or href's of vpn site
elements
:type element: list(str,Network)
:raises UpdateElementFailed: fails due to reason
:return: None
"""
element = element_resolver(element)
self.data['site_element'].extend(element)
self.update() | python | def add_site_element(self, element):
"""
Add a site element or list of elements to this VPN.
:param list element: list of Elements or href's of vpn site
elements
:type element: list(str,Network)
:raises UpdateElementFailed: fails due to reason
:return: None
"""
element = element_resolver(element)
self.data['site_element'].extend(element)
self.update() | [
"def",
"add_site_element",
"(",
"self",
",",
"element",
")",
":",
"element",
"=",
"element_resolver",
"(",
"element",
")",
"self",
".",
"data",
"[",
"'site_element'",
"]",
".",
"extend",
"(",
"element",
")",
"self",
".",
"update",
"(",
")"
] | Add a site element or list of elements to this VPN.
:param list element: list of Elements or href's of vpn site
elements
:type element: list(str,Network)
:raises UpdateElementFailed: fails due to reason
:return: None | [
"Add",
"a",
"site",
"element",
"or",
"list",
"of",
"elements",
"to",
"this",
"VPN",
"."
] | e027b8a5dcfaf884eada32d113d41c1e56b32457 | https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/vpn/elements.py#L514-L526 | train | 38,681 |
gabstopper/smc-python | smc/elements/helpers.py | location_helper | def location_helper(name, search_only=False):
"""
Location finder by name. If location doesn't exist, create it
and return the href
:param str,Element name: location to resolve. If the location is
by name, it will be retrieved or created, if href, returned
and if Location, href returned. If None, settings an elements
location to None will set it to the Default location.
:param bool search_only: only search for the location, if not found
do not create
:return str href: href of location if search_only is not False
:rtype: str or None
"""
try:
return name.href
except AttributeError:
if name and name.startswith('http'):
return name
except ElementNotFound:
return Location.create(name=name.name).href if not \
search_only else None
# Get all locations; tmp to support earlier 6.x versions.
if name is not None:
locations = [location for location in Search.objects.entry_point(
'location') if location.name == name]
if not locations:
return Location.create(name=name).href if not search_only \
else None
return locations[0].href | python | def location_helper(name, search_only=False):
"""
Location finder by name. If location doesn't exist, create it
and return the href
:param str,Element name: location to resolve. If the location is
by name, it will be retrieved or created, if href, returned
and if Location, href returned. If None, settings an elements
location to None will set it to the Default location.
:param bool search_only: only search for the location, if not found
do not create
:return str href: href of location if search_only is not False
:rtype: str or None
"""
try:
return name.href
except AttributeError:
if name and name.startswith('http'):
return name
except ElementNotFound:
return Location.create(name=name.name).href if not \
search_only else None
# Get all locations; tmp to support earlier 6.x versions.
if name is not None:
locations = [location for location in Search.objects.entry_point(
'location') if location.name == name]
if not locations:
return Location.create(name=name).href if not search_only \
else None
return locations[0].href | [
"def",
"location_helper",
"(",
"name",
",",
"search_only",
"=",
"False",
")",
":",
"try",
":",
"return",
"name",
".",
"href",
"except",
"AttributeError",
":",
"if",
"name",
"and",
"name",
".",
"startswith",
"(",
"'http'",
")",
":",
"return",
"name",
"exc... | Location finder by name. If location doesn't exist, create it
and return the href
:param str,Element name: location to resolve. If the location is
by name, it will be retrieved or created, if href, returned
and if Location, href returned. If None, settings an elements
location to None will set it to the Default location.
:param bool search_only: only search for the location, if not found
do not create
:return str href: href of location if search_only is not False
:rtype: str or None | [
"Location",
"finder",
"by",
"name",
".",
"If",
"location",
"doesn",
"t",
"exist",
"create",
"it",
"and",
"return",
"the",
"href"
] | e027b8a5dcfaf884eada32d113d41c1e56b32457 | https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/elements/helpers.py#L12-L42 | train | 38,682 |
gabstopper/smc-python | smc/elements/helpers.py | zone_helper | def zone_helper(zone):
"""
Zone finder by name. If zone doesn't exist, create it and
return the href
:param str zone: name of zone (if href, will be returned as is)
:return str href: href of zone
"""
if zone is None:
return None
elif isinstance(zone, Zone):
return zone.href
elif zone.startswith('http'):
return zone
return Zone.get_or_create(name=zone).href | python | def zone_helper(zone):
"""
Zone finder by name. If zone doesn't exist, create it and
return the href
:param str zone: name of zone (if href, will be returned as is)
:return str href: href of zone
"""
if zone is None:
return None
elif isinstance(zone, Zone):
return zone.href
elif zone.startswith('http'):
return zone
return Zone.get_or_create(name=zone).href | [
"def",
"zone_helper",
"(",
"zone",
")",
":",
"if",
"zone",
"is",
"None",
":",
"return",
"None",
"elif",
"isinstance",
"(",
"zone",
",",
"Zone",
")",
":",
"return",
"zone",
".",
"href",
"elif",
"zone",
".",
"startswith",
"(",
"'http'",
")",
":",
"retu... | Zone finder by name. If zone doesn't exist, create it and
return the href
:param str zone: name of zone (if href, will be returned as is)
:return str href: href of zone | [
"Zone",
"finder",
"by",
"name",
".",
"If",
"zone",
"doesn",
"t",
"exist",
"create",
"it",
"and",
"return",
"the",
"href"
] | e027b8a5dcfaf884eada32d113d41c1e56b32457 | https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/elements/helpers.py#L45-L59 | train | 38,683 |
gabstopper/smc-python | smc/elements/helpers.py | logical_intf_helper | def logical_intf_helper(interface):
"""
Logical Interface finder by name. Create if it doesn't exist.
This is useful when adding logical interfaces to for inline
or capture interfaces.
:param interface: logical interface name
:return str href: href of logical interface
"""
if interface is None:
return LogicalInterface.get_or_create(name='default_eth').href
elif isinstance(interface, LogicalInterface):
return interface.href
elif interface.startswith('http'):
return interface
return LogicalInterface.get_or_create(name=interface).href | python | def logical_intf_helper(interface):
"""
Logical Interface finder by name. Create if it doesn't exist.
This is useful when adding logical interfaces to for inline
or capture interfaces.
:param interface: logical interface name
:return str href: href of logical interface
"""
if interface is None:
return LogicalInterface.get_or_create(name='default_eth').href
elif isinstance(interface, LogicalInterface):
return interface.href
elif interface.startswith('http'):
return interface
return LogicalInterface.get_or_create(name=interface).href | [
"def",
"logical_intf_helper",
"(",
"interface",
")",
":",
"if",
"interface",
"is",
"None",
":",
"return",
"LogicalInterface",
".",
"get_or_create",
"(",
"name",
"=",
"'default_eth'",
")",
".",
"href",
"elif",
"isinstance",
"(",
"interface",
",",
"LogicalInterfac... | Logical Interface finder by name. Create if it doesn't exist.
This is useful when adding logical interfaces to for inline
or capture interfaces.
:param interface: logical interface name
:return str href: href of logical interface | [
"Logical",
"Interface",
"finder",
"by",
"name",
".",
"Create",
"if",
"it",
"doesn",
"t",
"exist",
".",
"This",
"is",
"useful",
"when",
"adding",
"logical",
"interfaces",
"to",
"for",
"inline",
"or",
"capture",
"interfaces",
"."
] | e027b8a5dcfaf884eada32d113d41c1e56b32457 | https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/elements/helpers.py#L62-L77 | train | 38,684 |
gabstopper/smc-python | smc/elements/user.py | UserMixin.change_password | def change_password(self, password):
"""
Change user password. Change is committed immediately.
:param str password: new password
:return: None
"""
self.make_request(
ModificationFailed,
method='update',
resource='change_password',
params={'password': password}) | python | def change_password(self, password):
"""
Change user password. Change is committed immediately.
:param str password: new password
:return: None
"""
self.make_request(
ModificationFailed,
method='update',
resource='change_password',
params={'password': password}) | [
"def",
"change_password",
"(",
"self",
",",
"password",
")",
":",
"self",
".",
"make_request",
"(",
"ModificationFailed",
",",
"method",
"=",
"'update'",
",",
"resource",
"=",
"'change_password'",
",",
"params",
"=",
"{",
"'password'",
":",
"password",
"}",
... | Change user password. Change is committed immediately.
:param str password: new password
:return: None | [
"Change",
"user",
"password",
".",
"Change",
"is",
"committed",
"immediately",
"."
] | e027b8a5dcfaf884eada32d113d41c1e56b32457 | https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/elements/user.py#L71-L82 | train | 38,685 |
gabstopper/smc-python | smc/elements/user.py | AdminUser.change_engine_password | def change_engine_password(self, password):
""" Change Engine password for engines on allowed
list.
:param str password: password for engine level
:raises ModificationFailed: failed setting password on engine
:return: None
"""
self.make_request(
ModificationFailed,
method='update',
resource='change_engine_password',
params={'password': password}) | python | def change_engine_password(self, password):
""" Change Engine password for engines on allowed
list.
:param str password: password for engine level
:raises ModificationFailed: failed setting password on engine
:return: None
"""
self.make_request(
ModificationFailed,
method='update',
resource='change_engine_password',
params={'password': password}) | [
"def",
"change_engine_password",
"(",
"self",
",",
"password",
")",
":",
"self",
".",
"make_request",
"(",
"ModificationFailed",
",",
"method",
"=",
"'update'",
",",
"resource",
"=",
"'change_engine_password'",
",",
"params",
"=",
"{",
"'password'",
":",
"passwo... | Change Engine password for engines on allowed
list.
:param str password: password for engine level
:raises ModificationFailed: failed setting password on engine
:return: None | [
"Change",
"Engine",
"password",
"for",
"engines",
"on",
"allowed",
"list",
"."
] | e027b8a5dcfaf884eada32d113d41c1e56b32457 | https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/elements/user.py#L212-L224 | train | 38,686 |
gabstopper/smc-python | smc/core/engine.py | Engine.location | def location(self):
"""
The location for this engine. May be None if no specific
location has been assigned.
:param value: location to assign engine. Can be name, str href,
or Location element. If name, it will be automatically created
if a Location with the same name doesn't exist.
:raises UpdateElementFailed: failure to update element
:return: Location element or None
"""
location = Element.from_href(self.location_ref)
if location and location.name == 'Default':
return None
return location | python | def location(self):
"""
The location for this engine. May be None if no specific
location has been assigned.
:param value: location to assign engine. Can be name, str href,
or Location element. If name, it will be automatically created
if a Location with the same name doesn't exist.
:raises UpdateElementFailed: failure to update element
:return: Location element or None
"""
location = Element.from_href(self.location_ref)
if location and location.name == 'Default':
return None
return location | [
"def",
"location",
"(",
"self",
")",
":",
"location",
"=",
"Element",
".",
"from_href",
"(",
"self",
".",
"location_ref",
")",
"if",
"location",
"and",
"location",
".",
"name",
"==",
"'Default'",
":",
"return",
"None",
"return",
"location"
] | The location for this engine. May be None if no specific
location has been assigned.
:param value: location to assign engine. Can be name, str href,
or Location element. If name, it will be automatically created
if a Location with the same name doesn't exist.
:raises UpdateElementFailed: failure to update element
:return: Location element or None | [
"The",
"location",
"for",
"this",
"engine",
".",
"May",
"be",
"None",
"if",
"no",
"specific",
"location",
"has",
"been",
"assigned",
"."
] | e027b8a5dcfaf884eada32d113d41c1e56b32457 | https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/core/engine.py#L208-L222 | train | 38,687 |
gabstopper/smc-python | smc/core/engine.py | Engine.pending_changes | def pending_changes(self):
"""
Pending changes provides insight into changes on an engine that are
pending approval or disapproval. Feature requires SMC >= v6.2.
:raises UnsupportedEngineFeature: SMC version >= 6.2 is required to
support pending changes
:rtype: PendingChanges
"""
if 'pending_changes' in self.data.links:
return PendingChanges(self)
raise UnsupportedEngineFeature(
'Pending changes is an unsupported feature on this engine: {}'
.format(self.type)) | python | def pending_changes(self):
"""
Pending changes provides insight into changes on an engine that are
pending approval or disapproval. Feature requires SMC >= v6.2.
:raises UnsupportedEngineFeature: SMC version >= 6.2 is required to
support pending changes
:rtype: PendingChanges
"""
if 'pending_changes' in self.data.links:
return PendingChanges(self)
raise UnsupportedEngineFeature(
'Pending changes is an unsupported feature on this engine: {}'
.format(self.type)) | [
"def",
"pending_changes",
"(",
"self",
")",
":",
"if",
"'pending_changes'",
"in",
"self",
".",
"data",
".",
"links",
":",
"return",
"PendingChanges",
"(",
"self",
")",
"raise",
"UnsupportedEngineFeature",
"(",
"'Pending changes is an unsupported feature on this engine: ... | Pending changes provides insight into changes on an engine that are
pending approval or disapproval. Feature requires SMC >= v6.2.
:raises UnsupportedEngineFeature: SMC version >= 6.2 is required to
support pending changes
:rtype: PendingChanges | [
"Pending",
"changes",
"provides",
"insight",
"into",
"changes",
"on",
"an",
"engine",
"that",
"are",
"pending",
"approval",
"or",
"disapproval",
".",
"Feature",
"requires",
"SMC",
">",
"=",
"v6",
".",
"2",
"."
] | e027b8a5dcfaf884eada32d113d41c1e56b32457 | https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/core/engine.py#L496-L509 | train | 38,688 |
gabstopper/smc-python | smc/core/engine.py | Engine.virtual_resource | def virtual_resource(self):
"""
Available on a Master Engine only.
To get all virtual resources call::
engine.virtual_resource.all()
:raises UnsupportedEngineFeature: master engine only
:rtype: CreateCollection(VirtualResource)
"""
resource = create_collection(
self.get_relation(
'virtual_resources',
UnsupportedEngineFeature),
VirtualResource)
resource._load_from_engine(self, 'virtualResources')
return resource | python | def virtual_resource(self):
"""
Available on a Master Engine only.
To get all virtual resources call::
engine.virtual_resource.all()
:raises UnsupportedEngineFeature: master engine only
:rtype: CreateCollection(VirtualResource)
"""
resource = create_collection(
self.get_relation(
'virtual_resources',
UnsupportedEngineFeature),
VirtualResource)
resource._load_from_engine(self, 'virtualResources')
return resource | [
"def",
"virtual_resource",
"(",
"self",
")",
":",
"resource",
"=",
"create_collection",
"(",
"self",
".",
"get_relation",
"(",
"'virtual_resources'",
",",
"UnsupportedEngineFeature",
")",
",",
"VirtualResource",
")",
"resource",
".",
"_load_from_engine",
"(",
"self"... | Available on a Master Engine only.
To get all virtual resources call::
engine.virtual_resource.all()
:raises UnsupportedEngineFeature: master engine only
:rtype: CreateCollection(VirtualResource) | [
"Available",
"on",
"a",
"Master",
"Engine",
"only",
"."
] | e027b8a5dcfaf884eada32d113d41c1e56b32457 | https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/core/engine.py#L784-L801 | train | 38,689 |
gabstopper/smc-python | smc/core/engine.py | Engine.generate_snapshot | def generate_snapshot(self, filename='snapshot.zip'):
"""
Generate and retrieve a policy snapshot from the engine
This is blocking as file is downloaded
:param str filename: name of file to save file to, including directory
path
:raises EngineCommandFailed: snapshot failed, possibly invalid filename
specified
:return: None
"""
try:
self.make_request(
EngineCommandFailed,
resource='generate_snapshot',
filename=filename)
except IOError as e:
raise EngineCommandFailed(
'Generate snapshot failed: {}'.format(e)) | python | def generate_snapshot(self, filename='snapshot.zip'):
"""
Generate and retrieve a policy snapshot from the engine
This is blocking as file is downloaded
:param str filename: name of file to save file to, including directory
path
:raises EngineCommandFailed: snapshot failed, possibly invalid filename
specified
:return: None
"""
try:
self.make_request(
EngineCommandFailed,
resource='generate_snapshot',
filename=filename)
except IOError as e:
raise EngineCommandFailed(
'Generate snapshot failed: {}'.format(e)) | [
"def",
"generate_snapshot",
"(",
"self",
",",
"filename",
"=",
"'snapshot.zip'",
")",
":",
"try",
":",
"self",
".",
"make_request",
"(",
"EngineCommandFailed",
",",
"resource",
"=",
"'generate_snapshot'",
",",
"filename",
"=",
"filename",
")",
"except",
"IOError... | Generate and retrieve a policy snapshot from the engine
This is blocking as file is downloaded
:param str filename: name of file to save file to, including directory
path
:raises EngineCommandFailed: snapshot failed, possibly invalid filename
specified
:return: None | [
"Generate",
"and",
"retrieve",
"a",
"policy",
"snapshot",
"from",
"the",
"engine",
"This",
"is",
"blocking",
"as",
"file",
"is",
"downloaded"
] | e027b8a5dcfaf884eada32d113d41c1e56b32457 | https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/core/engine.py#L1050-L1069 | train | 38,690 |
gabstopper/smc-python | smc/core/engine.py | VPN.generate_certificate | def generate_certificate(self, common_name, public_key_algorithm='rsa',
signature_algorithm='rsa_sha_512', key_length=2048,
signing_ca=None):
"""
Generate an internal gateway certificate used for VPN on this engine.
Certificate request should be an instance of VPNCertificate.
:param: str common_name: common name for certificate
:param str public_key_algorithm: public key type to use. Valid values
rsa, dsa, ecdsa.
:param str signature_algorithm: signature algorithm. Valid values
dsa_sha_1, dsa_sha_224, dsa_sha_256, rsa_md5, rsa_sha_1, rsa_sha_256,
rsa_sha_384, rsa_sha_512, ecdsa_sha_1, ecdsa_sha_256, ecdsa_sha_384,
ecdsa_sha_512. (Default: rsa_sha_512)
:param int key_length: length of key. Key length depends on the key
type. For example, RSA keys can be 1024, 2048, 3072, 4096. See SMC
documentation for more details.
:param str,VPNCertificateCA signing_ca: by default will use the
internal RSA CA
:raises CertificateError: error generating certificate
:return: GatewayCertificate
"""
return GatewayCertificate._create(self, common_name, public_key_algorithm,
signature_algorithm, key_length, signing_ca) | python | def generate_certificate(self, common_name, public_key_algorithm='rsa',
signature_algorithm='rsa_sha_512', key_length=2048,
signing_ca=None):
"""
Generate an internal gateway certificate used for VPN on this engine.
Certificate request should be an instance of VPNCertificate.
:param: str common_name: common name for certificate
:param str public_key_algorithm: public key type to use. Valid values
rsa, dsa, ecdsa.
:param str signature_algorithm: signature algorithm. Valid values
dsa_sha_1, dsa_sha_224, dsa_sha_256, rsa_md5, rsa_sha_1, rsa_sha_256,
rsa_sha_384, rsa_sha_512, ecdsa_sha_1, ecdsa_sha_256, ecdsa_sha_384,
ecdsa_sha_512. (Default: rsa_sha_512)
:param int key_length: length of key. Key length depends on the key
type. For example, RSA keys can be 1024, 2048, 3072, 4096. See SMC
documentation for more details.
:param str,VPNCertificateCA signing_ca: by default will use the
internal RSA CA
:raises CertificateError: error generating certificate
:return: GatewayCertificate
"""
return GatewayCertificate._create(self, common_name, public_key_algorithm,
signature_algorithm, key_length, signing_ca) | [
"def",
"generate_certificate",
"(",
"self",
",",
"common_name",
",",
"public_key_algorithm",
"=",
"'rsa'",
",",
"signature_algorithm",
"=",
"'rsa_sha_512'",
",",
"key_length",
"=",
"2048",
",",
"signing_ca",
"=",
"None",
")",
":",
"return",
"GatewayCertificate",
"... | Generate an internal gateway certificate used for VPN on this engine.
Certificate request should be an instance of VPNCertificate.
:param: str common_name: common name for certificate
:param str public_key_algorithm: public key type to use. Valid values
rsa, dsa, ecdsa.
:param str signature_algorithm: signature algorithm. Valid values
dsa_sha_1, dsa_sha_224, dsa_sha_256, rsa_md5, rsa_sha_1, rsa_sha_256,
rsa_sha_384, rsa_sha_512, ecdsa_sha_1, ecdsa_sha_256, ecdsa_sha_384,
ecdsa_sha_512. (Default: rsa_sha_512)
:param int key_length: length of key. Key length depends on the key
type. For example, RSA keys can be 1024, 2048, 3072, 4096. See SMC
documentation for more details.
:param str,VPNCertificateCA signing_ca: by default will use the
internal RSA CA
:raises CertificateError: error generating certificate
:return: GatewayCertificate | [
"Generate",
"an",
"internal",
"gateway",
"certificate",
"used",
"for",
"VPN",
"on",
"this",
"engine",
".",
"Certificate",
"request",
"should",
"be",
"an",
"instance",
"of",
"VPNCertificate",
"."
] | e027b8a5dcfaf884eada32d113d41c1e56b32457 | https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/core/engine.py#L1334-L1357 | train | 38,691 |
gabstopper/smc-python | smc/core/general.py | DNSRelay.enable | def enable(self, interface_id, dns_relay_profile=None):
"""
Enable the DNS Relay service on this engine.
:param int interface_id: interface id to enable relay
:param str,DNSRelayProfile dns_relay_profile: DNSRelayProfile element
or str href
:raises EngineCommandFailed: interface not found
:raises ElementNotFound: profile not found
:return: None
"""
if not dns_relay_profile: # Use default
href = DNSRelayProfile('Cache Only').href
else:
href = element_resolver(dns_relay_profile)
intf = self.engine.interface.get(interface_id)
self.engine.data.update(dns_relay_profile_ref=href)
self.engine.data.update(dns_relay_interface=intf.ndi_interfaces) | python | def enable(self, interface_id, dns_relay_profile=None):
"""
Enable the DNS Relay service on this engine.
:param int interface_id: interface id to enable relay
:param str,DNSRelayProfile dns_relay_profile: DNSRelayProfile element
or str href
:raises EngineCommandFailed: interface not found
:raises ElementNotFound: profile not found
:return: None
"""
if not dns_relay_profile: # Use default
href = DNSRelayProfile('Cache Only').href
else:
href = element_resolver(dns_relay_profile)
intf = self.engine.interface.get(interface_id)
self.engine.data.update(dns_relay_profile_ref=href)
self.engine.data.update(dns_relay_interface=intf.ndi_interfaces) | [
"def",
"enable",
"(",
"self",
",",
"interface_id",
",",
"dns_relay_profile",
"=",
"None",
")",
":",
"if",
"not",
"dns_relay_profile",
":",
"# Use default",
"href",
"=",
"DNSRelayProfile",
"(",
"'Cache Only'",
")",
".",
"href",
"else",
":",
"href",
"=",
"elem... | Enable the DNS Relay service on this engine.
:param int interface_id: interface id to enable relay
:param str,DNSRelayProfile dns_relay_profile: DNSRelayProfile element
or str href
:raises EngineCommandFailed: interface not found
:raises ElementNotFound: profile not found
:return: None | [
"Enable",
"the",
"DNS",
"Relay",
"service",
"on",
"this",
"engine",
"."
] | e027b8a5dcfaf884eada32d113d41c1e56b32457 | https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/core/general.py#L162-L181 | train | 38,692 |
gabstopper/smc-python | smc/policy/ips.py | IPSPolicy.create | def create(cls, name, template='High-Security IPS Template'):
"""
Create an IPS Policy
:param str name: Name of policy
:param str template: name of template
:raises CreatePolicyFailed: policy failed to create
:return: IPSPolicy
"""
try:
if cls.typeof == 'ips_template_policy' and template is None:
fw_template = None
else:
fw_template = IPSTemplatePolicy(template).href
except ElementNotFound:
raise LoadPolicyFailed(
'Cannot find specified firewall template: {}'.format(template))
json = {
'name': name,
'template': fw_template}
try:
return ElementCreator(cls, json)
except CreateElementFailed as err:
raise CreatePolicyFailed(err) | python | def create(cls, name, template='High-Security IPS Template'):
"""
Create an IPS Policy
:param str name: Name of policy
:param str template: name of template
:raises CreatePolicyFailed: policy failed to create
:return: IPSPolicy
"""
try:
if cls.typeof == 'ips_template_policy' and template is None:
fw_template = None
else:
fw_template = IPSTemplatePolicy(template).href
except ElementNotFound:
raise LoadPolicyFailed(
'Cannot find specified firewall template: {}'.format(template))
json = {
'name': name,
'template': fw_template}
try:
return ElementCreator(cls, json)
except CreateElementFailed as err:
raise CreatePolicyFailed(err) | [
"def",
"create",
"(",
"cls",
",",
"name",
",",
"template",
"=",
"'High-Security IPS Template'",
")",
":",
"try",
":",
"if",
"cls",
".",
"typeof",
"==",
"'ips_template_policy'",
"and",
"template",
"is",
"None",
":",
"fw_template",
"=",
"None",
"else",
":",
... | Create an IPS Policy
:param str name: Name of policy
:param str template: name of template
:raises CreatePolicyFailed: policy failed to create
:return: IPSPolicy | [
"Create",
"an",
"IPS",
"Policy"
] | e027b8a5dcfaf884eada32d113d41c1e56b32457 | https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/policy/ips.py#L98-L121 | train | 38,693 |
gabstopper/smc-python | smc/examples/ip_lists.py | upload_as_zip | def upload_as_zip(name, filename):
"""
Upload an IPList as a zip file. Useful when IPList is very large.
This is the default upload format for IPLists.
:param str name: name of IPList
:param str filename: name of zip file to upload, full path
:return: None
"""
location = list(IPList.objects.filter(name))
if location:
iplist = location[0]
return iplist.upload(filename=filename) | python | def upload_as_zip(name, filename):
"""
Upload an IPList as a zip file. Useful when IPList is very large.
This is the default upload format for IPLists.
:param str name: name of IPList
:param str filename: name of zip file to upload, full path
:return: None
"""
location = list(IPList.objects.filter(name))
if location:
iplist = location[0]
return iplist.upload(filename=filename) | [
"def",
"upload_as_zip",
"(",
"name",
",",
"filename",
")",
":",
"location",
"=",
"list",
"(",
"IPList",
".",
"objects",
".",
"filter",
"(",
"name",
")",
")",
"if",
"location",
":",
"iplist",
"=",
"location",
"[",
"0",
"]",
"return",
"iplist",
".",
"u... | Upload an IPList as a zip file. Useful when IPList is very large.
This is the default upload format for IPLists.
:param str name: name of IPList
:param str filename: name of zip file to upload, full path
:return: None | [
"Upload",
"an",
"IPList",
"as",
"a",
"zip",
"file",
".",
"Useful",
"when",
"IPList",
"is",
"very",
"large",
".",
"This",
"is",
"the",
"default",
"upload",
"format",
"for",
"IPLists",
"."
] | e027b8a5dcfaf884eada32d113d41c1e56b32457 | https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/examples/ip_lists.py#L42-L54 | train | 38,694 |
gabstopper/smc-python | smc/examples/ip_lists.py | upload_as_text | def upload_as_text(name, filename):
"""
Upload the IPList as text from a file.
:param str name: name of IPList
:param str filename: name of text file to upload
:return: None
"""
location = list(IPList.objects.filter(name))
if location:
iplist = location[0]
return iplist.upload(filename=filename, as_type='txt') | python | def upload_as_text(name, filename):
"""
Upload the IPList as text from a file.
:param str name: name of IPList
:param str filename: name of text file to upload
:return: None
"""
location = list(IPList.objects.filter(name))
if location:
iplist = location[0]
return iplist.upload(filename=filename, as_type='txt') | [
"def",
"upload_as_text",
"(",
"name",
",",
"filename",
")",
":",
"location",
"=",
"list",
"(",
"IPList",
".",
"objects",
".",
"filter",
"(",
"name",
")",
")",
"if",
"location",
":",
"iplist",
"=",
"location",
"[",
"0",
"]",
"return",
"iplist",
".",
"... | Upload the IPList as text from a file.
:param str name: name of IPList
:param str filename: name of text file to upload
:return: None | [
"Upload",
"the",
"IPList",
"as",
"text",
"from",
"a",
"file",
"."
] | e027b8a5dcfaf884eada32d113d41c1e56b32457 | https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/examples/ip_lists.py#L57-L68 | train | 38,695 |
gabstopper/smc-python | smc/examples/ip_lists.py | upload_as_json | def upload_as_json(name, mylist):
"""
Upload the IPList as json payload.
:param str name: name of IPList
:param list: list of IPList entries
:return: None
"""
location = list(IPList.objects.filter(name))
if location:
iplist = location[0]
return iplist.upload(json=mylist, as_type='json') | python | def upload_as_json(name, mylist):
"""
Upload the IPList as json payload.
:param str name: name of IPList
:param list: list of IPList entries
:return: None
"""
location = list(IPList.objects.filter(name))
if location:
iplist = location[0]
return iplist.upload(json=mylist, as_type='json') | [
"def",
"upload_as_json",
"(",
"name",
",",
"mylist",
")",
":",
"location",
"=",
"list",
"(",
"IPList",
".",
"objects",
".",
"filter",
"(",
"name",
")",
")",
"if",
"location",
":",
"iplist",
"=",
"location",
"[",
"0",
"]",
"return",
"iplist",
".",
"up... | Upload the IPList as json payload.
:param str name: name of IPList
:param list: list of IPList entries
:return: None | [
"Upload",
"the",
"IPList",
"as",
"json",
"payload",
"."
] | e027b8a5dcfaf884eada32d113d41c1e56b32457 | https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/examples/ip_lists.py#L71-L82 | train | 38,696 |
gabstopper/smc-python | smc/examples/ip_lists.py | download_as_zip | def download_as_zip(name, filename):
"""
Download IPList with zip compression. Recommended for IPLists
of larger sizes. This is the default format for downloading
IPLists.
:param str name: name of IPList
:param str filename: name of filename for IPList
"""
location = list(IPList.objects.filter(name))
if location:
iplist = location[0]
return iplist.download(filename=filename) | python | def download_as_zip(name, filename):
"""
Download IPList with zip compression. Recommended for IPLists
of larger sizes. This is the default format for downloading
IPLists.
:param str name: name of IPList
:param str filename: name of filename for IPList
"""
location = list(IPList.objects.filter(name))
if location:
iplist = location[0]
return iplist.download(filename=filename) | [
"def",
"download_as_zip",
"(",
"name",
",",
"filename",
")",
":",
"location",
"=",
"list",
"(",
"IPList",
".",
"objects",
".",
"filter",
"(",
"name",
")",
")",
"if",
"location",
":",
"iplist",
"=",
"location",
"[",
"0",
"]",
"return",
"iplist",
".",
... | Download IPList with zip compression. Recommended for IPLists
of larger sizes. This is the default format for downloading
IPLists.
:param str name: name of IPList
:param str filename: name of filename for IPList | [
"Download",
"IPList",
"with",
"zip",
"compression",
".",
"Recommended",
"for",
"IPLists",
"of",
"larger",
"sizes",
".",
"This",
"is",
"the",
"default",
"format",
"for",
"downloading",
"IPLists",
"."
] | e027b8a5dcfaf884eada32d113d41c1e56b32457 | https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/examples/ip_lists.py#L85-L97 | train | 38,697 |
gabstopper/smc-python | smc/examples/ip_lists.py | download_as_text | def download_as_text(name, filename):
"""
Download IPList as text to specified filename.
:param str name: name of IPList
:param str filename: name of file for IPList download
"""
location = list(IPList.objects.filter(name))
if location:
iplist = location[0]
return iplist.download(filename=filename, as_type='txt') | python | def download_as_text(name, filename):
"""
Download IPList as text to specified filename.
:param str name: name of IPList
:param str filename: name of file for IPList download
"""
location = list(IPList.objects.filter(name))
if location:
iplist = location[0]
return iplist.download(filename=filename, as_type='txt') | [
"def",
"download_as_text",
"(",
"name",
",",
"filename",
")",
":",
"location",
"=",
"list",
"(",
"IPList",
".",
"objects",
".",
"filter",
"(",
"name",
")",
")",
"if",
"location",
":",
"iplist",
"=",
"location",
"[",
"0",
"]",
"return",
"iplist",
".",
... | Download IPList as text to specified filename.
:param str name: name of IPList
:param str filename: name of file for IPList download | [
"Download",
"IPList",
"as",
"text",
"to",
"specified",
"filename",
"."
] | e027b8a5dcfaf884eada32d113d41c1e56b32457 | https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/examples/ip_lists.py#L100-L110 | train | 38,698 |
gabstopper/smc-python | smc/examples/ip_lists.py | download_as_json | def download_as_json(name):
"""
Download IPList as json. This would allow for easily
manipulation of the IPList, but generally recommended only for
smaller lists
:param str name: name of IPList
:return: None
"""
location = list(IPList.objects.filter(name))
if location:
iplist = location[0]
return iplist.download(as_type='json') | python | def download_as_json(name):
"""
Download IPList as json. This would allow for easily
manipulation of the IPList, but generally recommended only for
smaller lists
:param str name: name of IPList
:return: None
"""
location = list(IPList.objects.filter(name))
if location:
iplist = location[0]
return iplist.download(as_type='json') | [
"def",
"download_as_json",
"(",
"name",
")",
":",
"location",
"=",
"list",
"(",
"IPList",
".",
"objects",
".",
"filter",
"(",
"name",
")",
")",
"if",
"location",
":",
"iplist",
"=",
"location",
"[",
"0",
"]",
"return",
"iplist",
".",
"download",
"(",
... | Download IPList as json. This would allow for easily
manipulation of the IPList, but generally recommended only for
smaller lists
:param str name: name of IPList
:return: None | [
"Download",
"IPList",
"as",
"json",
".",
"This",
"would",
"allow",
"for",
"easily",
"manipulation",
"of",
"the",
"IPList",
"but",
"generally",
"recommended",
"only",
"for",
"smaller",
"lists"
] | e027b8a5dcfaf884eada32d113d41c1e56b32457 | https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/examples/ip_lists.py#L113-L125 | train | 38,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.