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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
splunk/splunk-sdk-python | splunklib/client.py | Job.cancel | def cancel(self):
"""Stops the current search and deletes the results cache.
:return: The :class:`Job`.
"""
try:
self.post("control", action="cancel")
except HTTPError as he:
if he.status == 404:
# The job has already been cancelled, so
# cancelling it twice is a nop.
pass
else:
raise
return self | python | def cancel(self):
"""Stops the current search and deletes the results cache.
:return: The :class:`Job`.
"""
try:
self.post("control", action="cancel")
except HTTPError as he:
if he.status == 404:
# The job has already been cancelled, so
# cancelling it twice is a nop.
pass
else:
raise
return self | [
"def",
"cancel",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"post",
"(",
"\"control\"",
",",
"action",
"=",
"\"cancel\"",
")",
"except",
"HTTPError",
"as",
"he",
":",
"if",
"he",
".",
"status",
"==",
"404",
":",
"# The job has already been cancelled, ... | Stops the current search and deletes the results cache.
:return: The :class:`Job`. | [
"Stops",
"the",
"current",
"search",
"and",
"deletes",
"the",
"results",
"cache",
"."
] | a245a4eeb93b3621730418008e31715912bcdcd8 | https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L2634-L2648 | train | 217,000 |
splunk/splunk-sdk-python | splunklib/client.py | Job.events | def events(self, **kwargs):
"""Returns a streaming handle to this job's events.
:param kwargs: Additional parameters (optional). For a list of valid
parameters, see `GET search/jobs/{search_id}/events
<http://docs.splunk.com/Documentation/Splunk/latest/RESTAPI/RESTsearch#GET_search.2Fjobs.2F.7Bsearch_id.7D.2Fevents>`_
in the REST API documentation.
:type kwargs: ``dict``
:return: The ``InputStream`` IO handle to this job's events.
"""
kwargs['segmentation'] = kwargs.get('segmentation', 'none')
return self.get("events", **kwargs).body | python | def events(self, **kwargs):
"""Returns a streaming handle to this job's events.
:param kwargs: Additional parameters (optional). For a list of valid
parameters, see `GET search/jobs/{search_id}/events
<http://docs.splunk.com/Documentation/Splunk/latest/RESTAPI/RESTsearch#GET_search.2Fjobs.2F.7Bsearch_id.7D.2Fevents>`_
in the REST API documentation.
:type kwargs: ``dict``
:return: The ``InputStream`` IO handle to this job's events.
"""
kwargs['segmentation'] = kwargs.get('segmentation', 'none')
return self.get("events", **kwargs).body | [
"def",
"events",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'segmentation'",
"]",
"=",
"kwargs",
".",
"get",
"(",
"'segmentation'",
",",
"'none'",
")",
"return",
"self",
".",
"get",
"(",
"\"events\"",
",",
"*",
"*",
"kwargs",
")"... | Returns a streaming handle to this job's events.
:param kwargs: Additional parameters (optional). For a list of valid
parameters, see `GET search/jobs/{search_id}/events
<http://docs.splunk.com/Documentation/Splunk/latest/RESTAPI/RESTsearch#GET_search.2Fjobs.2F.7Bsearch_id.7D.2Fevents>`_
in the REST API documentation.
:type kwargs: ``dict``
:return: The ``InputStream`` IO handle to this job's events. | [
"Returns",
"a",
"streaming",
"handle",
"to",
"this",
"job",
"s",
"events",
"."
] | a245a4eeb93b3621730418008e31715912bcdcd8 | https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L2668-L2680 | train | 217,001 |
splunk/splunk-sdk-python | splunklib/client.py | Job.is_done | def is_done(self):
"""Indicates whether this job finished running.
:return: ``True`` if the job is done, ``False`` if not.
:rtype: ``boolean``
"""
if not self.is_ready():
return False
done = (self._state.content['isDone'] == '1')
return done | python | def is_done(self):
"""Indicates whether this job finished running.
:return: ``True`` if the job is done, ``False`` if not.
:rtype: ``boolean``
"""
if not self.is_ready():
return False
done = (self._state.content['isDone'] == '1')
return done | [
"def",
"is_done",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_ready",
"(",
")",
":",
"return",
"False",
"done",
"=",
"(",
"self",
".",
"_state",
".",
"content",
"[",
"'isDone'",
"]",
"==",
"'1'",
")",
"return",
"done"
] | Indicates whether this job finished running.
:return: ``True`` if the job is done, ``False`` if not.
:rtype: ``boolean`` | [
"Indicates",
"whether",
"this",
"job",
"finished",
"running",
"."
] | a245a4eeb93b3621730418008e31715912bcdcd8 | https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L2690-L2699 | train | 217,002 |
splunk/splunk-sdk-python | splunklib/client.py | Job.is_ready | def is_ready(self):
"""Indicates whether this job is ready for querying.
:return: ``True`` if the job is ready, ``False`` if not.
:rtype: ``boolean``
"""
response = self.get()
if response.status == 204:
return False
self._state = self.read(response)
ready = self._state.content['dispatchState'] not in ['QUEUED', 'PARSING']
return ready | python | def is_ready(self):
"""Indicates whether this job is ready for querying.
:return: ``True`` if the job is ready, ``False`` if not.
:rtype: ``boolean``
"""
response = self.get()
if response.status == 204:
return False
self._state = self.read(response)
ready = self._state.content['dispatchState'] not in ['QUEUED', 'PARSING']
return ready | [
"def",
"is_ready",
"(",
"self",
")",
":",
"response",
"=",
"self",
".",
"get",
"(",
")",
"if",
"response",
".",
"status",
"==",
"204",
":",
"return",
"False",
"self",
".",
"_state",
"=",
"self",
".",
"read",
"(",
"response",
")",
"ready",
"=",
"sel... | Indicates whether this job is ready for querying.
:return: ``True`` if the job is ready, ``False`` if not.
:rtype: ``boolean`` | [
"Indicates",
"whether",
"this",
"job",
"is",
"ready",
"for",
"querying",
"."
] | a245a4eeb93b3621730418008e31715912bcdcd8 | https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L2701-L2713 | train | 217,003 |
splunk/splunk-sdk-python | splunklib/client.py | Job.preview | def preview(self, **query_params):
"""Returns a streaming handle to this job's preview search results.
Unlike :class:`splunklib.results.ResultsReader`, which requires a job to
be finished to
return any results, the ``preview`` method returns any results that have
been generated so far, whether the job is running or not. The
returned search results are the raw data from the server. Pass
the handle returned to :class:`splunklib.results.ResultsReader` to get a
nice, Pythonic iterator over objects, as in::
import splunklib.client as client
import splunklib.results as results
service = client.connect(...)
job = service.jobs.create("search * | head 5")
rr = results.ResultsReader(job.preview())
for result in rr:
if isinstance(result, results.Message):
# Diagnostic messages may be returned in the results
print '%s: %s' % (result.type, result.message)
elif isinstance(result, dict):
# Normal events are returned as dicts
print result
if rr.is_preview:
print "Preview of a running search job."
else:
print "Job is finished. Results are final."
This method makes one roundtrip to the server, plus at most
two more if
the ``autologin`` field of :func:`connect` is set to ``True``.
:param query_params: Additional parameters (optional). For a list of valid
parameters, see `GET search/jobs/{search_id}/results_preview
<http://docs.splunk.com/Documentation/Splunk/latest/RESTAPI/RESTsearch#GET_search.2Fjobs.2F.7Bsearch_id.7D.2Fresults_preview>`_
in the REST API documentation.
:type query_params: ``dict``
:return: The ``InputStream`` IO handle to this job's preview results.
"""
query_params['segmentation'] = query_params.get('segmentation', 'none')
return self.get("results_preview", **query_params).body | python | def preview(self, **query_params):
"""Returns a streaming handle to this job's preview search results.
Unlike :class:`splunklib.results.ResultsReader`, which requires a job to
be finished to
return any results, the ``preview`` method returns any results that have
been generated so far, whether the job is running or not. The
returned search results are the raw data from the server. Pass
the handle returned to :class:`splunklib.results.ResultsReader` to get a
nice, Pythonic iterator over objects, as in::
import splunklib.client as client
import splunklib.results as results
service = client.connect(...)
job = service.jobs.create("search * | head 5")
rr = results.ResultsReader(job.preview())
for result in rr:
if isinstance(result, results.Message):
# Diagnostic messages may be returned in the results
print '%s: %s' % (result.type, result.message)
elif isinstance(result, dict):
# Normal events are returned as dicts
print result
if rr.is_preview:
print "Preview of a running search job."
else:
print "Job is finished. Results are final."
This method makes one roundtrip to the server, plus at most
two more if
the ``autologin`` field of :func:`connect` is set to ``True``.
:param query_params: Additional parameters (optional). For a list of valid
parameters, see `GET search/jobs/{search_id}/results_preview
<http://docs.splunk.com/Documentation/Splunk/latest/RESTAPI/RESTsearch#GET_search.2Fjobs.2F.7Bsearch_id.7D.2Fresults_preview>`_
in the REST API documentation.
:type query_params: ``dict``
:return: The ``InputStream`` IO handle to this job's preview results.
"""
query_params['segmentation'] = query_params.get('segmentation', 'none')
return self.get("results_preview", **query_params).body | [
"def",
"preview",
"(",
"self",
",",
"*",
"*",
"query_params",
")",
":",
"query_params",
"[",
"'segmentation'",
"]",
"=",
"query_params",
".",
"get",
"(",
"'segmentation'",
",",
"'none'",
")",
"return",
"self",
".",
"get",
"(",
"\"results_preview\"",
",",
"... | Returns a streaming handle to this job's preview search results.
Unlike :class:`splunklib.results.ResultsReader`, which requires a job to
be finished to
return any results, the ``preview`` method returns any results that have
been generated so far, whether the job is running or not. The
returned search results are the raw data from the server. Pass
the handle returned to :class:`splunklib.results.ResultsReader` to get a
nice, Pythonic iterator over objects, as in::
import splunklib.client as client
import splunklib.results as results
service = client.connect(...)
job = service.jobs.create("search * | head 5")
rr = results.ResultsReader(job.preview())
for result in rr:
if isinstance(result, results.Message):
# Diagnostic messages may be returned in the results
print '%s: %s' % (result.type, result.message)
elif isinstance(result, dict):
# Normal events are returned as dicts
print result
if rr.is_preview:
print "Preview of a running search job."
else:
print "Job is finished. Results are final."
This method makes one roundtrip to the server, plus at most
two more if
the ``autologin`` field of :func:`connect` is set to ``True``.
:param query_params: Additional parameters (optional). For a list of valid
parameters, see `GET search/jobs/{search_id}/results_preview
<http://docs.splunk.com/Documentation/Splunk/latest/RESTAPI/RESTsearch#GET_search.2Fjobs.2F.7Bsearch_id.7D.2Fresults_preview>`_
in the REST API documentation.
:type query_params: ``dict``
:return: The ``InputStream`` IO handle to this job's preview results. | [
"Returns",
"a",
"streaming",
"handle",
"to",
"this",
"job",
"s",
"preview",
"search",
"results",
"."
] | a245a4eeb93b3621730418008e31715912bcdcd8 | https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L2771-L2812 | train | 217,004 |
splunk/splunk-sdk-python | splunklib/client.py | Jobs.create | def create(self, query, **kwargs):
""" Creates a search using a search query and any additional parameters
you provide.
:param query: The search query.
:type query: ``string``
:param kwargs: Additiona parameters (optional). For a list of available
parameters, see `Search job parameters
<http://dev.splunk.com/view/SP-CAAAEE5#searchjobparams>`_
on Splunk Developer Portal.
:type kwargs: ``dict``
:return: The :class:`Job`.
"""
if kwargs.get("exec_mode", None) == "oneshot":
raise TypeError("Cannot specify exec_mode=oneshot; use the oneshot method instead.")
response = self.post(search=query, **kwargs)
sid = _load_sid(response)
return Job(self.service, sid) | python | def create(self, query, **kwargs):
""" Creates a search using a search query and any additional parameters
you provide.
:param query: The search query.
:type query: ``string``
:param kwargs: Additiona parameters (optional). For a list of available
parameters, see `Search job parameters
<http://dev.splunk.com/view/SP-CAAAEE5#searchjobparams>`_
on Splunk Developer Portal.
:type kwargs: ``dict``
:return: The :class:`Job`.
"""
if kwargs.get("exec_mode", None) == "oneshot":
raise TypeError("Cannot specify exec_mode=oneshot; use the oneshot method instead.")
response = self.post(search=query, **kwargs)
sid = _load_sid(response)
return Job(self.service, sid) | [
"def",
"create",
"(",
"self",
",",
"query",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"kwargs",
".",
"get",
"(",
"\"exec_mode\"",
",",
"None",
")",
"==",
"\"oneshot\"",
":",
"raise",
"TypeError",
"(",
"\"Cannot specify exec_mode=oneshot; use the oneshot method in... | Creates a search using a search query and any additional parameters
you provide.
:param query: The search query.
:type query: ``string``
:param kwargs: Additiona parameters (optional). For a list of available
parameters, see `Search job parameters
<http://dev.splunk.com/view/SP-CAAAEE5#searchjobparams>`_
on Splunk Developer Portal.
:type kwargs: ``dict``
:return: The :class:`Job`. | [
"Creates",
"a",
"search",
"using",
"a",
"search",
"query",
"and",
"any",
"additional",
"parameters",
"you",
"provide",
"."
] | a245a4eeb93b3621730418008e31715912bcdcd8 | https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L2920-L2938 | train | 217,005 |
splunk/splunk-sdk-python | splunklib/client.py | Jobs.oneshot | def oneshot(self, query, **params):
"""Run a oneshot search and returns a streaming handle to the results.
The ``InputStream`` object streams XML fragments from the server. To
parse this stream into usable Python objects,
pass the handle to :class:`splunklib.results.ResultsReader`::
import splunklib.client as client
import splunklib.results as results
service = client.connect(...)
rr = results.ResultsReader(service.jobs.oneshot("search * | head 5"))
for result in rr:
if isinstance(result, results.Message):
# Diagnostic messages may be returned in the results
print '%s: %s' % (result.type, result.message)
elif isinstance(result, dict):
# Normal events are returned as dicts
print result
assert rr.is_preview == False
The ``oneshot`` method makes a single roundtrip to the server (as opposed
to two for :meth:`create` followed by :meth:`results`), plus at most two more
if the ``autologin`` field of :func:`connect` is set to ``True``.
:raises ValueError: Raised for invalid queries.
:param query: The search query.
:type query: ``string``
:param params: Additional arguments (optional):
- "output_mode": Specifies the output format of the results (XML,
JSON, or CSV).
- "earliest_time": Specifies the earliest time in the time range to
search. The time string can be a UTC time (with fractional seconds),
a relative time specifier (to now), or a formatted time string.
- "latest_time": Specifies the latest time in the time range to
search. The time string can be a UTC time (with fractional seconds),
a relative time specifier (to now), or a formatted time string.
- "rf": Specifies one or more fields to add to the search.
:type params: ``dict``
:return: The ``InputStream`` IO handle to raw XML returned from the server.
"""
if "exec_mode" in params:
raise TypeError("Cannot specify an exec_mode to oneshot.")
params['segmentation'] = params.get('segmentation', 'none')
return self.post(search=query,
exec_mode="oneshot",
**params).body | python | def oneshot(self, query, **params):
"""Run a oneshot search and returns a streaming handle to the results.
The ``InputStream`` object streams XML fragments from the server. To
parse this stream into usable Python objects,
pass the handle to :class:`splunklib.results.ResultsReader`::
import splunklib.client as client
import splunklib.results as results
service = client.connect(...)
rr = results.ResultsReader(service.jobs.oneshot("search * | head 5"))
for result in rr:
if isinstance(result, results.Message):
# Diagnostic messages may be returned in the results
print '%s: %s' % (result.type, result.message)
elif isinstance(result, dict):
# Normal events are returned as dicts
print result
assert rr.is_preview == False
The ``oneshot`` method makes a single roundtrip to the server (as opposed
to two for :meth:`create` followed by :meth:`results`), plus at most two more
if the ``autologin`` field of :func:`connect` is set to ``True``.
:raises ValueError: Raised for invalid queries.
:param query: The search query.
:type query: ``string``
:param params: Additional arguments (optional):
- "output_mode": Specifies the output format of the results (XML,
JSON, or CSV).
- "earliest_time": Specifies the earliest time in the time range to
search. The time string can be a UTC time (with fractional seconds),
a relative time specifier (to now), or a formatted time string.
- "latest_time": Specifies the latest time in the time range to
search. The time string can be a UTC time (with fractional seconds),
a relative time specifier (to now), or a formatted time string.
- "rf": Specifies one or more fields to add to the search.
:type params: ``dict``
:return: The ``InputStream`` IO handle to raw XML returned from the server.
"""
if "exec_mode" in params:
raise TypeError("Cannot specify an exec_mode to oneshot.")
params['segmentation'] = params.get('segmentation', 'none')
return self.post(search=query,
exec_mode="oneshot",
**params).body | [
"def",
"oneshot",
"(",
"self",
",",
"query",
",",
"*",
"*",
"params",
")",
":",
"if",
"\"exec_mode\"",
"in",
"params",
":",
"raise",
"TypeError",
"(",
"\"Cannot specify an exec_mode to oneshot.\"",
")",
"params",
"[",
"'segmentation'",
"]",
"=",
"params",
".",... | Run a oneshot search and returns a streaming handle to the results.
The ``InputStream`` object streams XML fragments from the server. To
parse this stream into usable Python objects,
pass the handle to :class:`splunklib.results.ResultsReader`::
import splunklib.client as client
import splunklib.results as results
service = client.connect(...)
rr = results.ResultsReader(service.jobs.oneshot("search * | head 5"))
for result in rr:
if isinstance(result, results.Message):
# Diagnostic messages may be returned in the results
print '%s: %s' % (result.type, result.message)
elif isinstance(result, dict):
# Normal events are returned as dicts
print result
assert rr.is_preview == False
The ``oneshot`` method makes a single roundtrip to the server (as opposed
to two for :meth:`create` followed by :meth:`results`), plus at most two more
if the ``autologin`` field of :func:`connect` is set to ``True``.
:raises ValueError: Raised for invalid queries.
:param query: The search query.
:type query: ``string``
:param params: Additional arguments (optional):
- "output_mode": Specifies the output format of the results (XML,
JSON, or CSV).
- "earliest_time": Specifies the earliest time in the time range to
search. The time string can be a UTC time (with fractional seconds),
a relative time specifier (to now), or a formatted time string.
- "latest_time": Specifies the latest time in the time range to
search. The time string can be a UTC time (with fractional seconds),
a relative time specifier (to now), or a formatted time string.
- "rf": Specifies one or more fields to add to the search.
:type params: ``dict``
:return: The ``InputStream`` IO handle to raw XML returned from the server. | [
"Run",
"a",
"oneshot",
"search",
"and",
"returns",
"a",
"streaming",
"handle",
"to",
"the",
"results",
"."
] | a245a4eeb93b3621730418008e31715912bcdcd8 | https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L2995-L3047 | train | 217,006 |
splunk/splunk-sdk-python | splunklib/client.py | SavedSearch.dispatch | def dispatch(self, **kwargs):
"""Runs the saved search and returns the resulting search job.
:param `kwargs`: Additional dispatch arguments (optional). For details,
see the `POST saved/searches/{name}/dispatch
<http://docs.splunk.com/Documentation/Splunk/latest/RESTAPI/RESTsearch#POST_saved.2Fsearches.2F.7Bname.7D.2Fdispatch>`_
endpoint in the REST API documentation.
:type kwargs: ``dict``
:return: The :class:`Job`.
"""
response = self.post("dispatch", **kwargs)
sid = _load_sid(response)
return Job(self.service, sid) | python | def dispatch(self, **kwargs):
"""Runs the saved search and returns the resulting search job.
:param `kwargs`: Additional dispatch arguments (optional). For details,
see the `POST saved/searches/{name}/dispatch
<http://docs.splunk.com/Documentation/Splunk/latest/RESTAPI/RESTsearch#POST_saved.2Fsearches.2F.7Bname.7D.2Fdispatch>`_
endpoint in the REST API documentation.
:type kwargs: ``dict``
:return: The :class:`Job`.
"""
response = self.post("dispatch", **kwargs)
sid = _load_sid(response)
return Job(self.service, sid) | [
"def",
"dispatch",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"response",
"=",
"self",
".",
"post",
"(",
"\"dispatch\"",
",",
"*",
"*",
"kwargs",
")",
"sid",
"=",
"_load_sid",
"(",
"response",
")",
"return",
"Job",
"(",
"self",
".",
"service",
... | Runs the saved search and returns the resulting search job.
:param `kwargs`: Additional dispatch arguments (optional). For details,
see the `POST saved/searches/{name}/dispatch
<http://docs.splunk.com/Documentation/Splunk/latest/RESTAPI/RESTsearch#POST_saved.2Fsearches.2F.7Bname.7D.2Fdispatch>`_
endpoint in the REST API documentation.
:type kwargs: ``dict``
:return: The :class:`Job`. | [
"Runs",
"the",
"saved",
"search",
"and",
"returns",
"the",
"resulting",
"search",
"job",
"."
] | a245a4eeb93b3621730418008e31715912bcdcd8 | https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L3142-L3154 | train | 217,007 |
splunk/splunk-sdk-python | splunklib/client.py | SavedSearch.history | def history(self):
"""Returns a list of search jobs corresponding to this saved search.
:return: A list of :class:`Job` objects.
"""
response = self.get("history")
entries = _load_atom_entries(response)
if entries is None: return []
jobs = []
for entry in entries:
job = Job(self.service, entry.title)
jobs.append(job)
return jobs | python | def history(self):
"""Returns a list of search jobs corresponding to this saved search.
:return: A list of :class:`Job` objects.
"""
response = self.get("history")
entries = _load_atom_entries(response)
if entries is None: return []
jobs = []
for entry in entries:
job = Job(self.service, entry.title)
jobs.append(job)
return jobs | [
"def",
"history",
"(",
"self",
")",
":",
"response",
"=",
"self",
".",
"get",
"(",
"\"history\"",
")",
"entries",
"=",
"_load_atom_entries",
"(",
"response",
")",
"if",
"entries",
"is",
"None",
":",
"return",
"[",
"]",
"jobs",
"=",
"[",
"]",
"for",
"... | Returns a list of search jobs corresponding to this saved search.
:return: A list of :class:`Job` objects. | [
"Returns",
"a",
"list",
"of",
"search",
"jobs",
"corresponding",
"to",
"this",
"saved",
"search",
"."
] | a245a4eeb93b3621730418008e31715912bcdcd8 | https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L3177-L3189 | train | 217,008 |
splunk/splunk-sdk-python | splunklib/client.py | SavedSearch.update | def update(self, search=None, **kwargs):
"""Updates the server with any changes you've made to the current saved
search along with any additional arguments you specify.
:param `search`: The search query (optional).
:type search: ``string``
:param `kwargs`: Additional arguments (optional). For a list of available
parameters, see `Saved search parameters
<http://dev.splunk.com/view/SP-CAAAEE5#savedsearchparams>`_
on Splunk Developer Portal.
:type kwargs: ``dict``
:return: The :class:`SavedSearch`.
"""
# Updates to a saved search *require* that the search string be
# passed, so we pass the current search string if a value wasn't
# provided by the caller.
if search is None: search = self.content.search
Entity.update(self, search=search, **kwargs)
return self | python | def update(self, search=None, **kwargs):
"""Updates the server with any changes you've made to the current saved
search along with any additional arguments you specify.
:param `search`: The search query (optional).
:type search: ``string``
:param `kwargs`: Additional arguments (optional). For a list of available
parameters, see `Saved search parameters
<http://dev.splunk.com/view/SP-CAAAEE5#savedsearchparams>`_
on Splunk Developer Portal.
:type kwargs: ``dict``
:return: The :class:`SavedSearch`.
"""
# Updates to a saved search *require* that the search string be
# passed, so we pass the current search string if a value wasn't
# provided by the caller.
if search is None: search = self.content.search
Entity.update(self, search=search, **kwargs)
return self | [
"def",
"update",
"(",
"self",
",",
"search",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# Updates to a saved search *require* that the search string be",
"# passed, so we pass the current search string if a value wasn't",
"# provided by the caller.",
"if",
"search",
"is",... | Updates the server with any changes you've made to the current saved
search along with any additional arguments you specify.
:param `search`: The search query (optional).
:type search: ``string``
:param `kwargs`: Additional arguments (optional). For a list of available
parameters, see `Saved search parameters
<http://dev.splunk.com/view/SP-CAAAEE5#savedsearchparams>`_
on Splunk Developer Portal.
:type kwargs: ``dict``
:return: The :class:`SavedSearch`. | [
"Updates",
"the",
"server",
"with",
"any",
"changes",
"you",
"ve",
"made",
"to",
"the",
"current",
"saved",
"search",
"along",
"with",
"any",
"additional",
"arguments",
"you",
"specify",
"."
] | a245a4eeb93b3621730418008e31715912bcdcd8 | https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L3191-L3210 | train | 217,009 |
splunk/splunk-sdk-python | splunklib/client.py | SavedSearch.scheduled_times | def scheduled_times(self, earliest_time='now', latest_time='+1h'):
"""Returns the times when this search is scheduled to run.
By default this method returns the times in the next hour. For different
time ranges, set *earliest_time* and *latest_time*. For example,
for all times in the last day use "earliest_time=-1d" and
"latest_time=now".
:param earliest_time: The earliest time.
:type earliest_time: ``string``
:param latest_time: The latest time.
:type latest_time: ``string``
:return: The list of search times.
"""
response = self.get("scheduled_times",
earliest_time=earliest_time,
latest_time=latest_time)
data = self._load_atom_entry(response)
rec = _parse_atom_entry(data)
times = [datetime.fromtimestamp(int(t))
for t in rec.content.scheduled_times]
return times | python | def scheduled_times(self, earliest_time='now', latest_time='+1h'):
"""Returns the times when this search is scheduled to run.
By default this method returns the times in the next hour. For different
time ranges, set *earliest_time* and *latest_time*. For example,
for all times in the last day use "earliest_time=-1d" and
"latest_time=now".
:param earliest_time: The earliest time.
:type earliest_time: ``string``
:param latest_time: The latest time.
:type latest_time: ``string``
:return: The list of search times.
"""
response = self.get("scheduled_times",
earliest_time=earliest_time,
latest_time=latest_time)
data = self._load_atom_entry(response)
rec = _parse_atom_entry(data)
times = [datetime.fromtimestamp(int(t))
for t in rec.content.scheduled_times]
return times | [
"def",
"scheduled_times",
"(",
"self",
",",
"earliest_time",
"=",
"'now'",
",",
"latest_time",
"=",
"'+1h'",
")",
":",
"response",
"=",
"self",
".",
"get",
"(",
"\"scheduled_times\"",
",",
"earliest_time",
"=",
"earliest_time",
",",
"latest_time",
"=",
"latest... | Returns the times when this search is scheduled to run.
By default this method returns the times in the next hour. For different
time ranges, set *earliest_time* and *latest_time*. For example,
for all times in the last day use "earliest_time=-1d" and
"latest_time=now".
:param earliest_time: The earliest time.
:type earliest_time: ``string``
:param latest_time: The latest time.
:type latest_time: ``string``
:return: The list of search times. | [
"Returns",
"the",
"times",
"when",
"this",
"search",
"is",
"scheduled",
"to",
"run",
"."
] | a245a4eeb93b3621730418008e31715912bcdcd8 | https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L3212-L3234 | train | 217,010 |
splunk/splunk-sdk-python | splunklib/client.py | SavedSearches.create | def create(self, name, search, **kwargs):
""" Creates a saved search.
:param name: The name for the saved search.
:type name: ``string``
:param search: The search query.
:type search: ``string``
:param kwargs: Additional arguments (optional). For a list of available
parameters, see `Saved search parameters
<http://dev.splunk.com/view/SP-CAAAEE5#savedsearchparams>`_
on Splunk Developer Portal.
:type kwargs: ``dict``
:return: The :class:`SavedSearches` collection.
"""
return Collection.create(self, name, search=search, **kwargs) | python | def create(self, name, search, **kwargs):
""" Creates a saved search.
:param name: The name for the saved search.
:type name: ``string``
:param search: The search query.
:type search: ``string``
:param kwargs: Additional arguments (optional). For a list of available
parameters, see `Saved search parameters
<http://dev.splunk.com/view/SP-CAAAEE5#savedsearchparams>`_
on Splunk Developer Portal.
:type kwargs: ``dict``
:return: The :class:`SavedSearches` collection.
"""
return Collection.create(self, name, search=search, **kwargs) | [
"def",
"create",
"(",
"self",
",",
"name",
",",
"search",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"Collection",
".",
"create",
"(",
"self",
",",
"name",
",",
"search",
"=",
"search",
",",
"*",
"*",
"kwargs",
")"
] | Creates a saved search.
:param name: The name for the saved search.
:type name: ``string``
:param search: The search query.
:type search: ``string``
:param kwargs: Additional arguments (optional). For a list of available
parameters, see `Saved search parameters
<http://dev.splunk.com/view/SP-CAAAEE5#savedsearchparams>`_
on Splunk Developer Portal.
:type kwargs: ``dict``
:return: The :class:`SavedSearches` collection. | [
"Creates",
"a",
"saved",
"search",
"."
] | a245a4eeb93b3621730418008e31715912bcdcd8 | https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L3278-L3292 | train | 217,011 |
splunk/splunk-sdk-python | splunklib/client.py | User.role_entities | def role_entities(self):
"""Returns a list of roles assigned to this user.
:return: The list of roles.
:rtype: ``list``
"""
return [self.service.roles[name] for name in self.content.roles] | python | def role_entities(self):
"""Returns a list of roles assigned to this user.
:return: The list of roles.
:rtype: ``list``
"""
return [self.service.roles[name] for name in self.content.roles] | [
"def",
"role_entities",
"(",
"self",
")",
":",
"return",
"[",
"self",
".",
"service",
".",
"roles",
"[",
"name",
"]",
"for",
"name",
"in",
"self",
".",
"content",
".",
"roles",
"]"
] | Returns a list of roles assigned to this user.
:return: The list of roles.
:rtype: ``list`` | [
"Returns",
"a",
"list",
"of",
"roles",
"assigned",
"to",
"this",
"user",
"."
] | a245a4eeb93b3621730418008e31715912bcdcd8 | https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L3320-L3326 | train | 217,012 |
splunk/splunk-sdk-python | splunklib/client.py | Role.grant | def grant(self, *capabilities_to_grant):
"""Grants additional capabilities to this role.
:param capabilities_to_grant: Zero or more capabilities to grant this
role. For a list of capabilities, see
`Capabilities <http://dev.splunk.com/view/SP-CAAAEJ6#capabilities>`_
on Splunk Developer Portal.
:type capabilities_to_grant: ``string`` or ``list``
:return: The :class:`Role`.
**Example**::
service = client.connect(...)
role = service.roles['somerole']
role.grant('change_own_password', 'search')
"""
possible_capabilities = self.service.capabilities
for capability in capabilities_to_grant:
if capability not in possible_capabilities:
raise NoSuchCapability(capability)
new_capabilities = self['capabilities'] + list(capabilities_to_grant)
self.post(capabilities=new_capabilities)
return self | python | def grant(self, *capabilities_to_grant):
"""Grants additional capabilities to this role.
:param capabilities_to_grant: Zero or more capabilities to grant this
role. For a list of capabilities, see
`Capabilities <http://dev.splunk.com/view/SP-CAAAEJ6#capabilities>`_
on Splunk Developer Portal.
:type capabilities_to_grant: ``string`` or ``list``
:return: The :class:`Role`.
**Example**::
service = client.connect(...)
role = service.roles['somerole']
role.grant('change_own_password', 'search')
"""
possible_capabilities = self.service.capabilities
for capability in capabilities_to_grant:
if capability not in possible_capabilities:
raise NoSuchCapability(capability)
new_capabilities = self['capabilities'] + list(capabilities_to_grant)
self.post(capabilities=new_capabilities)
return self | [
"def",
"grant",
"(",
"self",
",",
"*",
"capabilities_to_grant",
")",
":",
"possible_capabilities",
"=",
"self",
".",
"service",
".",
"capabilities",
"for",
"capability",
"in",
"capabilities_to_grant",
":",
"if",
"capability",
"not",
"in",
"possible_capabilities",
... | Grants additional capabilities to this role.
:param capabilities_to_grant: Zero or more capabilities to grant this
role. For a list of capabilities, see
`Capabilities <http://dev.splunk.com/view/SP-CAAAEJ6#capabilities>`_
on Splunk Developer Portal.
:type capabilities_to_grant: ``string`` or ``list``
:return: The :class:`Role`.
**Example**::
service = client.connect(...)
role = service.roles['somerole']
role.grant('change_own_password', 'search') | [
"Grants",
"additional",
"capabilities",
"to",
"this",
"role",
"."
] | a245a4eeb93b3621730418008e31715912bcdcd8 | https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L3404-L3426 | train | 217,013 |
splunk/splunk-sdk-python | splunklib/client.py | Role.revoke | def revoke(self, *capabilities_to_revoke):
"""Revokes zero or more capabilities from this role.
:param capabilities_to_revoke: Zero or more capabilities to grant this
role. For a list of capabilities, see
`Capabilities <http://dev.splunk.com/view/SP-CAAAEJ6#capabilities>`_
on Splunk Developer Portal.
:type capabilities_to_revoke: ``string`` or ``list``
:return: The :class:`Role`.
**Example**::
service = client.connect(...)
role = service.roles['somerole']
role.revoke('change_own_password', 'search')
"""
possible_capabilities = self.service.capabilities
for capability in capabilities_to_revoke:
if capability not in possible_capabilities:
raise NoSuchCapability(capability)
old_capabilities = self['capabilities']
new_capabilities = []
for c in old_capabilities:
if c not in capabilities_to_revoke:
new_capabilities.append(c)
if new_capabilities == []:
new_capabilities = '' # Empty lists don't get passed in the body, so we have to force an empty argument.
self.post(capabilities=new_capabilities)
return self | python | def revoke(self, *capabilities_to_revoke):
"""Revokes zero or more capabilities from this role.
:param capabilities_to_revoke: Zero or more capabilities to grant this
role. For a list of capabilities, see
`Capabilities <http://dev.splunk.com/view/SP-CAAAEJ6#capabilities>`_
on Splunk Developer Portal.
:type capabilities_to_revoke: ``string`` or ``list``
:return: The :class:`Role`.
**Example**::
service = client.connect(...)
role = service.roles['somerole']
role.revoke('change_own_password', 'search')
"""
possible_capabilities = self.service.capabilities
for capability in capabilities_to_revoke:
if capability not in possible_capabilities:
raise NoSuchCapability(capability)
old_capabilities = self['capabilities']
new_capabilities = []
for c in old_capabilities:
if c not in capabilities_to_revoke:
new_capabilities.append(c)
if new_capabilities == []:
new_capabilities = '' # Empty lists don't get passed in the body, so we have to force an empty argument.
self.post(capabilities=new_capabilities)
return self | [
"def",
"revoke",
"(",
"self",
",",
"*",
"capabilities_to_revoke",
")",
":",
"possible_capabilities",
"=",
"self",
".",
"service",
".",
"capabilities",
"for",
"capability",
"in",
"capabilities_to_revoke",
":",
"if",
"capability",
"not",
"in",
"possible_capabilities",... | Revokes zero or more capabilities from this role.
:param capabilities_to_revoke: Zero or more capabilities to grant this
role. For a list of capabilities, see
`Capabilities <http://dev.splunk.com/view/SP-CAAAEJ6#capabilities>`_
on Splunk Developer Portal.
:type capabilities_to_revoke: ``string`` or ``list``
:return: The :class:`Role`.
**Example**::
service = client.connect(...)
role = service.roles['somerole']
role.revoke('change_own_password', 'search') | [
"Revokes",
"zero",
"or",
"more",
"capabilities",
"from",
"this",
"role",
"."
] | a245a4eeb93b3621730418008e31715912bcdcd8 | https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L3428-L3457 | train | 217,014 |
splunk/splunk-sdk-python | splunklib/client.py | Roles.create | def create(self, name, **params):
"""Creates a new role.
This function makes two roundtrips to the server, plus at most
two more if
the ``autologin`` field of :func:`connect` is set to ``True``.
:param name: Name for the role.
:type name: ``string``
:param params: Additional arguments (optional). For a list of available
parameters, see `Roles parameters
<http://dev.splunk.com/view/SP-CAAAEJ6#rolesparams>`_
on Splunk Developer Portal.
:type params: ``dict``
:return: The new role.
:rtype: :class:`Role`
**Example**::
import splunklib.client as client
c = client.connect(...)
roles = c.roles
paltry = roles.create("paltry", imported_roles="user", defaultApp="search")
"""
if not isinstance(name, six.string_types):
raise ValueError("Invalid role name: %s" % str(name))
name = name.lower()
self.post(name=name, **params)
# splunkd doesn't return the user in the POST response body,
# so we have to make a second round trip to fetch it.
response = self.get(name)
entry = _load_atom(response, XNAME_ENTRY).entry
state = _parse_atom_entry(entry)
entity = self.item(
self.service,
urllib.parse.unquote(state.links.alternate),
state=state)
return entity | python | def create(self, name, **params):
"""Creates a new role.
This function makes two roundtrips to the server, plus at most
two more if
the ``autologin`` field of :func:`connect` is set to ``True``.
:param name: Name for the role.
:type name: ``string``
:param params: Additional arguments (optional). For a list of available
parameters, see `Roles parameters
<http://dev.splunk.com/view/SP-CAAAEJ6#rolesparams>`_
on Splunk Developer Portal.
:type params: ``dict``
:return: The new role.
:rtype: :class:`Role`
**Example**::
import splunklib.client as client
c = client.connect(...)
roles = c.roles
paltry = roles.create("paltry", imported_roles="user", defaultApp="search")
"""
if not isinstance(name, six.string_types):
raise ValueError("Invalid role name: %s" % str(name))
name = name.lower()
self.post(name=name, **params)
# splunkd doesn't return the user in the POST response body,
# so we have to make a second round trip to fetch it.
response = self.get(name)
entry = _load_atom(response, XNAME_ENTRY).entry
state = _parse_atom_entry(entry)
entity = self.item(
self.service,
urllib.parse.unquote(state.links.alternate),
state=state)
return entity | [
"def",
"create",
"(",
"self",
",",
"name",
",",
"*",
"*",
"params",
")",
":",
"if",
"not",
"isinstance",
"(",
"name",
",",
"six",
".",
"string_types",
")",
":",
"raise",
"ValueError",
"(",
"\"Invalid role name: %s\"",
"%",
"str",
"(",
"name",
")",
")",... | Creates a new role.
This function makes two roundtrips to the server, plus at most
two more if
the ``autologin`` field of :func:`connect` is set to ``True``.
:param name: Name for the role.
:type name: ``string``
:param params: Additional arguments (optional). For a list of available
parameters, see `Roles parameters
<http://dev.splunk.com/view/SP-CAAAEJ6#rolesparams>`_
on Splunk Developer Portal.
:type params: ``dict``
:return: The new role.
:rtype: :class:`Role`
**Example**::
import splunklib.client as client
c = client.connect(...)
roles = c.roles
paltry = roles.create("paltry", imported_roles="user", defaultApp="search") | [
"Creates",
"a",
"new",
"role",
"."
] | a245a4eeb93b3621730418008e31715912bcdcd8 | https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L3472-L3510 | train | 217,015 |
splunk/splunk-sdk-python | splunklib/client.py | KVStoreCollections.create | def create(self, name, indexes = {}, fields = {}, **kwargs):
"""Creates a KV Store Collection.
:param name: name of collection to create
:type name: ``string``
:param indexes: dictionary of index definitions
:type indexes: ``dict``
:param fields: dictionary of field definitions
:type fields: ``dict``
:param kwargs: a dictionary of additional parameters specifying indexes and field definitions
:type kwargs: ``dict``
:return: Result of POST request
"""
for k, v in six.iteritems(indexes):
if isinstance(v, dict):
v = json.dumps(v)
kwargs['index.' + k] = v
for k, v in six.iteritems(fields):
kwargs['field.' + k] = v
return self.post(name=name, **kwargs) | python | def create(self, name, indexes = {}, fields = {}, **kwargs):
"""Creates a KV Store Collection.
:param name: name of collection to create
:type name: ``string``
:param indexes: dictionary of index definitions
:type indexes: ``dict``
:param fields: dictionary of field definitions
:type fields: ``dict``
:param kwargs: a dictionary of additional parameters specifying indexes and field definitions
:type kwargs: ``dict``
:return: Result of POST request
"""
for k, v in six.iteritems(indexes):
if isinstance(v, dict):
v = json.dumps(v)
kwargs['index.' + k] = v
for k, v in six.iteritems(fields):
kwargs['field.' + k] = v
return self.post(name=name, **kwargs) | [
"def",
"create",
"(",
"self",
",",
"name",
",",
"indexes",
"=",
"{",
"}",
",",
"fields",
"=",
"{",
"}",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"indexes",
")",
":",
"if",
"isinstance",
"(",
... | Creates a KV Store Collection.
:param name: name of collection to create
:type name: ``string``
:param indexes: dictionary of index definitions
:type indexes: ``dict``
:param fields: dictionary of field definitions
:type fields: ``dict``
:param kwargs: a dictionary of additional parameters specifying indexes and field definitions
:type kwargs: ``dict``
:return: Result of POST request | [
"Creates",
"a",
"KV",
"Store",
"Collection",
"."
] | a245a4eeb93b3621730418008e31715912bcdcd8 | https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L3545-L3565 | train | 217,016 |
splunk/splunk-sdk-python | splunklib/client.py | KVStoreCollection.update_index | def update_index(self, name, value):
"""Changes the definition of a KV Store index.
:param name: name of index to change
:type name: ``string``
:param value: new index definition
:type value: ``dict`` or ``string``
:return: Result of POST request
"""
kwargs = {}
kwargs['index.' + name] = value if isinstance(value, basestring) else json.dumps(value)
return self.post(**kwargs) | python | def update_index(self, name, value):
"""Changes the definition of a KV Store index.
:param name: name of index to change
:type name: ``string``
:param value: new index definition
:type value: ``dict`` or ``string``
:return: Result of POST request
"""
kwargs = {}
kwargs['index.' + name] = value if isinstance(value, basestring) else json.dumps(value)
return self.post(**kwargs) | [
"def",
"update_index",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"kwargs",
"=",
"{",
"}",
"kwargs",
"[",
"'index.'",
"+",
"name",
"]",
"=",
"value",
"if",
"isinstance",
"(",
"value",
",",
"basestring",
")",
"else",
"json",
".",
"dumps",
"(",
... | Changes the definition of a KV Store index.
:param name: name of index to change
:type name: ``string``
:param value: new index definition
:type value: ``dict`` or ``string``
:return: Result of POST request | [
"Changes",
"the",
"definition",
"of",
"a",
"KV",
"Store",
"index",
"."
] | a245a4eeb93b3621730418008e31715912bcdcd8 | https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L3576-L3588 | train | 217,017 |
splunk/splunk-sdk-python | splunklib/client.py | KVStoreCollection.update_field | def update_field(self, name, value):
"""Changes the definition of a KV Store field.
:param name: name of field to change
:type name: ``string``
:param value: new field definition
:type value: ``string``
:return: Result of POST request
"""
kwargs = {}
kwargs['field.' + name] = value
return self.post(**kwargs) | python | def update_field(self, name, value):
"""Changes the definition of a KV Store field.
:param name: name of field to change
:type name: ``string``
:param value: new field definition
:type value: ``string``
:return: Result of POST request
"""
kwargs = {}
kwargs['field.' + name] = value
return self.post(**kwargs) | [
"def",
"update_field",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"kwargs",
"=",
"{",
"}",
"kwargs",
"[",
"'field.'",
"+",
"name",
"]",
"=",
"value",
"return",
"self",
".",
"post",
"(",
"*",
"*",
"kwargs",
")"
] | Changes the definition of a KV Store field.
:param name: name of field to change
:type name: ``string``
:param value: new field definition
:type value: ``string``
:return: Result of POST request | [
"Changes",
"the",
"definition",
"of",
"a",
"KV",
"Store",
"field",
"."
] | a245a4eeb93b3621730418008e31715912bcdcd8 | https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L3590-L3602 | train | 217,018 |
splunk/splunk-sdk-python | splunklib/client.py | KVStoreCollectionData.query | def query(self, **query):
"""
Gets the results of query, with optional parameters sort, limit, skip, and fields.
:param query: Optional parameters. Valid options are sort, limit, skip, and fields
:type query: ``dict``
:return: Array of documents retrieved by query.
:rtype: ``array``
"""
return json.loads(self._get('', **query).body.read().decode('utf-8')) | python | def query(self, **query):
"""
Gets the results of query, with optional parameters sort, limit, skip, and fields.
:param query: Optional parameters. Valid options are sort, limit, skip, and fields
:type query: ``dict``
:return: Array of documents retrieved by query.
:rtype: ``array``
"""
return json.loads(self._get('', **query).body.read().decode('utf-8')) | [
"def",
"query",
"(",
"self",
",",
"*",
"*",
"query",
")",
":",
"return",
"json",
".",
"loads",
"(",
"self",
".",
"_get",
"(",
"''",
",",
"*",
"*",
"query",
")",
".",
"body",
".",
"read",
"(",
")",
".",
"decode",
"(",
"'utf-8'",
")",
")"
] | Gets the results of query, with optional parameters sort, limit, skip, and fields.
:param query: Optional parameters. Valid options are sort, limit, skip, and fields
:type query: ``dict``
:return: Array of documents retrieved by query.
:rtype: ``array`` | [
"Gets",
"the",
"results",
"of",
"query",
"with",
"optional",
"parameters",
"sort",
"limit",
"skip",
"and",
"fields",
"."
] | a245a4eeb93b3621730418008e31715912bcdcd8 | https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L3626-L3636 | train | 217,019 |
splunk/splunk-sdk-python | splunklib/client.py | KVStoreCollectionData.query_by_id | def query_by_id(self, id):
"""
Returns object with _id = id.
:param id: Value for ID. If not a string will be coerced to string.
:type id: ``string``
:return: Document with id
:rtype: ``dict``
"""
return json.loads(self._get(UrlEncoded(str(id))).body.read().decode('utf-8')) | python | def query_by_id(self, id):
"""
Returns object with _id = id.
:param id: Value for ID. If not a string will be coerced to string.
:type id: ``string``
:return: Document with id
:rtype: ``dict``
"""
return json.loads(self._get(UrlEncoded(str(id))).body.read().decode('utf-8')) | [
"def",
"query_by_id",
"(",
"self",
",",
"id",
")",
":",
"return",
"json",
".",
"loads",
"(",
"self",
".",
"_get",
"(",
"UrlEncoded",
"(",
"str",
"(",
"id",
")",
")",
")",
".",
"body",
".",
"read",
"(",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"... | Returns object with _id = id.
:param id: Value for ID. If not a string will be coerced to string.
:type id: ``string``
:return: Document with id
:rtype: ``dict`` | [
"Returns",
"object",
"with",
"_id",
"=",
"id",
"."
] | a245a4eeb93b3621730418008e31715912bcdcd8 | https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L3638-L3648 | train | 217,020 |
splunk/splunk-sdk-python | splunklib/client.py | KVStoreCollectionData.insert | def insert(self, data):
"""
Inserts item into this collection. An _id field will be generated if not assigned in the data.
:param data: Document to insert
:type data: ``string``
:return: _id of inserted object
:rtype: ``dict``
"""
return json.loads(self._post('', headers=KVStoreCollectionData.JSON_HEADER, body=data).body.read().decode('utf-8')) | python | def insert(self, data):
"""
Inserts item into this collection. An _id field will be generated if not assigned in the data.
:param data: Document to insert
:type data: ``string``
:return: _id of inserted object
:rtype: ``dict``
"""
return json.loads(self._post('', headers=KVStoreCollectionData.JSON_HEADER, body=data).body.read().decode('utf-8')) | [
"def",
"insert",
"(",
"self",
",",
"data",
")",
":",
"return",
"json",
".",
"loads",
"(",
"self",
".",
"_post",
"(",
"''",
",",
"headers",
"=",
"KVStoreCollectionData",
".",
"JSON_HEADER",
",",
"body",
"=",
"data",
")",
".",
"body",
".",
"read",
"(",... | Inserts item into this collection. An _id field will be generated if not assigned in the data.
:param data: Document to insert
:type data: ``string``
:return: _id of inserted object
:rtype: ``dict`` | [
"Inserts",
"item",
"into",
"this",
"collection",
".",
"An",
"_id",
"field",
"will",
"be",
"generated",
"if",
"not",
"assigned",
"in",
"the",
"data",
"."
] | a245a4eeb93b3621730418008e31715912bcdcd8 | https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L3650-L3660 | train | 217,021 |
splunk/splunk-sdk-python | splunklib/client.py | KVStoreCollectionData.update | def update(self, id, data):
"""
Replaces document with _id = id with data.
:param id: _id of document to update
:type id: ``string``
:param data: the new document to insert
:type data: ``string``
:return: id of replaced document
:rtype: ``dict``
"""
return json.loads(self._post(UrlEncoded(str(id)), headers=KVStoreCollectionData.JSON_HEADER, body=data).body.read().decode('utf-8')) | python | def update(self, id, data):
"""
Replaces document with _id = id with data.
:param id: _id of document to update
:type id: ``string``
:param data: the new document to insert
:type data: ``string``
:return: id of replaced document
:rtype: ``dict``
"""
return json.loads(self._post(UrlEncoded(str(id)), headers=KVStoreCollectionData.JSON_HEADER, body=data).body.read().decode('utf-8')) | [
"def",
"update",
"(",
"self",
",",
"id",
",",
"data",
")",
":",
"return",
"json",
".",
"loads",
"(",
"self",
".",
"_post",
"(",
"UrlEncoded",
"(",
"str",
"(",
"id",
")",
")",
",",
"headers",
"=",
"KVStoreCollectionData",
".",
"JSON_HEADER",
",",
"bod... | Replaces document with _id = id with data.
:param id: _id of document to update
:type id: ``string``
:param data: the new document to insert
:type data: ``string``
:return: id of replaced document
:rtype: ``dict`` | [
"Replaces",
"document",
"with",
"_id",
"=",
"id",
"with",
"data",
"."
] | a245a4eeb93b3621730418008e31715912bcdcd8 | https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L3684-L3696 | train | 217,022 |
splunk/splunk-sdk-python | splunklib/client.py | KVStoreCollectionData.batch_find | def batch_find(self, *dbqueries):
"""
Returns array of results from queries dbqueries.
:param dbqueries: Array of individual queries as dictionaries
:type dbqueries: ``array`` of ``dict``
:return: Results of each query
:rtype: ``array`` of ``array``
"""
if len(dbqueries) < 1:
raise Exception('Must have at least one query.')
data = json.dumps(dbqueries)
return json.loads(self._post('batch_find', headers=KVStoreCollectionData.JSON_HEADER, body=data).body.read().decode('utf-8')) | python | def batch_find(self, *dbqueries):
"""
Returns array of results from queries dbqueries.
:param dbqueries: Array of individual queries as dictionaries
:type dbqueries: ``array`` of ``dict``
:return: Results of each query
:rtype: ``array`` of ``array``
"""
if len(dbqueries) < 1:
raise Exception('Must have at least one query.')
data = json.dumps(dbqueries)
return json.loads(self._post('batch_find', headers=KVStoreCollectionData.JSON_HEADER, body=data).body.read().decode('utf-8')) | [
"def",
"batch_find",
"(",
"self",
",",
"*",
"dbqueries",
")",
":",
"if",
"len",
"(",
"dbqueries",
")",
"<",
"1",
":",
"raise",
"Exception",
"(",
"'Must have at least one query.'",
")",
"data",
"=",
"json",
".",
"dumps",
"(",
"dbqueries",
")",
"return",
"... | Returns array of results from queries dbqueries.
:param dbqueries: Array of individual queries as dictionaries
:type dbqueries: ``array`` of ``dict``
:return: Results of each query
:rtype: ``array`` of ``array`` | [
"Returns",
"array",
"of",
"results",
"from",
"queries",
"dbqueries",
"."
] | a245a4eeb93b3621730418008e31715912bcdcd8 | https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L3698-L3713 | train | 217,023 |
splunk/splunk-sdk-python | splunklib/client.py | KVStoreCollectionData.batch_save | def batch_save(self, *documents):
"""
Inserts or updates every document specified in documents.
:param documents: Array of documents to save as dictionaries
:type documents: ``array`` of ``dict``
:return: Results of update operation as overall stats
:rtype: ``dict``
"""
if len(documents) < 1:
raise Exception('Must have at least one document.')
data = json.dumps(documents)
return json.loads(self._post('batch_save', headers=KVStoreCollectionData.JSON_HEADER, body=data).body.read().decode('utf-8')) | python | def batch_save(self, *documents):
"""
Inserts or updates every document specified in documents.
:param documents: Array of documents to save as dictionaries
:type documents: ``array`` of ``dict``
:return: Results of update operation as overall stats
:rtype: ``dict``
"""
if len(documents) < 1:
raise Exception('Must have at least one document.')
data = json.dumps(documents)
return json.loads(self._post('batch_save', headers=KVStoreCollectionData.JSON_HEADER, body=data).body.read().decode('utf-8')) | [
"def",
"batch_save",
"(",
"self",
",",
"*",
"documents",
")",
":",
"if",
"len",
"(",
"documents",
")",
"<",
"1",
":",
"raise",
"Exception",
"(",
"'Must have at least one document.'",
")",
"data",
"=",
"json",
".",
"dumps",
"(",
"documents",
")",
"return",
... | Inserts or updates every document specified in documents.
:param documents: Array of documents to save as dictionaries
:type documents: ``array`` of ``dict``
:return: Results of update operation as overall stats
:rtype: ``dict`` | [
"Inserts",
"or",
"updates",
"every",
"document",
"specified",
"in",
"documents",
"."
] | a245a4eeb93b3621730418008e31715912bcdcd8 | https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L3715-L3730 | train | 217,024 |
splunk/splunk-sdk-python | setup.py | DistCommand.get_python_files | def get_python_files(files):
"""Utility function to get .py files from a list"""
python_files = []
for file_name in files:
if file_name.endswith(".py"):
python_files.append(file_name)
return python_files | python | def get_python_files(files):
"""Utility function to get .py files from a list"""
python_files = []
for file_name in files:
if file_name.endswith(".py"):
python_files.append(file_name)
return python_files | [
"def",
"get_python_files",
"(",
"files",
")",
":",
"python_files",
"=",
"[",
"]",
"for",
"file_name",
"in",
"files",
":",
"if",
"file_name",
".",
"endswith",
"(",
"\".py\"",
")",
":",
"python_files",
".",
"append",
"(",
"file_name",
")",
"return",
"python_... | Utility function to get .py files from a list | [
"Utility",
"function",
"to",
"get",
".",
"py",
"files",
"from",
"a",
"list"
] | a245a4eeb93b3621730418008e31715912bcdcd8 | https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/setup.py#L146-L153 | train | 217,025 |
splunk/splunk-sdk-python | splunklib/binding.py | _parse_cookies | def _parse_cookies(cookie_str, dictionary):
"""Tries to parse any key-value pairs of cookies in a string,
then updates the the dictionary with any key-value pairs found.
**Example**::
dictionary = {}
_parse_cookies('my=value', dictionary)
# Now the following is True
dictionary['my'] == 'value'
:param cookie_str: A string containing "key=value" pairs from an HTTP "Set-Cookie" header.
:type cookie_str: ``str``
:param dictionary: A dictionary to update with any found key-value pairs.
:type dictionary: ``dict``
"""
parsed_cookie = six.moves.http_cookies.SimpleCookie(cookie_str)
for cookie in parsed_cookie.values():
dictionary[cookie.key] = cookie.coded_value | python | def _parse_cookies(cookie_str, dictionary):
"""Tries to parse any key-value pairs of cookies in a string,
then updates the the dictionary with any key-value pairs found.
**Example**::
dictionary = {}
_parse_cookies('my=value', dictionary)
# Now the following is True
dictionary['my'] == 'value'
:param cookie_str: A string containing "key=value" pairs from an HTTP "Set-Cookie" header.
:type cookie_str: ``str``
:param dictionary: A dictionary to update with any found key-value pairs.
:type dictionary: ``dict``
"""
parsed_cookie = six.moves.http_cookies.SimpleCookie(cookie_str)
for cookie in parsed_cookie.values():
dictionary[cookie.key] = cookie.coded_value | [
"def",
"_parse_cookies",
"(",
"cookie_str",
",",
"dictionary",
")",
":",
"parsed_cookie",
"=",
"six",
".",
"moves",
".",
"http_cookies",
".",
"SimpleCookie",
"(",
"cookie_str",
")",
"for",
"cookie",
"in",
"parsed_cookie",
".",
"values",
"(",
")",
":",
"dicti... | Tries to parse any key-value pairs of cookies in a string,
then updates the the dictionary with any key-value pairs found.
**Example**::
dictionary = {}
_parse_cookies('my=value', dictionary)
# Now the following is True
dictionary['my'] == 'value'
:param cookie_str: A string containing "key=value" pairs from an HTTP "Set-Cookie" header.
:type cookie_str: ``str``
:param dictionary: A dictionary to update with any found key-value pairs.
:type dictionary: ``dict`` | [
"Tries",
"to",
"parse",
"any",
"key",
"-",
"value",
"pairs",
"of",
"cookies",
"in",
"a",
"string",
"then",
"updates",
"the",
"the",
"dictionary",
"with",
"any",
"key",
"-",
"value",
"pairs",
"found",
"."
] | a245a4eeb93b3621730418008e31715912bcdcd8 | https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/binding.py#L78-L95 | train | 217,026 |
splunk/splunk-sdk-python | splunklib/binding.py | namespace | def namespace(sharing=None, owner=None, app=None, **kwargs):
"""This function constructs a Splunk namespace.
Every Splunk resource belongs to a namespace. The namespace is specified by
the pair of values ``owner`` and ``app`` and is governed by a ``sharing`` mode.
The possible values for ``sharing`` are: "user", "app", "global" and "system",
which map to the following combinations of ``owner`` and ``app`` values:
"user" => {owner}, {app}
"app" => nobody, {app}
"global" => nobody, {app}
"system" => nobody, system
"nobody" is a special user name that basically means no user, and "system"
is the name reserved for system resources.
"-" is a wildcard that can be used for both ``owner`` and ``app`` values and
refers to all users and all apps, respectively.
In general, when you specify a namespace you can specify any combination of
these three values and the library will reconcile the triple, overriding the
provided values as appropriate.
Finally, if no namespacing is specified the library will make use of the
``/services`` branch of the REST API, which provides a namespaced view of
Splunk resources equivelent to using ``owner={currentUser}`` and
``app={defaultApp}``.
The ``namespace`` function returns a representation of the namespace from
reconciling the values you provide. It ignores any keyword arguments other
than ``owner``, ``app``, and ``sharing``, so you can provide ``dicts`` of
configuration information without first having to extract individual keys.
:param sharing: The sharing mode (the default is "user").
:type sharing: "system", "global", "app", or "user"
:param owner: The owner context (the default is "None").
:type owner: ``string``
:param app: The app context (the default is "None").
:type app: ``string``
:returns: A :class:`splunklib.data.Record` containing the reconciled
namespace.
**Example**::
import splunklib.binding as binding
n = binding.namespace(sharing="user", owner="boris", app="search")
n = binding.namespace(sharing="global", app="search")
"""
if sharing in ["system"]:
return record({'sharing': sharing, 'owner': "nobody", 'app': "system" })
if sharing in ["global", "app"]:
return record({'sharing': sharing, 'owner': "nobody", 'app': app})
if sharing in ["user", None]:
return record({'sharing': sharing, 'owner': owner, 'app': app})
raise ValueError("Invalid value for argument: 'sharing'") | python | def namespace(sharing=None, owner=None, app=None, **kwargs):
"""This function constructs a Splunk namespace.
Every Splunk resource belongs to a namespace. The namespace is specified by
the pair of values ``owner`` and ``app`` and is governed by a ``sharing`` mode.
The possible values for ``sharing`` are: "user", "app", "global" and "system",
which map to the following combinations of ``owner`` and ``app`` values:
"user" => {owner}, {app}
"app" => nobody, {app}
"global" => nobody, {app}
"system" => nobody, system
"nobody" is a special user name that basically means no user, and "system"
is the name reserved for system resources.
"-" is a wildcard that can be used for both ``owner`` and ``app`` values and
refers to all users and all apps, respectively.
In general, when you specify a namespace you can specify any combination of
these three values and the library will reconcile the triple, overriding the
provided values as appropriate.
Finally, if no namespacing is specified the library will make use of the
``/services`` branch of the REST API, which provides a namespaced view of
Splunk resources equivelent to using ``owner={currentUser}`` and
``app={defaultApp}``.
The ``namespace`` function returns a representation of the namespace from
reconciling the values you provide. It ignores any keyword arguments other
than ``owner``, ``app``, and ``sharing``, so you can provide ``dicts`` of
configuration information without first having to extract individual keys.
:param sharing: The sharing mode (the default is "user").
:type sharing: "system", "global", "app", or "user"
:param owner: The owner context (the default is "None").
:type owner: ``string``
:param app: The app context (the default is "None").
:type app: ``string``
:returns: A :class:`splunklib.data.Record` containing the reconciled
namespace.
**Example**::
import splunklib.binding as binding
n = binding.namespace(sharing="user", owner="boris", app="search")
n = binding.namespace(sharing="global", app="search")
"""
if sharing in ["system"]:
return record({'sharing': sharing, 'owner': "nobody", 'app': "system" })
if sharing in ["global", "app"]:
return record({'sharing': sharing, 'owner': "nobody", 'app': app})
if sharing in ["user", None]:
return record({'sharing': sharing, 'owner': owner, 'app': app})
raise ValueError("Invalid value for argument: 'sharing'") | [
"def",
"namespace",
"(",
"sharing",
"=",
"None",
",",
"owner",
"=",
"None",
",",
"app",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"sharing",
"in",
"[",
"\"system\"",
"]",
":",
"return",
"record",
"(",
"{",
"'sharing'",
":",
"sharing",
"... | This function constructs a Splunk namespace.
Every Splunk resource belongs to a namespace. The namespace is specified by
the pair of values ``owner`` and ``app`` and is governed by a ``sharing`` mode.
The possible values for ``sharing`` are: "user", "app", "global" and "system",
which map to the following combinations of ``owner`` and ``app`` values:
"user" => {owner}, {app}
"app" => nobody, {app}
"global" => nobody, {app}
"system" => nobody, system
"nobody" is a special user name that basically means no user, and "system"
is the name reserved for system resources.
"-" is a wildcard that can be used for both ``owner`` and ``app`` values and
refers to all users and all apps, respectively.
In general, when you specify a namespace you can specify any combination of
these three values and the library will reconcile the triple, overriding the
provided values as appropriate.
Finally, if no namespacing is specified the library will make use of the
``/services`` branch of the REST API, which provides a namespaced view of
Splunk resources equivelent to using ``owner={currentUser}`` and
``app={defaultApp}``.
The ``namespace`` function returns a representation of the namespace from
reconciling the values you provide. It ignores any keyword arguments other
than ``owner``, ``app``, and ``sharing``, so you can provide ``dicts`` of
configuration information without first having to extract individual keys.
:param sharing: The sharing mode (the default is "user").
:type sharing: "system", "global", "app", or "user"
:param owner: The owner context (the default is "None").
:type owner: ``string``
:param app: The app context (the default is "None").
:type app: ``string``
:returns: A :class:`splunklib.data.Record` containing the reconciled
namespace.
**Example**::
import splunklib.binding as binding
n = binding.namespace(sharing="user", owner="boris", app="search")
n = binding.namespace(sharing="global", app="search") | [
"This",
"function",
"constructs",
"a",
"Splunk",
"namespace",
"."
] | a245a4eeb93b3621730418008e31715912bcdcd8 | https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/binding.py#L355-L412 | train | 217,027 |
splunk/splunk-sdk-python | splunklib/binding.py | Context.request | def request(self, path_segment, method="GET", headers=None, body="",
owner=None, app=None, sharing=None):
"""Issues an arbitrary HTTP request to the REST path segment.
This method is named to match ``httplib.request``. This function
makes a single round trip to the server.
If *owner*, *app*, and *sharing* are omitted, this method uses the
default :class:`Context` namespace. All other keyword arguments are
included in the URL as query parameters.
:raises AuthenticationError: Raised when the ``Context`` object is not
logged in.
:raises HTTPError: Raised when an error occurred in a GET operation from
*path_segment*.
:param path_segment: A REST path segment.
:type path_segment: ``string``
:param method: The HTTP method to use (optional).
:type method: ``string``
:param headers: List of extra HTTP headers to send (optional).
:type headers: ``list`` of 2-tuples.
:param body: Content of the HTTP request (optional).
:type body: ``string``
:param owner: The owner context of the namespace (optional).
:type owner: ``string``
:param app: The app context of the namespace (optional).
:type app: ``string``
:param sharing: The sharing mode of the namespace (optional).
:type sharing: ``string``
:param query: All other keyword arguments, which are used as query
parameters.
:type query: ``string``
:return: The response from the server.
:rtype: ``dict`` with keys ``body``, ``headers``, ``reason``,
and ``status``
**Example**::
c = binding.connect(...)
c.request('saved/searches', method='GET') == \\
{'body': ...a response reader object...,
'headers': [('content-length', '46722'),
('expires', 'Fri, 30 Oct 1998 00:00:00 GMT'),
('server', 'Splunkd'),
('connection', 'close'),
('cache-control', 'no-store, max-age=0, must-revalidate, no-cache'),
('date', 'Fri, 11 May 2012 17:24:19 GMT'),
('content-type', 'text/xml; charset=utf-8')],
'reason': 'OK',
'status': 200}
c.request('nonexistant/path', method='GET') # raises HTTPError
c.logout()
c.get('apps/local') # raises AuthenticationError
"""
if headers is None:
headers = []
path = self.authority \
+ self._abspath(path_segment, owner=owner,
app=app, sharing=sharing)
all_headers = headers + self.additional_headers + self._auth_headers
logging.debug("%s request to %s (headers: %s, body: %s)",
method, path, str(all_headers), repr(body))
response = self.http.request(path,
{'method': method,
'headers': all_headers,
'body': body})
return response | python | def request(self, path_segment, method="GET", headers=None, body="",
owner=None, app=None, sharing=None):
"""Issues an arbitrary HTTP request to the REST path segment.
This method is named to match ``httplib.request``. This function
makes a single round trip to the server.
If *owner*, *app*, and *sharing* are omitted, this method uses the
default :class:`Context` namespace. All other keyword arguments are
included in the URL as query parameters.
:raises AuthenticationError: Raised when the ``Context`` object is not
logged in.
:raises HTTPError: Raised when an error occurred in a GET operation from
*path_segment*.
:param path_segment: A REST path segment.
:type path_segment: ``string``
:param method: The HTTP method to use (optional).
:type method: ``string``
:param headers: List of extra HTTP headers to send (optional).
:type headers: ``list`` of 2-tuples.
:param body: Content of the HTTP request (optional).
:type body: ``string``
:param owner: The owner context of the namespace (optional).
:type owner: ``string``
:param app: The app context of the namespace (optional).
:type app: ``string``
:param sharing: The sharing mode of the namespace (optional).
:type sharing: ``string``
:param query: All other keyword arguments, which are used as query
parameters.
:type query: ``string``
:return: The response from the server.
:rtype: ``dict`` with keys ``body``, ``headers``, ``reason``,
and ``status``
**Example**::
c = binding.connect(...)
c.request('saved/searches', method='GET') == \\
{'body': ...a response reader object...,
'headers': [('content-length', '46722'),
('expires', 'Fri, 30 Oct 1998 00:00:00 GMT'),
('server', 'Splunkd'),
('connection', 'close'),
('cache-control', 'no-store, max-age=0, must-revalidate, no-cache'),
('date', 'Fri, 11 May 2012 17:24:19 GMT'),
('content-type', 'text/xml; charset=utf-8')],
'reason': 'OK',
'status': 200}
c.request('nonexistant/path', method='GET') # raises HTTPError
c.logout()
c.get('apps/local') # raises AuthenticationError
"""
if headers is None:
headers = []
path = self.authority \
+ self._abspath(path_segment, owner=owner,
app=app, sharing=sharing)
all_headers = headers + self.additional_headers + self._auth_headers
logging.debug("%s request to %s (headers: %s, body: %s)",
method, path, str(all_headers), repr(body))
response = self.http.request(path,
{'method': method,
'headers': all_headers,
'body': body})
return response | [
"def",
"request",
"(",
"self",
",",
"path_segment",
",",
"method",
"=",
"\"GET\"",
",",
"headers",
"=",
"None",
",",
"body",
"=",
"\"\"",
",",
"owner",
"=",
"None",
",",
"app",
"=",
"None",
",",
"sharing",
"=",
"None",
")",
":",
"if",
"headers",
"i... | Issues an arbitrary HTTP request to the REST path segment.
This method is named to match ``httplib.request``. This function
makes a single round trip to the server.
If *owner*, *app*, and *sharing* are omitted, this method uses the
default :class:`Context` namespace. All other keyword arguments are
included in the URL as query parameters.
:raises AuthenticationError: Raised when the ``Context`` object is not
logged in.
:raises HTTPError: Raised when an error occurred in a GET operation from
*path_segment*.
:param path_segment: A REST path segment.
:type path_segment: ``string``
:param method: The HTTP method to use (optional).
:type method: ``string``
:param headers: List of extra HTTP headers to send (optional).
:type headers: ``list`` of 2-tuples.
:param body: Content of the HTTP request (optional).
:type body: ``string``
:param owner: The owner context of the namespace (optional).
:type owner: ``string``
:param app: The app context of the namespace (optional).
:type app: ``string``
:param sharing: The sharing mode of the namespace (optional).
:type sharing: ``string``
:param query: All other keyword arguments, which are used as query
parameters.
:type query: ``string``
:return: The response from the server.
:rtype: ``dict`` with keys ``body``, ``headers``, ``reason``,
and ``status``
**Example**::
c = binding.connect(...)
c.request('saved/searches', method='GET') == \\
{'body': ...a response reader object...,
'headers': [('content-length', '46722'),
('expires', 'Fri, 30 Oct 1998 00:00:00 GMT'),
('server', 'Splunkd'),
('connection', 'close'),
('cache-control', 'no-store, max-age=0, must-revalidate, no-cache'),
('date', 'Fri, 11 May 2012 17:24:19 GMT'),
('content-type', 'text/xml; charset=utf-8')],
'reason': 'OK',
'status': 200}
c.request('nonexistant/path', method='GET') # raises HTTPError
c.logout()
c.get('apps/local') # raises AuthenticationError | [
"Issues",
"an",
"arbitrary",
"HTTP",
"request",
"to",
"the",
"REST",
"path",
"segment",
"."
] | a245a4eeb93b3621730418008e31715912bcdcd8 | https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/binding.py#L757-L824 | train | 217,028 |
splunk/splunk-sdk-python | splunklib/binding.py | HttpLib.delete | def delete(self, url, headers=None, **kwargs):
"""Sends a DELETE request to a URL.
:param url: The URL.
:type url: ``string``
:param headers: A list of pairs specifying the headers for the HTTP
response (for example, ``[('Content-Type': 'text/cthulhu'), ('Token': 'boris')]``).
:type headers: ``list``
:param kwargs: Additional keyword arguments (optional). These arguments
are interpreted as the query part of the URL. The order of keyword
arguments is not preserved in the request, but the keywords and
their arguments will be URL encoded.
:type kwargs: ``dict``
:returns: A dictionary describing the response (see :class:`HttpLib` for
its structure).
:rtype: ``dict``
"""
if headers is None: headers = []
if kwargs:
# url is already a UrlEncoded. We have to manually declare
# the query to be encoded or it will get automatically URL
# encoded by being appended to url.
url = url + UrlEncoded('?' + _encode(**kwargs), skip_encode=True)
message = {
'method': "DELETE",
'headers': headers,
}
return self.request(url, message) | python | def delete(self, url, headers=None, **kwargs):
"""Sends a DELETE request to a URL.
:param url: The URL.
:type url: ``string``
:param headers: A list of pairs specifying the headers for the HTTP
response (for example, ``[('Content-Type': 'text/cthulhu'), ('Token': 'boris')]``).
:type headers: ``list``
:param kwargs: Additional keyword arguments (optional). These arguments
are interpreted as the query part of the URL. The order of keyword
arguments is not preserved in the request, but the keywords and
their arguments will be URL encoded.
:type kwargs: ``dict``
:returns: A dictionary describing the response (see :class:`HttpLib` for
its structure).
:rtype: ``dict``
"""
if headers is None: headers = []
if kwargs:
# url is already a UrlEncoded. We have to manually declare
# the query to be encoded or it will get automatically URL
# encoded by being appended to url.
url = url + UrlEncoded('?' + _encode(**kwargs), skip_encode=True)
message = {
'method': "DELETE",
'headers': headers,
}
return self.request(url, message) | [
"def",
"delete",
"(",
"self",
",",
"url",
",",
"headers",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"headers",
"is",
"None",
":",
"headers",
"=",
"[",
"]",
"if",
"kwargs",
":",
"# url is already a UrlEncoded. We have to manually declare",
"# the ... | Sends a DELETE request to a URL.
:param url: The URL.
:type url: ``string``
:param headers: A list of pairs specifying the headers for the HTTP
response (for example, ``[('Content-Type': 'text/cthulhu'), ('Token': 'boris')]``).
:type headers: ``list``
:param kwargs: Additional keyword arguments (optional). These arguments
are interpreted as the query part of the URL. The order of keyword
arguments is not preserved in the request, but the keywords and
their arguments will be URL encoded.
:type kwargs: ``dict``
:returns: A dictionary describing the response (see :class:`HttpLib` for
its structure).
:rtype: ``dict`` | [
"Sends",
"a",
"DELETE",
"request",
"to",
"a",
"URL",
"."
] | a245a4eeb93b3621730418008e31715912bcdcd8 | https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/binding.py#L1131-L1158 | train | 217,029 |
splunk/splunk-sdk-python | splunklib/binding.py | HttpLib.get | def get(self, url, headers=None, **kwargs):
"""Sends a GET request to a URL.
:param url: The URL.
:type url: ``string``
:param headers: A list of pairs specifying the headers for the HTTP
response (for example, ``[('Content-Type': 'text/cthulhu'), ('Token': 'boris')]``).
:type headers: ``list``
:param kwargs: Additional keyword arguments (optional). These arguments
are interpreted as the query part of the URL. The order of keyword
arguments is not preserved in the request, but the keywords and
their arguments will be URL encoded.
:type kwargs: ``dict``
:returns: A dictionary describing the response (see :class:`HttpLib` for
its structure).
:rtype: ``dict``
"""
if headers is None: headers = []
if kwargs:
# url is already a UrlEncoded. We have to manually declare
# the query to be encoded or it will get automatically URL
# encoded by being appended to url.
url = url + UrlEncoded('?' + _encode(**kwargs), skip_encode=True)
return self.request(url, { 'method': "GET", 'headers': headers }) | python | def get(self, url, headers=None, **kwargs):
"""Sends a GET request to a URL.
:param url: The URL.
:type url: ``string``
:param headers: A list of pairs specifying the headers for the HTTP
response (for example, ``[('Content-Type': 'text/cthulhu'), ('Token': 'boris')]``).
:type headers: ``list``
:param kwargs: Additional keyword arguments (optional). These arguments
are interpreted as the query part of the URL. The order of keyword
arguments is not preserved in the request, but the keywords and
their arguments will be URL encoded.
:type kwargs: ``dict``
:returns: A dictionary describing the response (see :class:`HttpLib` for
its structure).
:rtype: ``dict``
"""
if headers is None: headers = []
if kwargs:
# url is already a UrlEncoded. We have to manually declare
# the query to be encoded or it will get automatically URL
# encoded by being appended to url.
url = url + UrlEncoded('?' + _encode(**kwargs), skip_encode=True)
return self.request(url, { 'method': "GET", 'headers': headers }) | [
"def",
"get",
"(",
"self",
",",
"url",
",",
"headers",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"headers",
"is",
"None",
":",
"headers",
"=",
"[",
"]",
"if",
"kwargs",
":",
"# url is already a UrlEncoded. We have to manually declare",
"# the que... | Sends a GET request to a URL.
:param url: The URL.
:type url: ``string``
:param headers: A list of pairs specifying the headers for the HTTP
response (for example, ``[('Content-Type': 'text/cthulhu'), ('Token': 'boris')]``).
:type headers: ``list``
:param kwargs: Additional keyword arguments (optional). These arguments
are interpreted as the query part of the URL. The order of keyword
arguments is not preserved in the request, but the keywords and
their arguments will be URL encoded.
:type kwargs: ``dict``
:returns: A dictionary describing the response (see :class:`HttpLib` for
its structure).
:rtype: ``dict`` | [
"Sends",
"a",
"GET",
"request",
"to",
"a",
"URL",
"."
] | a245a4eeb93b3621730418008e31715912bcdcd8 | https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/binding.py#L1160-L1183 | train | 217,030 |
splunk/splunk-sdk-python | splunklib/binding.py | ResponseReader.peek | def peek(self, size):
"""Nondestructively retrieves a given number of characters.
The next :meth:`read` operation behaves as though this method was never
called.
:param size: The number of characters to retrieve.
:type size: ``integer``
"""
c = self.read(size)
self._buffer = self._buffer + c
return c | python | def peek(self, size):
"""Nondestructively retrieves a given number of characters.
The next :meth:`read` operation behaves as though this method was never
called.
:param size: The number of characters to retrieve.
:type size: ``integer``
"""
c = self.read(size)
self._buffer = self._buffer + c
return c | [
"def",
"peek",
"(",
"self",
",",
"size",
")",
":",
"c",
"=",
"self",
".",
"read",
"(",
"size",
")",
"self",
".",
"_buffer",
"=",
"self",
".",
"_buffer",
"+",
"c",
"return",
"c"
] | Nondestructively retrieves a given number of characters.
The next :meth:`read` operation behaves as though this method was never
called.
:param size: The number of characters to retrieve.
:type size: ``integer`` | [
"Nondestructively",
"retrieves",
"a",
"given",
"number",
"of",
"characters",
"."
] | a245a4eeb93b3621730418008e31715912bcdcd8 | https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/binding.py#L1284-L1295 | train | 217,031 |
splunk/splunk-sdk-python | splunklib/binding.py | ResponseReader.close | def close(self):
"""Closes this response."""
if self._connection:
self._connection.close()
self._response.close() | python | def close(self):
"""Closes this response."""
if self._connection:
self._connection.close()
self._response.close() | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"_connection",
":",
"self",
".",
"_connection",
".",
"close",
"(",
")",
"self",
".",
"_response",
".",
"close",
"(",
")"
] | Closes this response. | [
"Closes",
"this",
"response",
"."
] | a245a4eeb93b3621730418008e31715912bcdcd8 | https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/binding.py#L1297-L1301 | train | 217,032 |
splunk/splunk-sdk-python | splunklib/binding.py | ResponseReader.readinto | def readinto(self, byte_array):
""" Read data into a byte array, upto the size of the byte array.
:param byte_array: A byte array/memory view to pour bytes into.
:type byte_array: ``bytearray`` or ``memoryview``
"""
max_size = len(byte_array)
data = self.read(max_size)
bytes_read = len(data)
byte_array[:bytes_read] = data
return bytes_read | python | def readinto(self, byte_array):
""" Read data into a byte array, upto the size of the byte array.
:param byte_array: A byte array/memory view to pour bytes into.
:type byte_array: ``bytearray`` or ``memoryview``
"""
max_size = len(byte_array)
data = self.read(max_size)
bytes_read = len(data)
byte_array[:bytes_read] = data
return bytes_read | [
"def",
"readinto",
"(",
"self",
",",
"byte_array",
")",
":",
"max_size",
"=",
"len",
"(",
"byte_array",
")",
"data",
"=",
"self",
".",
"read",
"(",
"max_size",
")",
"bytes_read",
"=",
"len",
"(",
"data",
")",
"byte_array",
"[",
":",
"bytes_read",
"]",
... | Read data into a byte array, upto the size of the byte array.
:param byte_array: A byte array/memory view to pour bytes into.
:type byte_array: ``bytearray`` or ``memoryview`` | [
"Read",
"data",
"into",
"a",
"byte",
"array",
"upto",
"the",
"size",
"of",
"the",
"byte",
"array",
"."
] | a245a4eeb93b3621730418008e31715912bcdcd8 | https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/binding.py#L1322-L1333 | train | 217,033 |
splunk/splunk-sdk-python | splunklib/modularinput/validation_definition.py | ValidationDefinition.parse | def parse(stream):
"""Creates a ``ValidationDefinition`` from a provided stream containing XML.
The XML typically will look like this:
``<items>``
`` <server_host>myHost</server_host>``
`` <server_uri>https://127.0.0.1:8089</server_uri>``
`` <session_key>123102983109283019283</session_key>``
`` <checkpoint_dir>/opt/splunk/var/lib/splunk/modinputs</checkpoint_dir>``
`` <item name="myScheme">``
`` <param name="param1">value1</param>``
`` <param_list name="param2">``
`` <value>value2</value>``
`` <value>value3</value>``
`` <value>value4</value>``
`` </param_list>``
`` </item>``
``</items>``
:param stream: ``Stream`` containing XML to parse.
:return definition: A ``ValidationDefinition`` object.
"""
definition = ValidationDefinition()
# parse XML from the stream, then get the root node
root = ET.parse(stream).getroot()
for node in root:
# lone item node
if node.tag == "item":
# name from item node
definition.metadata["name"] = node.get("name")
definition.parameters = parse_xml_data(node, "")
else:
# Store anything else in metadata
definition.metadata[node.tag] = node.text
return definition | python | def parse(stream):
"""Creates a ``ValidationDefinition`` from a provided stream containing XML.
The XML typically will look like this:
``<items>``
`` <server_host>myHost</server_host>``
`` <server_uri>https://127.0.0.1:8089</server_uri>``
`` <session_key>123102983109283019283</session_key>``
`` <checkpoint_dir>/opt/splunk/var/lib/splunk/modinputs</checkpoint_dir>``
`` <item name="myScheme">``
`` <param name="param1">value1</param>``
`` <param_list name="param2">``
`` <value>value2</value>``
`` <value>value3</value>``
`` <value>value4</value>``
`` </param_list>``
`` </item>``
``</items>``
:param stream: ``Stream`` containing XML to parse.
:return definition: A ``ValidationDefinition`` object.
"""
definition = ValidationDefinition()
# parse XML from the stream, then get the root node
root = ET.parse(stream).getroot()
for node in root:
# lone item node
if node.tag == "item":
# name from item node
definition.metadata["name"] = node.get("name")
definition.parameters = parse_xml_data(node, "")
else:
# Store anything else in metadata
definition.metadata[node.tag] = node.text
return definition | [
"def",
"parse",
"(",
"stream",
")",
":",
"definition",
"=",
"ValidationDefinition",
"(",
")",
"# parse XML from the stream, then get the root node",
"root",
"=",
"ET",
".",
"parse",
"(",
"stream",
")",
".",
"getroot",
"(",
")",
"for",
"node",
"in",
"root",
":"... | Creates a ``ValidationDefinition`` from a provided stream containing XML.
The XML typically will look like this:
``<items>``
`` <server_host>myHost</server_host>``
`` <server_uri>https://127.0.0.1:8089</server_uri>``
`` <session_key>123102983109283019283</session_key>``
`` <checkpoint_dir>/opt/splunk/var/lib/splunk/modinputs</checkpoint_dir>``
`` <item name="myScheme">``
`` <param name="param1">value1</param>``
`` <param_list name="param2">``
`` <value>value2</value>``
`` <value>value3</value>``
`` <value>value4</value>``
`` </param_list>``
`` </item>``
``</items>``
:param stream: ``Stream`` containing XML to parse.
:return definition: A ``ValidationDefinition`` object. | [
"Creates",
"a",
"ValidationDefinition",
"from",
"a",
"provided",
"stream",
"containing",
"XML",
"."
] | a245a4eeb93b3621730418008e31715912bcdcd8 | https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/modularinput/validation_definition.py#L44-L84 | train | 217,034 |
splunk/splunk-sdk-python | examples/custom_search/bin/usercount.py | output_results | def output_results(results, mvdelim = '\n', output = sys.stdout):
"""Given a list of dictionaries, each representing
a single result, and an optional list of fields,
output those results to stdout for consumption by the
Splunk pipeline"""
# We collect all the unique field names, as well as
# convert all multivalue keys to the right form
fields = set()
for result in results:
for key in result.keys():
if(isinstance(result[key], list)):
result['__mv_' + key] = encode_mv(result[key])
result[key] = mvdelim.join(result[key])
fields.update(list(result.keys()))
# convert the fields into a list and create a CSV writer
# to output to stdout
fields = sorted(list(fields))
writer = csv.DictWriter(output, fields)
# Write out the fields, and then the actual results
writer.writerow(dict(list(zip(fields, fields))))
writer.writerows(results) | python | def output_results(results, mvdelim = '\n', output = sys.stdout):
"""Given a list of dictionaries, each representing
a single result, and an optional list of fields,
output those results to stdout for consumption by the
Splunk pipeline"""
# We collect all the unique field names, as well as
# convert all multivalue keys to the right form
fields = set()
for result in results:
for key in result.keys():
if(isinstance(result[key], list)):
result['__mv_' + key] = encode_mv(result[key])
result[key] = mvdelim.join(result[key])
fields.update(list(result.keys()))
# convert the fields into a list and create a CSV writer
# to output to stdout
fields = sorted(list(fields))
writer = csv.DictWriter(output, fields)
# Write out the fields, and then the actual results
writer.writerow(dict(list(zip(fields, fields))))
writer.writerows(results) | [
"def",
"output_results",
"(",
"results",
",",
"mvdelim",
"=",
"'\\n'",
",",
"output",
"=",
"sys",
".",
"stdout",
")",
":",
"# We collect all the unique field names, as well as ",
"# convert all multivalue keys to the right form",
"fields",
"=",
"set",
"(",
")",
"for",
... | Given a list of dictionaries, each representing
a single result, and an optional list of fields,
output those results to stdout for consumption by the
Splunk pipeline | [
"Given",
"a",
"list",
"of",
"dictionaries",
"each",
"representing",
"a",
"single",
"result",
"and",
"an",
"optional",
"list",
"of",
"fields",
"output",
"those",
"results",
"to",
"stdout",
"for",
"consumption",
"by",
"the",
"Splunk",
"pipeline"
] | a245a4eeb93b3621730418008e31715912bcdcd8 | https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/examples/custom_search/bin/usercount.py#L79-L103 | train | 217,035 |
splunk/splunk-sdk-python | examples/github_forks/github_forks.py | MyScript.validate_input | def validate_input(self, validation_definition):
"""In this example we are using external validation to verify that the Github
repository exists. If validate_input does not raise an Exception, the input
is assumed to be valid. Otherwise it prints the exception as an error message
when telling splunkd that the configuration is invalid.
When using external validation, after splunkd calls the modular input with
--scheme to get a scheme, it calls it again with --validate-arguments for
each instance of the modular input in its configuration files, feeding XML
on stdin to the modular input to do validation. It is called the same way
whenever a modular input's configuration is edited.
:param validation_definition: a ValidationDefinition object
"""
# Get the values of the parameters, and construct a URL for the Github API
owner = validation_definition.parameters["owner"]
repo_name = validation_definition.parameters["repo_name"]
repo_url = "https://api.github.com/repos/%s/%s" % (owner, repo_name)
# Read the response from the Github API, then parse the JSON data into an object
response = urllib2.urlopen(repo_url).read()
jsondata = json.loads(response)
# If there is only 1 field in the jsondata object,some kind or error occurred
# with the Github API.
# Typically, this will happen with an invalid repository.
if len(jsondata) == 1:
raise ValueError("The Github repository was not found.")
# If the API response seems normal, validate the fork count
# If there's something wrong with getting fork_count, raise a ValueError
try:
fork_count = int(jsondata["forks_count"])
except ValueError as ve:
raise ValueError("Invalid fork count: %s", ve.message) | python | def validate_input(self, validation_definition):
"""In this example we are using external validation to verify that the Github
repository exists. If validate_input does not raise an Exception, the input
is assumed to be valid. Otherwise it prints the exception as an error message
when telling splunkd that the configuration is invalid.
When using external validation, after splunkd calls the modular input with
--scheme to get a scheme, it calls it again with --validate-arguments for
each instance of the modular input in its configuration files, feeding XML
on stdin to the modular input to do validation. It is called the same way
whenever a modular input's configuration is edited.
:param validation_definition: a ValidationDefinition object
"""
# Get the values of the parameters, and construct a URL for the Github API
owner = validation_definition.parameters["owner"]
repo_name = validation_definition.parameters["repo_name"]
repo_url = "https://api.github.com/repos/%s/%s" % (owner, repo_name)
# Read the response from the Github API, then parse the JSON data into an object
response = urllib2.urlopen(repo_url).read()
jsondata = json.loads(response)
# If there is only 1 field in the jsondata object,some kind or error occurred
# with the Github API.
# Typically, this will happen with an invalid repository.
if len(jsondata) == 1:
raise ValueError("The Github repository was not found.")
# If the API response seems normal, validate the fork count
# If there's something wrong with getting fork_count, raise a ValueError
try:
fork_count = int(jsondata["forks_count"])
except ValueError as ve:
raise ValueError("Invalid fork count: %s", ve.message) | [
"def",
"validate_input",
"(",
"self",
",",
"validation_definition",
")",
":",
"# Get the values of the parameters, and construct a URL for the Github API",
"owner",
"=",
"validation_definition",
".",
"parameters",
"[",
"\"owner\"",
"]",
"repo_name",
"=",
"validation_definition"... | In this example we are using external validation to verify that the Github
repository exists. If validate_input does not raise an Exception, the input
is assumed to be valid. Otherwise it prints the exception as an error message
when telling splunkd that the configuration is invalid.
When using external validation, after splunkd calls the modular input with
--scheme to get a scheme, it calls it again with --validate-arguments for
each instance of the modular input in its configuration files, feeding XML
on stdin to the modular input to do validation. It is called the same way
whenever a modular input's configuration is edited.
:param validation_definition: a ValidationDefinition object | [
"In",
"this",
"example",
"we",
"are",
"using",
"external",
"validation",
"to",
"verify",
"that",
"the",
"Github",
"repository",
"exists",
".",
"If",
"validate_input",
"does",
"not",
"raise",
"an",
"Exception",
"the",
"input",
"is",
"assumed",
"to",
"be",
"va... | a245a4eeb93b3621730418008e31715912bcdcd8 | https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/examples/github_forks/github_forks.py#L73-L107 | train | 217,036 |
splunk/splunk-sdk-python | splunklib/searchcommands/internals.py | InputHeader.read | def read(self, ifile):
""" Reads an input header from an input file.
The input header is read as a sequence of *<name>***:***<value>* pairs separated by a newline. The end of the
input header is signalled by an empty line or an end-of-file.
:param ifile: File-like object that supports iteration over lines.
"""
name, value = None, None
for line in ifile:
if line == '\n':
break
item = line.split(':', 1)
if len(item) == 2:
# start of a new item
if name is not None:
self[name] = value[:-1] # value sans trailing newline
name, value = item[0], urllib.parse.unquote(item[1])
elif name is not None:
# continuation of the current item
value += urllib.parse.unquote(line)
if name is not None: self[name] = value[:-1] if value[-1] == '\n' else value | python | def read(self, ifile):
""" Reads an input header from an input file.
The input header is read as a sequence of *<name>***:***<value>* pairs separated by a newline. The end of the
input header is signalled by an empty line or an end-of-file.
:param ifile: File-like object that supports iteration over lines.
"""
name, value = None, None
for line in ifile:
if line == '\n':
break
item = line.split(':', 1)
if len(item) == 2:
# start of a new item
if name is not None:
self[name] = value[:-1] # value sans trailing newline
name, value = item[0], urllib.parse.unquote(item[1])
elif name is not None:
# continuation of the current item
value += urllib.parse.unquote(line)
if name is not None: self[name] = value[:-1] if value[-1] == '\n' else value | [
"def",
"read",
"(",
"self",
",",
"ifile",
")",
":",
"name",
",",
"value",
"=",
"None",
",",
"None",
"for",
"line",
"in",
"ifile",
":",
"if",
"line",
"==",
"'\\n'",
":",
"break",
"item",
"=",
"line",
".",
"split",
"(",
"':'",
",",
"1",
")",
"if"... | Reads an input header from an input file.
The input header is read as a sequence of *<name>***:***<value>* pairs separated by a newline. The end of the
input header is signalled by an empty line or an end-of-file.
:param ifile: File-like object that supports iteration over lines. | [
"Reads",
"an",
"input",
"header",
"from",
"an",
"input",
"file",
"."
] | a245a4eeb93b3621730418008e31715912bcdcd8 | https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/searchcommands/internals.py#L352-L376 | train | 217,037 |
splunk/splunk-sdk-python | splunklib/modularinput/input_definition.py | InputDefinition.parse | def parse(stream):
"""Parse a stream containing XML into an ``InputDefinition``.
:param stream: stream containing XML to parse.
:return: definition: an ``InputDefinition`` object.
"""
definition = InputDefinition()
# parse XML from the stream, then get the root node
root = ET.parse(stream).getroot()
for node in root:
if node.tag == "configuration":
# get config for each stanza
definition.inputs = parse_xml_data(node, "stanza")
else:
definition.metadata[node.tag] = node.text
return definition | python | def parse(stream):
"""Parse a stream containing XML into an ``InputDefinition``.
:param stream: stream containing XML to parse.
:return: definition: an ``InputDefinition`` object.
"""
definition = InputDefinition()
# parse XML from the stream, then get the root node
root = ET.parse(stream).getroot()
for node in root:
if node.tag == "configuration":
# get config for each stanza
definition.inputs = parse_xml_data(node, "stanza")
else:
definition.metadata[node.tag] = node.text
return definition | [
"def",
"parse",
"(",
"stream",
")",
":",
"definition",
"=",
"InputDefinition",
"(",
")",
"# parse XML from the stream, then get the root node",
"root",
"=",
"ET",
".",
"parse",
"(",
"stream",
")",
".",
"getroot",
"(",
")",
"for",
"node",
"in",
"root",
":",
"... | Parse a stream containing XML into an ``InputDefinition``.
:param stream: stream containing XML to parse.
:return: definition: an ``InputDefinition`` object. | [
"Parse",
"a",
"stream",
"containing",
"XML",
"into",
"an",
"InputDefinition",
"."
] | a245a4eeb93b3621730418008e31715912bcdcd8 | https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/modularinput/input_definition.py#L42-L60 | train | 217,038 |
splunk/splunk-sdk-python | splunklib/searchcommands/environment.py | configure_logging | def configure_logging(logger_name, filename=None):
""" Configure logging and return the named logger and the location of the logging configuration file loaded.
This function expects a Splunk app directory structure::
<app-root>
bin
...
default
...
local
...
This function looks for a logging configuration file at each of these locations, loading the first, if any,
logging configuration file that it finds::
local/{name}.logging.conf
default/{name}.logging.conf
local/logging.conf
default/logging.conf
The current working directory is set to *<app-root>* before the logging configuration file is loaded. Hence, paths
in the logging configuration file are relative to *<app-root>*. The current directory is reset before return.
You may short circuit the search for a logging configuration file by providing an alternative file location in
`path`. Logging configuration files must be in `ConfigParser format`_.
#Arguments:
:param logger_name: Logger name
:type logger_name: bytes, unicode
:param filename: Location of an alternative logging configuration file or `None`.
:type filename: bytes, unicode or NoneType
:returns: The named logger and the location of the logging configuration file loaded.
:rtype: tuple
.. _ConfigParser format: https://docs.python.org/2/library/logging.config.html#configuration-file-format
"""
if filename is None:
if logger_name is None:
probing_paths = [path.join('local', 'logging.conf'), path.join('default', 'logging.conf')]
else:
probing_paths = [
path.join('local', logger_name + '.logging.conf'),
path.join('default', logger_name + '.logging.conf'),
path.join('local', 'logging.conf'),
path.join('default', 'logging.conf')]
for relative_path in probing_paths:
configuration_file = path.join(app_root, relative_path)
if path.exists(configuration_file):
filename = configuration_file
break
elif not path.isabs(filename):
found = False
for conf in 'local', 'default':
configuration_file = path.join(app_root, conf, filename)
if path.exists(configuration_file):
filename = configuration_file
found = True
break
if not found:
raise ValueError('Logging configuration file "{}" not found in local or default directory'.format(filename))
elif not path.exists(filename):
raise ValueError('Logging configuration file "{}" not found'.format(filename))
if filename is not None:
global _current_logging_configuration_file
filename = path.realpath(filename)
if filename != _current_logging_configuration_file:
working_directory = getcwd()
chdir(app_root)
try:
fileConfig(filename, {'SPLUNK_HOME': splunk_home})
finally:
chdir(working_directory)
_current_logging_configuration_file = filename
if len(root.handlers) == 0:
root.addHandler(StreamHandler())
return None if logger_name is None else getLogger(logger_name), filename | python | def configure_logging(logger_name, filename=None):
""" Configure logging and return the named logger and the location of the logging configuration file loaded.
This function expects a Splunk app directory structure::
<app-root>
bin
...
default
...
local
...
This function looks for a logging configuration file at each of these locations, loading the first, if any,
logging configuration file that it finds::
local/{name}.logging.conf
default/{name}.logging.conf
local/logging.conf
default/logging.conf
The current working directory is set to *<app-root>* before the logging configuration file is loaded. Hence, paths
in the logging configuration file are relative to *<app-root>*. The current directory is reset before return.
You may short circuit the search for a logging configuration file by providing an alternative file location in
`path`. Logging configuration files must be in `ConfigParser format`_.
#Arguments:
:param logger_name: Logger name
:type logger_name: bytes, unicode
:param filename: Location of an alternative logging configuration file or `None`.
:type filename: bytes, unicode or NoneType
:returns: The named logger and the location of the logging configuration file loaded.
:rtype: tuple
.. _ConfigParser format: https://docs.python.org/2/library/logging.config.html#configuration-file-format
"""
if filename is None:
if logger_name is None:
probing_paths = [path.join('local', 'logging.conf'), path.join('default', 'logging.conf')]
else:
probing_paths = [
path.join('local', logger_name + '.logging.conf'),
path.join('default', logger_name + '.logging.conf'),
path.join('local', 'logging.conf'),
path.join('default', 'logging.conf')]
for relative_path in probing_paths:
configuration_file = path.join(app_root, relative_path)
if path.exists(configuration_file):
filename = configuration_file
break
elif not path.isabs(filename):
found = False
for conf in 'local', 'default':
configuration_file = path.join(app_root, conf, filename)
if path.exists(configuration_file):
filename = configuration_file
found = True
break
if not found:
raise ValueError('Logging configuration file "{}" not found in local or default directory'.format(filename))
elif not path.exists(filename):
raise ValueError('Logging configuration file "{}" not found'.format(filename))
if filename is not None:
global _current_logging_configuration_file
filename = path.realpath(filename)
if filename != _current_logging_configuration_file:
working_directory = getcwd()
chdir(app_root)
try:
fileConfig(filename, {'SPLUNK_HOME': splunk_home})
finally:
chdir(working_directory)
_current_logging_configuration_file = filename
if len(root.handlers) == 0:
root.addHandler(StreamHandler())
return None if logger_name is None else getLogger(logger_name), filename | [
"def",
"configure_logging",
"(",
"logger_name",
",",
"filename",
"=",
"None",
")",
":",
"if",
"filename",
"is",
"None",
":",
"if",
"logger_name",
"is",
"None",
":",
"probing_paths",
"=",
"[",
"path",
".",
"join",
"(",
"'local'",
",",
"'logging.conf'",
")",... | Configure logging and return the named logger and the location of the logging configuration file loaded.
This function expects a Splunk app directory structure::
<app-root>
bin
...
default
...
local
...
This function looks for a logging configuration file at each of these locations, loading the first, if any,
logging configuration file that it finds::
local/{name}.logging.conf
default/{name}.logging.conf
local/logging.conf
default/logging.conf
The current working directory is set to *<app-root>* before the logging configuration file is loaded. Hence, paths
in the logging configuration file are relative to *<app-root>*. The current directory is reset before return.
You may short circuit the search for a logging configuration file by providing an alternative file location in
`path`. Logging configuration files must be in `ConfigParser format`_.
#Arguments:
:param logger_name: Logger name
:type logger_name: bytes, unicode
:param filename: Location of an alternative logging configuration file or `None`.
:type filename: bytes, unicode or NoneType
:returns: The named logger and the location of the logging configuration file loaded.
:rtype: tuple
.. _ConfigParser format: https://docs.python.org/2/library/logging.config.html#configuration-file-format | [
"Configure",
"logging",
"and",
"return",
"the",
"named",
"logger",
"and",
"the",
"location",
"of",
"the",
"logging",
"configuration",
"file",
"loaded",
"."
] | a245a4eeb93b3621730418008e31715912bcdcd8 | https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/searchcommands/environment.py#L27-L111 | train | 217,039 |
kennethreitz/legit | legit/scm.py | SCMRepo.git_exec | def git_exec(self, command, **kwargs):
"""Execute git commands"""
from .cli import verbose_echo
command.insert(0, self.git)
if kwargs.pop('no_verbose', False): # used when git output isn't helpful to user
verbose = False
else:
verbose = self.verbose
verbose_echo(' '.join(command), verbose, self.fake)
if not self.fake:
result = self.repo.git.execute(command, **kwargs)
else:
if 'with_extended_output' in kwargs:
result = (0, '', '')
else:
result = ''
return result | python | def git_exec(self, command, **kwargs):
"""Execute git commands"""
from .cli import verbose_echo
command.insert(0, self.git)
if kwargs.pop('no_verbose', False): # used when git output isn't helpful to user
verbose = False
else:
verbose = self.verbose
verbose_echo(' '.join(command), verbose, self.fake)
if not self.fake:
result = self.repo.git.execute(command, **kwargs)
else:
if 'with_extended_output' in kwargs:
result = (0, '', '')
else:
result = ''
return result | [
"def",
"git_exec",
"(",
"self",
",",
"command",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
".",
"cli",
"import",
"verbose_echo",
"command",
".",
"insert",
"(",
"0",
",",
"self",
".",
"git",
")",
"if",
"kwargs",
".",
"pop",
"(",
"'no_verbose'",
",",
... | Execute git commands | [
"Execute",
"git",
"commands"
] | 699802c5be665bd358456a940953b5c1d8672754 | https://github.com/kennethreitz/legit/blob/699802c5be665bd358456a940953b5c1d8672754/legit/scm.py#L47-L65 | train | 217,040 |
kennethreitz/legit | legit/scm.py | SCMRepo.unstash_index | def unstash_index(self, sync=False, branch=None):
"""Returns an unstash index if one is available."""
stash_list = self.git_exec(['stash', 'list'], no_verbose=True)
if branch is None:
branch = self.get_current_branch_name()
for stash in stash_list.splitlines():
verb = 'syncing' if sync else 'switching'
if (
(('Legit' in stash) and
('On {0}:'.format(branch) in stash) and
(verb in stash)
) or
(('GitHub' in stash) and
('On {0}:'.format(branch) in stash) and
(verb in stash)
)
):
return stash[7] | python | def unstash_index(self, sync=False, branch=None):
"""Returns an unstash index if one is available."""
stash_list = self.git_exec(['stash', 'list'], no_verbose=True)
if branch is None:
branch = self.get_current_branch_name()
for stash in stash_list.splitlines():
verb = 'syncing' if sync else 'switching'
if (
(('Legit' in stash) and
('On {0}:'.format(branch) in stash) and
(verb in stash)
) or
(('GitHub' in stash) and
('On {0}:'.format(branch) in stash) and
(verb in stash)
)
):
return stash[7] | [
"def",
"unstash_index",
"(",
"self",
",",
"sync",
"=",
"False",
",",
"branch",
"=",
"None",
")",
":",
"stash_list",
"=",
"self",
".",
"git_exec",
"(",
"[",
"'stash'",
",",
"'list'",
"]",
",",
"no_verbose",
"=",
"True",
")",
"if",
"branch",
"is",
"Non... | Returns an unstash index if one is available. | [
"Returns",
"an",
"unstash",
"index",
"if",
"one",
"is",
"available",
"."
] | 699802c5be665bd358456a940953b5c1d8672754 | https://github.com/kennethreitz/legit/blob/699802c5be665bd358456a940953b5c1d8672754/legit/scm.py#L88-L110 | train | 217,041 |
kennethreitz/legit | legit/scm.py | SCMRepo.unstash_it | def unstash_it(self, sync=False):
"""
Unstashes changes from current branch for branch sync.
Requires prior code setting self.stash_index.
"""
if self.stash_index is not None:
return self.git_exec(
['stash', 'pop', 'stash@{{{0}}}'.format(self.stash_index)]) | python | def unstash_it(self, sync=False):
"""
Unstashes changes from current branch for branch sync.
Requires prior code setting self.stash_index.
"""
if self.stash_index is not None:
return self.git_exec(
['stash', 'pop', 'stash@{{{0}}}'.format(self.stash_index)]) | [
"def",
"unstash_it",
"(",
"self",
",",
"sync",
"=",
"False",
")",
":",
"if",
"self",
".",
"stash_index",
"is",
"not",
"None",
":",
"return",
"self",
".",
"git_exec",
"(",
"[",
"'stash'",
",",
"'pop'",
",",
"'stash@{{{0}}}'",
".",
"format",
"(",
"self",... | Unstashes changes from current branch for branch sync.
Requires prior code setting self.stash_index. | [
"Unstashes",
"changes",
"from",
"current",
"branch",
"for",
"branch",
"sync",
".",
"Requires",
"prior",
"code",
"setting",
"self",
".",
"stash_index",
"."
] | 699802c5be665bd358456a940953b5c1d8672754 | https://github.com/kennethreitz/legit/blob/699802c5be665bd358456a940953b5c1d8672754/legit/scm.py#L118-L125 | train | 217,042 |
kennethreitz/legit | legit/scm.py | SCMRepo.checkout_branch | def checkout_branch(self, branch):
"""Checks out given branch."""
_, stdout, stderr = self.git_exec(
['checkout', branch],
with_extended_output=True)
return '\n'.join([stderr, stdout]) | python | def checkout_branch(self, branch):
"""Checks out given branch."""
_, stdout, stderr = self.git_exec(
['checkout', branch],
with_extended_output=True)
return '\n'.join([stderr, stdout]) | [
"def",
"checkout_branch",
"(",
"self",
",",
"branch",
")",
":",
"_",
",",
"stdout",
",",
"stderr",
"=",
"self",
".",
"git_exec",
"(",
"[",
"'checkout'",
",",
"branch",
"]",
",",
"with_extended_output",
"=",
"True",
")",
"return",
"'\\n'",
".",
"join",
... | Checks out given branch. | [
"Checks",
"out",
"given",
"branch",
"."
] | 699802c5be665bd358456a940953b5c1d8672754 | https://github.com/kennethreitz/legit/blob/699802c5be665bd358456a940953b5c1d8672754/legit/scm.py#L194-L200 | train | 217,043 |
kennethreitz/legit | legit/scm.py | SCMRepo.unpublish_branch | def unpublish_branch(self, branch):
"""Unpublishes given branch."""
try:
return self.git_exec(
['push', self.remote.name, ':{0}'.format(branch)])
except GitCommandError:
_, _, log = self.git_exec(
['fetch', self.remote.name, '--prune'],
with_extended_output=True)
abort('Unpublish failed. Fetching.', log=log, type='unpublish') | python | def unpublish_branch(self, branch):
"""Unpublishes given branch."""
try:
return self.git_exec(
['push', self.remote.name, ':{0}'.format(branch)])
except GitCommandError:
_, _, log = self.git_exec(
['fetch', self.remote.name, '--prune'],
with_extended_output=True)
abort('Unpublish failed. Fetching.', log=log, type='unpublish') | [
"def",
"unpublish_branch",
"(",
"self",
",",
"branch",
")",
":",
"try",
":",
"return",
"self",
".",
"git_exec",
"(",
"[",
"'push'",
",",
"self",
".",
"remote",
".",
"name",
",",
"':{0}'",
".",
"format",
"(",
"branch",
")",
"]",
")",
"except",
"GitCom... | Unpublishes given branch. | [
"Unpublishes",
"given",
"branch",
"."
] | 699802c5be665bd358456a940953b5c1d8672754 | https://github.com/kennethreitz/legit/blob/699802c5be665bd358456a940953b5c1d8672754/legit/scm.py#L202-L212 | train | 217,044 |
kennethreitz/legit | legit/scm.py | SCMRepo.undo | def undo(self, hard=False):
"""Makes last commit not exist"""
if not self.fake:
return self.repo.git.reset('HEAD^', working_tree=hard)
else:
click.echo(crayons.red('Faked! >>> git reset {}{}'
.format('--hard ' if hard else '', 'HEAD^')))
return 0 | python | def undo(self, hard=False):
"""Makes last commit not exist"""
if not self.fake:
return self.repo.git.reset('HEAD^', working_tree=hard)
else:
click.echo(crayons.red('Faked! >>> git reset {}{}'
.format('--hard ' if hard else '', 'HEAD^')))
return 0 | [
"def",
"undo",
"(",
"self",
",",
"hard",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"fake",
":",
"return",
"self",
".",
"repo",
".",
"git",
".",
"reset",
"(",
"'HEAD^'",
",",
"working_tree",
"=",
"hard",
")",
"else",
":",
"click",
".",
"ec... | Makes last commit not exist | [
"Makes",
"last",
"commit",
"not",
"exist"
] | 699802c5be665bd358456a940953b5c1d8672754 | https://github.com/kennethreitz/legit/blob/699802c5be665bd358456a940953b5c1d8672754/legit/scm.py#L220-L228 | train | 217,045 |
kennethreitz/legit | legit/scm.py | SCMRepo.get_branches | def get_branches(self, local=True, remote_branches=True):
"""Returns a list of local and remote branches."""
if not self.repo.remotes:
remote_branches = False
branches = []
if remote_branches:
# Remote refs.
try:
for b in self.remote.refs:
name = '/'.join(b.name.split('/')[1:])
if name not in legit_settings.forbidden_branches:
branches.append(Branch(name, is_published=True))
except (IndexError, AssertionError):
pass
if local:
# Local refs.
for b in [h.name for h in self.repo.heads]:
if (not remote_branches) or (b not in [br.name for br in branches]):
if b not in legit_settings.forbidden_branches:
branches.append(Branch(b, is_published=False))
return sorted(branches, key=attrgetter('name')) | python | def get_branches(self, local=True, remote_branches=True):
"""Returns a list of local and remote branches."""
if not self.repo.remotes:
remote_branches = False
branches = []
if remote_branches:
# Remote refs.
try:
for b in self.remote.refs:
name = '/'.join(b.name.split('/')[1:])
if name not in legit_settings.forbidden_branches:
branches.append(Branch(name, is_published=True))
except (IndexError, AssertionError):
pass
if local:
# Local refs.
for b in [h.name for h in self.repo.heads]:
if (not remote_branches) or (b not in [br.name for br in branches]):
if b not in legit_settings.forbidden_branches:
branches.append(Branch(b, is_published=False))
return sorted(branches, key=attrgetter('name')) | [
"def",
"get_branches",
"(",
"self",
",",
"local",
"=",
"True",
",",
"remote_branches",
"=",
"True",
")",
":",
"if",
"not",
"self",
".",
"repo",
".",
"remotes",
":",
"remote_branches",
"=",
"False",
"branches",
"=",
"[",
"]",
"if",
"remote_branches",
":",... | Returns a list of local and remote branches. | [
"Returns",
"a",
"list",
"of",
"local",
"and",
"remote",
"branches",
"."
] | 699802c5be665bd358456a940953b5c1d8672754 | https://github.com/kennethreitz/legit/blob/699802c5be665bd358456a940953b5c1d8672754/legit/scm.py#L289-L318 | train | 217,046 |
kennethreitz/legit | legit/scm.py | SCMRepo.display_available_branches | def display_available_branches(self):
"""Displays available branches."""
if not self.repo.remotes:
remote_branches = False
else:
remote_branches = True
branches = self.get_branches(local=True, remote_branches=remote_branches)
if not branches:
click.echo(crayons.red('No branches available'))
return
branch_col = len(max([b.name for b in branches], key=len)) + 1
for branch in branches:
try:
branch_is_selected = (branch.name == self.get_current_branch_name())
except TypeError:
branch_is_selected = False
marker = '*' if branch_is_selected else ' '
color = colored.green if branch_is_selected else colored.yellow
pub = '(published)' if branch.is_published else '(unpublished)'
click.echo(columns(
[colored.red(marker), 2],
[color(branch.name, bold=True), branch_col],
[black(pub), 14]
)) | python | def display_available_branches(self):
"""Displays available branches."""
if not self.repo.remotes:
remote_branches = False
else:
remote_branches = True
branches = self.get_branches(local=True, remote_branches=remote_branches)
if not branches:
click.echo(crayons.red('No branches available'))
return
branch_col = len(max([b.name for b in branches], key=len)) + 1
for branch in branches:
try:
branch_is_selected = (branch.name == self.get_current_branch_name())
except TypeError:
branch_is_selected = False
marker = '*' if branch_is_selected else ' '
color = colored.green if branch_is_selected else colored.yellow
pub = '(published)' if branch.is_published else '(unpublished)'
click.echo(columns(
[colored.red(marker), 2],
[color(branch.name, bold=True), branch_col],
[black(pub), 14]
)) | [
"def",
"display_available_branches",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"repo",
".",
"remotes",
":",
"remote_branches",
"=",
"False",
"else",
":",
"remote_branches",
"=",
"True",
"branches",
"=",
"self",
".",
"get_branches",
"(",
"local",
"=",
... | Displays available branches. | [
"Displays",
"available",
"branches",
"."
] | 699802c5be665bd358456a940953b5c1d8672754 | https://github.com/kennethreitz/legit/blob/699802c5be665bd358456a940953b5c1d8672754/legit/scm.py#L326-L356 | train | 217,047 |
kennethreitz/legit | legit/utils.py | status_log | def status_log(func, message, *args, **kwargs):
"""Emits header message, executes a callable, and echoes the return strings."""
click.echo(message)
log = func(*args, **kwargs)
if log:
out = []
for line in log.split('\n'):
if not line.startswith('#'):
out.append(line)
click.echo(black('\n'.join(out))) | python | def status_log(func, message, *args, **kwargs):
"""Emits header message, executes a callable, and echoes the return strings."""
click.echo(message)
log = func(*args, **kwargs)
if log:
out = []
for line in log.split('\n'):
if not line.startswith('#'):
out.append(line)
click.echo(black('\n'.join(out))) | [
"def",
"status_log",
"(",
"func",
",",
"message",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"click",
".",
"echo",
"(",
"message",
")",
"log",
"=",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"log",
":",
"out",
"=",
... | Emits header message, executes a callable, and echoes the return strings. | [
"Emits",
"header",
"message",
"executes",
"a",
"callable",
"and",
"echoes",
"the",
"return",
"strings",
"."
] | 699802c5be665bd358456a940953b5c1d8672754 | https://github.com/kennethreitz/legit/blob/699802c5be665bd358456a940953b5c1d8672754/legit/utils.py#L8-L20 | train | 217,048 |
kennethreitz/legit | legit/utils.py | verbose_echo | def verbose_echo(str, verbose=False, fake=False):
"""Selectively output ``str``, with special formatting if ``fake`` is True"""
verbose = fake or verbose
if verbose:
color = crayons.green
prefix = ''
if fake:
color = crayons.red
prefix = 'Faked!'
click.echo(color('{} >>> {}'.format(prefix, str))) | python | def verbose_echo(str, verbose=False, fake=False):
"""Selectively output ``str``, with special formatting if ``fake`` is True"""
verbose = fake or verbose
if verbose:
color = crayons.green
prefix = ''
if fake:
color = crayons.red
prefix = 'Faked!'
click.echo(color('{} >>> {}'.format(prefix, str))) | [
"def",
"verbose_echo",
"(",
"str",
",",
"verbose",
"=",
"False",
",",
"fake",
"=",
"False",
")",
":",
"verbose",
"=",
"fake",
"or",
"verbose",
"if",
"verbose",
":",
"color",
"=",
"crayons",
".",
"green",
"prefix",
"=",
"''",
"if",
"fake",
":",
"color... | Selectively output ``str``, with special formatting if ``fake`` is True | [
"Selectively",
"output",
"str",
"with",
"special",
"formatting",
"if",
"fake",
"is",
"True"
] | 699802c5be665bd358456a940953b5c1d8672754 | https://github.com/kennethreitz/legit/blob/699802c5be665bd358456a940953b5c1d8672754/legit/utils.py#L23-L33 | train | 217,049 |
kennethreitz/legit | legit/utils.py | output_aliases | def output_aliases(aliases):
"""Display git aliases"""
for alias in aliases:
cmd = '!legit ' + alias
click.echo(columns([colored.yellow('git ' + alias), 20], [cmd, None])) | python | def output_aliases(aliases):
"""Display git aliases"""
for alias in aliases:
cmd = '!legit ' + alias
click.echo(columns([colored.yellow('git ' + alias), 20], [cmd, None])) | [
"def",
"output_aliases",
"(",
"aliases",
")",
":",
"for",
"alias",
"in",
"aliases",
":",
"cmd",
"=",
"'!legit '",
"+",
"alias",
"click",
".",
"echo",
"(",
"columns",
"(",
"[",
"colored",
".",
"yellow",
"(",
"'git '",
"+",
"alias",
")",
",",
"20",
"]"... | Display git aliases | [
"Display",
"git",
"aliases"
] | 699802c5be665bd358456a940953b5c1d8672754 | https://github.com/kennethreitz/legit/blob/699802c5be665bd358456a940953b5c1d8672754/legit/utils.py#L36-L40 | train | 217,050 |
kennethreitz/legit | legit/cli.py | cli | def cli(ctx, verbose, fake, install, uninstall, config):
"""legit command line interface"""
# Create a repo object and remember it as as the context object. From
# this point onwards other commands can refer to it by using the
# @pass_scm decorator.
ctx.obj = SCMRepo()
ctx.obj.fake = fake
ctx.obj.verbose = fake or verbose
if install:
do_install(ctx, verbose, fake)
ctx.exit()
elif uninstall:
do_uninstall(ctx, verbose, fake)
ctx.exit()
elif config:
do_edit_settings(fake)
ctx.exit()
else:
if ctx.invoked_subcommand is None:
# Display help to user if no commands were passed.
click.echo(format_help(ctx.get_help())) | python | def cli(ctx, verbose, fake, install, uninstall, config):
"""legit command line interface"""
# Create a repo object and remember it as as the context object. From
# this point onwards other commands can refer to it by using the
# @pass_scm decorator.
ctx.obj = SCMRepo()
ctx.obj.fake = fake
ctx.obj.verbose = fake or verbose
if install:
do_install(ctx, verbose, fake)
ctx.exit()
elif uninstall:
do_uninstall(ctx, verbose, fake)
ctx.exit()
elif config:
do_edit_settings(fake)
ctx.exit()
else:
if ctx.invoked_subcommand is None:
# Display help to user if no commands were passed.
click.echo(format_help(ctx.get_help())) | [
"def",
"cli",
"(",
"ctx",
",",
"verbose",
",",
"fake",
",",
"install",
",",
"uninstall",
",",
"config",
")",
":",
"# Create a repo object and remember it as as the context object. From",
"# this point onwards other commands can refer to it by using the",
"# @pass_scm decorator."... | legit command line interface | [
"legit",
"command",
"line",
"interface"
] | 699802c5be665bd358456a940953b5c1d8672754 | https://github.com/kennethreitz/legit/blob/699802c5be665bd358456a940953b5c1d8672754/legit/cli.py#L82-L103 | train | 217,051 |
kennethreitz/legit | legit/cli.py | switch | def switch(scm, to_branch, verbose, fake):
"""Switches from one branch to another, safely stashing and restoring local changes.
"""
scm.fake = fake
scm.verbose = fake or verbose
scm.repo_check()
if to_branch is None:
scm.display_available_branches()
raise click.BadArgumentUsage('Please specify a branch to switch to')
scm.stash_log()
status_log(scm.checkout_branch, 'Switching to {0}.'.format(
crayons.yellow(to_branch)), to_branch)
scm.unstash_log() | python | def switch(scm, to_branch, verbose, fake):
"""Switches from one branch to another, safely stashing and restoring local changes.
"""
scm.fake = fake
scm.verbose = fake or verbose
scm.repo_check()
if to_branch is None:
scm.display_available_branches()
raise click.BadArgumentUsage('Please specify a branch to switch to')
scm.stash_log()
status_log(scm.checkout_branch, 'Switching to {0}.'.format(
crayons.yellow(to_branch)), to_branch)
scm.unstash_log() | [
"def",
"switch",
"(",
"scm",
",",
"to_branch",
",",
"verbose",
",",
"fake",
")",
":",
"scm",
".",
"fake",
"=",
"fake",
"scm",
".",
"verbose",
"=",
"fake",
"or",
"verbose",
"scm",
".",
"repo_check",
"(",
")",
"if",
"to_branch",
"is",
"None",
":",
"s... | Switches from one branch to another, safely stashing and restoring local changes. | [
"Switches",
"from",
"one",
"branch",
"to",
"another",
"safely",
"stashing",
"and",
"restoring",
"local",
"changes",
"."
] | 699802c5be665bd358456a940953b5c1d8672754 | https://github.com/kennethreitz/legit/blob/699802c5be665bd358456a940953b5c1d8672754/legit/cli.py#L111-L126 | train | 217,052 |
kennethreitz/legit | legit/cli.py | sync | def sync(ctx, scm, to_branch, verbose, fake):
"""Stashes unstaged changes, Fetches remote data, Performs smart
pull+merge, Pushes local commits up, and Unstashes changes.
Defaults to current branch.
"""
scm.fake = fake
scm.verbose = fake or verbose
scm.repo_check(require_remote=True)
if to_branch:
# Optional branch specifier.
branch = scm.fuzzy_match_branch(to_branch)
if branch:
is_external = True
original_branch = scm.get_current_branch_name()
else:
raise click.BadArgumentUsage(
"Branch {0} does not exist. Use an existing branch."
.format(crayons.yellow(branch)))
else:
# Sync current branch.
branch = scm.get_current_branch_name()
is_external = False
if branch in scm.get_branch_names(local=False):
if is_external:
ctx.invoke(switch, to_branch=branch, verbose=verbose, fake=fake)
scm.stash_log(sync=True)
status_log(scm.smart_pull, 'Pulling commits from the server.')
status_log(scm.push, 'Pushing commits to the server.', branch)
scm.unstash_log(sync=True)
if is_external:
ctx.invoke(switch, to_branch=original_branch, verbose=verbose, fake=fake)
else:
raise click.BadArgumentUsage(
"Branch {0} is not published. Publish before syncing."
.format(crayons.yellow(branch))) | python | def sync(ctx, scm, to_branch, verbose, fake):
"""Stashes unstaged changes, Fetches remote data, Performs smart
pull+merge, Pushes local commits up, and Unstashes changes.
Defaults to current branch.
"""
scm.fake = fake
scm.verbose = fake or verbose
scm.repo_check(require_remote=True)
if to_branch:
# Optional branch specifier.
branch = scm.fuzzy_match_branch(to_branch)
if branch:
is_external = True
original_branch = scm.get_current_branch_name()
else:
raise click.BadArgumentUsage(
"Branch {0} does not exist. Use an existing branch."
.format(crayons.yellow(branch)))
else:
# Sync current branch.
branch = scm.get_current_branch_name()
is_external = False
if branch in scm.get_branch_names(local=False):
if is_external:
ctx.invoke(switch, to_branch=branch, verbose=verbose, fake=fake)
scm.stash_log(sync=True)
status_log(scm.smart_pull, 'Pulling commits from the server.')
status_log(scm.push, 'Pushing commits to the server.', branch)
scm.unstash_log(sync=True)
if is_external:
ctx.invoke(switch, to_branch=original_branch, verbose=verbose, fake=fake)
else:
raise click.BadArgumentUsage(
"Branch {0} is not published. Publish before syncing."
.format(crayons.yellow(branch))) | [
"def",
"sync",
"(",
"ctx",
",",
"scm",
",",
"to_branch",
",",
"verbose",
",",
"fake",
")",
":",
"scm",
".",
"fake",
"=",
"fake",
"scm",
".",
"verbose",
"=",
"fake",
"or",
"verbose",
"scm",
".",
"repo_check",
"(",
"require_remote",
"=",
"True",
")",
... | Stashes unstaged changes, Fetches remote data, Performs smart
pull+merge, Pushes local commits up, and Unstashes changes.
Defaults to current branch. | [
"Stashes",
"unstaged",
"changes",
"Fetches",
"remote",
"data",
"Performs",
"smart",
"pull",
"+",
"merge",
"Pushes",
"local",
"commits",
"up",
"and",
"Unstashes",
"changes",
"."
] | 699802c5be665bd358456a940953b5c1d8672754 | https://github.com/kennethreitz/legit/blob/699802c5be665bd358456a940953b5c1d8672754/legit/cli.py#L135-L173 | train | 217,053 |
kennethreitz/legit | legit/cli.py | publish | def publish(scm, to_branch, verbose, fake):
"""Pushes an unpublished branch to a remote repository."""
scm.fake = fake
scm.verbose = fake or verbose
scm.repo_check(require_remote=True)
branch = scm.fuzzy_match_branch(to_branch)
if not branch:
branch = scm.get_current_branch_name()
scm.display_available_branches()
if to_branch is None:
click.echo("Using current branch {0}".format(crayons.yellow(branch)))
else:
click.echo(
"Branch {0} not found, using current branch {1}"
.format(crayons.red(to_branch), crayons.yellow(branch)))
branch_names = scm.get_branch_names(local=False)
if branch in branch_names:
raise click.BadArgumentUsage(
"Branch {0} is already published. Use a branch that is not published."
.format(crayons.yellow(branch)))
status_log(scm.publish_branch, 'Publishing {0}.'.format(
crayons.yellow(branch)), branch) | python | def publish(scm, to_branch, verbose, fake):
"""Pushes an unpublished branch to a remote repository."""
scm.fake = fake
scm.verbose = fake or verbose
scm.repo_check(require_remote=True)
branch = scm.fuzzy_match_branch(to_branch)
if not branch:
branch = scm.get_current_branch_name()
scm.display_available_branches()
if to_branch is None:
click.echo("Using current branch {0}".format(crayons.yellow(branch)))
else:
click.echo(
"Branch {0} not found, using current branch {1}"
.format(crayons.red(to_branch), crayons.yellow(branch)))
branch_names = scm.get_branch_names(local=False)
if branch in branch_names:
raise click.BadArgumentUsage(
"Branch {0} is already published. Use a branch that is not published."
.format(crayons.yellow(branch)))
status_log(scm.publish_branch, 'Publishing {0}.'.format(
crayons.yellow(branch)), branch) | [
"def",
"publish",
"(",
"scm",
",",
"to_branch",
",",
"verbose",
",",
"fake",
")",
":",
"scm",
".",
"fake",
"=",
"fake",
"scm",
".",
"verbose",
"=",
"fake",
"or",
"verbose",
"scm",
".",
"repo_check",
"(",
"require_remote",
"=",
"True",
")",
"branch",
... | Pushes an unpublished branch to a remote repository. | [
"Pushes",
"an",
"unpublished",
"branch",
"to",
"a",
"remote",
"repository",
"."
] | 699802c5be665bd358456a940953b5c1d8672754 | https://github.com/kennethreitz/legit/blob/699802c5be665bd358456a940953b5c1d8672754/legit/cli.py#L181-L207 | train | 217,054 |
kennethreitz/legit | legit/cli.py | unpublish | def unpublish(scm, published_branch, verbose, fake):
"""Removes a published branch from the remote repository."""
scm.fake = fake
scm.verbose = fake or verbose
scm.repo_check(require_remote=True)
branch = scm.fuzzy_match_branch(published_branch)
if not branch:
scm.display_available_branches()
raise click.BadArgumentUsage('Please specify a branch to unpublish')
branch_names = scm.get_branch_names(local=False)
if branch not in branch_names:
raise click.BadArgumentUsage(
"Branch {0} is not published. Use a branch that is published."
.format(crayons.yellow(branch)))
status_log(scm.unpublish_branch, 'Unpublishing {0}.'.format(
crayons.yellow(branch)), branch) | python | def unpublish(scm, published_branch, verbose, fake):
"""Removes a published branch from the remote repository."""
scm.fake = fake
scm.verbose = fake or verbose
scm.repo_check(require_remote=True)
branch = scm.fuzzy_match_branch(published_branch)
if not branch:
scm.display_available_branches()
raise click.BadArgumentUsage('Please specify a branch to unpublish')
branch_names = scm.get_branch_names(local=False)
if branch not in branch_names:
raise click.BadArgumentUsage(
"Branch {0} is not published. Use a branch that is published."
.format(crayons.yellow(branch)))
status_log(scm.unpublish_branch, 'Unpublishing {0}.'.format(
crayons.yellow(branch)), branch) | [
"def",
"unpublish",
"(",
"scm",
",",
"published_branch",
",",
"verbose",
",",
"fake",
")",
":",
"scm",
".",
"fake",
"=",
"fake",
"scm",
".",
"verbose",
"=",
"fake",
"or",
"verbose",
"scm",
".",
"repo_check",
"(",
"require_remote",
"=",
"True",
")",
"br... | Removes a published branch from the remote repository. | [
"Removes",
"a",
"published",
"branch",
"from",
"the",
"remote",
"repository",
"."
] | 699802c5be665bd358456a940953b5c1d8672754 | https://github.com/kennethreitz/legit/blob/699802c5be665bd358456a940953b5c1d8672754/legit/cli.py#L215-L235 | train | 217,055 |
kennethreitz/legit | legit/cli.py | undo | def undo(scm, verbose, fake, hard):
"""Removes the last commit from history."""
scm.fake = fake
scm.verbose = fake or verbose
scm.repo_check()
status_log(scm.undo, 'Last commit removed from history.', hard) | python | def undo(scm, verbose, fake, hard):
"""Removes the last commit from history."""
scm.fake = fake
scm.verbose = fake or verbose
scm.repo_check()
status_log(scm.undo, 'Last commit removed from history.', hard) | [
"def",
"undo",
"(",
"scm",
",",
"verbose",
",",
"fake",
",",
"hard",
")",
":",
"scm",
".",
"fake",
"=",
"fake",
"scm",
".",
"verbose",
"=",
"fake",
"or",
"verbose",
"scm",
".",
"repo_check",
"(",
")",
"status_log",
"(",
"scm",
".",
"undo",
",",
"... | Removes the last commit from history. | [
"Removes",
"the",
"last",
"commit",
"from",
"history",
"."
] | 699802c5be665bd358456a940953b5c1d8672754 | https://github.com/kennethreitz/legit/blob/699802c5be665bd358456a940953b5c1d8672754/legit/cli.py#L243-L250 | train | 217,056 |
kennethreitz/legit | legit/cli.py | do_install | def do_install(ctx, verbose, fake):
"""Installs legit git aliases."""
click.echo('The following git aliases will be installed:\n')
aliases = cli.list_commands(ctx)
output_aliases(aliases)
if click.confirm('\n{}Install aliases above?'.format('FAKE ' if fake else ''), default=fake):
for alias in aliases:
cmd = '!legit ' + alias
system_command = 'git config --global --replace-all alias.{0} "{1}"'.format(alias, cmd)
verbose_echo(system_command, verbose, fake)
if not fake:
os.system(system_command)
if not fake:
click.echo("\nAliases installed.")
else:
click.echo("\nAliases will not be installed.") | python | def do_install(ctx, verbose, fake):
"""Installs legit git aliases."""
click.echo('The following git aliases will be installed:\n')
aliases = cli.list_commands(ctx)
output_aliases(aliases)
if click.confirm('\n{}Install aliases above?'.format('FAKE ' if fake else ''), default=fake):
for alias in aliases:
cmd = '!legit ' + alias
system_command = 'git config --global --replace-all alias.{0} "{1}"'.format(alias, cmd)
verbose_echo(system_command, verbose, fake)
if not fake:
os.system(system_command)
if not fake:
click.echo("\nAliases installed.")
else:
click.echo("\nAliases will not be installed.") | [
"def",
"do_install",
"(",
"ctx",
",",
"verbose",
",",
"fake",
")",
":",
"click",
".",
"echo",
"(",
"'The following git aliases will be installed:\\n'",
")",
"aliases",
"=",
"cli",
".",
"list_commands",
"(",
"ctx",
")",
"output_aliases",
"(",
"aliases",
")",
"i... | Installs legit git aliases. | [
"Installs",
"legit",
"git",
"aliases",
"."
] | 699802c5be665bd358456a940953b5c1d8672754 | https://github.com/kennethreitz/legit/blob/699802c5be665bd358456a940953b5c1d8672754/legit/cli.py#L262-L278 | train | 217,057 |
kennethreitz/legit | legit/cli.py | do_uninstall | def do_uninstall(ctx, verbose, fake):
"""Uninstalls legit git aliases, including deprecated legit sub-commands."""
aliases = cli.list_commands(ctx)
# Add deprecated aliases
aliases.extend(['graft', 'harvest', 'sprout', 'resync', 'settings', 'install', 'uninstall'])
for alias in aliases:
system_command = 'git config --global --unset-all alias.{0}'.format(alias)
verbose_echo(system_command, verbose, fake)
if not fake:
os.system(system_command)
if not fake:
click.echo('\nThe following git aliases are uninstalled:\n')
output_aliases(aliases) | python | def do_uninstall(ctx, verbose, fake):
"""Uninstalls legit git aliases, including deprecated legit sub-commands."""
aliases = cli.list_commands(ctx)
# Add deprecated aliases
aliases.extend(['graft', 'harvest', 'sprout', 'resync', 'settings', 'install', 'uninstall'])
for alias in aliases:
system_command = 'git config --global --unset-all alias.{0}'.format(alias)
verbose_echo(system_command, verbose, fake)
if not fake:
os.system(system_command)
if not fake:
click.echo('\nThe following git aliases are uninstalled:\n')
output_aliases(aliases) | [
"def",
"do_uninstall",
"(",
"ctx",
",",
"verbose",
",",
"fake",
")",
":",
"aliases",
"=",
"cli",
".",
"list_commands",
"(",
"ctx",
")",
"# Add deprecated aliases",
"aliases",
".",
"extend",
"(",
"[",
"'graft'",
",",
"'harvest'",
",",
"'sprout'",
",",
"'res... | Uninstalls legit git aliases, including deprecated legit sub-commands. | [
"Uninstalls",
"legit",
"git",
"aliases",
"including",
"deprecated",
"legit",
"sub",
"-",
"commands",
"."
] | 699802c5be665bd358456a940953b5c1d8672754 | https://github.com/kennethreitz/legit/blob/699802c5be665bd358456a940953b5c1d8672754/legit/cli.py#L281-L293 | train | 217,058 |
kennethreitz/legit | legit/cli.py | do_edit_settings | def do_edit_settings(fake):
"""Opens legit settings in editor."""
path = resources.user.open('config.ini').name
click.echo('Legit Settings:\n')
for (option, _, description) in legit_settings.config_defaults:
click.echo(columns([crayons.yellow(option), 25], [description, None]))
click.echo("") # separate settings info from os output
if fake:
click.echo(crayons.red('Faked! >>> edit {}'.format(path)))
else:
click.edit(path) | python | def do_edit_settings(fake):
"""Opens legit settings in editor."""
path = resources.user.open('config.ini').name
click.echo('Legit Settings:\n')
for (option, _, description) in legit_settings.config_defaults:
click.echo(columns([crayons.yellow(option), 25], [description, None]))
click.echo("") # separate settings info from os output
if fake:
click.echo(crayons.red('Faked! >>> edit {}'.format(path)))
else:
click.edit(path) | [
"def",
"do_edit_settings",
"(",
"fake",
")",
":",
"path",
"=",
"resources",
".",
"user",
".",
"open",
"(",
"'config.ini'",
")",
".",
"name",
"click",
".",
"echo",
"(",
"'Legit Settings:\\n'",
")",
"for",
"(",
"option",
",",
"_",
",",
"description",
")",
... | Opens legit settings in editor. | [
"Opens",
"legit",
"settings",
"in",
"editor",
"."
] | 699802c5be665bd358456a940953b5c1d8672754 | https://github.com/kennethreitz/legit/blob/699802c5be665bd358456a940953b5c1d8672754/legit/cli.py#L296-L310 | train | 217,059 |
kennethreitz/legit | legit/cli.py | LegitGroup.get_command | def get_command(self, ctx, cmd_name):
"""Override to handle command aliases"""
rv = click.Group.get_command(self, ctx, cmd_name)
if rv is not None:
return rv
cmd_name = self.command_aliases.get(cmd_name, "")
return click.Group.get_command(self, ctx, cmd_name) | python | def get_command(self, ctx, cmd_name):
"""Override to handle command aliases"""
rv = click.Group.get_command(self, ctx, cmd_name)
if rv is not None:
return rv
cmd_name = self.command_aliases.get(cmd_name, "")
return click.Group.get_command(self, ctx, cmd_name) | [
"def",
"get_command",
"(",
"self",
",",
"ctx",
",",
"cmd_name",
")",
":",
"rv",
"=",
"click",
".",
"Group",
".",
"get_command",
"(",
"self",
",",
"ctx",
",",
"cmd_name",
")",
"if",
"rv",
"is",
"not",
"None",
":",
"return",
"rv",
"cmd_name",
"=",
"s... | Override to handle command aliases | [
"Override",
"to",
"handle",
"command",
"aliases"
] | 699802c5be665bd358456a940953b5c1d8672754 | https://github.com/kennethreitz/legit/blob/699802c5be665bd358456a940953b5c1d8672754/legit/cli.py#L42-L48 | train | 217,060 |
nschloe/meshio | meshio/cli.py | _get_parser | def _get_parser():
"""Parse input options."""
import argparse
parser = argparse.ArgumentParser(description=("Convert between mesh formats."))
parser.add_argument("infile", type=str, help="mesh file to be read from")
parser.add_argument(
"--input-format",
"-i",
type=str,
choices=input_filetypes,
help="input file format",
default=None,
)
parser.add_argument(
"--output-format",
"-o",
type=str,
choices=output_filetypes,
help="output file format",
default=None,
)
parser.add_argument("outfile", type=str, help="mesh file to be written to")
parser.add_argument(
"--prune",
"-p",
action="store_true",
help="remove lower order cells, remove orphaned nodes",
)
parser.add_argument(
"--prune-z-0",
"-z",
action="store_true",
help="remove third (z) dimension if all points are 0",
)
parser.add_argument(
"--version",
"-v",
action="version",
version="%(prog)s {}, Python {}".format(__version__, sys.version),
help="display version information",
)
return parser | python | def _get_parser():
"""Parse input options."""
import argparse
parser = argparse.ArgumentParser(description=("Convert between mesh formats."))
parser.add_argument("infile", type=str, help="mesh file to be read from")
parser.add_argument(
"--input-format",
"-i",
type=str,
choices=input_filetypes,
help="input file format",
default=None,
)
parser.add_argument(
"--output-format",
"-o",
type=str,
choices=output_filetypes,
help="output file format",
default=None,
)
parser.add_argument("outfile", type=str, help="mesh file to be written to")
parser.add_argument(
"--prune",
"-p",
action="store_true",
help="remove lower order cells, remove orphaned nodes",
)
parser.add_argument(
"--prune-z-0",
"-z",
action="store_true",
help="remove third (z) dimension if all points are 0",
)
parser.add_argument(
"--version",
"-v",
action="version",
version="%(prog)s {}, Python {}".format(__version__, sys.version),
help="display version information",
)
return parser | [
"def",
"_get_parser",
"(",
")",
":",
"import",
"argparse",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"(",
"\"Convert between mesh formats.\"",
")",
")",
"parser",
".",
"add_argument",
"(",
"\"infile\"",
",",
"type",
"=",
"str",
... | Parse input options. | [
"Parse",
"input",
"options",
"."
] | cb78285962b573fb46a4f3f54276206d922bdbcb | https://github.com/nschloe/meshio/blob/cb78285962b573fb46a4f3f54276206d922bdbcb/meshio/cli.py#L43-L93 | train | 217,061 |
nschloe/meshio | meshio/msh_io/main.py | _read_header | def _read_header(f):
"""Read the mesh format block
specified as
version(ASCII double; currently 4.1)
file-type(ASCII int; 0 for ASCII mode, 1 for binary mode)
data-size(ASCII int; sizeof(size_t))
< int with value one; only in binary mode, to detect endianness >
though here the version is left as str
"""
# http://gmsh.info/doc/texinfo/gmsh.html#MSH-file-format
line = f.readline().decode("utf-8")
# Split the line
# 4.1 0 8
# into its components.
str_list = list(filter(None, line.split()))
fmt_version = str_list[0]
assert str_list[1] in ["0", "1"]
is_ascii = str_list[1] == "0"
data_size = int(str_list[2])
if not is_ascii:
# The next line is the integer 1 in bytes. Useful for checking
# endianness. Just assert that we get 1 here.
one = f.read(struct.calcsize("i"))
assert struct.unpack("i", one)[0] == 1
line = f.readline().decode("utf-8")
assert line == "\n"
line = f.readline().decode("utf-8")
assert line.strip() == "$EndMeshFormat"
return fmt_version, data_size, is_ascii | python | def _read_header(f):
"""Read the mesh format block
specified as
version(ASCII double; currently 4.1)
file-type(ASCII int; 0 for ASCII mode, 1 for binary mode)
data-size(ASCII int; sizeof(size_t))
< int with value one; only in binary mode, to detect endianness >
though here the version is left as str
"""
# http://gmsh.info/doc/texinfo/gmsh.html#MSH-file-format
line = f.readline().decode("utf-8")
# Split the line
# 4.1 0 8
# into its components.
str_list = list(filter(None, line.split()))
fmt_version = str_list[0]
assert str_list[1] in ["0", "1"]
is_ascii = str_list[1] == "0"
data_size = int(str_list[2])
if not is_ascii:
# The next line is the integer 1 in bytes. Useful for checking
# endianness. Just assert that we get 1 here.
one = f.read(struct.calcsize("i"))
assert struct.unpack("i", one)[0] == 1
line = f.readline().decode("utf-8")
assert line == "\n"
line = f.readline().decode("utf-8")
assert line.strip() == "$EndMeshFormat"
return fmt_version, data_size, is_ascii | [
"def",
"_read_header",
"(",
"f",
")",
":",
"# http://gmsh.info/doc/texinfo/gmsh.html#MSH-file-format",
"line",
"=",
"f",
".",
"readline",
"(",
")",
".",
"decode",
"(",
"\"utf-8\"",
")",
"# Split the line",
"# 4.1 0 8",
"# into its components.",
"str_list",
"=",
"list"... | Read the mesh format block
specified as
version(ASCII double; currently 4.1)
file-type(ASCII int; 0 for ASCII mode, 1 for binary mode)
data-size(ASCII int; sizeof(size_t))
< int with value one; only in binary mode, to detect endianness >
though here the version is left as str | [
"Read",
"the",
"mesh",
"format",
"block"
] | cb78285962b573fb46a4f3f54276206d922bdbcb | https://github.com/nschloe/meshio/blob/cb78285962b573fb46a4f3f54276206d922bdbcb/meshio/msh_io/main.py#L48-L81 | train | 217,062 |
nschloe/meshio | meshio/msh_io/main.py | write | def write(filename, mesh, fmt_version, write_binary=True):
"""Writes a Gmsh msh file.
"""
try:
writer = _writers[fmt_version]
except KeyError:
try:
writer = _writers[fmt_version.split(".")[0]]
except KeyError:
raise ValueError(
"Need mesh format in {} (got {})".format(
sorted(_writers.keys()), fmt_version
)
)
writer.write(filename, mesh, write_binary=write_binary) | python | def write(filename, mesh, fmt_version, write_binary=True):
"""Writes a Gmsh msh file.
"""
try:
writer = _writers[fmt_version]
except KeyError:
try:
writer = _writers[fmt_version.split(".")[0]]
except KeyError:
raise ValueError(
"Need mesh format in {} (got {})".format(
sorted(_writers.keys()), fmt_version
)
)
writer.write(filename, mesh, write_binary=write_binary) | [
"def",
"write",
"(",
"filename",
",",
"mesh",
",",
"fmt_version",
",",
"write_binary",
"=",
"True",
")",
":",
"try",
":",
"writer",
"=",
"_writers",
"[",
"fmt_version",
"]",
"except",
"KeyError",
":",
"try",
":",
"writer",
"=",
"_writers",
"[",
"fmt_vers... | Writes a Gmsh msh file. | [
"Writes",
"a",
"Gmsh",
"msh",
"file",
"."
] | cb78285962b573fb46a4f3f54276206d922bdbcb | https://github.com/nschloe/meshio/blob/cb78285962b573fb46a4f3f54276206d922bdbcb/meshio/msh_io/main.py#L84-L99 | train | 217,063 |
nschloe/meshio | meshio/helpers.py | write | def write(filename, mesh, file_format=None, **kwargs):
"""Writes mesh together with data to a file.
:params filename: File to write to.
:type filename: str
:params point_data: Named additional point data to write to the file.
:type point_data: dict
"""
if not file_format:
# deduce file format from extension
file_format = _filetype_from_filename(filename)
# check cells for sanity
for key, value in mesh.cells.items():
if key[:7] == "polygon":
assert value.shape[1] == int(key[7:])
else:
assert value.shape[1] == num_nodes_per_cell[key]
try:
interface, args, default_kwargs = _writer_map[file_format]
except KeyError:
raise KeyError(
"Unknown format '{}'. Pick one of {}".format(
file_format, sorted(list(_writer_map.keys()))
)
)
# Build kwargs
_kwargs = default_kwargs.copy()
_kwargs.update(kwargs)
# Write
return interface.write(filename, mesh, *args, **_kwargs) | python | def write(filename, mesh, file_format=None, **kwargs):
"""Writes mesh together with data to a file.
:params filename: File to write to.
:type filename: str
:params point_data: Named additional point data to write to the file.
:type point_data: dict
"""
if not file_format:
# deduce file format from extension
file_format = _filetype_from_filename(filename)
# check cells for sanity
for key, value in mesh.cells.items():
if key[:7] == "polygon":
assert value.shape[1] == int(key[7:])
else:
assert value.shape[1] == num_nodes_per_cell[key]
try:
interface, args, default_kwargs = _writer_map[file_format]
except KeyError:
raise KeyError(
"Unknown format '{}'. Pick one of {}".format(
file_format, sorted(list(_writer_map.keys()))
)
)
# Build kwargs
_kwargs = default_kwargs.copy()
_kwargs.update(kwargs)
# Write
return interface.write(filename, mesh, *args, **_kwargs) | [
"def",
"write",
"(",
"filename",
",",
"mesh",
",",
"file_format",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"file_format",
":",
"# deduce file format from extension",
"file_format",
"=",
"_filetype_from_filename",
"(",
"filename",
")",
"# chec... | Writes mesh together with data to a file.
:params filename: File to write to.
:type filename: str
:params point_data: Named additional point data to write to the file.
:type point_data: dict | [
"Writes",
"mesh",
"together",
"with",
"data",
"to",
"a",
"file",
"."
] | cb78285962b573fb46a4f3f54276206d922bdbcb | https://github.com/nschloe/meshio/blob/cb78285962b573fb46a4f3f54276206d922bdbcb/meshio/helpers.py#L193-L227 | train | 217,064 |
nschloe/meshio | meshio/medit_io.py | _ItemReader.next_items | def next_items(self, n):
"""Returns the next n items.
Throws StopIteration when there is not enough data to return n items.
"""
items = []
while len(items) < n:
if self._line_ptr >= len(self._line):
# Load the next line.
line = next(self._file).strip()
# Skip all comment and empty lines.
while not line or line[0] == "#":
line = next(self._file).strip()
self._line = self._re_delimiter.split(line)
self._line_ptr = 0
n_read = min(n - len(items), len(self._line) - self._line_ptr)
items.extend(self._line[self._line_ptr : self._line_ptr + n_read])
self._line_ptr += n_read
return items | python | def next_items(self, n):
"""Returns the next n items.
Throws StopIteration when there is not enough data to return n items.
"""
items = []
while len(items) < n:
if self._line_ptr >= len(self._line):
# Load the next line.
line = next(self._file).strip()
# Skip all comment and empty lines.
while not line or line[0] == "#":
line = next(self._file).strip()
self._line = self._re_delimiter.split(line)
self._line_ptr = 0
n_read = min(n - len(items), len(self._line) - self._line_ptr)
items.extend(self._line[self._line_ptr : self._line_ptr + n_read])
self._line_ptr += n_read
return items | [
"def",
"next_items",
"(",
"self",
",",
"n",
")",
":",
"items",
"=",
"[",
"]",
"while",
"len",
"(",
"items",
")",
"<",
"n",
":",
"if",
"self",
".",
"_line_ptr",
">=",
"len",
"(",
"self",
".",
"_line",
")",
":",
"# Load the next line.",
"line",
"=",
... | Returns the next n items.
Throws StopIteration when there is not enough data to return n items. | [
"Returns",
"the",
"next",
"n",
"items",
"."
] | cb78285962b573fb46a4f3f54276206d922bdbcb | https://github.com/nschloe/meshio/blob/cb78285962b573fb46a4f3f54276206d922bdbcb/meshio/medit_io.py#L35-L53 | train | 217,065 |
nschloe/meshio | meshio/abaqus_io.py | get_param_map | def get_param_map(word, required_keys=None):
"""
get the optional arguments on a line
Example
-------
>>> iline = 0
>>> word = 'elset,instance=dummy2,generate'
>>> params = get_param_map(iline, word, required_keys=['instance'])
params = {
'elset' : None,
'instance' : 'dummy2,
'generate' : None,
}
"""
if required_keys is None:
required_keys = []
words = word.split(",")
param_map = {}
for wordi in words:
if "=" not in wordi:
key = wordi.strip()
value = None
else:
sword = wordi.split("=")
assert len(sword) == 2, sword
key = sword[0].strip()
value = sword[1].strip()
param_map[key] = value
msg = ""
for key in required_keys:
if key not in param_map:
msg += "%r not found in %r\n" % (key, word)
if msg:
raise RuntimeError(msg)
return param_map | python | def get_param_map(word, required_keys=None):
"""
get the optional arguments on a line
Example
-------
>>> iline = 0
>>> word = 'elset,instance=dummy2,generate'
>>> params = get_param_map(iline, word, required_keys=['instance'])
params = {
'elset' : None,
'instance' : 'dummy2,
'generate' : None,
}
"""
if required_keys is None:
required_keys = []
words = word.split(",")
param_map = {}
for wordi in words:
if "=" not in wordi:
key = wordi.strip()
value = None
else:
sword = wordi.split("=")
assert len(sword) == 2, sword
key = sword[0].strip()
value = sword[1].strip()
param_map[key] = value
msg = ""
for key in required_keys:
if key not in param_map:
msg += "%r not found in %r\n" % (key, word)
if msg:
raise RuntimeError(msg)
return param_map | [
"def",
"get_param_map",
"(",
"word",
",",
"required_keys",
"=",
"None",
")",
":",
"if",
"required_keys",
"is",
"None",
":",
"required_keys",
"=",
"[",
"]",
"words",
"=",
"word",
".",
"split",
"(",
"\",\"",
")",
"param_map",
"=",
"{",
"}",
"for",
"wordi... | get the optional arguments on a line
Example
-------
>>> iline = 0
>>> word = 'elset,instance=dummy2,generate'
>>> params = get_param_map(iline, word, required_keys=['instance'])
params = {
'elset' : None,
'instance' : 'dummy2,
'generate' : None,
} | [
"get",
"the",
"optional",
"arguments",
"on",
"a",
"line"
] | cb78285962b573fb46a4f3f54276206d922bdbcb | https://github.com/nschloe/meshio/blob/cb78285962b573fb46a4f3f54276206d922bdbcb/meshio/abaqus_io.py#L193-L229 | train | 217,066 |
spulec/moto | moto/ssm/models.py | SimpleSystemManagerBackend.get_parameters_by_path | def get_parameters_by_path(self, path, with_decryption, recursive, filters=None):
"""Implement the get-parameters-by-path-API in the backend."""
result = []
# path could be with or without a trailing /. we handle this
# difference here.
path = path.rstrip('/') + '/'
for param in self._parameters:
if path != '/' and not param.startswith(path):
continue
if '/' in param[len(path) + 1:] and not recursive:
continue
if not self._match_filters(self._parameters[param], filters):
continue
result.append(self._parameters[param])
return result | python | def get_parameters_by_path(self, path, with_decryption, recursive, filters=None):
"""Implement the get-parameters-by-path-API in the backend."""
result = []
# path could be with or without a trailing /. we handle this
# difference here.
path = path.rstrip('/') + '/'
for param in self._parameters:
if path != '/' and not param.startswith(path):
continue
if '/' in param[len(path) + 1:] and not recursive:
continue
if not self._match_filters(self._parameters[param], filters):
continue
result.append(self._parameters[param])
return result | [
"def",
"get_parameters_by_path",
"(",
"self",
",",
"path",
",",
"with_decryption",
",",
"recursive",
",",
"filters",
"=",
"None",
")",
":",
"result",
"=",
"[",
"]",
"# path could be with or without a trailing /. we handle this",
"# difference here.",
"path",
"=",
"pat... | Implement the get-parameters-by-path-API in the backend. | [
"Implement",
"the",
"get",
"-",
"parameters",
"-",
"by",
"-",
"path",
"-",
"API",
"in",
"the",
"backend",
"."
] | 4a286c4bc288933bb023396e2784a6fdbb966bc9 | https://github.com/spulec/moto/blob/4a286c4bc288933bb023396e2784a6fdbb966bc9/moto/ssm/models.py#L255-L270 | train | 217,067 |
spulec/moto | moto/ssm/models.py | SimpleSystemManagerBackend._match_filters | def _match_filters(parameter, filters=None):
"""Return True if the given parameter matches all the filters"""
for filter_obj in (filters or []):
key = filter_obj['Key']
option = filter_obj.get('Option', 'Equals')
values = filter_obj.get('Values', [])
what = None
if key == 'Type':
what = parameter.type
elif key == 'KeyId':
what = parameter.keyid
if option == 'Equals'\
and not any(what == value for value in values):
return False
elif option == 'BeginsWith'\
and not any(what.startswith(value) for value in values):
return False
# True if no false match (or no filters at all)
return True | python | def _match_filters(parameter, filters=None):
"""Return True if the given parameter matches all the filters"""
for filter_obj in (filters or []):
key = filter_obj['Key']
option = filter_obj.get('Option', 'Equals')
values = filter_obj.get('Values', [])
what = None
if key == 'Type':
what = parameter.type
elif key == 'KeyId':
what = parameter.keyid
if option == 'Equals'\
and not any(what == value for value in values):
return False
elif option == 'BeginsWith'\
and not any(what.startswith(value) for value in values):
return False
# True if no false match (or no filters at all)
return True | [
"def",
"_match_filters",
"(",
"parameter",
",",
"filters",
"=",
"None",
")",
":",
"for",
"filter_obj",
"in",
"(",
"filters",
"or",
"[",
"]",
")",
":",
"key",
"=",
"filter_obj",
"[",
"'Key'",
"]",
"option",
"=",
"filter_obj",
".",
"get",
"(",
"'Option'"... | Return True if the given parameter matches all the filters | [
"Return",
"True",
"if",
"the",
"given",
"parameter",
"matches",
"all",
"the",
"filters"
] | 4a286c4bc288933bb023396e2784a6fdbb966bc9 | https://github.com/spulec/moto/blob/4a286c4bc288933bb023396e2784a6fdbb966bc9/moto/ssm/models.py#L273-L293 | train | 217,068 |
spulec/moto | scripts/scaffold.py | initialize_service | def initialize_service(service, operation, api_protocol):
"""create lib and test dirs if not exist
"""
lib_dir = get_lib_dir(service)
test_dir = get_test_dir(service)
print_progress('Initializing service', service, 'green')
client = boto3.client(service)
service_class = client.__class__.__name__
endpoint_prefix = client._service_model.endpoint_prefix
tmpl_context = {
'service': service,
'service_class': service_class,
'endpoint_prefix': endpoint_prefix,
'api_protocol': api_protocol,
'escaped_service': get_escaped_service(service)
}
# initialize service directory
if os.path.exists(lib_dir):
print_progress('skip creating', lib_dir, 'yellow')
else:
print_progress('creating', lib_dir, 'green')
os.makedirs(lib_dir)
tmpl_dir = os.path.join(TEMPLATE_DIR, 'lib')
for tmpl_filename in os.listdir(tmpl_dir):
render_template(
tmpl_dir, tmpl_filename, tmpl_context, service
)
# initialize test directory
if os.path.exists(test_dir):
print_progress('skip creating', test_dir, 'yellow')
else:
print_progress('creating', test_dir, 'green')
os.makedirs(test_dir)
tmpl_dir = os.path.join(TEMPLATE_DIR, 'test')
for tmpl_filename in os.listdir(tmpl_dir):
alt_filename = 'test_{}.py'.format(get_escaped_service(service)) if tmpl_filename == 'test_service.py.j2' else None
render_template(
tmpl_dir, tmpl_filename, tmpl_context, service, alt_filename
)
# append mock to init files
append_mock_to_init_py(service)
append_mock_import_to_backends_py(service)
append_mock_dict_to_backends_py(service) | python | def initialize_service(service, operation, api_protocol):
"""create lib and test dirs if not exist
"""
lib_dir = get_lib_dir(service)
test_dir = get_test_dir(service)
print_progress('Initializing service', service, 'green')
client = boto3.client(service)
service_class = client.__class__.__name__
endpoint_prefix = client._service_model.endpoint_prefix
tmpl_context = {
'service': service,
'service_class': service_class,
'endpoint_prefix': endpoint_prefix,
'api_protocol': api_protocol,
'escaped_service': get_escaped_service(service)
}
# initialize service directory
if os.path.exists(lib_dir):
print_progress('skip creating', lib_dir, 'yellow')
else:
print_progress('creating', lib_dir, 'green')
os.makedirs(lib_dir)
tmpl_dir = os.path.join(TEMPLATE_DIR, 'lib')
for tmpl_filename in os.listdir(tmpl_dir):
render_template(
tmpl_dir, tmpl_filename, tmpl_context, service
)
# initialize test directory
if os.path.exists(test_dir):
print_progress('skip creating', test_dir, 'yellow')
else:
print_progress('creating', test_dir, 'green')
os.makedirs(test_dir)
tmpl_dir = os.path.join(TEMPLATE_DIR, 'test')
for tmpl_filename in os.listdir(tmpl_dir):
alt_filename = 'test_{}.py'.format(get_escaped_service(service)) if tmpl_filename == 'test_service.py.j2' else None
render_template(
tmpl_dir, tmpl_filename, tmpl_context, service, alt_filename
)
# append mock to init files
append_mock_to_init_py(service)
append_mock_import_to_backends_py(service)
append_mock_dict_to_backends_py(service) | [
"def",
"initialize_service",
"(",
"service",
",",
"operation",
",",
"api_protocol",
")",
":",
"lib_dir",
"=",
"get_lib_dir",
"(",
"service",
")",
"test_dir",
"=",
"get_test_dir",
"(",
"service",
")",
"print_progress",
"(",
"'Initializing service'",
",",
"service",... | create lib and test dirs if not exist | [
"create",
"lib",
"and",
"test",
"dirs",
"if",
"not",
"exist"
] | 4a286c4bc288933bb023396e2784a6fdbb966bc9 | https://github.com/spulec/moto/blob/4a286c4bc288933bb023396e2784a6fdbb966bc9/scripts/scaffold.py#L167-L216 | train | 217,069 |
spulec/moto | scripts/scaffold.py | get_response_query_template | def get_response_query_template(service, operation):
"""refers to definition of API in botocore, and autogenerates template
Assume that response format is xml when protocol is query
You can see example of elbv2 from link below.
https://github.com/boto/botocore/blob/develop/botocore/data/elbv2/2015-12-01/service-2.json
"""
client = boto3.client(service)
aws_operation_name = to_upper_camel_case(operation)
op_model = client._service_model.operation_model(aws_operation_name)
result_wrapper = op_model.output_shape.serialization['resultWrapper']
response_wrapper = result_wrapper.replace('Result', 'Response')
metadata = op_model.metadata
xml_namespace = metadata['xmlNamespace']
# build xml tree
t_root = etree.Element(response_wrapper, xmlns=xml_namespace)
# build metadata
t_metadata = etree.Element('ResponseMetadata')
t_request_id = etree.Element('RequestId')
t_request_id.text = '1549581b-12b7-11e3-895e-1334aEXAMPLE'
t_metadata.append(t_request_id)
t_root.append(t_metadata)
# build result
t_result = etree.Element(result_wrapper)
outputs = op_model.output_shape.members
replace_list = []
for output_name, output_shape in outputs.items():
t_result.append(_get_subtree(output_name, output_shape, replace_list))
t_root.append(t_result)
xml_body = etree.tostring(t_root, pretty_print=True).decode('utf-8')
xml_body_lines = xml_body.splitlines()
for replace in replace_list:
name = replace[0]
prefix = replace[1]
singular_name = singularize(name)
start_tag = '<%s>' % name
iter_name = '{}.{}'.format(prefix[-1], name.lower())if prefix else name.lower()
loop_start = '{%% for %s in %s %%}' % (singular_name.lower(), iter_name)
end_tag = '</%s>' % name
loop_end = '{{ endfor }}'
start_tag_indexes = [i for i, l in enumerate(xml_body_lines) if start_tag in l]
if len(start_tag_indexes) != 1:
raise Exception('tag %s not found in response body' % start_tag)
start_tag_index = start_tag_indexes[0]
xml_body_lines.insert(start_tag_index + 1, loop_start)
end_tag_indexes = [i for i, l in enumerate(xml_body_lines) if end_tag in l]
if len(end_tag_indexes) != 1:
raise Exception('tag %s not found in response body' % end_tag)
end_tag_index = end_tag_indexes[0]
xml_body_lines.insert(end_tag_index, loop_end)
xml_body = '\n'.join(xml_body_lines)
body = '\n{}_TEMPLATE = """{}"""'.format(operation.upper(), xml_body)
return body | python | def get_response_query_template(service, operation):
"""refers to definition of API in botocore, and autogenerates template
Assume that response format is xml when protocol is query
You can see example of elbv2 from link below.
https://github.com/boto/botocore/blob/develop/botocore/data/elbv2/2015-12-01/service-2.json
"""
client = boto3.client(service)
aws_operation_name = to_upper_camel_case(operation)
op_model = client._service_model.operation_model(aws_operation_name)
result_wrapper = op_model.output_shape.serialization['resultWrapper']
response_wrapper = result_wrapper.replace('Result', 'Response')
metadata = op_model.metadata
xml_namespace = metadata['xmlNamespace']
# build xml tree
t_root = etree.Element(response_wrapper, xmlns=xml_namespace)
# build metadata
t_metadata = etree.Element('ResponseMetadata')
t_request_id = etree.Element('RequestId')
t_request_id.text = '1549581b-12b7-11e3-895e-1334aEXAMPLE'
t_metadata.append(t_request_id)
t_root.append(t_metadata)
# build result
t_result = etree.Element(result_wrapper)
outputs = op_model.output_shape.members
replace_list = []
for output_name, output_shape in outputs.items():
t_result.append(_get_subtree(output_name, output_shape, replace_list))
t_root.append(t_result)
xml_body = etree.tostring(t_root, pretty_print=True).decode('utf-8')
xml_body_lines = xml_body.splitlines()
for replace in replace_list:
name = replace[0]
prefix = replace[1]
singular_name = singularize(name)
start_tag = '<%s>' % name
iter_name = '{}.{}'.format(prefix[-1], name.lower())if prefix else name.lower()
loop_start = '{%% for %s in %s %%}' % (singular_name.lower(), iter_name)
end_tag = '</%s>' % name
loop_end = '{{ endfor }}'
start_tag_indexes = [i for i, l in enumerate(xml_body_lines) if start_tag in l]
if len(start_tag_indexes) != 1:
raise Exception('tag %s not found in response body' % start_tag)
start_tag_index = start_tag_indexes[0]
xml_body_lines.insert(start_tag_index + 1, loop_start)
end_tag_indexes = [i for i, l in enumerate(xml_body_lines) if end_tag in l]
if len(end_tag_indexes) != 1:
raise Exception('tag %s not found in response body' % end_tag)
end_tag_index = end_tag_indexes[0]
xml_body_lines.insert(end_tag_index, loop_end)
xml_body = '\n'.join(xml_body_lines)
body = '\n{}_TEMPLATE = """{}"""'.format(operation.upper(), xml_body)
return body | [
"def",
"get_response_query_template",
"(",
"service",
",",
"operation",
")",
":",
"client",
"=",
"boto3",
".",
"client",
"(",
"service",
")",
"aws_operation_name",
"=",
"to_upper_camel_case",
"(",
"operation",
")",
"op_model",
"=",
"client",
".",
"_service_model",... | refers to definition of API in botocore, and autogenerates template
Assume that response format is xml when protocol is query
You can see example of elbv2 from link below.
https://github.com/boto/botocore/blob/develop/botocore/data/elbv2/2015-12-01/service-2.json | [
"refers",
"to",
"definition",
"of",
"API",
"in",
"botocore",
"and",
"autogenerates",
"template",
"Assume",
"that",
"response",
"format",
"is",
"xml",
"when",
"protocol",
"is",
"query"
] | 4a286c4bc288933bb023396e2784a6fdbb966bc9 | https://github.com/spulec/moto/blob/4a286c4bc288933bb023396e2784a6fdbb966bc9/scripts/scaffold.py#L324-L382 | train | 217,070 |
spulec/moto | moto/core/utils.py | camelcase_to_underscores | def camelcase_to_underscores(argument):
''' Converts a camelcase param like theNewAttribute to the equivalent
python underscore variable like the_new_attribute'''
result = ''
prev_char_title = True
if not argument:
return argument
for index, char in enumerate(argument):
try:
next_char_title = argument[index + 1].istitle()
except IndexError:
next_char_title = True
upper_to_lower = char.istitle() and not next_char_title
lower_to_upper = char.istitle() and not prev_char_title
if index and (upper_to_lower or lower_to_upper):
# Only add underscore if char is capital, not first letter, and next
# char is not capital
result += "_"
prev_char_title = char.istitle()
if not char.isspace(): # Only add non-whitespace
result += char.lower()
return result | python | def camelcase_to_underscores(argument):
''' Converts a camelcase param like theNewAttribute to the equivalent
python underscore variable like the_new_attribute'''
result = ''
prev_char_title = True
if not argument:
return argument
for index, char in enumerate(argument):
try:
next_char_title = argument[index + 1].istitle()
except IndexError:
next_char_title = True
upper_to_lower = char.istitle() and not next_char_title
lower_to_upper = char.istitle() and not prev_char_title
if index and (upper_to_lower or lower_to_upper):
# Only add underscore if char is capital, not first letter, and next
# char is not capital
result += "_"
prev_char_title = char.istitle()
if not char.isspace(): # Only add non-whitespace
result += char.lower()
return result | [
"def",
"camelcase_to_underscores",
"(",
"argument",
")",
":",
"result",
"=",
"''",
"prev_char_title",
"=",
"True",
"if",
"not",
"argument",
":",
"return",
"argument",
"for",
"index",
",",
"char",
"in",
"enumerate",
"(",
"argument",
")",
":",
"try",
":",
"n... | Converts a camelcase param like theNewAttribute to the equivalent
python underscore variable like the_new_attribute | [
"Converts",
"a",
"camelcase",
"param",
"like",
"theNewAttribute",
"to",
"the",
"equivalent",
"python",
"underscore",
"variable",
"like",
"the_new_attribute"
] | 4a286c4bc288933bb023396e2784a6fdbb966bc9 | https://github.com/spulec/moto/blob/4a286c4bc288933bb023396e2784a6fdbb966bc9/moto/core/utils.py#L17-L40 | train | 217,071 |
spulec/moto | moto/core/utils.py | underscores_to_camelcase | def underscores_to_camelcase(argument):
''' Converts a camelcase param like the_new_attribute to the equivalent
camelcase version like theNewAttribute. Note that the first letter is
NOT capitalized by this function '''
result = ''
previous_was_underscore = False
for char in argument:
if char != '_':
if previous_was_underscore:
result += char.upper()
else:
result += char
previous_was_underscore = char == '_'
return result | python | def underscores_to_camelcase(argument):
''' Converts a camelcase param like the_new_attribute to the equivalent
camelcase version like theNewAttribute. Note that the first letter is
NOT capitalized by this function '''
result = ''
previous_was_underscore = False
for char in argument:
if char != '_':
if previous_was_underscore:
result += char.upper()
else:
result += char
previous_was_underscore = char == '_'
return result | [
"def",
"underscores_to_camelcase",
"(",
"argument",
")",
":",
"result",
"=",
"''",
"previous_was_underscore",
"=",
"False",
"for",
"char",
"in",
"argument",
":",
"if",
"char",
"!=",
"'_'",
":",
"if",
"previous_was_underscore",
":",
"result",
"+=",
"char",
".",... | Converts a camelcase param like the_new_attribute to the equivalent
camelcase version like theNewAttribute. Note that the first letter is
NOT capitalized by this function | [
"Converts",
"a",
"camelcase",
"param",
"like",
"the_new_attribute",
"to",
"the",
"equivalent",
"camelcase",
"version",
"like",
"theNewAttribute",
".",
"Note",
"that",
"the",
"first",
"letter",
"is",
"NOT",
"capitalized",
"by",
"this",
"function"
] | 4a286c4bc288933bb023396e2784a6fdbb966bc9 | https://github.com/spulec/moto/blob/4a286c4bc288933bb023396e2784a6fdbb966bc9/moto/core/utils.py#L43-L56 | train | 217,072 |
spulec/moto | moto/core/utils.py | convert_regex_to_flask_path | def convert_regex_to_flask_path(url_path):
"""
Converts a regex matching url to one that can be used with flask
"""
for token in ["$"]:
url_path = url_path.replace(token, "")
def caller(reg):
match_name, match_pattern = reg.groups()
return '<regex("{0}"):{1}>'.format(match_pattern, match_name)
url_path = re.sub("\(\?P<(.*?)>(.*?)\)", caller, url_path)
if url_path.endswith("/?"):
# Flask does own handling of trailing slashes
url_path = url_path.rstrip("/?")
return url_path | python | def convert_regex_to_flask_path(url_path):
"""
Converts a regex matching url to one that can be used with flask
"""
for token in ["$"]:
url_path = url_path.replace(token, "")
def caller(reg):
match_name, match_pattern = reg.groups()
return '<regex("{0}"):{1}>'.format(match_pattern, match_name)
url_path = re.sub("\(\?P<(.*?)>(.*?)\)", caller, url_path)
if url_path.endswith("/?"):
# Flask does own handling of trailing slashes
url_path = url_path.rstrip("/?")
return url_path | [
"def",
"convert_regex_to_flask_path",
"(",
"url_path",
")",
":",
"for",
"token",
"in",
"[",
"\"$\"",
"]",
":",
"url_path",
"=",
"url_path",
".",
"replace",
"(",
"token",
",",
"\"\"",
")",
"def",
"caller",
"(",
"reg",
")",
":",
"match_name",
",",
"match_p... | Converts a regex matching url to one that can be used with flask | [
"Converts",
"a",
"regex",
"matching",
"url",
"to",
"one",
"that",
"can",
"be",
"used",
"with",
"flask"
] | 4a286c4bc288933bb023396e2784a6fdbb966bc9 | https://github.com/spulec/moto/blob/4a286c4bc288933bb023396e2784a6fdbb966bc9/moto/core/utils.py#L80-L96 | train | 217,073 |
spulec/moto | moto/emr/responses.py | generate_boto3_response | def generate_boto3_response(operation):
"""The decorator to convert an XML response to JSON, if the request is
determined to be from boto3. Pass the API action as a parameter.
"""
def _boto3_request(method):
@wraps(method)
def f(self, *args, **kwargs):
rendered = method(self, *args, **kwargs)
if 'json' in self.headers.get('Content-Type', []):
self.response_headers.update(
{'x-amzn-requestid': '2690d7eb-ed86-11dd-9877-6fad448a8419',
'date': datetime.now(pytz.utc).strftime('%a, %d %b %Y %H:%M:%S %Z'),
'content-type': 'application/x-amz-json-1.1'})
resp = xml_to_json_response(
self.aws_service_spec, operation, rendered)
return '' if resp is None else json.dumps(resp)
return rendered
return f
return _boto3_request | python | def generate_boto3_response(operation):
"""The decorator to convert an XML response to JSON, if the request is
determined to be from boto3. Pass the API action as a parameter.
"""
def _boto3_request(method):
@wraps(method)
def f(self, *args, **kwargs):
rendered = method(self, *args, **kwargs)
if 'json' in self.headers.get('Content-Type', []):
self.response_headers.update(
{'x-amzn-requestid': '2690d7eb-ed86-11dd-9877-6fad448a8419',
'date': datetime.now(pytz.utc).strftime('%a, %d %b %Y %H:%M:%S %Z'),
'content-type': 'application/x-amz-json-1.1'})
resp = xml_to_json_response(
self.aws_service_spec, operation, rendered)
return '' if resp is None else json.dumps(resp)
return rendered
return f
return _boto3_request | [
"def",
"generate_boto3_response",
"(",
"operation",
")",
":",
"def",
"_boto3_request",
"(",
"method",
")",
":",
"@",
"wraps",
"(",
"method",
")",
"def",
"f",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"rendered",
"=",
"method",
... | The decorator to convert an XML response to JSON, if the request is
determined to be from boto3. Pass the API action as a parameter. | [
"The",
"decorator",
"to",
"convert",
"an",
"XML",
"response",
"to",
"JSON",
"if",
"the",
"request",
"is",
"determined",
"to",
"be",
"from",
"boto3",
".",
"Pass",
"the",
"API",
"action",
"as",
"a",
"parameter",
"."
] | 4a286c4bc288933bb023396e2784a6fdbb966bc9 | https://github.com/spulec/moto/blob/4a286c4bc288933bb023396e2784a6fdbb966bc9/moto/emr/responses.py#L18-L37 | train | 217,074 |
spulec/moto | moto/ecr/models.py | ECRBackend.describe_repositories | def describe_repositories(self, registry_id=None, repository_names=None):
"""
maxResults and nextToken not implemented
"""
if repository_names:
for repository_name in repository_names:
if repository_name not in self.repositories:
raise RepositoryNotFoundException(repository_name, registry_id or DEFAULT_REGISTRY_ID)
repositories = []
for repository in self.repositories.values():
# If a registry_id was supplied, ensure this repository matches
if registry_id:
if repository.registry_id != registry_id:
continue
# If a list of repository names was supplied, esure this repository
# is in that list
if repository_names:
if repository.name not in repository_names:
continue
repositories.append(repository.response_object)
return repositories | python | def describe_repositories(self, registry_id=None, repository_names=None):
"""
maxResults and nextToken not implemented
"""
if repository_names:
for repository_name in repository_names:
if repository_name not in self.repositories:
raise RepositoryNotFoundException(repository_name, registry_id or DEFAULT_REGISTRY_ID)
repositories = []
for repository in self.repositories.values():
# If a registry_id was supplied, ensure this repository matches
if registry_id:
if repository.registry_id != registry_id:
continue
# If a list of repository names was supplied, esure this repository
# is in that list
if repository_names:
if repository.name not in repository_names:
continue
repositories.append(repository.response_object)
return repositories | [
"def",
"describe_repositories",
"(",
"self",
",",
"registry_id",
"=",
"None",
",",
"repository_names",
"=",
"None",
")",
":",
"if",
"repository_names",
":",
"for",
"repository_name",
"in",
"repository_names",
":",
"if",
"repository_name",
"not",
"in",
"self",
".... | maxResults and nextToken not implemented | [
"maxResults",
"and",
"nextToken",
"not",
"implemented"
] | 4a286c4bc288933bb023396e2784a6fdbb966bc9 | https://github.com/spulec/moto/blob/4a286c4bc288933bb023396e2784a6fdbb966bc9/moto/ecr/models.py#L174-L195 | train | 217,075 |
spulec/moto | moto/ecr/models.py | ECRBackend.list_images | def list_images(self, repository_name, registry_id=None):
"""
maxResults and filtering not implemented
"""
repository = None
found = False
if repository_name in self.repositories:
repository = self.repositories[repository_name]
if registry_id:
if repository.registry_id == registry_id:
found = True
else:
found = True
if not found:
raise RepositoryNotFoundException(repository_name, registry_id or DEFAULT_REGISTRY_ID)
images = []
for image in repository.images:
images.append(image)
return images | python | def list_images(self, repository_name, registry_id=None):
"""
maxResults and filtering not implemented
"""
repository = None
found = False
if repository_name in self.repositories:
repository = self.repositories[repository_name]
if registry_id:
if repository.registry_id == registry_id:
found = True
else:
found = True
if not found:
raise RepositoryNotFoundException(repository_name, registry_id or DEFAULT_REGISTRY_ID)
images = []
for image in repository.images:
images.append(image)
return images | [
"def",
"list_images",
"(",
"self",
",",
"repository_name",
",",
"registry_id",
"=",
"None",
")",
":",
"repository",
"=",
"None",
"found",
"=",
"False",
"if",
"repository_name",
"in",
"self",
".",
"repositories",
":",
"repository",
"=",
"self",
".",
"reposito... | maxResults and filtering not implemented | [
"maxResults",
"and",
"filtering",
"not",
"implemented"
] | 4a286c4bc288933bb023396e2784a6fdbb966bc9 | https://github.com/spulec/moto/blob/4a286c4bc288933bb023396e2784a6fdbb966bc9/moto/ecr/models.py#L208-L228 | train | 217,076 |
spulec/moto | moto/packages/httpretty/core.py | httprettified | def httprettified(test):
"A decorator tests that use HTTPretty"
def decorate_class(klass):
for attr in dir(klass):
if not attr.startswith('test_'):
continue
attr_value = getattr(klass, attr)
if not hasattr(attr_value, "__call__"):
continue
setattr(klass, attr, decorate_callable(attr_value))
return klass
def decorate_callable(test):
@functools.wraps(test)
def wrapper(*args, **kw):
httpretty.reset()
httpretty.enable()
try:
return test(*args, **kw)
finally:
httpretty.disable()
return wrapper
if isinstance(test, ClassTypes):
return decorate_class(test)
return decorate_callable(test) | python | def httprettified(test):
"A decorator tests that use HTTPretty"
def decorate_class(klass):
for attr in dir(klass):
if not attr.startswith('test_'):
continue
attr_value = getattr(klass, attr)
if not hasattr(attr_value, "__call__"):
continue
setattr(klass, attr, decorate_callable(attr_value))
return klass
def decorate_callable(test):
@functools.wraps(test)
def wrapper(*args, **kw):
httpretty.reset()
httpretty.enable()
try:
return test(*args, **kw)
finally:
httpretty.disable()
return wrapper
if isinstance(test, ClassTypes):
return decorate_class(test)
return decorate_callable(test) | [
"def",
"httprettified",
"(",
"test",
")",
":",
"def",
"decorate_class",
"(",
"klass",
")",
":",
"for",
"attr",
"in",
"dir",
"(",
"klass",
")",
":",
"if",
"not",
"attr",
".",
"startswith",
"(",
"'test_'",
")",
":",
"continue",
"attr_value",
"=",
"getatt... | A decorator tests that use HTTPretty | [
"A",
"decorator",
"tests",
"that",
"use",
"HTTPretty"
] | 4a286c4bc288933bb023396e2784a6fdbb966bc9 | https://github.com/spulec/moto/blob/4a286c4bc288933bb023396e2784a6fdbb966bc9/moto/packages/httpretty/core.py#L1089-L1116 | train | 217,077 |
spulec/moto | moto/packages/httpretty/core.py | URIMatcher.get_next_entry | def get_next_entry(self, method, info, request):
"""Cycle through available responses, but only once.
Any subsequent requests will receive the last response"""
if method not in self.current_entries:
self.current_entries[method] = 0
# restrict selection to entries that match the requested method
entries_for_method = [e for e in self.entries if e.method == method]
if self.current_entries[method] >= len(entries_for_method):
self.current_entries[method] = -1
if not self.entries or not entries_for_method:
raise ValueError('I have no entries for method %s: %s'
% (method, self))
entry = entries_for_method[self.current_entries[method]]
if self.current_entries[method] != -1:
self.current_entries[method] += 1
# Attach more info to the entry
# So the callback can be more clever about what to do
# This does also fix the case where the callback
# would be handed a compiled regex as uri instead of the
# real uri
entry.info = info
entry.request = request
return entry | python | def get_next_entry(self, method, info, request):
"""Cycle through available responses, but only once.
Any subsequent requests will receive the last response"""
if method not in self.current_entries:
self.current_entries[method] = 0
# restrict selection to entries that match the requested method
entries_for_method = [e for e in self.entries if e.method == method]
if self.current_entries[method] >= len(entries_for_method):
self.current_entries[method] = -1
if not self.entries or not entries_for_method:
raise ValueError('I have no entries for method %s: %s'
% (method, self))
entry = entries_for_method[self.current_entries[method]]
if self.current_entries[method] != -1:
self.current_entries[method] += 1
# Attach more info to the entry
# So the callback can be more clever about what to do
# This does also fix the case where the callback
# would be handed a compiled regex as uri instead of the
# real uri
entry.info = info
entry.request = request
return entry | [
"def",
"get_next_entry",
"(",
"self",
",",
"method",
",",
"info",
",",
"request",
")",
":",
"if",
"method",
"not",
"in",
"self",
".",
"current_entries",
":",
"self",
".",
"current_entries",
"[",
"method",
"]",
"=",
"0",
"# restrict selection to entries that ma... | Cycle through available responses, but only once.
Any subsequent requests will receive the last response | [
"Cycle",
"through",
"available",
"responses",
"but",
"only",
"once",
".",
"Any",
"subsequent",
"requests",
"will",
"receive",
"the",
"last",
"response"
] | 4a286c4bc288933bb023396e2784a6fdbb966bc9 | https://github.com/spulec/moto/blob/4a286c4bc288933bb023396e2784a6fdbb966bc9/moto/packages/httpretty/core.py#L809-L837 | train | 217,078 |
spulec/moto | moto/xray/mock_client.py | mock_xray_client | def mock_xray_client(f):
"""
Mocks the X-Ray sdk by pwning its evil singleton with our methods
The X-Ray SDK has normally been imported and `patched()` called long before we start mocking.
This means the Context() will be very unhappy if an env var isnt present, so we set that, save
the old context, then supply our new context.
We also patch the Emitter by subclassing the UDPEmitter class replacing its methods and pushing
that itno the recorder instance.
"""
@wraps(f)
def _wrapped(*args, **kwargs):
print("Starting X-Ray Patch")
old_xray_context_var = os.environ.get('AWS_XRAY_CONTEXT_MISSING')
os.environ['AWS_XRAY_CONTEXT_MISSING'] = 'LOG_ERROR'
old_xray_context = aws_xray_sdk.core.xray_recorder._context
old_xray_emitter = aws_xray_sdk.core.xray_recorder._emitter
aws_xray_sdk.core.xray_recorder._context = AWSContext()
aws_xray_sdk.core.xray_recorder._emitter = MockEmitter()
try:
return f(*args, **kwargs)
finally:
if old_xray_context_var is None:
del os.environ['AWS_XRAY_CONTEXT_MISSING']
else:
os.environ['AWS_XRAY_CONTEXT_MISSING'] = old_xray_context_var
aws_xray_sdk.core.xray_recorder._emitter = old_xray_emitter
aws_xray_sdk.core.xray_recorder._context = old_xray_context
return _wrapped | python | def mock_xray_client(f):
"""
Mocks the X-Ray sdk by pwning its evil singleton with our methods
The X-Ray SDK has normally been imported and `patched()` called long before we start mocking.
This means the Context() will be very unhappy if an env var isnt present, so we set that, save
the old context, then supply our new context.
We also patch the Emitter by subclassing the UDPEmitter class replacing its methods and pushing
that itno the recorder instance.
"""
@wraps(f)
def _wrapped(*args, **kwargs):
print("Starting X-Ray Patch")
old_xray_context_var = os.environ.get('AWS_XRAY_CONTEXT_MISSING')
os.environ['AWS_XRAY_CONTEXT_MISSING'] = 'LOG_ERROR'
old_xray_context = aws_xray_sdk.core.xray_recorder._context
old_xray_emitter = aws_xray_sdk.core.xray_recorder._emitter
aws_xray_sdk.core.xray_recorder._context = AWSContext()
aws_xray_sdk.core.xray_recorder._emitter = MockEmitter()
try:
return f(*args, **kwargs)
finally:
if old_xray_context_var is None:
del os.environ['AWS_XRAY_CONTEXT_MISSING']
else:
os.environ['AWS_XRAY_CONTEXT_MISSING'] = old_xray_context_var
aws_xray_sdk.core.xray_recorder._emitter = old_xray_emitter
aws_xray_sdk.core.xray_recorder._context = old_xray_context
return _wrapped | [
"def",
"mock_xray_client",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"_wrapped",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"print",
"(",
"\"Starting X-Ray Patch\"",
")",
"old_xray_context_var",
"=",
"os",
".",
"environ",
".",
"... | Mocks the X-Ray sdk by pwning its evil singleton with our methods
The X-Ray SDK has normally been imported and `patched()` called long before we start mocking.
This means the Context() will be very unhappy if an env var isnt present, so we set that, save
the old context, then supply our new context.
We also patch the Emitter by subclassing the UDPEmitter class replacing its methods and pushing
that itno the recorder instance. | [
"Mocks",
"the",
"X",
"-",
"Ray",
"sdk",
"by",
"pwning",
"its",
"evil",
"singleton",
"with",
"our",
"methods"
] | 4a286c4bc288933bb023396e2784a6fdbb966bc9 | https://github.com/spulec/moto/blob/4a286c4bc288933bb023396e2784a6fdbb966bc9/moto/xray/mock_client.py#L32-L65 | train | 217,079 |
spulec/moto | moto/iot/models.py | FakeCertificate.to_description_dict | def to_description_dict(self):
"""
You might need keys below in some situation
- caCertificateId
- previousOwnedBy
"""
return {
'certificateArn': self.arn,
'certificateId': self.certificate_id,
'status': self.status,
'certificatePem': self.certificate_pem,
'ownedBy': self.owner,
'creationDate': self.creation_date,
'lastModifiedDate': self.last_modified_date,
'transferData': self.transfer_data
} | python | def to_description_dict(self):
"""
You might need keys below in some situation
- caCertificateId
- previousOwnedBy
"""
return {
'certificateArn': self.arn,
'certificateId': self.certificate_id,
'status': self.status,
'certificatePem': self.certificate_pem,
'ownedBy': self.owner,
'creationDate': self.creation_date,
'lastModifiedDate': self.last_modified_date,
'transferData': self.transfer_data
} | [
"def",
"to_description_dict",
"(",
"self",
")",
":",
"return",
"{",
"'certificateArn'",
":",
"self",
".",
"arn",
",",
"'certificateId'",
":",
"self",
".",
"certificate_id",
",",
"'status'",
":",
"self",
".",
"status",
",",
"'certificatePem'",
":",
"self",
".... | You might need keys below in some situation
- caCertificateId
- previousOwnedBy | [
"You",
"might",
"need",
"keys",
"below",
"in",
"some",
"situation",
"-",
"caCertificateId",
"-",
"previousOwnedBy"
] | 4a286c4bc288933bb023396e2784a6fdbb966bc9 | https://github.com/spulec/moto/blob/4a286c4bc288933bb023396e2784a6fdbb966bc9/moto/iot/models.py#L122-L137 | train | 217,080 |
spulec/moto | moto/opsworks/models.py | OpsworkInstance.start | def start(self):
"""
create an ec2 reservation if one doesn't already exist and call
start_instance. Update instance attributes to the newly created instance
attributes
"""
if self.instance is None:
reservation = self.ec2_backend.add_instances(
image_id=self.ami_id,
count=1,
user_data="",
security_group_names=[],
security_group_ids=self.security_group_ids,
instance_type=self.instance_type,
key_name=self.ssh_keyname,
ebs_optimized=self.ebs_optimized,
subnet_id=self.subnet_id,
associate_public_ip=self.associate_public_ip,
)
self.instance = reservation.instances[0]
self.reported_os = {
'Family': 'rhel (fixed)',
'Name': 'amazon (fixed)',
'Version': '2016.03 (fixed)'
}
self.platform = self.instance.platform
self.security_group_ids = self.instance.security_groups
self.architecture = self.instance.architecture
self.virtualization_type = self.instance.virtualization_type
self.subnet_id = self.instance.subnet_id
self.root_device_type = self.instance.root_device_type
self.ec2_backend.start_instances([self.instance.id]) | python | def start(self):
"""
create an ec2 reservation if one doesn't already exist and call
start_instance. Update instance attributes to the newly created instance
attributes
"""
if self.instance is None:
reservation = self.ec2_backend.add_instances(
image_id=self.ami_id,
count=1,
user_data="",
security_group_names=[],
security_group_ids=self.security_group_ids,
instance_type=self.instance_type,
key_name=self.ssh_keyname,
ebs_optimized=self.ebs_optimized,
subnet_id=self.subnet_id,
associate_public_ip=self.associate_public_ip,
)
self.instance = reservation.instances[0]
self.reported_os = {
'Family': 'rhel (fixed)',
'Name': 'amazon (fixed)',
'Version': '2016.03 (fixed)'
}
self.platform = self.instance.platform
self.security_group_ids = self.instance.security_groups
self.architecture = self.instance.architecture
self.virtualization_type = self.instance.virtualization_type
self.subnet_id = self.instance.subnet_id
self.root_device_type = self.instance.root_device_type
self.ec2_backend.start_instances([self.instance.id]) | [
"def",
"start",
"(",
"self",
")",
":",
"if",
"self",
".",
"instance",
"is",
"None",
":",
"reservation",
"=",
"self",
".",
"ec2_backend",
".",
"add_instances",
"(",
"image_id",
"=",
"self",
".",
"ami_id",
",",
"count",
"=",
"1",
",",
"user_data",
"=",
... | create an ec2 reservation if one doesn't already exist and call
start_instance. Update instance attributes to the newly created instance
attributes | [
"create",
"an",
"ec2",
"reservation",
"if",
"one",
"doesn",
"t",
"already",
"exist",
"and",
"call",
"start_instance",
".",
"Update",
"instance",
"attributes",
"to",
"the",
"newly",
"created",
"instance",
"attributes"
] | 4a286c4bc288933bb023396e2784a6fdbb966bc9 | https://github.com/spulec/moto/blob/4a286c4bc288933bb023396e2784a6fdbb966bc9/moto/opsworks/models.py#L84-L116 | train | 217,081 |
spulec/moto | moto/core/responses.py | flatten_json_request_body | def flatten_json_request_body(prefix, dict_body, spec):
"""Convert a JSON request body into query params."""
if len(spec) == 1 and 'type' in spec:
return {prefix: to_str(dict_body, spec)}
flat = {}
for key, value in dict_body.items():
node_type = spec[key]['type']
if node_type == 'list':
for idx, v in enumerate(value, 1):
pref = key + '.member.' + str(idx)
flat.update(flatten_json_request_body(
pref, v, spec[key]['member']))
elif node_type == 'map':
for idx, (k, v) in enumerate(value.items(), 1):
pref = key + '.entry.' + str(idx)
flat.update(flatten_json_request_body(
pref + '.key', k, spec[key]['key']))
flat.update(flatten_json_request_body(
pref + '.value', v, spec[key]['value']))
else:
flat.update(flatten_json_request_body(key, value, spec[key]))
if prefix:
prefix = prefix + '.'
return dict((prefix + k, v) for k, v in flat.items()) | python | def flatten_json_request_body(prefix, dict_body, spec):
"""Convert a JSON request body into query params."""
if len(spec) == 1 and 'type' in spec:
return {prefix: to_str(dict_body, spec)}
flat = {}
for key, value in dict_body.items():
node_type = spec[key]['type']
if node_type == 'list':
for idx, v in enumerate(value, 1):
pref = key + '.member.' + str(idx)
flat.update(flatten_json_request_body(
pref, v, spec[key]['member']))
elif node_type == 'map':
for idx, (k, v) in enumerate(value.items(), 1):
pref = key + '.entry.' + str(idx)
flat.update(flatten_json_request_body(
pref + '.key', k, spec[key]['key']))
flat.update(flatten_json_request_body(
pref + '.value', v, spec[key]['value']))
else:
flat.update(flatten_json_request_body(key, value, spec[key]))
if prefix:
prefix = prefix + '.'
return dict((prefix + k, v) for k, v in flat.items()) | [
"def",
"flatten_json_request_body",
"(",
"prefix",
",",
"dict_body",
",",
"spec",
")",
":",
"if",
"len",
"(",
"spec",
")",
"==",
"1",
"and",
"'type'",
"in",
"spec",
":",
"return",
"{",
"prefix",
":",
"to_str",
"(",
"dict_body",
",",
"spec",
")",
"}",
... | Convert a JSON request body into query params. | [
"Convert",
"a",
"JSON",
"request",
"body",
"into",
"query",
"params",
"."
] | 4a286c4bc288933bb023396e2784a6fdbb966bc9 | https://github.com/spulec/moto/blob/4a286c4bc288933bb023396e2784a6fdbb966bc9/moto/core/responses.py#L751-L776 | train | 217,082 |
spulec/moto | moto/core/responses.py | xml_to_json_response | def xml_to_json_response(service_spec, operation, xml, result_node=None):
"""Convert rendered XML response to JSON for use with boto3."""
def transform(value, spec):
"""Apply transformations to make the output JSON comply with the
expected form. This function applies:
(1) Type cast to nodes with "type" property (e.g., 'true' to
True). XML field values are all in text so this step is
necessary to convert it to valid JSON objects.
(2) Squashes "member" nodes to lists.
"""
if len(spec) == 1:
return from_str(value, spec)
od = OrderedDict()
for k, v in value.items():
if k.startswith('@'):
continue
if k not in spec:
# this can happen when with an older version of
# botocore for which the node in XML template is not
# defined in service spec.
log.warning(
'Field %s is not defined by the botocore version in use', k)
continue
if spec[k]['type'] == 'list':
if v is None:
od[k] = []
elif len(spec[k]['member']) == 1:
if isinstance(v['member'], list):
od[k] = transform(v['member'], spec[k]['member'])
else:
od[k] = [transform(v['member'], spec[k]['member'])]
elif isinstance(v['member'], list):
od[k] = [transform(o, spec[k]['member'])
for o in v['member']]
elif isinstance(v['member'], OrderedDict):
od[k] = [transform(v['member'], spec[k]['member'])]
else:
raise ValueError('Malformatted input')
elif spec[k]['type'] == 'map':
if v is None:
od[k] = {}
else:
items = ([v['entry']] if not isinstance(v['entry'], list) else
v['entry'])
for item in items:
key = from_str(item['key'], spec[k]['key'])
val = from_str(item['value'], spec[k]['value'])
if k not in od:
od[k] = {}
od[k][key] = val
else:
if v is None:
od[k] = None
else:
od[k] = transform(v, spec[k])
return od
dic = xmltodict.parse(xml)
output_spec = service_spec.output_spec(operation)
try:
for k in (result_node or (operation + 'Response', operation + 'Result')):
dic = dic[k]
except KeyError:
return None
else:
return transform(dic, output_spec)
return None | python | def xml_to_json_response(service_spec, operation, xml, result_node=None):
"""Convert rendered XML response to JSON for use with boto3."""
def transform(value, spec):
"""Apply transformations to make the output JSON comply with the
expected form. This function applies:
(1) Type cast to nodes with "type" property (e.g., 'true' to
True). XML field values are all in text so this step is
necessary to convert it to valid JSON objects.
(2) Squashes "member" nodes to lists.
"""
if len(spec) == 1:
return from_str(value, spec)
od = OrderedDict()
for k, v in value.items():
if k.startswith('@'):
continue
if k not in spec:
# this can happen when with an older version of
# botocore for which the node in XML template is not
# defined in service spec.
log.warning(
'Field %s is not defined by the botocore version in use', k)
continue
if spec[k]['type'] == 'list':
if v is None:
od[k] = []
elif len(spec[k]['member']) == 1:
if isinstance(v['member'], list):
od[k] = transform(v['member'], spec[k]['member'])
else:
od[k] = [transform(v['member'], spec[k]['member'])]
elif isinstance(v['member'], list):
od[k] = [transform(o, spec[k]['member'])
for o in v['member']]
elif isinstance(v['member'], OrderedDict):
od[k] = [transform(v['member'], spec[k]['member'])]
else:
raise ValueError('Malformatted input')
elif spec[k]['type'] == 'map':
if v is None:
od[k] = {}
else:
items = ([v['entry']] if not isinstance(v['entry'], list) else
v['entry'])
for item in items:
key = from_str(item['key'], spec[k]['key'])
val = from_str(item['value'], spec[k]['value'])
if k not in od:
od[k] = {}
od[k][key] = val
else:
if v is None:
od[k] = None
else:
od[k] = transform(v, spec[k])
return od
dic = xmltodict.parse(xml)
output_spec = service_spec.output_spec(operation)
try:
for k in (result_node or (operation + 'Response', operation + 'Result')):
dic = dic[k]
except KeyError:
return None
else:
return transform(dic, output_spec)
return None | [
"def",
"xml_to_json_response",
"(",
"service_spec",
",",
"operation",
",",
"xml",
",",
"result_node",
"=",
"None",
")",
":",
"def",
"transform",
"(",
"value",
",",
"spec",
")",
":",
"\"\"\"Apply transformations to make the output JSON comply with the\n expected for... | Convert rendered XML response to JSON for use with boto3. | [
"Convert",
"rendered",
"XML",
"response",
"to",
"JSON",
"for",
"use",
"with",
"boto3",
"."
] | 4a286c4bc288933bb023396e2784a6fdbb966bc9 | https://github.com/spulec/moto/blob/4a286c4bc288933bb023396e2784a6fdbb966bc9/moto/core/responses.py#L779-L852 | train | 217,083 |
spulec/moto | moto/core/responses.py | BaseResponse.get_current_user | def get_current_user(self):
"""
Returns the access key id used in this request as the current user id
"""
if 'Authorization' in self.headers:
match = self.access_key_regex.search(self.headers['Authorization'])
if match:
return match.group(1)
if self.querystring.get('AWSAccessKeyId'):
return self.querystring.get('AWSAccessKeyId')
else:
# Should we raise an unauthorized exception instead?
return '111122223333' | python | def get_current_user(self):
"""
Returns the access key id used in this request as the current user id
"""
if 'Authorization' in self.headers:
match = self.access_key_regex.search(self.headers['Authorization'])
if match:
return match.group(1)
if self.querystring.get('AWSAccessKeyId'):
return self.querystring.get('AWSAccessKeyId')
else:
# Should we raise an unauthorized exception instead?
return '111122223333' | [
"def",
"get_current_user",
"(",
"self",
")",
":",
"if",
"'Authorization'",
"in",
"self",
".",
"headers",
":",
"match",
"=",
"self",
".",
"access_key_regex",
".",
"search",
"(",
"self",
".",
"headers",
"[",
"'Authorization'",
"]",
")",
"if",
"match",
":",
... | Returns the access key id used in this request as the current user id | [
"Returns",
"the",
"access",
"key",
"id",
"used",
"in",
"this",
"request",
"as",
"the",
"current",
"user",
"id"
] | 4a286c4bc288933bb023396e2784a6fdbb966bc9 | https://github.com/spulec/moto/blob/4a286c4bc288933bb023396e2784a6fdbb966bc9/moto/core/responses.py#L183-L196 | train | 217,084 |
spulec/moto | moto/kms/models.py | KmsBackend.delete_alias | def delete_alias(self, alias_name):
"""Delete the alias."""
for aliases in self.key_to_aliases.values():
if alias_name in aliases:
aliases.remove(alias_name) | python | def delete_alias(self, alias_name):
"""Delete the alias."""
for aliases in self.key_to_aliases.values():
if alias_name in aliases:
aliases.remove(alias_name) | [
"def",
"delete_alias",
"(",
"self",
",",
"alias_name",
")",
":",
"for",
"aliases",
"in",
"self",
".",
"key_to_aliases",
".",
"values",
"(",
")",
":",
"if",
"alias_name",
"in",
"aliases",
":",
"aliases",
".",
"remove",
"(",
"alias_name",
")"
] | Delete the alias. | [
"Delete",
"the",
"alias",
"."
] | 4a286c4bc288933bb023396e2784a6fdbb966bc9 | https://github.com/spulec/moto/blob/4a286c4bc288933bb023396e2784a6fdbb966bc9/moto/kms/models.py#L132-L136 | train | 217,085 |
spulec/moto | moto/dynamodb/models.py | DynamoType.compare | def compare(self, range_comparison, range_objs):
"""
Compares this type against comparison filters
"""
range_values = [obj.value for obj in range_objs]
comparison_func = get_comparison_func(range_comparison)
return comparison_func(self.value, *range_values) | python | def compare(self, range_comparison, range_objs):
"""
Compares this type against comparison filters
"""
range_values = [obj.value for obj in range_objs]
comparison_func = get_comparison_func(range_comparison)
return comparison_func(self.value, *range_values) | [
"def",
"compare",
"(",
"self",
",",
"range_comparison",
",",
"range_objs",
")",
":",
"range_values",
"=",
"[",
"obj",
".",
"value",
"for",
"obj",
"in",
"range_objs",
"]",
"comparison_func",
"=",
"get_comparison_func",
"(",
"range_comparison",
")",
"return",
"c... | Compares this type against comparison filters | [
"Compares",
"this",
"type",
"against",
"comparison",
"filters"
] | 4a286c4bc288933bb023396e2784a6fdbb966bc9 | https://github.com/spulec/moto/blob/4a286c4bc288933bb023396e2784a6fdbb966bc9/moto/dynamodb/models.py#L47-L53 | train | 217,086 |
spulec/moto | moto/cognitoidp/models.py | paginate | def paginate(limit, start_arg="next_token", limit_arg="max_results"):
"""Returns a limited result list, and an offset into list of remaining items
Takes the next_token, and max_results kwargs given to a function and handles
the slicing of the results. The kwarg `next_token` is the offset into the
list to begin slicing from. `max_results` is the size of the result required
If the max_results is not supplied then the `limit` parameter is used as a
default
:param limit_arg: the name of argument in the decorated function that
controls amount of items returned
:param start_arg: the name of the argument in the decorated that provides
the starting offset
:param limit: A default maximum items to return
:return: a tuple containing a list of items, and the offset into the list
"""
default_start = 0
def outer_wrapper(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
start = int(default_start if kwargs.get(start_arg) is None else kwargs[start_arg])
lim = int(limit if kwargs.get(limit_arg) is None else kwargs[limit_arg])
stop = start + lim
result = func(*args, **kwargs)
limited_results = list(itertools.islice(result, start, stop))
next_token = stop if stop < len(result) else None
return limited_results, next_token
return wrapper
return outer_wrapper | python | def paginate(limit, start_arg="next_token", limit_arg="max_results"):
"""Returns a limited result list, and an offset into list of remaining items
Takes the next_token, and max_results kwargs given to a function and handles
the slicing of the results. The kwarg `next_token` is the offset into the
list to begin slicing from. `max_results` is the size of the result required
If the max_results is not supplied then the `limit` parameter is used as a
default
:param limit_arg: the name of argument in the decorated function that
controls amount of items returned
:param start_arg: the name of the argument in the decorated that provides
the starting offset
:param limit: A default maximum items to return
:return: a tuple containing a list of items, and the offset into the list
"""
default_start = 0
def outer_wrapper(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
start = int(default_start if kwargs.get(start_arg) is None else kwargs[start_arg])
lim = int(limit if kwargs.get(limit_arg) is None else kwargs[limit_arg])
stop = start + lim
result = func(*args, **kwargs)
limited_results = list(itertools.islice(result, start, stop))
next_token = stop if stop < len(result) else None
return limited_results, next_token
return wrapper
return outer_wrapper | [
"def",
"paginate",
"(",
"limit",
",",
"start_arg",
"=",
"\"next_token\"",
",",
"limit_arg",
"=",
"\"max_results\"",
")",
":",
"default_start",
"=",
"0",
"def",
"outer_wrapper",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",... | Returns a limited result list, and an offset into list of remaining items
Takes the next_token, and max_results kwargs given to a function and handles
the slicing of the results. The kwarg `next_token` is the offset into the
list to begin slicing from. `max_results` is the size of the result required
If the max_results is not supplied then the `limit` parameter is used as a
default
:param limit_arg: the name of argument in the decorated function that
controls amount of items returned
:param start_arg: the name of the argument in the decorated that provides
the starting offset
:param limit: A default maximum items to return
:return: a tuple containing a list of items, and the offset into the list | [
"Returns",
"a",
"limited",
"result",
"list",
"and",
"an",
"offset",
"into",
"list",
"of",
"remaining",
"items"
] | 4a286c4bc288933bb023396e2784a6fdbb966bc9 | https://github.com/spulec/moto/blob/4a286c4bc288933bb023396e2784a6fdbb966bc9/moto/cognitoidp/models.py#L24-L54 | train | 217,087 |
spulec/moto | moto/core/models.py | CallbackResponse._url_matches | def _url_matches(self, url, other, match_querystring=False):
'''
Need to override this so we can fix querystrings breaking regex matching
'''
if not match_querystring:
other = other.split('?', 1)[0]
if responses._is_string(url):
if responses._has_unicode(url):
url = responses._clean_unicode(url)
if not isinstance(other, six.text_type):
other = other.encode('ascii').decode('utf8')
return self._url_matches_strict(url, other)
elif isinstance(url, responses.Pattern) and url.match(other):
return True
else:
return False | python | def _url_matches(self, url, other, match_querystring=False):
'''
Need to override this so we can fix querystrings breaking regex matching
'''
if not match_querystring:
other = other.split('?', 1)[0]
if responses._is_string(url):
if responses._has_unicode(url):
url = responses._clean_unicode(url)
if not isinstance(other, six.text_type):
other = other.encode('ascii').decode('utf8')
return self._url_matches_strict(url, other)
elif isinstance(url, responses.Pattern) and url.match(other):
return True
else:
return False | [
"def",
"_url_matches",
"(",
"self",
",",
"url",
",",
"other",
",",
"match_querystring",
"=",
"False",
")",
":",
"if",
"not",
"match_querystring",
":",
"other",
"=",
"other",
".",
"split",
"(",
"'?'",
",",
"1",
")",
"[",
"0",
"]",
"if",
"responses",
"... | Need to override this so we can fix querystrings breaking regex matching | [
"Need",
"to",
"override",
"this",
"so",
"we",
"can",
"fix",
"querystrings",
"breaking",
"regex",
"matching"
] | 4a286c4bc288933bb023396e2784a6fdbb966bc9 | https://github.com/spulec/moto/blob/4a286c4bc288933bb023396e2784a6fdbb966bc9/moto/core/models.py#L175-L191 | train | 217,088 |
spulec/moto | moto/core/models.py | BaseBackend.urls | def urls(self):
"""
A dictionary of the urls to be mocked with this service and the handlers
that should be called in their place
"""
url_bases = self._url_module.url_bases
unformatted_paths = self._url_module.url_paths
urls = {}
for url_base in url_bases:
for url_path, handler in unformatted_paths.items():
url = url_path.format(url_base)
urls[url] = handler
return urls | python | def urls(self):
"""
A dictionary of the urls to be mocked with this service and the handlers
that should be called in their place
"""
url_bases = self._url_module.url_bases
unformatted_paths = self._url_module.url_paths
urls = {}
for url_base in url_bases:
for url_path, handler in unformatted_paths.items():
url = url_path.format(url_base)
urls[url] = handler
return urls | [
"def",
"urls",
"(",
"self",
")",
":",
"url_bases",
"=",
"self",
".",
"_url_module",
".",
"url_bases",
"unformatted_paths",
"=",
"self",
".",
"_url_module",
".",
"url_paths",
"urls",
"=",
"{",
"}",
"for",
"url_base",
"in",
"url_bases",
":",
"for",
"url_path... | A dictionary of the urls to be mocked with this service and the handlers
that should be called in their place | [
"A",
"dictionary",
"of",
"the",
"urls",
"to",
"be",
"mocked",
"with",
"this",
"service",
"and",
"the",
"handlers",
"that",
"should",
"be",
"called",
"in",
"their",
"place"
] | 4a286c4bc288933bb023396e2784a6fdbb966bc9 | https://github.com/spulec/moto/blob/4a286c4bc288933bb023396e2784a6fdbb966bc9/moto/core/models.py#L484-L498 | train | 217,089 |
spulec/moto | moto/core/models.py | BaseBackend.url_paths | def url_paths(self):
"""
A dictionary of the paths of the urls to be mocked with this service and
the handlers that should be called in their place
"""
unformatted_paths = self._url_module.url_paths
paths = {}
for unformatted_path, handler in unformatted_paths.items():
path = unformatted_path.format("")
paths[path] = handler
return paths | python | def url_paths(self):
"""
A dictionary of the paths of the urls to be mocked with this service and
the handlers that should be called in their place
"""
unformatted_paths = self._url_module.url_paths
paths = {}
for unformatted_path, handler in unformatted_paths.items():
path = unformatted_path.format("")
paths[path] = handler
return paths | [
"def",
"url_paths",
"(",
"self",
")",
":",
"unformatted_paths",
"=",
"self",
".",
"_url_module",
".",
"url_paths",
"paths",
"=",
"{",
"}",
"for",
"unformatted_path",
",",
"handler",
"in",
"unformatted_paths",
".",
"items",
"(",
")",
":",
"path",
"=",
"unfo... | A dictionary of the paths of the urls to be mocked with this service and
the handlers that should be called in their place | [
"A",
"dictionary",
"of",
"the",
"paths",
"of",
"the",
"urls",
"to",
"be",
"mocked",
"with",
"this",
"service",
"and",
"the",
"handlers",
"that",
"should",
"be",
"called",
"in",
"their",
"place"
] | 4a286c4bc288933bb023396e2784a6fdbb966bc9 | https://github.com/spulec/moto/blob/4a286c4bc288933bb023396e2784a6fdbb966bc9/moto/core/models.py#L501-L513 | train | 217,090 |
spulec/moto | moto/core/models.py | BaseBackend.flask_paths | def flask_paths(self):
"""
The url paths that will be used for the flask server
"""
paths = {}
for url_path, handler in self.url_paths.items():
url_path = convert_regex_to_flask_path(url_path)
paths[url_path] = handler
return paths | python | def flask_paths(self):
"""
The url paths that will be used for the flask server
"""
paths = {}
for url_path, handler in self.url_paths.items():
url_path = convert_regex_to_flask_path(url_path)
paths[url_path] = handler
return paths | [
"def",
"flask_paths",
"(",
"self",
")",
":",
"paths",
"=",
"{",
"}",
"for",
"url_path",
",",
"handler",
"in",
"self",
".",
"url_paths",
".",
"items",
"(",
")",
":",
"url_path",
"=",
"convert_regex_to_flask_path",
"(",
"url_path",
")",
"paths",
"[",
"url_... | The url paths that will be used for the flask server | [
"The",
"url",
"paths",
"that",
"will",
"be",
"used",
"for",
"the",
"flask",
"server"
] | 4a286c4bc288933bb023396e2784a6fdbb966bc9 | https://github.com/spulec/moto/blob/4a286c4bc288933bb023396e2784a6fdbb966bc9/moto/core/models.py#L523-L532 | train | 217,091 |
spulec/moto | moto/cloudformation/utils.py | yaml_tag_constructor | def yaml_tag_constructor(loader, tag, node):
"""convert shorthand intrinsic function to full name
"""
def _f(loader, tag, node):
if tag == '!GetAtt':
return node.value.split('.')
elif type(node) == yaml.SequenceNode:
return loader.construct_sequence(node)
else:
return node.value
if tag == '!Ref':
key = 'Ref'
else:
key = 'Fn::{}'.format(tag[1:])
return {key: _f(loader, tag, node)} | python | def yaml_tag_constructor(loader, tag, node):
"""convert shorthand intrinsic function to full name
"""
def _f(loader, tag, node):
if tag == '!GetAtt':
return node.value.split('.')
elif type(node) == yaml.SequenceNode:
return loader.construct_sequence(node)
else:
return node.value
if tag == '!Ref':
key = 'Ref'
else:
key = 'Fn::{}'.format(tag[1:])
return {key: _f(loader, tag, node)} | [
"def",
"yaml_tag_constructor",
"(",
"loader",
",",
"tag",
",",
"node",
")",
":",
"def",
"_f",
"(",
"loader",
",",
"tag",
",",
"node",
")",
":",
"if",
"tag",
"==",
"'!GetAtt'",
":",
"return",
"node",
".",
"value",
".",
"split",
"(",
"'.'",
")",
"eli... | convert shorthand intrinsic function to full name | [
"convert",
"shorthand",
"intrinsic",
"function",
"to",
"full",
"name"
] | 4a286c4bc288933bb023396e2784a6fdbb966bc9 | https://github.com/spulec/moto/blob/4a286c4bc288933bb023396e2784a6fdbb966bc9/moto/cloudformation/utils.py#L36-L52 | train | 217,092 |
spulec/moto | moto/dynamodb/responses.py | DynamoHandler.get_endpoint_name | def get_endpoint_name(self, headers):
"""Parses request headers and extracts part od the X-Amz-Target
that corresponds to a method of DynamoHandler
ie: X-Amz-Target: DynamoDB_20111205.ListTables -> ListTables
"""
# Headers are case-insensitive. Probably a better way to do this.
match = headers.get('x-amz-target') or headers.get('X-Amz-Target')
if match:
return match.split(".")[1] | python | def get_endpoint_name(self, headers):
"""Parses request headers and extracts part od the X-Amz-Target
that corresponds to a method of DynamoHandler
ie: X-Amz-Target: DynamoDB_20111205.ListTables -> ListTables
"""
# Headers are case-insensitive. Probably a better way to do this.
match = headers.get('x-amz-target') or headers.get('X-Amz-Target')
if match:
return match.split(".")[1] | [
"def",
"get_endpoint_name",
"(",
"self",
",",
"headers",
")",
":",
"# Headers are case-insensitive. Probably a better way to do this.",
"match",
"=",
"headers",
".",
"get",
"(",
"'x-amz-target'",
")",
"or",
"headers",
".",
"get",
"(",
"'X-Amz-Target'",
")",
"if",
"m... | Parses request headers and extracts part od the X-Amz-Target
that corresponds to a method of DynamoHandler
ie: X-Amz-Target: DynamoDB_20111205.ListTables -> ListTables | [
"Parses",
"request",
"headers",
"and",
"extracts",
"part",
"od",
"the",
"X",
"-",
"Amz",
"-",
"Target",
"that",
"corresponds",
"to",
"a",
"method",
"of",
"DynamoHandler"
] | 4a286c4bc288933bb023396e2784a6fdbb966bc9 | https://github.com/spulec/moto/blob/4a286c4bc288933bb023396e2784a6fdbb966bc9/moto/dynamodb/responses.py#L12-L21 | train | 217,093 |
spulec/moto | moto/ec2/models.py | InstanceBackend.get_reservations_by_instance_ids | def get_reservations_by_instance_ids(self, instance_ids, filters=None):
""" Go through all of the reservations and filter to only return those
associated with the given instance_ids.
"""
reservations = []
for reservation in self.all_reservations():
reservation_instance_ids = [
instance.id for instance in reservation.instances]
matching_reservation = any(
instance_id in reservation_instance_ids for instance_id in instance_ids)
if matching_reservation:
reservation.instances = [
instance for instance in reservation.instances if instance.id in instance_ids]
reservations.append(reservation)
found_instance_ids = [
instance.id for reservation in reservations for instance in reservation.instances]
if len(found_instance_ids) != len(instance_ids):
invalid_id = list(set(instance_ids).difference(
set(found_instance_ids)))[0]
raise InvalidInstanceIdError(invalid_id)
if filters is not None:
reservations = filter_reservations(reservations, filters)
return reservations | python | def get_reservations_by_instance_ids(self, instance_ids, filters=None):
""" Go through all of the reservations and filter to only return those
associated with the given instance_ids.
"""
reservations = []
for reservation in self.all_reservations():
reservation_instance_ids = [
instance.id for instance in reservation.instances]
matching_reservation = any(
instance_id in reservation_instance_ids for instance_id in instance_ids)
if matching_reservation:
reservation.instances = [
instance for instance in reservation.instances if instance.id in instance_ids]
reservations.append(reservation)
found_instance_ids = [
instance.id for reservation in reservations for instance in reservation.instances]
if len(found_instance_ids) != len(instance_ids):
invalid_id = list(set(instance_ids).difference(
set(found_instance_ids)))[0]
raise InvalidInstanceIdError(invalid_id)
if filters is not None:
reservations = filter_reservations(reservations, filters)
return reservations | [
"def",
"get_reservations_by_instance_ids",
"(",
"self",
",",
"instance_ids",
",",
"filters",
"=",
"None",
")",
":",
"reservations",
"=",
"[",
"]",
"for",
"reservation",
"in",
"self",
".",
"all_reservations",
"(",
")",
":",
"reservation_instance_ids",
"=",
"[",
... | Go through all of the reservations and filter to only return those
associated with the given instance_ids. | [
"Go",
"through",
"all",
"of",
"the",
"reservations",
"and",
"filter",
"to",
"only",
"return",
"those",
"associated",
"with",
"the",
"given",
"instance_ids",
"."
] | 4a286c4bc288933bb023396e2784a6fdbb966bc9 | https://github.com/spulec/moto/blob/4a286c4bc288933bb023396e2784a6fdbb966bc9/moto/ec2/models.py#L829-L851 | train | 217,094 |
spulec/moto | moto/ecs/models.py | EC2ContainerServiceBackend.list_task_definitions | def list_task_definitions(self):
"""
Filtering not implemented
"""
task_arns = []
for task_definition_list in self.task_definitions.values():
task_arns.extend(
[task_definition.arn for task_definition in task_definition_list])
return task_arns | python | def list_task_definitions(self):
"""
Filtering not implemented
"""
task_arns = []
for task_definition_list in self.task_definitions.values():
task_arns.extend(
[task_definition.arn for task_definition in task_definition_list])
return task_arns | [
"def",
"list_task_definitions",
"(",
"self",
")",
":",
"task_arns",
"=",
"[",
"]",
"for",
"task_definition_list",
"in",
"self",
".",
"task_definitions",
".",
"values",
"(",
")",
":",
"task_arns",
".",
"extend",
"(",
"[",
"task_definition",
".",
"arn",
"for",... | Filtering not implemented | [
"Filtering",
"not",
"implemented"
] | 4a286c4bc288933bb023396e2784a6fdbb966bc9 | https://github.com/spulec/moto/blob/4a286c4bc288933bb023396e2784a6fdbb966bc9/moto/ecs/models.py#L481-L489 | train | 217,095 |
spulec/moto | moto/iotdata/models.py | FakeShadow.create_from_previous_version | def create_from_previous_version(cls, previous_shadow, payload):
"""
set None to payload when you want to delete shadow
"""
version, previous_payload = (previous_shadow.version + 1, previous_shadow.to_dict(include_delta=False)) if previous_shadow else (1, {})
if payload is None:
# if given payload is None, delete existing payload
# this means the request was delete_thing_shadow
shadow = FakeShadow(None, None, None, version, deleted=True)
return shadow
# we can make sure that payload has 'state' key
desired = payload['state'].get(
'desired',
previous_payload.get('state', {}).get('desired', None)
)
reported = payload['state'].get(
'reported',
previous_payload.get('state', {}).get('reported', None)
)
shadow = FakeShadow(desired, reported, payload, version)
return shadow | python | def create_from_previous_version(cls, previous_shadow, payload):
"""
set None to payload when you want to delete shadow
"""
version, previous_payload = (previous_shadow.version + 1, previous_shadow.to_dict(include_delta=False)) if previous_shadow else (1, {})
if payload is None:
# if given payload is None, delete existing payload
# this means the request was delete_thing_shadow
shadow = FakeShadow(None, None, None, version, deleted=True)
return shadow
# we can make sure that payload has 'state' key
desired = payload['state'].get(
'desired',
previous_payload.get('state', {}).get('desired', None)
)
reported = payload['state'].get(
'reported',
previous_payload.get('state', {}).get('reported', None)
)
shadow = FakeShadow(desired, reported, payload, version)
return shadow | [
"def",
"create_from_previous_version",
"(",
"cls",
",",
"previous_shadow",
",",
"payload",
")",
":",
"version",
",",
"previous_payload",
"=",
"(",
"previous_shadow",
".",
"version",
"+",
"1",
",",
"previous_shadow",
".",
"to_dict",
"(",
"include_delta",
"=",
"Fa... | set None to payload when you want to delete shadow | [
"set",
"None",
"to",
"payload",
"when",
"you",
"want",
"to",
"delete",
"shadow"
] | 4a286c4bc288933bb023396e2784a6fdbb966bc9 | https://github.com/spulec/moto/blob/4a286c4bc288933bb023396e2784a6fdbb966bc9/moto/iotdata/models.py#L30-L52 | train | 217,096 |
spulec/moto | moto/iotdata/models.py | FakeShadow.to_dict | def to_dict(self, include_delta=True):
"""returning nothing except for just top-level keys for now.
"""
if self.deleted:
return {
'timestamp': self.timestamp,
'version': self.version
}
delta = self.parse_payload(self.desired, self.reported)
payload = {}
if self.desired is not None:
payload['desired'] = self.desired
if self.reported is not None:
payload['reported'] = self.reported
if include_delta and (delta is not None and len(delta.keys()) != 0):
payload['delta'] = delta
metadata = {}
if self.metadata_desired is not None:
metadata['desired'] = self.metadata_desired
if self.metadata_reported is not None:
metadata['reported'] = self.metadata_reported
return {
'state': payload,
'metadata': metadata,
'timestamp': self.timestamp,
'version': self.version
} | python | def to_dict(self, include_delta=True):
"""returning nothing except for just top-level keys for now.
"""
if self.deleted:
return {
'timestamp': self.timestamp,
'version': self.version
}
delta = self.parse_payload(self.desired, self.reported)
payload = {}
if self.desired is not None:
payload['desired'] = self.desired
if self.reported is not None:
payload['reported'] = self.reported
if include_delta and (delta is not None and len(delta.keys()) != 0):
payload['delta'] = delta
metadata = {}
if self.metadata_desired is not None:
metadata['desired'] = self.metadata_desired
if self.metadata_reported is not None:
metadata['reported'] = self.metadata_reported
return {
'state': payload,
'metadata': metadata,
'timestamp': self.timestamp,
'version': self.version
} | [
"def",
"to_dict",
"(",
"self",
",",
"include_delta",
"=",
"True",
")",
":",
"if",
"self",
".",
"deleted",
":",
"return",
"{",
"'timestamp'",
":",
"self",
".",
"timestamp",
",",
"'version'",
":",
"self",
".",
"version",
"}",
"delta",
"=",
"self",
".",
... | returning nothing except for just top-level keys for now. | [
"returning",
"nothing",
"except",
"for",
"just",
"top",
"-",
"level",
"keys",
"for",
"now",
"."
] | 4a286c4bc288933bb023396e2784a6fdbb966bc9 | https://github.com/spulec/moto/blob/4a286c4bc288933bb023396e2784a6fdbb966bc9/moto/iotdata/models.py#L102-L130 | train | 217,097 |
spulec/moto | moto/iotdata/models.py | IoTDataPlaneBackend.delete_thing_shadow | def delete_thing_shadow(self, thing_name):
"""after deleting, get_thing_shadow will raise ResourceNotFound.
But version of the shadow keep increasing...
"""
thing = iot_backends[self.region_name].describe_thing(thing_name)
if thing.thing_shadow is None:
raise ResourceNotFoundException()
payload = None
new_shadow = FakeShadow.create_from_previous_version(thing.thing_shadow, payload)
thing.thing_shadow = new_shadow
return thing.thing_shadow | python | def delete_thing_shadow(self, thing_name):
"""after deleting, get_thing_shadow will raise ResourceNotFound.
But version of the shadow keep increasing...
"""
thing = iot_backends[self.region_name].describe_thing(thing_name)
if thing.thing_shadow is None:
raise ResourceNotFoundException()
payload = None
new_shadow = FakeShadow.create_from_previous_version(thing.thing_shadow, payload)
thing.thing_shadow = new_shadow
return thing.thing_shadow | [
"def",
"delete_thing_shadow",
"(",
"self",
",",
"thing_name",
")",
":",
"thing",
"=",
"iot_backends",
"[",
"self",
".",
"region_name",
"]",
".",
"describe_thing",
"(",
"thing_name",
")",
"if",
"thing",
".",
"thing_shadow",
"is",
"None",
":",
"raise",
"Resour... | after deleting, get_thing_shadow will raise ResourceNotFound.
But version of the shadow keep increasing... | [
"after",
"deleting",
"get_thing_shadow",
"will",
"raise",
"ResourceNotFound",
".",
"But",
"version",
"of",
"the",
"shadow",
"keep",
"increasing",
"..."
] | 4a286c4bc288933bb023396e2784a6fdbb966bc9 | https://github.com/spulec/moto/blob/4a286c4bc288933bb023396e2784a6fdbb966bc9/moto/iotdata/models.py#L175-L185 | train | 217,098 |
spulec/moto | moto/acm/models.py | AWSCertificateManagerBackend._get_arn_from_idempotency_token | def _get_arn_from_idempotency_token(self, token):
"""
If token doesnt exist, return None, later it will be
set with an expiry and arn.
If token expiry has passed, delete entry and return None
Else return ARN
:param token: String token
:return: None or ARN
"""
now = datetime.datetime.now()
if token in self._idempotency_tokens:
if self._idempotency_tokens[token]['expires'] < now:
# Token has expired, new request
del self._idempotency_tokens[token]
return None
else:
return self._idempotency_tokens[token]['arn']
return None | python | def _get_arn_from_idempotency_token(self, token):
"""
If token doesnt exist, return None, later it will be
set with an expiry and arn.
If token expiry has passed, delete entry and return None
Else return ARN
:param token: String token
:return: None or ARN
"""
now = datetime.datetime.now()
if token in self._idempotency_tokens:
if self._idempotency_tokens[token]['expires'] < now:
# Token has expired, new request
del self._idempotency_tokens[token]
return None
else:
return self._idempotency_tokens[token]['arn']
return None | [
"def",
"_get_arn_from_idempotency_token",
"(",
"self",
",",
"token",
")",
":",
"now",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"if",
"token",
"in",
"self",
".",
"_idempotency_tokens",
":",
"if",
"self",
".",
"_idempotency_tokens",
"[",
"token"... | If token doesnt exist, return None, later it will be
set with an expiry and arn.
If token expiry has passed, delete entry and return None
Else return ARN
:param token: String token
:return: None or ARN | [
"If",
"token",
"doesnt",
"exist",
"return",
"None",
"later",
"it",
"will",
"be",
"set",
"with",
"an",
"expiry",
"and",
"arn",
"."
] | 4a286c4bc288933bb023396e2784a6fdbb966bc9 | https://github.com/spulec/moto/blob/4a286c4bc288933bb023396e2784a6fdbb966bc9/moto/acm/models.py#L287-L308 | train | 217,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.