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
sequence | docstring
stringlengths 3
17.3k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 87
242
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
cloudbase/python-hnvclient | hnv/client.py | _BaseHNVModel.refresh | def refresh(self):
"""Get the latest representation of the current model."""
client = self._get_client()
endpoint = self._endpoint.format(
resource_id=self.resource_id or "",
parent_id=self.parent_id or "",
grandparent_id=self.grandparent_id or "")
response = client.get_resource(endpoint)
self._reset_model(response) | python | def refresh(self):
"""Get the latest representation of the current model."""
client = self._get_client()
endpoint = self._endpoint.format(
resource_id=self.resource_id or "",
parent_id=self.parent_id or "",
grandparent_id=self.grandparent_id or "")
response = client.get_resource(endpoint)
self._reset_model(response) | [
"def",
"refresh",
"(",
"self",
")",
":",
"client",
"=",
"self",
".",
"_get_client",
"(",
")",
"endpoint",
"=",
"self",
".",
"_endpoint",
".",
"format",
"(",
"resource_id",
"=",
"self",
".",
"resource_id",
"or",
"\"\"",
",",
"parent_id",
"=",
"self",
".",
"parent_id",
"or",
"\"\"",
",",
"grandparent_id",
"=",
"self",
".",
"grandparent_id",
"or",
"\"\"",
")",
"response",
"=",
"client",
".",
"get_resource",
"(",
"endpoint",
")",
"self",
".",
"_reset_model",
"(",
"response",
")"
] | Get the latest representation of the current model. | [
"Get",
"the",
"latest",
"representation",
"of",
"the",
"current",
"model",
"."
] | b019452af01db22629809b8930357a2ebf6494be | https://github.com/cloudbase/python-hnvclient/blob/b019452af01db22629809b8930357a2ebf6494be/hnv/client.py#L245-L253 | train |
cloudbase/python-hnvclient | hnv/client.py | _BaseHNVModel.commit | def commit(self, if_match=None, wait=True, timeout=None):
"""Apply all the changes on the current model.
:param wait: Whether to wait until the operation is completed
:param timeout: The maximum amount of time required for this
operation to be completed.
If optional :param wait: is True and timeout is None (the default),
block if necessary until the resource is available. If timeout is a
positive number, it blocks at most timeout seconds and raises the
`TimeOut` exception if no item was available within that time.
Otherwise (block is false), return a resource if one is immediately
available, else raise the `NotFound` exception (timeout is ignored
in that case).
"""
if not self._changes:
LOG.debug("No changes available for %s: %s",
self.__class__.__name__, self.resource_id)
return
LOG.debug("Apply all the changes on the current %s: %s",
self.__class__.__name__, self.resource_id)
client = self._get_client()
endpoint = self._endpoint.format(
resource_id=self.resource_id or "",
parent_id=self.parent_id or "",
grandparent_id=self.grandparent_id or "")
request_body = self.dump(include_read_only=False)
response = client.update_resource(endpoint, data=request_body,
if_match=if_match)
elapsed_time = 0
while wait:
self.refresh() # Update the representation of the current model
if self.is_ready():
break
elapsed_time += CONFIG.HNV.retry_interval
if timeout and elapsed_time > timeout:
raise exception.TimeOut("The request timed out.")
time.sleep(CONFIG.HNV.retry_interval)
else:
self._reset_model(response)
# NOTE(alexcoman): In order to keep backwards compatibility the
# `method: commit` will return a reference to itself.
# An example for that can be the following use case:
# label = client.Model().commit()
return self | python | def commit(self, if_match=None, wait=True, timeout=None):
"""Apply all the changes on the current model.
:param wait: Whether to wait until the operation is completed
:param timeout: The maximum amount of time required for this
operation to be completed.
If optional :param wait: is True and timeout is None (the default),
block if necessary until the resource is available. If timeout is a
positive number, it blocks at most timeout seconds and raises the
`TimeOut` exception if no item was available within that time.
Otherwise (block is false), return a resource if one is immediately
available, else raise the `NotFound` exception (timeout is ignored
in that case).
"""
if not self._changes:
LOG.debug("No changes available for %s: %s",
self.__class__.__name__, self.resource_id)
return
LOG.debug("Apply all the changes on the current %s: %s",
self.__class__.__name__, self.resource_id)
client = self._get_client()
endpoint = self._endpoint.format(
resource_id=self.resource_id or "",
parent_id=self.parent_id or "",
grandparent_id=self.grandparent_id or "")
request_body = self.dump(include_read_only=False)
response = client.update_resource(endpoint, data=request_body,
if_match=if_match)
elapsed_time = 0
while wait:
self.refresh() # Update the representation of the current model
if self.is_ready():
break
elapsed_time += CONFIG.HNV.retry_interval
if timeout and elapsed_time > timeout:
raise exception.TimeOut("The request timed out.")
time.sleep(CONFIG.HNV.retry_interval)
else:
self._reset_model(response)
# NOTE(alexcoman): In order to keep backwards compatibility the
# `method: commit` will return a reference to itself.
# An example for that can be the following use case:
# label = client.Model().commit()
return self | [
"def",
"commit",
"(",
"self",
",",
"if_match",
"=",
"None",
",",
"wait",
"=",
"True",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"_changes",
":",
"LOG",
".",
"debug",
"(",
"\"No changes available for %s: %s\"",
",",
"self",
".",
"__class__",
".",
"__name__",
",",
"self",
".",
"resource_id",
")",
"return",
"LOG",
".",
"debug",
"(",
"\"Apply all the changes on the current %s: %s\"",
",",
"self",
".",
"__class__",
".",
"__name__",
",",
"self",
".",
"resource_id",
")",
"client",
"=",
"self",
".",
"_get_client",
"(",
")",
"endpoint",
"=",
"self",
".",
"_endpoint",
".",
"format",
"(",
"resource_id",
"=",
"self",
".",
"resource_id",
"or",
"\"\"",
",",
"parent_id",
"=",
"self",
".",
"parent_id",
"or",
"\"\"",
",",
"grandparent_id",
"=",
"self",
".",
"grandparent_id",
"or",
"\"\"",
")",
"request_body",
"=",
"self",
".",
"dump",
"(",
"include_read_only",
"=",
"False",
")",
"response",
"=",
"client",
".",
"update_resource",
"(",
"endpoint",
",",
"data",
"=",
"request_body",
",",
"if_match",
"=",
"if_match",
")",
"elapsed_time",
"=",
"0",
"while",
"wait",
":",
"self",
".",
"refresh",
"(",
")",
"# Update the representation of the current model",
"if",
"self",
".",
"is_ready",
"(",
")",
":",
"break",
"elapsed_time",
"+=",
"CONFIG",
".",
"HNV",
".",
"retry_interval",
"if",
"timeout",
"and",
"elapsed_time",
">",
"timeout",
":",
"raise",
"exception",
".",
"TimeOut",
"(",
"\"The request timed out.\"",
")",
"time",
".",
"sleep",
"(",
"CONFIG",
".",
"HNV",
".",
"retry_interval",
")",
"else",
":",
"self",
".",
"_reset_model",
"(",
"response",
")",
"# NOTE(alexcoman): In order to keep backwards compatibility the",
"# `method: commit` will return a reference to itself.",
"# An example for that can be the following use case:",
"# label = client.Model().commit()",
"return",
"self"
] | Apply all the changes on the current model.
:param wait: Whether to wait until the operation is completed
:param timeout: The maximum amount of time required for this
operation to be completed.
If optional :param wait: is True and timeout is None (the default),
block if necessary until the resource is available. If timeout is a
positive number, it blocks at most timeout seconds and raises the
`TimeOut` exception if no item was available within that time.
Otherwise (block is false), return a resource if one is immediately
available, else raise the `NotFound` exception (timeout is ignored
in that case). | [
"Apply",
"all",
"the",
"changes",
"on",
"the",
"current",
"model",
"."
] | b019452af01db22629809b8930357a2ebf6494be | https://github.com/cloudbase/python-hnvclient/blob/b019452af01db22629809b8930357a2ebf6494be/hnv/client.py#L255-L303 | train |
cloudbase/python-hnvclient | hnv/client.py | _BaseHNVModel._set_fields | def _set_fields(self, fields):
"""Set or update the fields value."""
super(_BaseHNVModel, self)._set_fields(fields)
if not self.resource_ref:
endpoint = self._endpoint.format(
resource_id=self.resource_id, parent_id=self.parent_id,
grandparent_id=self.grandparent_id)
self.resource_ref = re.sub("(/networking/v[0-9]+)", "", endpoint) | python | def _set_fields(self, fields):
"""Set or update the fields value."""
super(_BaseHNVModel, self)._set_fields(fields)
if not self.resource_ref:
endpoint = self._endpoint.format(
resource_id=self.resource_id, parent_id=self.parent_id,
grandparent_id=self.grandparent_id)
self.resource_ref = re.sub("(/networking/v[0-9]+)", "", endpoint) | [
"def",
"_set_fields",
"(",
"self",
",",
"fields",
")",
":",
"super",
"(",
"_BaseHNVModel",
",",
"self",
")",
".",
"_set_fields",
"(",
"fields",
")",
"if",
"not",
"self",
".",
"resource_ref",
":",
"endpoint",
"=",
"self",
".",
"_endpoint",
".",
"format",
"(",
"resource_id",
"=",
"self",
".",
"resource_id",
",",
"parent_id",
"=",
"self",
".",
"parent_id",
",",
"grandparent_id",
"=",
"self",
".",
"grandparent_id",
")",
"self",
".",
"resource_ref",
"=",
"re",
".",
"sub",
"(",
"\"(/networking/v[0-9]+)\"",
",",
"\"\"",
",",
"endpoint",
")"
] | Set or update the fields value. | [
"Set",
"or",
"update",
"the",
"fields",
"value",
"."
] | b019452af01db22629809b8930357a2ebf6494be | https://github.com/cloudbase/python-hnvclient/blob/b019452af01db22629809b8930357a2ebf6494be/hnv/client.py#L322-L329 | train |
cloudbase/python-hnvclient | hnv/client.py | Resource.get_resource | def get_resource(self):
"""Return the associated resource."""
references = {"resource_id": None, "parent_id": None,
"grandparent_id": None}
for model_cls, regexp in self._regexp.iteritems():
match = regexp.search(self.resource_ref)
if match is not None:
references.update(match.groupdict())
return model_cls.get(**references)
raise exception.NotFound("No model available for %(resource_ref)r",
resource_ref=self.resource_ref) | python | def get_resource(self):
"""Return the associated resource."""
references = {"resource_id": None, "parent_id": None,
"grandparent_id": None}
for model_cls, regexp in self._regexp.iteritems():
match = regexp.search(self.resource_ref)
if match is not None:
references.update(match.groupdict())
return model_cls.get(**references)
raise exception.NotFound("No model available for %(resource_ref)r",
resource_ref=self.resource_ref) | [
"def",
"get_resource",
"(",
"self",
")",
":",
"references",
"=",
"{",
"\"resource_id\"",
":",
"None",
",",
"\"parent_id\"",
":",
"None",
",",
"\"grandparent_id\"",
":",
"None",
"}",
"for",
"model_cls",
",",
"regexp",
"in",
"self",
".",
"_regexp",
".",
"iteritems",
"(",
")",
":",
"match",
"=",
"regexp",
".",
"search",
"(",
"self",
".",
"resource_ref",
")",
"if",
"match",
"is",
"not",
"None",
":",
"references",
".",
"update",
"(",
"match",
".",
"groupdict",
"(",
")",
")",
"return",
"model_cls",
".",
"get",
"(",
"*",
"*",
"references",
")",
"raise",
"exception",
".",
"NotFound",
"(",
"\"No model available for %(resource_ref)r\"",
",",
"resource_ref",
"=",
"self",
".",
"resource_ref",
")"
] | Return the associated resource. | [
"Return",
"the",
"associated",
"resource",
"."
] | b019452af01db22629809b8930357a2ebf6494be | https://github.com/cloudbase/python-hnvclient/blob/b019452af01db22629809b8930357a2ebf6494be/hnv/client.py#L364-L375 | train |
geophysics-ubonn/reda | lib/reda/plotters/histograms.py | _get_nr_bins | def _get_nr_bins(count):
"""depending on the number of data points, compute a best guess for an
optimal number of bins
https://en.wikipedia.org/wiki/Histogram#Number_of_bins_and_width
"""
if count <= 30:
# use the square-root choice, used by Excel and Co
k = np.ceil(np.sqrt(count))
else:
# use Sturges' formula
k = np.ceil(np.log2(count)) + 1
return int(k) | python | def _get_nr_bins(count):
"""depending on the number of data points, compute a best guess for an
optimal number of bins
https://en.wikipedia.org/wiki/Histogram#Number_of_bins_and_width
"""
if count <= 30:
# use the square-root choice, used by Excel and Co
k = np.ceil(np.sqrt(count))
else:
# use Sturges' formula
k = np.ceil(np.log2(count)) + 1
return int(k) | [
"def",
"_get_nr_bins",
"(",
"count",
")",
":",
"if",
"count",
"<=",
"30",
":",
"# use the square-root choice, used by Excel and Co",
"k",
"=",
"np",
".",
"ceil",
"(",
"np",
".",
"sqrt",
"(",
"count",
")",
")",
"else",
":",
"# use Sturges' formula",
"k",
"=",
"np",
".",
"ceil",
"(",
"np",
".",
"log2",
"(",
"count",
")",
")",
"+",
"1",
"return",
"int",
"(",
"k",
")"
] | depending on the number of data points, compute a best guess for an
optimal number of bins
https://en.wikipedia.org/wiki/Histogram#Number_of_bins_and_width | [
"depending",
"on",
"the",
"number",
"of",
"data",
"points",
"compute",
"a",
"best",
"guess",
"for",
"an",
"optimal",
"number",
"of",
"bins"
] | 46a939729e40c7c4723315c03679c40761152e9e | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/plotters/histograms.py#L14-L26 | train |
geophysics-ubonn/reda | lib/reda/plotters/histograms.py | plot_histograms | def plot_histograms(ertobj, keys, **kwargs):
"""Generate histograms for one or more keys in the given container.
Parameters
----------
ertobj : container instance or :class:`pandas.DataFrame`
data object which contains the data.
keys : str or list of strings
which keys (column names) to plot
merge : bool, optional
if True, then generate only one figure with all key-plots as columns
(default True)
log10plot : bool, optional
default: True
extra_dims : list, optional
Examples
--------
>>> from reda.plotters import plot_histograms
>>> from reda.testing import ERTContainer
>>> figs_dict = plot_histograms(ERTContainer, "r", merge=False)
Generating histogram plot for key: r
Returns
-------
figures : dict
dictionary with the generated histogram figures
"""
# you can either provide a DataFrame or an ERT object
if isinstance(ertobj, pd.DataFrame):
df = ertobj
else:
df = ertobj.data
if df.shape[0] == 0:
raise Exception('No data present, cannot plot')
if isinstance(keys, str):
keys = [keys, ]
figures = {}
merge_figs = kwargs.get('merge', True)
if merge_figs:
nr_x = 2
nr_y = len(keys)
size_x = 15 / 2.54
size_y = 5 * nr_y / 2.54
fig, axes_all = plt.subplots(nr_y, nr_x, figsize=(size_x, size_y))
axes_all = np.atleast_2d(axes_all)
for row_nr, key in enumerate(keys):
print('Generating histogram plot for key: {0}'.format(key))
subdata_raw = df[key].values
subdata = subdata_raw[~np.isnan(subdata_raw)]
subdata = subdata[np.isfinite(subdata)]
subdata_log10_with_nan = np.log10(subdata[subdata > 0])
subdata_log10 = subdata_log10_with_nan[~np.isnan(
subdata_log10_with_nan)
]
subdata_log10 = subdata_log10[np.isfinite(subdata_log10)]
if merge_figs:
axes = axes_all[row_nr].squeeze()
else:
fig, axes = plt.subplots(1, 2, figsize=(10 / 2.54, 5 / 2.54))
ax = axes[0]
ax.hist(
subdata,
_get_nr_bins(subdata.size),
)
ax.set_xlabel(
units.get_label(key)
)
ax.set_ylabel('count')
ax.xaxis.set_major_locator(mpl.ticker.MaxNLocator(5))
ax.tick_params(axis='both', which='major', labelsize=6)
ax.tick_params(axis='both', which='minor', labelsize=6)
if subdata_log10.size > 0:
ax = axes[1]
ax.hist(
subdata_log10,
_get_nr_bins(subdata.size),
)
ax.set_xlabel(r'$log_{10}($' + units.get_label(key) + ')')
ax.set_ylabel('count')
ax.xaxis.set_major_locator(mpl.ticker.MaxNLocator(5))
else:
pass
# del(axes[1])
fig.tight_layout()
if not merge_figs:
figures[key] = fig
if merge_figs:
figures['all'] = fig
return figures | python | def plot_histograms(ertobj, keys, **kwargs):
"""Generate histograms for one or more keys in the given container.
Parameters
----------
ertobj : container instance or :class:`pandas.DataFrame`
data object which contains the data.
keys : str or list of strings
which keys (column names) to plot
merge : bool, optional
if True, then generate only one figure with all key-plots as columns
(default True)
log10plot : bool, optional
default: True
extra_dims : list, optional
Examples
--------
>>> from reda.plotters import plot_histograms
>>> from reda.testing import ERTContainer
>>> figs_dict = plot_histograms(ERTContainer, "r", merge=False)
Generating histogram plot for key: r
Returns
-------
figures : dict
dictionary with the generated histogram figures
"""
# you can either provide a DataFrame or an ERT object
if isinstance(ertobj, pd.DataFrame):
df = ertobj
else:
df = ertobj.data
if df.shape[0] == 0:
raise Exception('No data present, cannot plot')
if isinstance(keys, str):
keys = [keys, ]
figures = {}
merge_figs = kwargs.get('merge', True)
if merge_figs:
nr_x = 2
nr_y = len(keys)
size_x = 15 / 2.54
size_y = 5 * nr_y / 2.54
fig, axes_all = plt.subplots(nr_y, nr_x, figsize=(size_x, size_y))
axes_all = np.atleast_2d(axes_all)
for row_nr, key in enumerate(keys):
print('Generating histogram plot for key: {0}'.format(key))
subdata_raw = df[key].values
subdata = subdata_raw[~np.isnan(subdata_raw)]
subdata = subdata[np.isfinite(subdata)]
subdata_log10_with_nan = np.log10(subdata[subdata > 0])
subdata_log10 = subdata_log10_with_nan[~np.isnan(
subdata_log10_with_nan)
]
subdata_log10 = subdata_log10[np.isfinite(subdata_log10)]
if merge_figs:
axes = axes_all[row_nr].squeeze()
else:
fig, axes = plt.subplots(1, 2, figsize=(10 / 2.54, 5 / 2.54))
ax = axes[0]
ax.hist(
subdata,
_get_nr_bins(subdata.size),
)
ax.set_xlabel(
units.get_label(key)
)
ax.set_ylabel('count')
ax.xaxis.set_major_locator(mpl.ticker.MaxNLocator(5))
ax.tick_params(axis='both', which='major', labelsize=6)
ax.tick_params(axis='both', which='minor', labelsize=6)
if subdata_log10.size > 0:
ax = axes[1]
ax.hist(
subdata_log10,
_get_nr_bins(subdata.size),
)
ax.set_xlabel(r'$log_{10}($' + units.get_label(key) + ')')
ax.set_ylabel('count')
ax.xaxis.set_major_locator(mpl.ticker.MaxNLocator(5))
else:
pass
# del(axes[1])
fig.tight_layout()
if not merge_figs:
figures[key] = fig
if merge_figs:
figures['all'] = fig
return figures | [
"def",
"plot_histograms",
"(",
"ertobj",
",",
"keys",
",",
"*",
"*",
"kwargs",
")",
":",
"# you can either provide a DataFrame or an ERT object",
"if",
"isinstance",
"(",
"ertobj",
",",
"pd",
".",
"DataFrame",
")",
":",
"df",
"=",
"ertobj",
"else",
":",
"df",
"=",
"ertobj",
".",
"data",
"if",
"df",
".",
"shape",
"[",
"0",
"]",
"==",
"0",
":",
"raise",
"Exception",
"(",
"'No data present, cannot plot'",
")",
"if",
"isinstance",
"(",
"keys",
",",
"str",
")",
":",
"keys",
"=",
"[",
"keys",
",",
"]",
"figures",
"=",
"{",
"}",
"merge_figs",
"=",
"kwargs",
".",
"get",
"(",
"'merge'",
",",
"True",
")",
"if",
"merge_figs",
":",
"nr_x",
"=",
"2",
"nr_y",
"=",
"len",
"(",
"keys",
")",
"size_x",
"=",
"15",
"/",
"2.54",
"size_y",
"=",
"5",
"*",
"nr_y",
"/",
"2.54",
"fig",
",",
"axes_all",
"=",
"plt",
".",
"subplots",
"(",
"nr_y",
",",
"nr_x",
",",
"figsize",
"=",
"(",
"size_x",
",",
"size_y",
")",
")",
"axes_all",
"=",
"np",
".",
"atleast_2d",
"(",
"axes_all",
")",
"for",
"row_nr",
",",
"key",
"in",
"enumerate",
"(",
"keys",
")",
":",
"print",
"(",
"'Generating histogram plot for key: {0}'",
".",
"format",
"(",
"key",
")",
")",
"subdata_raw",
"=",
"df",
"[",
"key",
"]",
".",
"values",
"subdata",
"=",
"subdata_raw",
"[",
"~",
"np",
".",
"isnan",
"(",
"subdata_raw",
")",
"]",
"subdata",
"=",
"subdata",
"[",
"np",
".",
"isfinite",
"(",
"subdata",
")",
"]",
"subdata_log10_with_nan",
"=",
"np",
".",
"log10",
"(",
"subdata",
"[",
"subdata",
">",
"0",
"]",
")",
"subdata_log10",
"=",
"subdata_log10_with_nan",
"[",
"~",
"np",
".",
"isnan",
"(",
"subdata_log10_with_nan",
")",
"]",
"subdata_log10",
"=",
"subdata_log10",
"[",
"np",
".",
"isfinite",
"(",
"subdata_log10",
")",
"]",
"if",
"merge_figs",
":",
"axes",
"=",
"axes_all",
"[",
"row_nr",
"]",
".",
"squeeze",
"(",
")",
"else",
":",
"fig",
",",
"axes",
"=",
"plt",
".",
"subplots",
"(",
"1",
",",
"2",
",",
"figsize",
"=",
"(",
"10",
"/",
"2.54",
",",
"5",
"/",
"2.54",
")",
")",
"ax",
"=",
"axes",
"[",
"0",
"]",
"ax",
".",
"hist",
"(",
"subdata",
",",
"_get_nr_bins",
"(",
"subdata",
".",
"size",
")",
",",
")",
"ax",
".",
"set_xlabel",
"(",
"units",
".",
"get_label",
"(",
"key",
")",
")",
"ax",
".",
"set_ylabel",
"(",
"'count'",
")",
"ax",
".",
"xaxis",
".",
"set_major_locator",
"(",
"mpl",
".",
"ticker",
".",
"MaxNLocator",
"(",
"5",
")",
")",
"ax",
".",
"tick_params",
"(",
"axis",
"=",
"'both'",
",",
"which",
"=",
"'major'",
",",
"labelsize",
"=",
"6",
")",
"ax",
".",
"tick_params",
"(",
"axis",
"=",
"'both'",
",",
"which",
"=",
"'minor'",
",",
"labelsize",
"=",
"6",
")",
"if",
"subdata_log10",
".",
"size",
">",
"0",
":",
"ax",
"=",
"axes",
"[",
"1",
"]",
"ax",
".",
"hist",
"(",
"subdata_log10",
",",
"_get_nr_bins",
"(",
"subdata",
".",
"size",
")",
",",
")",
"ax",
".",
"set_xlabel",
"(",
"r'$log_{10}($'",
"+",
"units",
".",
"get_label",
"(",
"key",
")",
"+",
"')'",
")",
"ax",
".",
"set_ylabel",
"(",
"'count'",
")",
"ax",
".",
"xaxis",
".",
"set_major_locator",
"(",
"mpl",
".",
"ticker",
".",
"MaxNLocator",
"(",
"5",
")",
")",
"else",
":",
"pass",
"# del(axes[1])",
"fig",
".",
"tight_layout",
"(",
")",
"if",
"not",
"merge_figs",
":",
"figures",
"[",
"key",
"]",
"=",
"fig",
"if",
"merge_figs",
":",
"figures",
"[",
"'all'",
"]",
"=",
"fig",
"return",
"figures"
] | Generate histograms for one or more keys in the given container.
Parameters
----------
ertobj : container instance or :class:`pandas.DataFrame`
data object which contains the data.
keys : str or list of strings
which keys (column names) to plot
merge : bool, optional
if True, then generate only one figure with all key-plots as columns
(default True)
log10plot : bool, optional
default: True
extra_dims : list, optional
Examples
--------
>>> from reda.plotters import plot_histograms
>>> from reda.testing import ERTContainer
>>> figs_dict = plot_histograms(ERTContainer, "r", merge=False)
Generating histogram plot for key: r
Returns
-------
figures : dict
dictionary with the generated histogram figures | [
"Generate",
"histograms",
"for",
"one",
"or",
"more",
"keys",
"in",
"the",
"given",
"container",
"."
] | 46a939729e40c7c4723315c03679c40761152e9e | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/plotters/histograms.py#L29-L130 | train |
geophysics-ubonn/reda | lib/reda/plotters/histograms.py | plot_histograms_extra_dims | def plot_histograms_extra_dims(dataobj, keys, **kwargs):
"""Produce histograms grouped by the extra dimensions.
Extra dimensions are:
* timesteps
* frequency
Parameters
----------
dataobj : :py:class:`pandas.DataFrame` or reda container
The data container/data frame which holds the data
keys: list|tuple|iterable
The keys (columns) of the dataobj to plot
subquery : string, optional
?
log10plot: bool
if True, generate linear and log10 versions of the histogram
Nx : int, optional
?
Returns
-------
Examples
--------
>>> import reda.testing.containers
>>> ert = reda.testing.containers.ERTContainer_nr
>>> import reda.plotters.histograms as RH
>>> fig = RH.plot_histograms_extra_dims(ert, ['r', ])
>>> import reda.testing.containers
>>> ert = reda.testing.containers.ERTContainer_nr
>>> import reda.plotters.histograms as RH
>>> fig = RH.plot_histograms_extra_dims(ert, ['r', 'a'])
"""
if isinstance(dataobj, pd.DataFrame):
df_raw = dataobj
else:
df_raw = dataobj.data
if kwargs.get('subquery', False):
df = df_raw.query(kwargs.get('subquery'))
else:
df = df_raw
split_timestamps = True
if split_timestamps:
group_timestamps = df.groupby('timestep')
N_ts = len(group_timestamps.groups.keys())
else:
group_timestamps = ('all', df)
N_ts = 1
columns = keys
N_c = len(columns)
plot_log10 = kwargs.get('log10plot', False)
if plot_log10:
transformers = ['lin', 'log10']
N_log10 = 2
else:
transformers = ['lin', ]
N_log10 = 1
# determine layout of plots
Nx_max = kwargs.get('Nx', 4)
N = N_ts * N_c * N_log10
Nx = min(Nx_max, N)
Ny = int(np.ceil(N / Nx))
size_x = 5 * Nx / 2.54
size_y = 5 * Ny / 2.54
fig, axes = plt.subplots(Ny, Nx, figsize=(size_x, size_y), sharex=True,
sharey=True)
axes = np.atleast_2d(axes)
index = 0
for ts_name, tgroup in group_timestamps:
for column in columns:
for transformer in transformers:
# print('{0}-{1}-{2}'.format(ts_name, column, transformer))
subdata_raw = tgroup[column].values
subdata = subdata_raw[~np.isnan(subdata_raw)]
subdata = subdata[np.isfinite(subdata)]
if transformer == 'log10':
subdata_log10_with_nan = np.log10(subdata[subdata > 0])
subdata_log10 = subdata_log10_with_nan[~np.isnan(
subdata_log10_with_nan)
]
subdata_log10 = subdata_log10[np.isfinite(subdata_log10)]
subdata = subdata_log10
ax = axes.flat[index]
ax.hist(
subdata,
_get_nr_bins(subdata.size),
)
ax.set_xlabel(
units.get_label(column)
)
ax.set_ylabel('count')
ax.xaxis.set_major_locator(mpl.ticker.MaxNLocator(3))
ax.tick_params(axis='both', which='major', labelsize=6)
ax.tick_params(axis='both', which='minor', labelsize=6)
ax.set_title("timestep: %d" % ts_name)
index += 1
# remove some labels
for ax in axes[:, 1:].flat:
ax.set_ylabel('')
for ax in axes[:-1, :].flat:
ax.set_xlabel('')
fig.tight_layout()
return fig | python | def plot_histograms_extra_dims(dataobj, keys, **kwargs):
"""Produce histograms grouped by the extra dimensions.
Extra dimensions are:
* timesteps
* frequency
Parameters
----------
dataobj : :py:class:`pandas.DataFrame` or reda container
The data container/data frame which holds the data
keys: list|tuple|iterable
The keys (columns) of the dataobj to plot
subquery : string, optional
?
log10plot: bool
if True, generate linear and log10 versions of the histogram
Nx : int, optional
?
Returns
-------
Examples
--------
>>> import reda.testing.containers
>>> ert = reda.testing.containers.ERTContainer_nr
>>> import reda.plotters.histograms as RH
>>> fig = RH.plot_histograms_extra_dims(ert, ['r', ])
>>> import reda.testing.containers
>>> ert = reda.testing.containers.ERTContainer_nr
>>> import reda.plotters.histograms as RH
>>> fig = RH.plot_histograms_extra_dims(ert, ['r', 'a'])
"""
if isinstance(dataobj, pd.DataFrame):
df_raw = dataobj
else:
df_raw = dataobj.data
if kwargs.get('subquery', False):
df = df_raw.query(kwargs.get('subquery'))
else:
df = df_raw
split_timestamps = True
if split_timestamps:
group_timestamps = df.groupby('timestep')
N_ts = len(group_timestamps.groups.keys())
else:
group_timestamps = ('all', df)
N_ts = 1
columns = keys
N_c = len(columns)
plot_log10 = kwargs.get('log10plot', False)
if plot_log10:
transformers = ['lin', 'log10']
N_log10 = 2
else:
transformers = ['lin', ]
N_log10 = 1
# determine layout of plots
Nx_max = kwargs.get('Nx', 4)
N = N_ts * N_c * N_log10
Nx = min(Nx_max, N)
Ny = int(np.ceil(N / Nx))
size_x = 5 * Nx / 2.54
size_y = 5 * Ny / 2.54
fig, axes = plt.subplots(Ny, Nx, figsize=(size_x, size_y), sharex=True,
sharey=True)
axes = np.atleast_2d(axes)
index = 0
for ts_name, tgroup in group_timestamps:
for column in columns:
for transformer in transformers:
# print('{0}-{1}-{2}'.format(ts_name, column, transformer))
subdata_raw = tgroup[column].values
subdata = subdata_raw[~np.isnan(subdata_raw)]
subdata = subdata[np.isfinite(subdata)]
if transformer == 'log10':
subdata_log10_with_nan = np.log10(subdata[subdata > 0])
subdata_log10 = subdata_log10_with_nan[~np.isnan(
subdata_log10_with_nan)
]
subdata_log10 = subdata_log10[np.isfinite(subdata_log10)]
subdata = subdata_log10
ax = axes.flat[index]
ax.hist(
subdata,
_get_nr_bins(subdata.size),
)
ax.set_xlabel(
units.get_label(column)
)
ax.set_ylabel('count')
ax.xaxis.set_major_locator(mpl.ticker.MaxNLocator(3))
ax.tick_params(axis='both', which='major', labelsize=6)
ax.tick_params(axis='both', which='minor', labelsize=6)
ax.set_title("timestep: %d" % ts_name)
index += 1
# remove some labels
for ax in axes[:, 1:].flat:
ax.set_ylabel('')
for ax in axes[:-1, :].flat:
ax.set_xlabel('')
fig.tight_layout()
return fig | [
"def",
"plot_histograms_extra_dims",
"(",
"dataobj",
",",
"keys",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"dataobj",
",",
"pd",
".",
"DataFrame",
")",
":",
"df_raw",
"=",
"dataobj",
"else",
":",
"df_raw",
"=",
"dataobj",
".",
"data",
"if",
"kwargs",
".",
"get",
"(",
"'subquery'",
",",
"False",
")",
":",
"df",
"=",
"df_raw",
".",
"query",
"(",
"kwargs",
".",
"get",
"(",
"'subquery'",
")",
")",
"else",
":",
"df",
"=",
"df_raw",
"split_timestamps",
"=",
"True",
"if",
"split_timestamps",
":",
"group_timestamps",
"=",
"df",
".",
"groupby",
"(",
"'timestep'",
")",
"N_ts",
"=",
"len",
"(",
"group_timestamps",
".",
"groups",
".",
"keys",
"(",
")",
")",
"else",
":",
"group_timestamps",
"=",
"(",
"'all'",
",",
"df",
")",
"N_ts",
"=",
"1",
"columns",
"=",
"keys",
"N_c",
"=",
"len",
"(",
"columns",
")",
"plot_log10",
"=",
"kwargs",
".",
"get",
"(",
"'log10plot'",
",",
"False",
")",
"if",
"plot_log10",
":",
"transformers",
"=",
"[",
"'lin'",
",",
"'log10'",
"]",
"N_log10",
"=",
"2",
"else",
":",
"transformers",
"=",
"[",
"'lin'",
",",
"]",
"N_log10",
"=",
"1",
"# determine layout of plots",
"Nx_max",
"=",
"kwargs",
".",
"get",
"(",
"'Nx'",
",",
"4",
")",
"N",
"=",
"N_ts",
"*",
"N_c",
"*",
"N_log10",
"Nx",
"=",
"min",
"(",
"Nx_max",
",",
"N",
")",
"Ny",
"=",
"int",
"(",
"np",
".",
"ceil",
"(",
"N",
"/",
"Nx",
")",
")",
"size_x",
"=",
"5",
"*",
"Nx",
"/",
"2.54",
"size_y",
"=",
"5",
"*",
"Ny",
"/",
"2.54",
"fig",
",",
"axes",
"=",
"plt",
".",
"subplots",
"(",
"Ny",
",",
"Nx",
",",
"figsize",
"=",
"(",
"size_x",
",",
"size_y",
")",
",",
"sharex",
"=",
"True",
",",
"sharey",
"=",
"True",
")",
"axes",
"=",
"np",
".",
"atleast_2d",
"(",
"axes",
")",
"index",
"=",
"0",
"for",
"ts_name",
",",
"tgroup",
"in",
"group_timestamps",
":",
"for",
"column",
"in",
"columns",
":",
"for",
"transformer",
"in",
"transformers",
":",
"# print('{0}-{1}-{2}'.format(ts_name, column, transformer))",
"subdata_raw",
"=",
"tgroup",
"[",
"column",
"]",
".",
"values",
"subdata",
"=",
"subdata_raw",
"[",
"~",
"np",
".",
"isnan",
"(",
"subdata_raw",
")",
"]",
"subdata",
"=",
"subdata",
"[",
"np",
".",
"isfinite",
"(",
"subdata",
")",
"]",
"if",
"transformer",
"==",
"'log10'",
":",
"subdata_log10_with_nan",
"=",
"np",
".",
"log10",
"(",
"subdata",
"[",
"subdata",
">",
"0",
"]",
")",
"subdata_log10",
"=",
"subdata_log10_with_nan",
"[",
"~",
"np",
".",
"isnan",
"(",
"subdata_log10_with_nan",
")",
"]",
"subdata_log10",
"=",
"subdata_log10",
"[",
"np",
".",
"isfinite",
"(",
"subdata_log10",
")",
"]",
"subdata",
"=",
"subdata_log10",
"ax",
"=",
"axes",
".",
"flat",
"[",
"index",
"]",
"ax",
".",
"hist",
"(",
"subdata",
",",
"_get_nr_bins",
"(",
"subdata",
".",
"size",
")",
",",
")",
"ax",
".",
"set_xlabel",
"(",
"units",
".",
"get_label",
"(",
"column",
")",
")",
"ax",
".",
"set_ylabel",
"(",
"'count'",
")",
"ax",
".",
"xaxis",
".",
"set_major_locator",
"(",
"mpl",
".",
"ticker",
".",
"MaxNLocator",
"(",
"3",
")",
")",
"ax",
".",
"tick_params",
"(",
"axis",
"=",
"'both'",
",",
"which",
"=",
"'major'",
",",
"labelsize",
"=",
"6",
")",
"ax",
".",
"tick_params",
"(",
"axis",
"=",
"'both'",
",",
"which",
"=",
"'minor'",
",",
"labelsize",
"=",
"6",
")",
"ax",
".",
"set_title",
"(",
"\"timestep: %d\"",
"%",
"ts_name",
")",
"index",
"+=",
"1",
"# remove some labels",
"for",
"ax",
"in",
"axes",
"[",
":",
",",
"1",
":",
"]",
".",
"flat",
":",
"ax",
".",
"set_ylabel",
"(",
"''",
")",
"for",
"ax",
"in",
"axes",
"[",
":",
"-",
"1",
",",
":",
"]",
".",
"flat",
":",
"ax",
".",
"set_xlabel",
"(",
"''",
")",
"fig",
".",
"tight_layout",
"(",
")",
"return",
"fig"
] | Produce histograms grouped by the extra dimensions.
Extra dimensions are:
* timesteps
* frequency
Parameters
----------
dataobj : :py:class:`pandas.DataFrame` or reda container
The data container/data frame which holds the data
keys: list|tuple|iterable
The keys (columns) of the dataobj to plot
subquery : string, optional
?
log10plot: bool
if True, generate linear and log10 versions of the histogram
Nx : int, optional
?
Returns
-------
Examples
--------
>>> import reda.testing.containers
>>> ert = reda.testing.containers.ERTContainer_nr
>>> import reda.plotters.histograms as RH
>>> fig = RH.plot_histograms_extra_dims(ert, ['r', ])
>>> import reda.testing.containers
>>> ert = reda.testing.containers.ERTContainer_nr
>>> import reda.plotters.histograms as RH
>>> fig = RH.plot_histograms_extra_dims(ert, ['r', 'a']) | [
"Produce",
"histograms",
"grouped",
"by",
"the",
"extra",
"dimensions",
"."
] | 46a939729e40c7c4723315c03679c40761152e9e | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/plotters/histograms.py#L133-L252 | train |
openvax/mhcnames | mhcnames/parsing_helpers.py | parse_substring | def parse_substring(allele, pred, max_len=None):
"""
Extract substring of letters for which predicate is True
"""
result = ""
pos = 0
if max_len is None:
max_len = len(allele)
else:
max_len = min(max_len, len(allele))
while pos < max_len and pred(allele[pos]):
result += allele[pos]
pos += 1
return result, allele[pos:] | python | def parse_substring(allele, pred, max_len=None):
"""
Extract substring of letters for which predicate is True
"""
result = ""
pos = 0
if max_len is None:
max_len = len(allele)
else:
max_len = min(max_len, len(allele))
while pos < max_len and pred(allele[pos]):
result += allele[pos]
pos += 1
return result, allele[pos:] | [
"def",
"parse_substring",
"(",
"allele",
",",
"pred",
",",
"max_len",
"=",
"None",
")",
":",
"result",
"=",
"\"\"",
"pos",
"=",
"0",
"if",
"max_len",
"is",
"None",
":",
"max_len",
"=",
"len",
"(",
"allele",
")",
"else",
":",
"max_len",
"=",
"min",
"(",
"max_len",
",",
"len",
"(",
"allele",
")",
")",
"while",
"pos",
"<",
"max_len",
"and",
"pred",
"(",
"allele",
"[",
"pos",
"]",
")",
":",
"result",
"+=",
"allele",
"[",
"pos",
"]",
"pos",
"+=",
"1",
"return",
"result",
",",
"allele",
"[",
"pos",
":",
"]"
] | Extract substring of letters for which predicate is True | [
"Extract",
"substring",
"of",
"letters",
"for",
"which",
"predicate",
"is",
"True"
] | 71694b9d620db68ceee44da1b8422ff436f15bd3 | https://github.com/openvax/mhcnames/blob/71694b9d620db68ceee44da1b8422ff436f15bd3/mhcnames/parsing_helpers.py#L18-L31 | train |
gitenberg-dev/gitberg | gitenberg/book.py | Book.fetch | def fetch(self):
""" just pull files from PG
"""
if not self.local_path:
self.make_local_path()
fetcher = BookFetcher(self)
fetcher.fetch() | python | def fetch(self):
""" just pull files from PG
"""
if not self.local_path:
self.make_local_path()
fetcher = BookFetcher(self)
fetcher.fetch() | [
"def",
"fetch",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"local_path",
":",
"self",
".",
"make_local_path",
"(",
")",
"fetcher",
"=",
"BookFetcher",
"(",
"self",
")",
"fetcher",
".",
"fetch",
"(",
")"
] | just pull files from PG | [
"just",
"pull",
"files",
"from",
"PG"
] | 3f6db8b5a22ccdd2110d3199223c30db4e558b5c | https://github.com/gitenberg-dev/gitberg/blob/3f6db8b5a22ccdd2110d3199223c30db4e558b5c/gitenberg/book.py#L174-L180 | train |
gitenberg-dev/gitberg | gitenberg/book.py | Book.make | def make(self):
""" turn fetched files into a local repo, make auxiliary files
"""
logger.debug("preparing to add all git files")
num_added = self.local_repo.add_all_files()
if num_added:
self.local_repo.commit("Initial import from Project Gutenberg")
file_handler = NewFilesHandler(self)
file_handler.add_new_files()
num_added = self.local_repo.add_all_files()
if num_added:
self.local_repo.commit(
"Updates Readme, contributing, license files, cover, metadata."
) | python | def make(self):
""" turn fetched files into a local repo, make auxiliary files
"""
logger.debug("preparing to add all git files")
num_added = self.local_repo.add_all_files()
if num_added:
self.local_repo.commit("Initial import from Project Gutenberg")
file_handler = NewFilesHandler(self)
file_handler.add_new_files()
num_added = self.local_repo.add_all_files()
if num_added:
self.local_repo.commit(
"Updates Readme, contributing, license files, cover, metadata."
) | [
"def",
"make",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"\"preparing to add all git files\"",
")",
"num_added",
"=",
"self",
".",
"local_repo",
".",
"add_all_files",
"(",
")",
"if",
"num_added",
":",
"self",
".",
"local_repo",
".",
"commit",
"(",
"\"Initial import from Project Gutenberg\"",
")",
"file_handler",
"=",
"NewFilesHandler",
"(",
"self",
")",
"file_handler",
".",
"add_new_files",
"(",
")",
"num_added",
"=",
"self",
".",
"local_repo",
".",
"add_all_files",
"(",
")",
"if",
"num_added",
":",
"self",
".",
"local_repo",
".",
"commit",
"(",
"\"Updates Readme, contributing, license files, cover, metadata.\"",
")"
] | turn fetched files into a local repo, make auxiliary files | [
"turn",
"fetched",
"files",
"into",
"a",
"local",
"repo",
"make",
"auxiliary",
"files"
] | 3f6db8b5a22ccdd2110d3199223c30db4e558b5c | https://github.com/gitenberg-dev/gitberg/blob/3f6db8b5a22ccdd2110d3199223c30db4e558b5c/gitenberg/book.py#L193-L208 | train |
gitenberg-dev/gitberg | gitenberg/book.py | Book.push | def push(self):
""" create a github repo and push the local repo into it
"""
self.github_repo.create_and_push()
self._repo = self.github_repo.repo
return self._repo | python | def push(self):
""" create a github repo and push the local repo into it
"""
self.github_repo.create_and_push()
self._repo = self.github_repo.repo
return self._repo | [
"def",
"push",
"(",
"self",
")",
":",
"self",
".",
"github_repo",
".",
"create_and_push",
"(",
")",
"self",
".",
"_repo",
"=",
"self",
".",
"github_repo",
".",
"repo",
"return",
"self",
".",
"_repo"
] | create a github repo and push the local repo into it | [
"create",
"a",
"github",
"repo",
"and",
"push",
"the",
"local",
"repo",
"into",
"it"
] | 3f6db8b5a22ccdd2110d3199223c30db4e558b5c | https://github.com/gitenberg-dev/gitberg/blob/3f6db8b5a22ccdd2110d3199223c30db4e558b5c/gitenberg/book.py#L213-L218 | train |
gitenberg-dev/gitberg | gitenberg/book.py | Book.tag | def tag(self, version='bump', message=''):
""" tag and commit
"""
self.clone_from_github()
self.github_repo.tag(version, message=message) | python | def tag(self, version='bump', message=''):
""" tag and commit
"""
self.clone_from_github()
self.github_repo.tag(version, message=message) | [
"def",
"tag",
"(",
"self",
",",
"version",
"=",
"'bump'",
",",
"message",
"=",
"''",
")",
":",
"self",
".",
"clone_from_github",
"(",
")",
"self",
".",
"github_repo",
".",
"tag",
"(",
"version",
",",
"message",
"=",
"message",
")"
] | tag and commit | [
"tag",
"and",
"commit"
] | 3f6db8b5a22ccdd2110d3199223c30db4e558b5c | https://github.com/gitenberg-dev/gitberg/blob/3f6db8b5a22ccdd2110d3199223c30db4e558b5c/gitenberg/book.py#L225-L229 | train |
gitenberg-dev/gitberg | gitenberg/book.py | Book.format_title | def format_title(self):
def asciify(_title):
_title = unicodedata.normalize('NFD', unicode(_title))
ascii = True
out = []
ok = u"1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM- ',"
for ch in _title:
if ch in ok:
out.append(ch)
elif unicodedata.category(ch)[0] == ("L"): #a letter
out.append(hex(ord(ch)))
ascii = False
elif ch in u'\r\n\t':
out.append(u'-')
return (ascii, sub("[ ',-]+", '-', "".join(out)) )
""" Takes a string and sanitizes it for Github's url name format """
(ascii, _title) = asciify(self.meta.title)
if not ascii and self.meta.alternative_title:
(ascii, _title2) = asciify(self.meta.alternative_title)
if ascii:
_title = _title2
title_length = 99 - len(str(self.book_id)) - 1
if len(_title) > title_length:
# if the title was shortened, replace the trailing _ with an ellipsis
repo_title = "{0}__{1}".format(_title[:title_length], self.book_id)
else:
repo_title = "{0}_{1}".format(_title[:title_length], self.book_id)
logger.debug("%s %s" % (len(repo_title), repo_title))
self.meta.metadata['_repo'] = repo_title
return repo_title | python | def format_title(self):
def asciify(_title):
_title = unicodedata.normalize('NFD', unicode(_title))
ascii = True
out = []
ok = u"1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM- ',"
for ch in _title:
if ch in ok:
out.append(ch)
elif unicodedata.category(ch)[0] == ("L"): #a letter
out.append(hex(ord(ch)))
ascii = False
elif ch in u'\r\n\t':
out.append(u'-')
return (ascii, sub("[ ',-]+", '-', "".join(out)) )
""" Takes a string and sanitizes it for Github's url name format """
(ascii, _title) = asciify(self.meta.title)
if not ascii and self.meta.alternative_title:
(ascii, _title2) = asciify(self.meta.alternative_title)
if ascii:
_title = _title2
title_length = 99 - len(str(self.book_id)) - 1
if len(_title) > title_length:
# if the title was shortened, replace the trailing _ with an ellipsis
repo_title = "{0}__{1}".format(_title[:title_length], self.book_id)
else:
repo_title = "{0}_{1}".format(_title[:title_length], self.book_id)
logger.debug("%s %s" % (len(repo_title), repo_title))
self.meta.metadata['_repo'] = repo_title
return repo_title | [
"def",
"format_title",
"(",
"self",
")",
":",
"def",
"asciify",
"(",
"_title",
")",
":",
"_title",
"=",
"unicodedata",
".",
"normalize",
"(",
"'NFD'",
",",
"unicode",
"(",
"_title",
")",
")",
"ascii",
"=",
"True",
"out",
"=",
"[",
"]",
"ok",
"=",
"u\"1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM- ',\"",
"for",
"ch",
"in",
"_title",
":",
"if",
"ch",
"in",
"ok",
":",
"out",
".",
"append",
"(",
"ch",
")",
"elif",
"unicodedata",
".",
"category",
"(",
"ch",
")",
"[",
"0",
"]",
"==",
"(",
"\"L\"",
")",
":",
"#a letter",
"out",
".",
"append",
"(",
"hex",
"(",
"ord",
"(",
"ch",
")",
")",
")",
"ascii",
"=",
"False",
"elif",
"ch",
"in",
"u'\\r\\n\\t'",
":",
"out",
".",
"append",
"(",
"u'-'",
")",
"return",
"(",
"ascii",
",",
"sub",
"(",
"\"[ ',-]+\"",
",",
"'-'",
",",
"\"\"",
".",
"join",
"(",
"out",
")",
")",
")",
"(",
"ascii",
",",
"_title",
")",
"=",
"asciify",
"(",
"self",
".",
"meta",
".",
"title",
")",
"if",
"not",
"ascii",
"and",
"self",
".",
"meta",
".",
"alternative_title",
":",
"(",
"ascii",
",",
"_title2",
")",
"=",
"asciify",
"(",
"self",
".",
"meta",
".",
"alternative_title",
")",
"if",
"ascii",
":",
"_title",
"=",
"_title2",
"title_length",
"=",
"99",
"-",
"len",
"(",
"str",
"(",
"self",
".",
"book_id",
")",
")",
"-",
"1",
"if",
"len",
"(",
"_title",
")",
">",
"title_length",
":",
"# if the title was shortened, replace the trailing _ with an ellipsis",
"repo_title",
"=",
"\"{0}__{1}\"",
".",
"format",
"(",
"_title",
"[",
":",
"title_length",
"]",
",",
"self",
".",
"book_id",
")",
"else",
":",
"repo_title",
"=",
"\"{0}_{1}\"",
".",
"format",
"(",
"_title",
"[",
":",
"title_length",
"]",
",",
"self",
".",
"book_id",
")",
"logger",
".",
"debug",
"(",
"\"%s %s\"",
"%",
"(",
"len",
"(",
"repo_title",
")",
",",
"repo_title",
")",
")",
"self",
".",
"meta",
".",
"metadata",
"[",
"'_repo'",
"]",
"=",
"repo_title",
"return",
"repo_title"
] | Takes a string and sanitizes it for Github's url name format | [
"Takes",
"a",
"string",
"and",
"sanitizes",
"it",
"for",
"Github",
"s",
"url",
"name",
"format"
] | 3f6db8b5a22ccdd2110d3199223c30db4e558b5c | https://github.com/gitenberg-dev/gitberg/blob/3f6db8b5a22ccdd2110d3199223c30db4e558b5c/gitenberg/book.py#L266-L296 | train |
rfverbruggen/rachiopy | rachiopy/__init__.py | Rachio._request | def _request(self, path, method, body=None):
"""Make a request from the API."""
url = '/'.join([_SERVER, path])
(resp, content) = _HTTP.request(url, method,
headers=self._headers, body=body)
content_type = resp.get('content-type')
if content_type and content_type.startswith('application/json'):
content = json.loads(content.decode('UTF-8'))
return (resp, content) | python | def _request(self, path, method, body=None):
"""Make a request from the API."""
url = '/'.join([_SERVER, path])
(resp, content) = _HTTP.request(url, method,
headers=self._headers, body=body)
content_type = resp.get('content-type')
if content_type and content_type.startswith('application/json'):
content = json.loads(content.decode('UTF-8'))
return (resp, content) | [
"def",
"_request",
"(",
"self",
",",
"path",
",",
"method",
",",
"body",
"=",
"None",
")",
":",
"url",
"=",
"'/'",
".",
"join",
"(",
"[",
"_SERVER",
",",
"path",
"]",
")",
"(",
"resp",
",",
"content",
")",
"=",
"_HTTP",
".",
"request",
"(",
"url",
",",
"method",
",",
"headers",
"=",
"self",
".",
"_headers",
",",
"body",
"=",
"body",
")",
"content_type",
"=",
"resp",
".",
"get",
"(",
"'content-type'",
")",
"if",
"content_type",
"and",
"content_type",
".",
"startswith",
"(",
"'application/json'",
")",
":",
"content",
"=",
"json",
".",
"loads",
"(",
"content",
".",
"decode",
"(",
"'UTF-8'",
")",
")",
"return",
"(",
"resp",
",",
"content",
")"
] | Make a request from the API. | [
"Make",
"a",
"request",
"from",
"the",
"API",
"."
] | c91abc9984f0f453e60fa905285c1b640c3390ae | https://github.com/rfverbruggen/rachiopy/blob/c91abc9984f0f453e60fa905285c1b640c3390ae/rachiopy/__init__.py#L32-L42 | train |
rfverbruggen/rachiopy | rachiopy/__init__.py | Rachio.put | def put(self, path, payload):
"""Make a PUT request from the API."""
body = json.dumps(payload)
return self._request(path, 'PUT', body) | python | def put(self, path, payload):
"""Make a PUT request from the API."""
body = json.dumps(payload)
return self._request(path, 'PUT', body) | [
"def",
"put",
"(",
"self",
",",
"path",
",",
"payload",
")",
":",
"body",
"=",
"json",
".",
"dumps",
"(",
"payload",
")",
"return",
"self",
".",
"_request",
"(",
"path",
",",
"'PUT'",
",",
"body",
")"
] | Make a PUT request from the API. | [
"Make",
"a",
"PUT",
"request",
"from",
"the",
"API",
"."
] | c91abc9984f0f453e60fa905285c1b640c3390ae | https://github.com/rfverbruggen/rachiopy/blob/c91abc9984f0f453e60fa905285c1b640c3390ae/rachiopy/__init__.py#L52-L55 | train |
rfverbruggen/rachiopy | rachiopy/__init__.py | Rachio.post | def post(self, path, payload):
"""Make a POST request from the API."""
body = json.dumps(payload)
return self._request(path, 'POST', body) | python | def post(self, path, payload):
"""Make a POST request from the API."""
body = json.dumps(payload)
return self._request(path, 'POST', body) | [
"def",
"post",
"(",
"self",
",",
"path",
",",
"payload",
")",
":",
"body",
"=",
"json",
".",
"dumps",
"(",
"payload",
")",
"return",
"self",
".",
"_request",
"(",
"path",
",",
"'POST'",
",",
"body",
")"
] | Make a POST request from the API. | [
"Make",
"a",
"POST",
"request",
"from",
"the",
"API",
"."
] | c91abc9984f0f453e60fa905285c1b640c3390ae | https://github.com/rfverbruggen/rachiopy/blob/c91abc9984f0f453e60fa905285c1b640c3390ae/rachiopy/__init__.py#L57-L60 | train |
dstanek/snake-guice | snakeguice/injector.py | Injector.create_child | def create_child(self, modules):
"""Create a new injector that inherits the state from this injector.
All bindings are inherited. In the future this may become closer to
child injectors on google-guice.
"""
binder = self._binder.create_child()
return Injector(modules, binder=binder, stage=self._stage) | python | def create_child(self, modules):
"""Create a new injector that inherits the state from this injector.
All bindings are inherited. In the future this may become closer to
child injectors on google-guice.
"""
binder = self._binder.create_child()
return Injector(modules, binder=binder, stage=self._stage) | [
"def",
"create_child",
"(",
"self",
",",
"modules",
")",
":",
"binder",
"=",
"self",
".",
"_binder",
".",
"create_child",
"(",
")",
"return",
"Injector",
"(",
"modules",
",",
"binder",
"=",
"binder",
",",
"stage",
"=",
"self",
".",
"_stage",
")"
] | Create a new injector that inherits the state from this injector.
All bindings are inherited. In the future this may become closer to
child injectors on google-guice. | [
"Create",
"a",
"new",
"injector",
"that",
"inherits",
"the",
"state",
"from",
"this",
"injector",
"."
] | d20b62de3ee31e84119c801756398c35ed803fb3 | https://github.com/dstanek/snake-guice/blob/d20b62de3ee31e84119c801756398c35ed803fb3/snakeguice/injector.py#L92-L99 | train |
spotify/gordon-gcp | src/gordon_gcp/schema/validate.py | MessageValidator.validate | def validate(self, message, schema_name):
"""Validate a message given a schema.
Args:
message (dict): Loaded JSON of pulled message from Google
PubSub.
schema_name (str): Name of schema to validate ``message``
against. ``schema_name`` will be used to look up
schema from :py:attr:`.MessageValidator.schemas` dict
Raises:
InvalidMessageError: if message is invalid against the
given schema.
InvalidMessageError: if given schema name can not be found.
"""
err = None
try:
jsonschema.validate(message, self.schemas[schema_name])
except KeyError:
msg = (f'Schema "{schema_name}" was not found (available: '
f'{", ".join(self.schemas.keys())})')
err = {'msg': msg}
except jsonschema.ValidationError as e:
msg = (f'Given message was not valid against the schema '
f'"{schema_name}": {e.message}')
err = {'msg': msg}
if err:
logging.error(**err)
raise exceptions.InvalidMessageError(err['msg']) | python | def validate(self, message, schema_name):
"""Validate a message given a schema.
Args:
message (dict): Loaded JSON of pulled message from Google
PubSub.
schema_name (str): Name of schema to validate ``message``
against. ``schema_name`` will be used to look up
schema from :py:attr:`.MessageValidator.schemas` dict
Raises:
InvalidMessageError: if message is invalid against the
given schema.
InvalidMessageError: if given schema name can not be found.
"""
err = None
try:
jsonschema.validate(message, self.schemas[schema_name])
except KeyError:
msg = (f'Schema "{schema_name}" was not found (available: '
f'{", ".join(self.schemas.keys())})')
err = {'msg': msg}
except jsonschema.ValidationError as e:
msg = (f'Given message was not valid against the schema '
f'"{schema_name}": {e.message}')
err = {'msg': msg}
if err:
logging.error(**err)
raise exceptions.InvalidMessageError(err['msg']) | [
"def",
"validate",
"(",
"self",
",",
"message",
",",
"schema_name",
")",
":",
"err",
"=",
"None",
"try",
":",
"jsonschema",
".",
"validate",
"(",
"message",
",",
"self",
".",
"schemas",
"[",
"schema_name",
"]",
")",
"except",
"KeyError",
":",
"msg",
"=",
"(",
"f'Schema \"{schema_name}\" was not found (available: '",
"f'{\", \".join(self.schemas.keys())})'",
")",
"err",
"=",
"{",
"'msg'",
":",
"msg",
"}",
"except",
"jsonschema",
".",
"ValidationError",
"as",
"e",
":",
"msg",
"=",
"(",
"f'Given message was not valid against the schema '",
"f'\"{schema_name}\": {e.message}'",
")",
"err",
"=",
"{",
"'msg'",
":",
"msg",
"}",
"if",
"err",
":",
"logging",
".",
"error",
"(",
"*",
"*",
"err",
")",
"raise",
"exceptions",
".",
"InvalidMessageError",
"(",
"err",
"[",
"'msg'",
"]",
")"
] | Validate a message given a schema.
Args:
message (dict): Loaded JSON of pulled message from Google
PubSub.
schema_name (str): Name of schema to validate ``message``
against. ``schema_name`` will be used to look up
schema from :py:attr:`.MessageValidator.schemas` dict
Raises:
InvalidMessageError: if message is invalid against the
given schema.
InvalidMessageError: if given schema name can not be found. | [
"Validate",
"a",
"message",
"given",
"a",
"schema",
"."
] | 5ab19e3c2fe6ace72ee91e2ef1a1326f90b805da | https://github.com/spotify/gordon-gcp/blob/5ab19e3c2fe6ace72ee91e2ef1a1326f90b805da/src/gordon_gcp/schema/validate.py#L111-L141 | train |
fabianvf/schema-transformer | schema_transformer/helpers.py | compose | def compose(*functions):
''' evaluates functions from right to left.
>>> add = lambda x, y: x + y
>>> add3 = lambda x: x + 3
>>> divide2 = lambda x: x/2
>>> subtract4 = lambda x: x - 4
>>> subtract1 = compose(add3, subtract4)
>>> subtract1(1)
0
>>> compose(subtract1, add3)(4)
6
>>> compose(int, add3, add3, divide2)(4)
8
>>> compose(int, divide2, add3, add3)(4)
5
>>> compose(int, divide2, compose(add3, add3), add)(7, 3)
8
'''
def inner(func1, func2):
return lambda *x, **y: func1(func2(*x, **y))
return functools.reduce(inner, functions) | python | def compose(*functions):
''' evaluates functions from right to left.
>>> add = lambda x, y: x + y
>>> add3 = lambda x: x + 3
>>> divide2 = lambda x: x/2
>>> subtract4 = lambda x: x - 4
>>> subtract1 = compose(add3, subtract4)
>>> subtract1(1)
0
>>> compose(subtract1, add3)(4)
6
>>> compose(int, add3, add3, divide2)(4)
8
>>> compose(int, divide2, add3, add3)(4)
5
>>> compose(int, divide2, compose(add3, add3), add)(7, 3)
8
'''
def inner(func1, func2):
return lambda *x, **y: func1(func2(*x, **y))
return functools.reduce(inner, functions) | [
"def",
"compose",
"(",
"*",
"functions",
")",
":",
"def",
"inner",
"(",
"func1",
",",
"func2",
")",
":",
"return",
"lambda",
"*",
"x",
",",
"*",
"*",
"y",
":",
"func1",
"(",
"func2",
"(",
"*",
"x",
",",
"*",
"*",
"y",
")",
")",
"return",
"functools",
".",
"reduce",
"(",
"inner",
",",
"functions",
")"
] | evaluates functions from right to left.
>>> add = lambda x, y: x + y
>>> add3 = lambda x: x + 3
>>> divide2 = lambda x: x/2
>>> subtract4 = lambda x: x - 4
>>> subtract1 = compose(add3, subtract4)
>>> subtract1(1)
0
>>> compose(subtract1, add3)(4)
6
>>> compose(int, add3, add3, divide2)(4)
8
>>> compose(int, divide2, add3, add3)(4)
5
>>> compose(int, divide2, compose(add3, add3), add)(7, 3)
8 | [
"evaluates",
"functions",
"from",
"right",
"to",
"left",
"."
] | 1ddce4f7615de71593a1adabee4dbfc4ae086433 | https://github.com/fabianvf/schema-transformer/blob/1ddce4f7615de71593a1adabee4dbfc4ae086433/schema_transformer/helpers.py#L19-L40 | train |
indietyp/django-automated-logging | automated_logging/signals/__init__.py | validate_instance | def validate_instance(instance):
"""Validating if the instance should be logged, or is excluded"""
excludes = settings.AUTOMATED_LOGGING['exclude']['model']
for excluded in excludes:
if (excluded in [instance._meta.app_label.lower(),
instance.__class__.__name__.lower()] or
instance.__module__.lower().startswith(excluded)):
return False
return True | python | def validate_instance(instance):
"""Validating if the instance should be logged, or is excluded"""
excludes = settings.AUTOMATED_LOGGING['exclude']['model']
for excluded in excludes:
if (excluded in [instance._meta.app_label.lower(),
instance.__class__.__name__.lower()] or
instance.__module__.lower().startswith(excluded)):
return False
return True | [
"def",
"validate_instance",
"(",
"instance",
")",
":",
"excludes",
"=",
"settings",
".",
"AUTOMATED_LOGGING",
"[",
"'exclude'",
"]",
"[",
"'model'",
"]",
"for",
"excluded",
"in",
"excludes",
":",
"if",
"(",
"excluded",
"in",
"[",
"instance",
".",
"_meta",
".",
"app_label",
".",
"lower",
"(",
")",
",",
"instance",
".",
"__class__",
".",
"__name__",
".",
"lower",
"(",
")",
"]",
"or",
"instance",
".",
"__module__",
".",
"lower",
"(",
")",
".",
"startswith",
"(",
"excluded",
")",
")",
":",
"return",
"False",
"return",
"True"
] | Validating if the instance should be logged, or is excluded | [
"Validating",
"if",
"the",
"instance",
"should",
"be",
"logged",
"or",
"is",
"excluded"
] | 095dfc6df62dca45f7db4516bc35e52085d0a01c | https://github.com/indietyp/django-automated-logging/blob/095dfc6df62dca45f7db4516bc35e52085d0a01c/automated_logging/signals/__init__.py#L23-L33 | train |
indietyp/django-automated-logging | automated_logging/signals/__init__.py | get_current_user | def get_current_user():
"""Get current user object from middleware"""
thread_local = AutomatedLoggingMiddleware.thread_local
if hasattr(thread_local, 'current_user'):
user = thread_local.current_user
if isinstance(user, AnonymousUser):
user = None
else:
user = None
return user | python | def get_current_user():
"""Get current user object from middleware"""
thread_local = AutomatedLoggingMiddleware.thread_local
if hasattr(thread_local, 'current_user'):
user = thread_local.current_user
if isinstance(user, AnonymousUser):
user = None
else:
user = None
return user | [
"def",
"get_current_user",
"(",
")",
":",
"thread_local",
"=",
"AutomatedLoggingMiddleware",
".",
"thread_local",
"if",
"hasattr",
"(",
"thread_local",
",",
"'current_user'",
")",
":",
"user",
"=",
"thread_local",
".",
"current_user",
"if",
"isinstance",
"(",
"user",
",",
"AnonymousUser",
")",
":",
"user",
"=",
"None",
"else",
":",
"user",
"=",
"None",
"return",
"user"
] | Get current user object from middleware | [
"Get",
"current",
"user",
"object",
"from",
"middleware"
] | 095dfc6df62dca45f7db4516bc35e52085d0a01c | https://github.com/indietyp/django-automated-logging/blob/095dfc6df62dca45f7db4516bc35e52085d0a01c/automated_logging/signals/__init__.py#L36-L46 | train |
indietyp/django-automated-logging | automated_logging/signals/__init__.py | get_current_environ | def get_current_environ():
"""Get current application and path object from middleware"""
thread_local = AutomatedLoggingMiddleware.thread_local
if hasattr(thread_local, 'request_uri'):
request_uri = thread_local.request_uri
else:
request_uri = None
if hasattr(thread_local, 'application'):
application = thread_local.application
application = Application.objects.get_or_create(name=application)[0]
else:
application = None
if hasattr(thread_local, 'method'):
method = thread_local.method
else:
method = None
if hasattr(thread_local, 'status'):
status = thread_local.status
else:
status = None
return request_uri, application, method, status | python | def get_current_environ():
"""Get current application and path object from middleware"""
thread_local = AutomatedLoggingMiddleware.thread_local
if hasattr(thread_local, 'request_uri'):
request_uri = thread_local.request_uri
else:
request_uri = None
if hasattr(thread_local, 'application'):
application = thread_local.application
application = Application.objects.get_or_create(name=application)[0]
else:
application = None
if hasattr(thread_local, 'method'):
method = thread_local.method
else:
method = None
if hasattr(thread_local, 'status'):
status = thread_local.status
else:
status = None
return request_uri, application, method, status | [
"def",
"get_current_environ",
"(",
")",
":",
"thread_local",
"=",
"AutomatedLoggingMiddleware",
".",
"thread_local",
"if",
"hasattr",
"(",
"thread_local",
",",
"'request_uri'",
")",
":",
"request_uri",
"=",
"thread_local",
".",
"request_uri",
"else",
":",
"request_uri",
"=",
"None",
"if",
"hasattr",
"(",
"thread_local",
",",
"'application'",
")",
":",
"application",
"=",
"thread_local",
".",
"application",
"application",
"=",
"Application",
".",
"objects",
".",
"get_or_create",
"(",
"name",
"=",
"application",
")",
"[",
"0",
"]",
"else",
":",
"application",
"=",
"None",
"if",
"hasattr",
"(",
"thread_local",
",",
"'method'",
")",
":",
"method",
"=",
"thread_local",
".",
"method",
"else",
":",
"method",
"=",
"None",
"if",
"hasattr",
"(",
"thread_local",
",",
"'status'",
")",
":",
"status",
"=",
"thread_local",
".",
"status",
"else",
":",
"status",
"=",
"None",
"return",
"request_uri",
",",
"application",
",",
"method",
",",
"status"
] | Get current application and path object from middleware | [
"Get",
"current",
"application",
"and",
"path",
"object",
"from",
"middleware"
] | 095dfc6df62dca45f7db4516bc35e52085d0a01c | https://github.com/indietyp/django-automated-logging/blob/095dfc6df62dca45f7db4516bc35e52085d0a01c/automated_logging/signals/__init__.py#L49-L73 | train |
indietyp/django-automated-logging | automated_logging/signals/__init__.py | processor | def processor(status, sender, instance, updated=None, addition=''):
"""
This is the standard logging processor.
This is used to send the log to the handler and to other systems.
"""
logger = logging.getLogger(__name__)
if validate_instance(instance):
user = get_current_user()
application = instance._meta.app_label
model_name = instance.__class__.__name__
level = settings.AUTOMATED_LOGGING['loglevel']['model']
if status == 'change':
corrected = 'changed'
elif status == 'add':
corrected = 'added'
elif status == 'delete':
corrected = 'deleted'
logger.log(level,
('%s %s %s(%s) in %s%s' % (user, corrected, instance, model_name, application, addition)).replace(" ", " "),
extra={'action': 'model',
'data': {
'status': status,
'user': user,
'sender': sender,
'instance': instance,
'update_fields': updated
}
}) | python | def processor(status, sender, instance, updated=None, addition=''):
"""
This is the standard logging processor.
This is used to send the log to the handler and to other systems.
"""
logger = logging.getLogger(__name__)
if validate_instance(instance):
user = get_current_user()
application = instance._meta.app_label
model_name = instance.__class__.__name__
level = settings.AUTOMATED_LOGGING['loglevel']['model']
if status == 'change':
corrected = 'changed'
elif status == 'add':
corrected = 'added'
elif status == 'delete':
corrected = 'deleted'
logger.log(level,
('%s %s %s(%s) in %s%s' % (user, corrected, instance, model_name, application, addition)).replace(" ", " "),
extra={'action': 'model',
'data': {
'status': status,
'user': user,
'sender': sender,
'instance': instance,
'update_fields': updated
}
}) | [
"def",
"processor",
"(",
"status",
",",
"sender",
",",
"instance",
",",
"updated",
"=",
"None",
",",
"addition",
"=",
"''",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"if",
"validate_instance",
"(",
"instance",
")",
":",
"user",
"=",
"get_current_user",
"(",
")",
"application",
"=",
"instance",
".",
"_meta",
".",
"app_label",
"model_name",
"=",
"instance",
".",
"__class__",
".",
"__name__",
"level",
"=",
"settings",
".",
"AUTOMATED_LOGGING",
"[",
"'loglevel'",
"]",
"[",
"'model'",
"]",
"if",
"status",
"==",
"'change'",
":",
"corrected",
"=",
"'changed'",
"elif",
"status",
"==",
"'add'",
":",
"corrected",
"=",
"'added'",
"elif",
"status",
"==",
"'delete'",
":",
"corrected",
"=",
"'deleted'",
"logger",
".",
"log",
"(",
"level",
",",
"(",
"'%s %s %s(%s) in %s%s'",
"%",
"(",
"user",
",",
"corrected",
",",
"instance",
",",
"model_name",
",",
"application",
",",
"addition",
")",
")",
".",
"replace",
"(",
"\" \"",
",",
"\" \"",
")",
",",
"extra",
"=",
"{",
"'action'",
":",
"'model'",
",",
"'data'",
":",
"{",
"'status'",
":",
"status",
",",
"'user'",
":",
"user",
",",
"'sender'",
":",
"sender",
",",
"'instance'",
":",
"instance",
",",
"'update_fields'",
":",
"updated",
"}",
"}",
")"
] | This is the standard logging processor.
This is used to send the log to the handler and to other systems. | [
"This",
"is",
"the",
"standard",
"logging",
"processor",
"."
] | 095dfc6df62dca45f7db4516bc35e52085d0a01c | https://github.com/indietyp/django-automated-logging/blob/095dfc6df62dca45f7db4516bc35e52085d0a01c/automated_logging/signals/__init__.py#L76-L106 | train |
bunchesofdonald/django-hermes | hermes/models.py | Category.parents | def parents(self):
""" Returns a list of all the current category's parents."""
parents = []
if self.parent is None:
return []
category = self
while category.parent is not None:
parents.append(category.parent)
category = category.parent
return parents[::-1] | python | def parents(self):
""" Returns a list of all the current category's parents."""
parents = []
if self.parent is None:
return []
category = self
while category.parent is not None:
parents.append(category.parent)
category = category.parent
return parents[::-1] | [
"def",
"parents",
"(",
"self",
")",
":",
"parents",
"=",
"[",
"]",
"if",
"self",
".",
"parent",
"is",
"None",
":",
"return",
"[",
"]",
"category",
"=",
"self",
"while",
"category",
".",
"parent",
"is",
"not",
"None",
":",
"parents",
".",
"append",
"(",
"category",
".",
"parent",
")",
"category",
"=",
"category",
".",
"parent",
"return",
"parents",
"[",
":",
":",
"-",
"1",
"]"
] | Returns a list of all the current category's parents. | [
"Returns",
"a",
"list",
"of",
"all",
"the",
"current",
"category",
"s",
"parents",
"."
] | ff5395a7b5debfd0756aab43db61f7a6cfa06aea | https://github.com/bunchesofdonald/django-hermes/blob/ff5395a7b5debfd0756aab43db61f7a6cfa06aea/hermes/models.py#L72-L84 | train |
bunchesofdonald/django-hermes | hermes/models.py | Category.root_parent | def root_parent(self, category=None):
""" Returns the topmost parent of the current category. """
return next(filter(lambda c: c.is_root, self.hierarchy())) | python | def root_parent(self, category=None):
""" Returns the topmost parent of the current category. """
return next(filter(lambda c: c.is_root, self.hierarchy())) | [
"def",
"root_parent",
"(",
"self",
",",
"category",
"=",
"None",
")",
":",
"return",
"next",
"(",
"filter",
"(",
"lambda",
"c",
":",
"c",
".",
"is_root",
",",
"self",
".",
"hierarchy",
"(",
")",
")",
")"
] | Returns the topmost parent of the current category. | [
"Returns",
"the",
"topmost",
"parent",
"of",
"the",
"current",
"category",
"."
] | ff5395a7b5debfd0756aab43db61f7a6cfa06aea | https://github.com/bunchesofdonald/django-hermes/blob/ff5395a7b5debfd0756aab43db61f7a6cfa06aea/hermes/models.py#L89-L91 | train |
rohankapoorcom/zm-py | zoneminder/run_state.py | RunState.active | def active(self) -> bool:
"""Indicate if this RunState is currently active."""
states = self._client.get_state(self._state_url)['states']
for state in states:
state = state['State']
if int(state['Id']) == self._state_id:
# yes, the ZM API uses the *string* "1" for this...
return state['IsActive'] == "1"
return False | python | def active(self) -> bool:
"""Indicate if this RunState is currently active."""
states = self._client.get_state(self._state_url)['states']
for state in states:
state = state['State']
if int(state['Id']) == self._state_id:
# yes, the ZM API uses the *string* "1" for this...
return state['IsActive'] == "1"
return False | [
"def",
"active",
"(",
"self",
")",
"->",
"bool",
":",
"states",
"=",
"self",
".",
"_client",
".",
"get_state",
"(",
"self",
".",
"_state_url",
")",
"[",
"'states'",
"]",
"for",
"state",
"in",
"states",
":",
"state",
"=",
"state",
"[",
"'State'",
"]",
"if",
"int",
"(",
"state",
"[",
"'Id'",
"]",
")",
"==",
"self",
".",
"_state_id",
":",
"# yes, the ZM API uses the *string* \"1\" for this...",
"return",
"state",
"[",
"'IsActive'",
"]",
"==",
"\"1\"",
"return",
"False"
] | Indicate if this RunState is currently active. | [
"Indicate",
"if",
"this",
"RunState",
"is",
"currently",
"active",
"."
] | bd3a9f6b2f7b84b37589e2939f628b479a5531bf | https://github.com/rohankapoorcom/zm-py/blob/bd3a9f6b2f7b84b37589e2939f628b479a5531bf/zoneminder/run_state.py#L26-L34 | train |
mgk/urwid_timed_progress | urwid_timed_progress/__init__.py | to_reasonable_unit | def to_reasonable_unit(value, units, round_digits=2):
"""Convert a value to the most reasonable unit.
The most reasonable unit is roughly the one with the smallest exponent
absolute value when written in scientific notation. For example
`1.5` is more reasonable that `.0015` and `22` is more reasonable
than `22000`. There is a bias towards numbers > 1, so `3.2` is
considered more reasonable that `.32`.
"""
def to_unit(unit):
return float(value) / unit[1]
exponents = [abs(Decimal(to_unit(u)).adjusted() - 1) for u in units]
best = min(enumerate(exponents), key=itemgetter(1))[0]
return dict(val=round(to_unit(units[best]), round_digits),
label=units[best][0],
multiplier=units[best][1]) | python | def to_reasonable_unit(value, units, round_digits=2):
"""Convert a value to the most reasonable unit.
The most reasonable unit is roughly the one with the smallest exponent
absolute value when written in scientific notation. For example
`1.5` is more reasonable that `.0015` and `22` is more reasonable
than `22000`. There is a bias towards numbers > 1, so `3.2` is
considered more reasonable that `.32`.
"""
def to_unit(unit):
return float(value) / unit[1]
exponents = [abs(Decimal(to_unit(u)).adjusted() - 1) for u in units]
best = min(enumerate(exponents), key=itemgetter(1))[0]
return dict(val=round(to_unit(units[best]), round_digits),
label=units[best][0],
multiplier=units[best][1]) | [
"def",
"to_reasonable_unit",
"(",
"value",
",",
"units",
",",
"round_digits",
"=",
"2",
")",
":",
"def",
"to_unit",
"(",
"unit",
")",
":",
"return",
"float",
"(",
"value",
")",
"/",
"unit",
"[",
"1",
"]",
"exponents",
"=",
"[",
"abs",
"(",
"Decimal",
"(",
"to_unit",
"(",
"u",
")",
")",
".",
"adjusted",
"(",
")",
"-",
"1",
")",
"for",
"u",
"in",
"units",
"]",
"best",
"=",
"min",
"(",
"enumerate",
"(",
"exponents",
")",
",",
"key",
"=",
"itemgetter",
"(",
"1",
")",
")",
"[",
"0",
"]",
"return",
"dict",
"(",
"val",
"=",
"round",
"(",
"to_unit",
"(",
"units",
"[",
"best",
"]",
")",
",",
"round_digits",
")",
",",
"label",
"=",
"units",
"[",
"best",
"]",
"[",
"0",
"]",
",",
"multiplier",
"=",
"units",
"[",
"best",
"]",
"[",
"1",
"]",
")"
] | Convert a value to the most reasonable unit.
The most reasonable unit is roughly the one with the smallest exponent
absolute value when written in scientific notation. For example
`1.5` is more reasonable that `.0015` and `22` is more reasonable
than `22000`. There is a bias towards numbers > 1, so `3.2` is
considered more reasonable that `.32`. | [
"Convert",
"a",
"value",
"to",
"the",
"most",
"reasonable",
"unit",
"."
] | b7292e78a58f35f285736988c48e815e71fa2060 | https://github.com/mgk/urwid_timed_progress/blob/b7292e78a58f35f285736988c48e815e71fa2060/urwid_timed_progress/__init__.py#L170-L185 | train |
mgk/urwid_timed_progress | urwid_timed_progress/__init__.py | FancyProgressBar.get_text | def get_text(self):
"""Return extended progress bar text"""
done_units = to_reasonable_unit(self.done, self.units)
current = round(self.current / done_units['multiplier'], 2)
percent = int(self.current * 100 / self.done)
return '{0:.2f} of {1:.2f} {2} ({3}%)'.format(current,
done_units['val'],
done_units['label'],
percent) | python | def get_text(self):
"""Return extended progress bar text"""
done_units = to_reasonable_unit(self.done, self.units)
current = round(self.current / done_units['multiplier'], 2)
percent = int(self.current * 100 / self.done)
return '{0:.2f} of {1:.2f} {2} ({3}%)'.format(current,
done_units['val'],
done_units['label'],
percent) | [
"def",
"get_text",
"(",
"self",
")",
":",
"done_units",
"=",
"to_reasonable_unit",
"(",
"self",
".",
"done",
",",
"self",
".",
"units",
")",
"current",
"=",
"round",
"(",
"self",
".",
"current",
"/",
"done_units",
"[",
"'multiplier'",
"]",
",",
"2",
")",
"percent",
"=",
"int",
"(",
"self",
".",
"current",
"*",
"100",
"/",
"self",
".",
"done",
")",
"return",
"'{0:.2f} of {1:.2f} {2} ({3}%)'",
".",
"format",
"(",
"current",
",",
"done_units",
"[",
"'val'",
"]",
",",
"done_units",
"[",
"'label'",
"]",
",",
"percent",
")"
] | Return extended progress bar text | [
"Return",
"extended",
"progress",
"bar",
"text"
] | b7292e78a58f35f285736988c48e815e71fa2060 | https://github.com/mgk/urwid_timed_progress/blob/b7292e78a58f35f285736988c48e815e71fa2060/urwid_timed_progress/__init__.py#L19-L27 | train |
mgk/urwid_timed_progress | urwid_timed_progress/__init__.py | TimedProgressBar.add_progress | def add_progress(self, delta, done=None):
"""Add to the current progress amount
Add `delta` to the current progress amount. This also updates
:attr:`rate` and :attr:`remaining_time`.
The :attr:`current` progress is never less than 0 or greater
than :attr:`done`.
:param delta: amount to add, may be negative
:param done: new value to use for done
"""
if done is not None:
self.done = done
self.bar.current = max(min(self.done, self.current + delta), 0)
self.rate_display.set_text(self.rate_text)
self.remaining_time_display.set_text(self.remaining_time_text)
return self.current == self.done | python | def add_progress(self, delta, done=None):
"""Add to the current progress amount
Add `delta` to the current progress amount. This also updates
:attr:`rate` and :attr:`remaining_time`.
The :attr:`current` progress is never less than 0 or greater
than :attr:`done`.
:param delta: amount to add, may be negative
:param done: new value to use for done
"""
if done is not None:
self.done = done
self.bar.current = max(min(self.done, self.current + delta), 0)
self.rate_display.set_text(self.rate_text)
self.remaining_time_display.set_text(self.remaining_time_text)
return self.current == self.done | [
"def",
"add_progress",
"(",
"self",
",",
"delta",
",",
"done",
"=",
"None",
")",
":",
"if",
"done",
"is",
"not",
"None",
":",
"self",
".",
"done",
"=",
"done",
"self",
".",
"bar",
".",
"current",
"=",
"max",
"(",
"min",
"(",
"self",
".",
"done",
",",
"self",
".",
"current",
"+",
"delta",
")",
",",
"0",
")",
"self",
".",
"rate_display",
".",
"set_text",
"(",
"self",
".",
"rate_text",
")",
"self",
".",
"remaining_time_display",
".",
"set_text",
"(",
"self",
".",
"remaining_time_text",
")",
"return",
"self",
".",
"current",
"==",
"self",
".",
"done"
] | Add to the current progress amount
Add `delta` to the current progress amount. This also updates
:attr:`rate` and :attr:`remaining_time`.
The :attr:`current` progress is never less than 0 or greater
than :attr:`done`.
:param delta: amount to add, may be negative
:param done: new value to use for done | [
"Add",
"to",
"the",
"current",
"progress",
"amount"
] | b7292e78a58f35f285736988c48e815e71fa2060 | https://github.com/mgk/urwid_timed_progress/blob/b7292e78a58f35f285736988c48e815e71fa2060/urwid_timed_progress/__init__.py#L90-L107 | train |
spotify/gordon-gcp | src/gordon_gcp/clients/http.py | AIOConnection.valid_token_set | async def valid_token_set(self):
"""Check for validity of token, and refresh if none or expired."""
is_valid = False
if self._auth_client.token:
# Account for a token near expiration
now = datetime.datetime.utcnow()
skew = datetime.timedelta(seconds=60)
if self._auth_client.expiry > (now + skew):
is_valid = True
return is_valid | python | async def valid_token_set(self):
"""Check for validity of token, and refresh if none or expired."""
is_valid = False
if self._auth_client.token:
# Account for a token near expiration
now = datetime.datetime.utcnow()
skew = datetime.timedelta(seconds=60)
if self._auth_client.expiry > (now + skew):
is_valid = True
return is_valid | [
"async",
"def",
"valid_token_set",
"(",
"self",
")",
":",
"is_valid",
"=",
"False",
"if",
"self",
".",
"_auth_client",
".",
"token",
":",
"# Account for a token near expiration",
"now",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
"skew",
"=",
"datetime",
".",
"timedelta",
"(",
"seconds",
"=",
"60",
")",
"if",
"self",
".",
"_auth_client",
".",
"expiry",
">",
"(",
"now",
"+",
"skew",
")",
":",
"is_valid",
"=",
"True",
"return",
"is_valid"
] | Check for validity of token, and refresh if none or expired. | [
"Check",
"for",
"validity",
"of",
"token",
"and",
"refresh",
"if",
"none",
"or",
"expired",
"."
] | 5ab19e3c2fe6ace72ee91e2ef1a1326f90b805da | https://github.com/spotify/gordon-gcp/blob/5ab19e3c2fe6ace72ee91e2ef1a1326f90b805da/src/gordon_gcp/clients/http.py#L72-L82 | train |
spotify/gordon-gcp | src/gordon_gcp/clients/http.py | AIOConnection.request | async def request(self, method, url, params=None, headers=None,
data=None, json=None, token_refresh_attempts=2,
**kwargs):
"""Make an asynchronous HTTP request.
Args:
method (str): HTTP method to use for the request.
url (str): URL to be requested.
params (dict): (optional) Query parameters for the request.
Defaults to ``None``.
headers (dict): (optional) HTTP headers to send with the
request. Headers pass through to the request will
include :attr:`DEFAULT_REQUEST_HEADERS`.
data (obj): (optional) A dictionary, bytes, or file-like
object to send in the body of the request.
json (obj): (optional) Any json compatible python
object.
NOTE: json and body parameters cannot be used at the same time.
token_refresh_attempts (int): (optional) Number of attempts a token
refresh should be performed.
Returns:
(str) HTTP response body.
Raises:
:exc:`.GCPHTTPError`: if any exception occurred,
specifically a :exc:`.GCPHTTPResponseError`, if the
exception is associated with a response status code.
"""
if all([data, json]):
msg = ('"data" and "json" request parameters can not be used '
'at the same time')
logging.warn(msg)
raise exceptions.GCPHTTPError(msg)
req_headers = headers or {}
req_headers.update(_utils.DEFAULT_REQUEST_HEADERS)
req_kwargs = {
'params': params,
'headers': req_headers,
}
if data:
req_kwargs['data'] = data
if json:
req_kwargs['json'] = json
if token_refresh_attempts:
if not await self.valid_token_set():
await self._auth_client.refresh_token()
token_refresh_attempts -= 1
req_headers.update(
{'Authorization': f'Bearer {self._auth_client.token}'}
)
request_id = kwargs.get('request_id', uuid.uuid4())
logging.debug(_utils.REQ_LOG_FMT.format(
request_id=request_id,
method=method.upper(),
url=url,
kwargs=req_kwargs))
try:
async with self._session.request(method, url, **req_kwargs) as resp:
log_kw = {
'request_id': request_id,
'method': method.upper(),
'url': resp.url,
'status': resp.status,
'reason': resp.reason
}
logging.debug(_utils.RESP_LOG_FMT.format(**log_kw))
if resp.status in REFRESH_STATUS_CODES:
logging.warning(
f'[{request_id}] HTTP Status Code {resp.status}'
f' returned requesting {resp.url}: {resp.reason}')
if token_refresh_attempts:
logging.info(
f'[{request_id}] Attempting request to {resp.url} '
'again.')
return await self.request(
method, url,
token_refresh_attempts=token_refresh_attempts,
request_id=request_id,
**req_kwargs)
logging.warning(
f'[{request_id}] Max attempts refreshing auth token '
f'exhausted while requesting {resp.url}')
resp.raise_for_status()
return await resp.text()
except aiohttp.ClientResponseError as e:
# bad HTTP status; avoid leaky abstractions and wrap HTTP errors
# with our own
msg = f'[{request_id}] HTTP error response from {resp.url}: {e}'
logging.error(msg, exc_info=e)
raise exceptions.GCPHTTPResponseError(msg, resp.status)
except exceptions.GCPHTTPResponseError as e:
# from recursive call
raise e
except Exception as e:
msg = f'[{request_id}] Request call failed: {e}'
logging.error(msg, exc_info=e)
raise exceptions.GCPHTTPError(msg) | python | async def request(self, method, url, params=None, headers=None,
data=None, json=None, token_refresh_attempts=2,
**kwargs):
"""Make an asynchronous HTTP request.
Args:
method (str): HTTP method to use for the request.
url (str): URL to be requested.
params (dict): (optional) Query parameters for the request.
Defaults to ``None``.
headers (dict): (optional) HTTP headers to send with the
request. Headers pass through to the request will
include :attr:`DEFAULT_REQUEST_HEADERS`.
data (obj): (optional) A dictionary, bytes, or file-like
object to send in the body of the request.
json (obj): (optional) Any json compatible python
object.
NOTE: json and body parameters cannot be used at the same time.
token_refresh_attempts (int): (optional) Number of attempts a token
refresh should be performed.
Returns:
(str) HTTP response body.
Raises:
:exc:`.GCPHTTPError`: if any exception occurred,
specifically a :exc:`.GCPHTTPResponseError`, if the
exception is associated with a response status code.
"""
if all([data, json]):
msg = ('"data" and "json" request parameters can not be used '
'at the same time')
logging.warn(msg)
raise exceptions.GCPHTTPError(msg)
req_headers = headers or {}
req_headers.update(_utils.DEFAULT_REQUEST_HEADERS)
req_kwargs = {
'params': params,
'headers': req_headers,
}
if data:
req_kwargs['data'] = data
if json:
req_kwargs['json'] = json
if token_refresh_attempts:
if not await self.valid_token_set():
await self._auth_client.refresh_token()
token_refresh_attempts -= 1
req_headers.update(
{'Authorization': f'Bearer {self._auth_client.token}'}
)
request_id = kwargs.get('request_id', uuid.uuid4())
logging.debug(_utils.REQ_LOG_FMT.format(
request_id=request_id,
method=method.upper(),
url=url,
kwargs=req_kwargs))
try:
async with self._session.request(method, url, **req_kwargs) as resp:
log_kw = {
'request_id': request_id,
'method': method.upper(),
'url': resp.url,
'status': resp.status,
'reason': resp.reason
}
logging.debug(_utils.RESP_LOG_FMT.format(**log_kw))
if resp.status in REFRESH_STATUS_CODES:
logging.warning(
f'[{request_id}] HTTP Status Code {resp.status}'
f' returned requesting {resp.url}: {resp.reason}')
if token_refresh_attempts:
logging.info(
f'[{request_id}] Attempting request to {resp.url} '
'again.')
return await self.request(
method, url,
token_refresh_attempts=token_refresh_attempts,
request_id=request_id,
**req_kwargs)
logging.warning(
f'[{request_id}] Max attempts refreshing auth token '
f'exhausted while requesting {resp.url}')
resp.raise_for_status()
return await resp.text()
except aiohttp.ClientResponseError as e:
# bad HTTP status; avoid leaky abstractions and wrap HTTP errors
# with our own
msg = f'[{request_id}] HTTP error response from {resp.url}: {e}'
logging.error(msg, exc_info=e)
raise exceptions.GCPHTTPResponseError(msg, resp.status)
except exceptions.GCPHTTPResponseError as e:
# from recursive call
raise e
except Exception as e:
msg = f'[{request_id}] Request call failed: {e}'
logging.error(msg, exc_info=e)
raise exceptions.GCPHTTPError(msg) | [
"async",
"def",
"request",
"(",
"self",
",",
"method",
",",
"url",
",",
"params",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"data",
"=",
"None",
",",
"json",
"=",
"None",
",",
"token_refresh_attempts",
"=",
"2",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"all",
"(",
"[",
"data",
",",
"json",
"]",
")",
":",
"msg",
"=",
"(",
"'\"data\" and \"json\" request parameters can not be used '",
"'at the same time'",
")",
"logging",
".",
"warn",
"(",
"msg",
")",
"raise",
"exceptions",
".",
"GCPHTTPError",
"(",
"msg",
")",
"req_headers",
"=",
"headers",
"or",
"{",
"}",
"req_headers",
".",
"update",
"(",
"_utils",
".",
"DEFAULT_REQUEST_HEADERS",
")",
"req_kwargs",
"=",
"{",
"'params'",
":",
"params",
",",
"'headers'",
":",
"req_headers",
",",
"}",
"if",
"data",
":",
"req_kwargs",
"[",
"'data'",
"]",
"=",
"data",
"if",
"json",
":",
"req_kwargs",
"[",
"'json'",
"]",
"=",
"json",
"if",
"token_refresh_attempts",
":",
"if",
"not",
"await",
"self",
".",
"valid_token_set",
"(",
")",
":",
"await",
"self",
".",
"_auth_client",
".",
"refresh_token",
"(",
")",
"token_refresh_attempts",
"-=",
"1",
"req_headers",
".",
"update",
"(",
"{",
"'Authorization'",
":",
"f'Bearer {self._auth_client.token}'",
"}",
")",
"request_id",
"=",
"kwargs",
".",
"get",
"(",
"'request_id'",
",",
"uuid",
".",
"uuid4",
"(",
")",
")",
"logging",
".",
"debug",
"(",
"_utils",
".",
"REQ_LOG_FMT",
".",
"format",
"(",
"request_id",
"=",
"request_id",
",",
"method",
"=",
"method",
".",
"upper",
"(",
")",
",",
"url",
"=",
"url",
",",
"kwargs",
"=",
"req_kwargs",
")",
")",
"try",
":",
"async",
"with",
"self",
".",
"_session",
".",
"request",
"(",
"method",
",",
"url",
",",
"*",
"*",
"req_kwargs",
")",
"as",
"resp",
":",
"log_kw",
"=",
"{",
"'request_id'",
":",
"request_id",
",",
"'method'",
":",
"method",
".",
"upper",
"(",
")",
",",
"'url'",
":",
"resp",
".",
"url",
",",
"'status'",
":",
"resp",
".",
"status",
",",
"'reason'",
":",
"resp",
".",
"reason",
"}",
"logging",
".",
"debug",
"(",
"_utils",
".",
"RESP_LOG_FMT",
".",
"format",
"(",
"*",
"*",
"log_kw",
")",
")",
"if",
"resp",
".",
"status",
"in",
"REFRESH_STATUS_CODES",
":",
"logging",
".",
"warning",
"(",
"f'[{request_id}] HTTP Status Code {resp.status}'",
"f' returned requesting {resp.url}: {resp.reason}'",
")",
"if",
"token_refresh_attempts",
":",
"logging",
".",
"info",
"(",
"f'[{request_id}] Attempting request to {resp.url} '",
"'again.'",
")",
"return",
"await",
"self",
".",
"request",
"(",
"method",
",",
"url",
",",
"token_refresh_attempts",
"=",
"token_refresh_attempts",
",",
"request_id",
"=",
"request_id",
",",
"*",
"*",
"req_kwargs",
")",
"logging",
".",
"warning",
"(",
"f'[{request_id}] Max attempts refreshing auth token '",
"f'exhausted while requesting {resp.url}'",
")",
"resp",
".",
"raise_for_status",
"(",
")",
"return",
"await",
"resp",
".",
"text",
"(",
")",
"except",
"aiohttp",
".",
"ClientResponseError",
"as",
"e",
":",
"# bad HTTP status; avoid leaky abstractions and wrap HTTP errors",
"# with our own",
"msg",
"=",
"f'[{request_id}] HTTP error response from {resp.url}: {e}'",
"logging",
".",
"error",
"(",
"msg",
",",
"exc_info",
"=",
"e",
")",
"raise",
"exceptions",
".",
"GCPHTTPResponseError",
"(",
"msg",
",",
"resp",
".",
"status",
")",
"except",
"exceptions",
".",
"GCPHTTPResponseError",
"as",
"e",
":",
"# from recursive call",
"raise",
"e",
"except",
"Exception",
"as",
"e",
":",
"msg",
"=",
"f'[{request_id}] Request call failed: {e}'",
"logging",
".",
"error",
"(",
"msg",
",",
"exc_info",
"=",
"e",
")",
"raise",
"exceptions",
".",
"GCPHTTPError",
"(",
"msg",
")"
] | Make an asynchronous HTTP request.
Args:
method (str): HTTP method to use for the request.
url (str): URL to be requested.
params (dict): (optional) Query parameters for the request.
Defaults to ``None``.
headers (dict): (optional) HTTP headers to send with the
request. Headers pass through to the request will
include :attr:`DEFAULT_REQUEST_HEADERS`.
data (obj): (optional) A dictionary, bytes, or file-like
object to send in the body of the request.
json (obj): (optional) Any json compatible python
object.
NOTE: json and body parameters cannot be used at the same time.
token_refresh_attempts (int): (optional) Number of attempts a token
refresh should be performed.
Returns:
(str) HTTP response body.
Raises:
:exc:`.GCPHTTPError`: if any exception occurred,
specifically a :exc:`.GCPHTTPResponseError`, if the
exception is associated with a response status code. | [
"Make",
"an",
"asynchronous",
"HTTP",
"request",
"."
] | 5ab19e3c2fe6ace72ee91e2ef1a1326f90b805da | https://github.com/spotify/gordon-gcp/blob/5ab19e3c2fe6ace72ee91e2ef1a1326f90b805da/src/gordon_gcp/clients/http.py#L84-L189 | train |
spotify/gordon-gcp | src/gordon_gcp/clients/http.py | AIOConnection.get_json | async def get_json(self, url, json_callback=None, **kwargs):
"""Get a URL and return its JSON response.
Args:
url (str): URL to be requested.
json_callback (func): Custom JSON loader function. Defaults
to :meth:`json.loads`.
kwargs (dict): Additional arguments to pass through to the
request.
Returns:
response body returned by :func:`json_callback` function.
"""
if not json_callback:
json_callback = json.loads
response = await self.request(method='get', url=url, **kwargs)
return json_callback(response) | python | async def get_json(self, url, json_callback=None, **kwargs):
"""Get a URL and return its JSON response.
Args:
url (str): URL to be requested.
json_callback (func): Custom JSON loader function. Defaults
to :meth:`json.loads`.
kwargs (dict): Additional arguments to pass through to the
request.
Returns:
response body returned by :func:`json_callback` function.
"""
if not json_callback:
json_callback = json.loads
response = await self.request(method='get', url=url, **kwargs)
return json_callback(response) | [
"async",
"def",
"get_json",
"(",
"self",
",",
"url",
",",
"json_callback",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"json_callback",
":",
"json_callback",
"=",
"json",
".",
"loads",
"response",
"=",
"await",
"self",
".",
"request",
"(",
"method",
"=",
"'get'",
",",
"url",
"=",
"url",
",",
"*",
"*",
"kwargs",
")",
"return",
"json_callback",
"(",
"response",
")"
] | Get a URL and return its JSON response.
Args:
url (str): URL to be requested.
json_callback (func): Custom JSON loader function. Defaults
to :meth:`json.loads`.
kwargs (dict): Additional arguments to pass through to the
request.
Returns:
response body returned by :func:`json_callback` function. | [
"Get",
"a",
"URL",
"and",
"return",
"its",
"JSON",
"response",
"."
] | 5ab19e3c2fe6ace72ee91e2ef1a1326f90b805da | https://github.com/spotify/gordon-gcp/blob/5ab19e3c2fe6ace72ee91e2ef1a1326f90b805da/src/gordon_gcp/clients/http.py#L191-L206 | train |
spotify/gordon-gcp | src/gordon_gcp/clients/http.py | AIOConnection.get_all | async def get_all(self, url, params=None):
"""Aggregate data from all pages of an API query.
Args:
url (str): Google API endpoint URL.
params (dict): (optional) URL query parameters.
Returns:
list: Parsed JSON query response results.
"""
if not params:
params = {}
items = []
next_page_token = None
while True:
if next_page_token:
params['pageToken'] = next_page_token
response = await self.get_json(url, params=params)
items.append(response)
next_page_token = response.get('nextPageToken')
if not next_page_token:
break
return items | python | async def get_all(self, url, params=None):
"""Aggregate data from all pages of an API query.
Args:
url (str): Google API endpoint URL.
params (dict): (optional) URL query parameters.
Returns:
list: Parsed JSON query response results.
"""
if not params:
params = {}
items = []
next_page_token = None
while True:
if next_page_token:
params['pageToken'] = next_page_token
response = await self.get_json(url, params=params)
items.append(response)
next_page_token = response.get('nextPageToken')
if not next_page_token:
break
return items | [
"async",
"def",
"get_all",
"(",
"self",
",",
"url",
",",
"params",
"=",
"None",
")",
":",
"if",
"not",
"params",
":",
"params",
"=",
"{",
"}",
"items",
"=",
"[",
"]",
"next_page_token",
"=",
"None",
"while",
"True",
":",
"if",
"next_page_token",
":",
"params",
"[",
"'pageToken'",
"]",
"=",
"next_page_token",
"response",
"=",
"await",
"self",
".",
"get_json",
"(",
"url",
",",
"params",
"=",
"params",
")",
"items",
".",
"append",
"(",
"response",
")",
"next_page_token",
"=",
"response",
".",
"get",
"(",
"'nextPageToken'",
")",
"if",
"not",
"next_page_token",
":",
"break",
"return",
"items"
] | Aggregate data from all pages of an API query.
Args:
url (str): Google API endpoint URL.
params (dict): (optional) URL query parameters.
Returns:
list: Parsed JSON query response results. | [
"Aggregate",
"data",
"from",
"all",
"pages",
"of",
"an",
"API",
"query",
"."
] | 5ab19e3c2fe6ace72ee91e2ef1a1326f90b805da | https://github.com/spotify/gordon-gcp/blob/5ab19e3c2fe6ace72ee91e2ef1a1326f90b805da/src/gordon_gcp/clients/http.py#L208-L232 | train |
gitenberg-dev/gitberg | gitenberg/config.py | check_config | def check_config():
""" Report if there is an existing config file
"""
configfile = ConfigFile()
global data
if data.keys() > 0:
# FIXME: run a better check of this file
print("gitberg config file exists")
print("\twould you like to edit your gitberg config file?")
else:
print("No config found")
print("\twould you like to create a gitberg config file?")
answer = input("--> [Y/n]")
# By default, the answer is yes, as denoted by the capital Y
if not answer:
answer = 'Y'
# If yes, generate a new configuration
# to be written out as yaml
if answer in 'Yy':
print("Running gitberg config generator ...")
# config.exists_or_make()
config_gen = ConfigGenerator(current=data)
config_gen.ask()
# print(config_gen.answers)
data = config_gen.answers
configfile.write()
print("Config written to {}".format(configfile.file_path)) | python | def check_config():
""" Report if there is an existing config file
"""
configfile = ConfigFile()
global data
if data.keys() > 0:
# FIXME: run a better check of this file
print("gitberg config file exists")
print("\twould you like to edit your gitberg config file?")
else:
print("No config found")
print("\twould you like to create a gitberg config file?")
answer = input("--> [Y/n]")
# By default, the answer is yes, as denoted by the capital Y
if not answer:
answer = 'Y'
# If yes, generate a new configuration
# to be written out as yaml
if answer in 'Yy':
print("Running gitberg config generator ...")
# config.exists_or_make()
config_gen = ConfigGenerator(current=data)
config_gen.ask()
# print(config_gen.answers)
data = config_gen.answers
configfile.write()
print("Config written to {}".format(configfile.file_path)) | [
"def",
"check_config",
"(",
")",
":",
"configfile",
"=",
"ConfigFile",
"(",
")",
"global",
"data",
"if",
"data",
".",
"keys",
"(",
")",
">",
"0",
":",
"# FIXME: run a better check of this file",
"print",
"(",
"\"gitberg config file exists\"",
")",
"print",
"(",
"\"\\twould you like to edit your gitberg config file?\"",
")",
"else",
":",
"print",
"(",
"\"No config found\"",
")",
"print",
"(",
"\"\\twould you like to create a gitberg config file?\"",
")",
"answer",
"=",
"input",
"(",
"\"--> [Y/n]\"",
")",
"# By default, the answer is yes, as denoted by the capital Y",
"if",
"not",
"answer",
":",
"answer",
"=",
"'Y'",
"# If yes, generate a new configuration",
"# to be written out as yaml",
"if",
"answer",
"in",
"'Yy'",
":",
"print",
"(",
"\"Running gitberg config generator ...\"",
")",
"# config.exists_or_make()",
"config_gen",
"=",
"ConfigGenerator",
"(",
"current",
"=",
"data",
")",
"config_gen",
".",
"ask",
"(",
")",
"# print(config_gen.answers)",
"data",
"=",
"config_gen",
".",
"answers",
"configfile",
".",
"write",
"(",
")",
"print",
"(",
"\"Config written to {}\"",
".",
"format",
"(",
"configfile",
".",
"file_path",
")",
")"
] | Report if there is an existing config file | [
"Report",
"if",
"there",
"is",
"an",
"existing",
"config",
"file"
] | 3f6db8b5a22ccdd2110d3199223c30db4e558b5c | https://github.com/gitenberg-dev/gitberg/blob/3f6db8b5a22ccdd2110d3199223c30db4e558b5c/gitenberg/config.py#L94-L122 | train |
fabaff/python-luftdaten | example.py | main | async def main():
"""Sample code to retrieve the data."""
async with aiohttp.ClientSession() as session:
data = Luftdaten(SENSOR_ID, loop, session)
await data.get_data()
if not await data.validate_sensor():
print("Station is not available:", data.sensor_id)
return
if data.values and data.meta:
# Print the sensor values
print("Sensor values:", data.values)
# Print the coordinates fo the sensor
print("Location:", data.meta['latitude'], data.meta['longitude']) | python | async def main():
"""Sample code to retrieve the data."""
async with aiohttp.ClientSession() as session:
data = Luftdaten(SENSOR_ID, loop, session)
await data.get_data()
if not await data.validate_sensor():
print("Station is not available:", data.sensor_id)
return
if data.values and data.meta:
# Print the sensor values
print("Sensor values:", data.values)
# Print the coordinates fo the sensor
print("Location:", data.meta['latitude'], data.meta['longitude']) | [
"async",
"def",
"main",
"(",
")",
":",
"async",
"with",
"aiohttp",
".",
"ClientSession",
"(",
")",
"as",
"session",
":",
"data",
"=",
"Luftdaten",
"(",
"SENSOR_ID",
",",
"loop",
",",
"session",
")",
"await",
"data",
".",
"get_data",
"(",
")",
"if",
"not",
"await",
"data",
".",
"validate_sensor",
"(",
")",
":",
"print",
"(",
"\"Station is not available:\"",
",",
"data",
".",
"sensor_id",
")",
"return",
"if",
"data",
".",
"values",
"and",
"data",
".",
"meta",
":",
"# Print the sensor values",
"print",
"(",
"\"Sensor values:\"",
",",
"data",
".",
"values",
")",
"# Print the coordinates fo the sensor",
"print",
"(",
"\"Location:\"",
",",
"data",
".",
"meta",
"[",
"'latitude'",
"]",
",",
"data",
".",
"meta",
"[",
"'longitude'",
"]",
")"
] | Sample code to retrieve the data. | [
"Sample",
"code",
"to",
"retrieve",
"the",
"data",
"."
] | 30be973257fccb19baa8dbd55206da00f62dc81c | https://github.com/fabaff/python-luftdaten/blob/30be973257fccb19baa8dbd55206da00f62dc81c/example.py#L11-L26 | train |
spotify/gordon-gcp | src/gordon_gcp/clients/gce.py | GCEClient.list_instances | async def list_instances(self,
project,
page_size=100,
instance_filter=None):
"""Fetch all instances in a GCE project.
You can find the endpoint documentation `here <https://cloud.
google.com/compute/docs/reference/latest/instances/
aggregatedList>`__.
Args:
project (str): unique, user-provided project ID.
page_size (int): hint for the client to only retrieve up to
this number of results per API call.
instance_filter (str): endpoint-specific filter string used
to retrieve a subset of instances. This is passed
directly to the endpoint's "filter" URL query parameter.
Returns:
list(dicts): data of all instances in the given
:obj:`project`
"""
url = (f'{self.BASE_URL}{self.api_version}/projects/{project}'
'/aggregated/instances')
params = {'maxResults': page_size}
if instance_filter:
params['filter'] = instance_filter
responses = await self.list_all(url, params)
instances = self._parse_rsps_for_instances(responses)
return instances | python | async def list_instances(self,
project,
page_size=100,
instance_filter=None):
"""Fetch all instances in a GCE project.
You can find the endpoint documentation `here <https://cloud.
google.com/compute/docs/reference/latest/instances/
aggregatedList>`__.
Args:
project (str): unique, user-provided project ID.
page_size (int): hint for the client to only retrieve up to
this number of results per API call.
instance_filter (str): endpoint-specific filter string used
to retrieve a subset of instances. This is passed
directly to the endpoint's "filter" URL query parameter.
Returns:
list(dicts): data of all instances in the given
:obj:`project`
"""
url = (f'{self.BASE_URL}{self.api_version}/projects/{project}'
'/aggregated/instances')
params = {'maxResults': page_size}
if instance_filter:
params['filter'] = instance_filter
responses = await self.list_all(url, params)
instances = self._parse_rsps_for_instances(responses)
return instances | [
"async",
"def",
"list_instances",
"(",
"self",
",",
"project",
",",
"page_size",
"=",
"100",
",",
"instance_filter",
"=",
"None",
")",
":",
"url",
"=",
"(",
"f'{self.BASE_URL}{self.api_version}/projects/{project}'",
"'/aggregated/instances'",
")",
"params",
"=",
"{",
"'maxResults'",
":",
"page_size",
"}",
"if",
"instance_filter",
":",
"params",
"[",
"'filter'",
"]",
"=",
"instance_filter",
"responses",
"=",
"await",
"self",
".",
"list_all",
"(",
"url",
",",
"params",
")",
"instances",
"=",
"self",
".",
"_parse_rsps_for_instances",
"(",
"responses",
")",
"return",
"instances"
] | Fetch all instances in a GCE project.
You can find the endpoint documentation `here <https://cloud.
google.com/compute/docs/reference/latest/instances/
aggregatedList>`__.
Args:
project (str): unique, user-provided project ID.
page_size (int): hint for the client to only retrieve up to
this number of results per API call.
instance_filter (str): endpoint-specific filter string used
to retrieve a subset of instances. This is passed
directly to the endpoint's "filter" URL query parameter.
Returns:
list(dicts): data of all instances in the given
:obj:`project` | [
"Fetch",
"all",
"instances",
"in",
"a",
"GCE",
"project",
"."
] | 5ab19e3c2fe6ace72ee91e2ef1a1326f90b805da | https://github.com/spotify/gordon-gcp/blob/5ab19e3c2fe6ace72ee91e2ef1a1326f90b805da/src/gordon_gcp/clients/gce.py#L89-L118 | train |
openvax/mhcnames | mhcnames/class2.py | infer_alpha_chain | def infer_alpha_chain(beta):
"""
Given a parsed beta chain of a class II MHC, infer the most frequent
corresponding alpha chain.
"""
if beta.gene.startswith("DRB"):
return AlleleName(species="HLA", gene="DRA1", allele_family="01", allele_code="01")
elif beta.gene.startswith("DPB"):
# Most common alpha chain for DP is DPA*01:03 but we really
# need to change this logic to use a lookup table of pairwise
# frequencies for inferring the alpha-beta pairing
return AlleleName(
species="HLA", gene="DPA1", allele_family="01", allele_code="03")
elif beta.gene.startswith("DQB"):
# Most common DQ alpha (according to wikipedia)
# DQA1*01:02
return AlleleName(
species="HLA", gene="DQA1", allele_family="01", allele_code="02")
return None | python | def infer_alpha_chain(beta):
"""
Given a parsed beta chain of a class II MHC, infer the most frequent
corresponding alpha chain.
"""
if beta.gene.startswith("DRB"):
return AlleleName(species="HLA", gene="DRA1", allele_family="01", allele_code="01")
elif beta.gene.startswith("DPB"):
# Most common alpha chain for DP is DPA*01:03 but we really
# need to change this logic to use a lookup table of pairwise
# frequencies for inferring the alpha-beta pairing
return AlleleName(
species="HLA", gene="DPA1", allele_family="01", allele_code="03")
elif beta.gene.startswith("DQB"):
# Most common DQ alpha (according to wikipedia)
# DQA1*01:02
return AlleleName(
species="HLA", gene="DQA1", allele_family="01", allele_code="02")
return None | [
"def",
"infer_alpha_chain",
"(",
"beta",
")",
":",
"if",
"beta",
".",
"gene",
".",
"startswith",
"(",
"\"DRB\"",
")",
":",
"return",
"AlleleName",
"(",
"species",
"=",
"\"HLA\"",
",",
"gene",
"=",
"\"DRA1\"",
",",
"allele_family",
"=",
"\"01\"",
",",
"allele_code",
"=",
"\"01\"",
")",
"elif",
"beta",
".",
"gene",
".",
"startswith",
"(",
"\"DPB\"",
")",
":",
"# Most common alpha chain for DP is DPA*01:03 but we really",
"# need to change this logic to use a lookup table of pairwise",
"# frequencies for inferring the alpha-beta pairing",
"return",
"AlleleName",
"(",
"species",
"=",
"\"HLA\"",
",",
"gene",
"=",
"\"DPA1\"",
",",
"allele_family",
"=",
"\"01\"",
",",
"allele_code",
"=",
"\"03\"",
")",
"elif",
"beta",
".",
"gene",
".",
"startswith",
"(",
"\"DQB\"",
")",
":",
"# Most common DQ alpha (according to wikipedia)",
"# DQA1*01:02",
"return",
"AlleleName",
"(",
"species",
"=",
"\"HLA\"",
",",
"gene",
"=",
"\"DQA1\"",
",",
"allele_family",
"=",
"\"01\"",
",",
"allele_code",
"=",
"\"02\"",
")",
"return",
"None"
] | Given a parsed beta chain of a class II MHC, infer the most frequent
corresponding alpha chain. | [
"Given",
"a",
"parsed",
"beta",
"chain",
"of",
"a",
"class",
"II",
"MHC",
"infer",
"the",
"most",
"frequent",
"corresponding",
"alpha",
"chain",
"."
] | 71694b9d620db68ceee44da1b8422ff436f15bd3 | https://github.com/openvax/mhcnames/blob/71694b9d620db68ceee44da1b8422ff436f15bd3/mhcnames/class2.py#L21-L39 | train |
ministryofjustice/django-zendesk-tickets | zendesk_tickets/client.py | create_ticket | def create_ticket(subject, tags, ticket_body, requester_email=None,
custom_fields=[]):
""" Create a new Zendesk ticket """
payload = {'ticket': {
'subject': subject,
'comment': {
'body': ticket_body
},
'group_id': settings.ZENDESK_GROUP_ID,
'tags': tags,
'custom_fields': custom_fields
}}
if requester_email:
payload['ticket']['requester'] = {
'name': 'Sender: %s' % requester_email.split('@')[0],
'email': requester_email,
}
else:
payload['ticket']['requester_id'] = settings.ZENDESK_REQUESTER_ID
requests.post(
get_ticket_endpoint(),
data=json.dumps(payload),
auth=zendesk_auth(),
headers={'content-type': 'application/json'}).raise_for_status() | python | def create_ticket(subject, tags, ticket_body, requester_email=None,
custom_fields=[]):
""" Create a new Zendesk ticket """
payload = {'ticket': {
'subject': subject,
'comment': {
'body': ticket_body
},
'group_id': settings.ZENDESK_GROUP_ID,
'tags': tags,
'custom_fields': custom_fields
}}
if requester_email:
payload['ticket']['requester'] = {
'name': 'Sender: %s' % requester_email.split('@')[0],
'email': requester_email,
}
else:
payload['ticket']['requester_id'] = settings.ZENDESK_REQUESTER_ID
requests.post(
get_ticket_endpoint(),
data=json.dumps(payload),
auth=zendesk_auth(),
headers={'content-type': 'application/json'}).raise_for_status() | [
"def",
"create_ticket",
"(",
"subject",
",",
"tags",
",",
"ticket_body",
",",
"requester_email",
"=",
"None",
",",
"custom_fields",
"=",
"[",
"]",
")",
":",
"payload",
"=",
"{",
"'ticket'",
":",
"{",
"'subject'",
":",
"subject",
",",
"'comment'",
":",
"{",
"'body'",
":",
"ticket_body",
"}",
",",
"'group_id'",
":",
"settings",
".",
"ZENDESK_GROUP_ID",
",",
"'tags'",
":",
"tags",
",",
"'custom_fields'",
":",
"custom_fields",
"}",
"}",
"if",
"requester_email",
":",
"payload",
"[",
"'ticket'",
"]",
"[",
"'requester'",
"]",
"=",
"{",
"'name'",
":",
"'Sender: %s'",
"%",
"requester_email",
".",
"split",
"(",
"'@'",
")",
"[",
"0",
"]",
",",
"'email'",
":",
"requester_email",
",",
"}",
"else",
":",
"payload",
"[",
"'ticket'",
"]",
"[",
"'requester_id'",
"]",
"=",
"settings",
".",
"ZENDESK_REQUESTER_ID",
"requests",
".",
"post",
"(",
"get_ticket_endpoint",
"(",
")",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"payload",
")",
",",
"auth",
"=",
"zendesk_auth",
"(",
")",
",",
"headers",
"=",
"{",
"'content-type'",
":",
"'application/json'",
"}",
")",
".",
"raise_for_status",
"(",
")"
] | Create a new Zendesk ticket | [
"Create",
"a",
"new",
"Zendesk",
"ticket"
] | 8c1332b5536dc1cf967b612aad5d07e02439d280 | https://github.com/ministryofjustice/django-zendesk-tickets/blob/8c1332b5536dc1cf967b612aad5d07e02439d280/zendesk_tickets/client.py#L19-L45 | train |
ponty/psidialogs | psidialogs/__init__.py | message | def message(message, title=''):
"""
Display a message
:ref:`screenshots<message>`
:param message: message to be displayed.
:param title: window title
:rtype: None
"""
return backend_api.opendialog("message", dict(message=message, title=title)) | python | def message(message, title=''):
"""
Display a message
:ref:`screenshots<message>`
:param message: message to be displayed.
:param title: window title
:rtype: None
"""
return backend_api.opendialog("message", dict(message=message, title=title)) | [
"def",
"message",
"(",
"message",
",",
"title",
"=",
"''",
")",
":",
"return",
"backend_api",
".",
"opendialog",
"(",
"\"message\"",
",",
"dict",
"(",
"message",
"=",
"message",
",",
"title",
"=",
"title",
")",
")"
] | Display a message
:ref:`screenshots<message>`
:param message: message to be displayed.
:param title: window title
:rtype: None | [
"Display",
"a",
"message"
] | e385ab6b48cb43af52b810a1bf76a8135f4585b8 | https://github.com/ponty/psidialogs/blob/e385ab6b48cb43af52b810a1bf76a8135f4585b8/psidialogs/__init__.py#L9-L19 | train |
ponty/psidialogs | psidialogs/__init__.py | ask_file | def ask_file(message='Select file for open.', default='', title='', save=False):
"""
A dialog to get a file name.
The "default" argument specifies a file path.
save=False -> file for loading
save=True -> file for saving
Return the file path that the user entered, or None if he cancels the operation.
:param message: message to be displayed.
:param save: bool 0 -> load , 1 -> save
:param title: window title
:param default: default file path
:rtype: None or string
"""
return backend_api.opendialog("ask_file", dict(message=message, default=default, title=title, save=save)) | python | def ask_file(message='Select file for open.', default='', title='', save=False):
"""
A dialog to get a file name.
The "default" argument specifies a file path.
save=False -> file for loading
save=True -> file for saving
Return the file path that the user entered, or None if he cancels the operation.
:param message: message to be displayed.
:param save: bool 0 -> load , 1 -> save
:param title: window title
:param default: default file path
:rtype: None or string
"""
return backend_api.opendialog("ask_file", dict(message=message, default=default, title=title, save=save)) | [
"def",
"ask_file",
"(",
"message",
"=",
"'Select file for open.'",
",",
"default",
"=",
"''",
",",
"title",
"=",
"''",
",",
"save",
"=",
"False",
")",
":",
"return",
"backend_api",
".",
"opendialog",
"(",
"\"ask_file\"",
",",
"dict",
"(",
"message",
"=",
"message",
",",
"default",
"=",
"default",
",",
"title",
"=",
"title",
",",
"save",
"=",
"save",
")",
")"
] | A dialog to get a file name.
The "default" argument specifies a file path.
save=False -> file for loading
save=True -> file for saving
Return the file path that the user entered, or None if he cancels the operation.
:param message: message to be displayed.
:param save: bool 0 -> load , 1 -> save
:param title: window title
:param default: default file path
:rtype: None or string | [
"A",
"dialog",
"to",
"get",
"a",
"file",
"name",
".",
"The",
"default",
"argument",
"specifies",
"a",
"file",
"path",
"."
] | e385ab6b48cb43af52b810a1bf76a8135f4585b8 | https://github.com/ponty/psidialogs/blob/e385ab6b48cb43af52b810a1bf76a8135f4585b8/psidialogs/__init__.py#L82-L98 | train |
ponty/psidialogs | psidialogs/__init__.py | ask_folder | def ask_folder(message='Select folder.', default='', title=''):
"""
A dialog to get a directory name.
Returns the name of a directory, or None if user chose to cancel.
If the "default" argument specifies a directory name, and that
directory exists, then the dialog box will start with that directory.
:param message: message to be displayed.
:param title: window title
:param default: default folder path
:rtype: None or string
"""
return backend_api.opendialog("ask_folder", dict(message=message, default=default, title=title)) | python | def ask_folder(message='Select folder.', default='', title=''):
"""
A dialog to get a directory name.
Returns the name of a directory, or None if user chose to cancel.
If the "default" argument specifies a directory name, and that
directory exists, then the dialog box will start with that directory.
:param message: message to be displayed.
:param title: window title
:param default: default folder path
:rtype: None or string
"""
return backend_api.opendialog("ask_folder", dict(message=message, default=default, title=title)) | [
"def",
"ask_folder",
"(",
"message",
"=",
"'Select folder.'",
",",
"default",
"=",
"''",
",",
"title",
"=",
"''",
")",
":",
"return",
"backend_api",
".",
"opendialog",
"(",
"\"ask_folder\"",
",",
"dict",
"(",
"message",
"=",
"message",
",",
"default",
"=",
"default",
",",
"title",
"=",
"title",
")",
")"
] | A dialog to get a directory name.
Returns the name of a directory, or None if user chose to cancel.
If the "default" argument specifies a directory name, and that
directory exists, then the dialog box will start with that directory.
:param message: message to be displayed.
:param title: window title
:param default: default folder path
:rtype: None or string | [
"A",
"dialog",
"to",
"get",
"a",
"directory",
"name",
".",
"Returns",
"the",
"name",
"of",
"a",
"directory",
"or",
"None",
"if",
"user",
"chose",
"to",
"cancel",
".",
"If",
"the",
"default",
"argument",
"specifies",
"a",
"directory",
"name",
"and",
"that",
"directory",
"exists",
"then",
"the",
"dialog",
"box",
"will",
"start",
"with",
"that",
"directory",
"."
] | e385ab6b48cb43af52b810a1bf76a8135f4585b8 | https://github.com/ponty/psidialogs/blob/e385ab6b48cb43af52b810a1bf76a8135f4585b8/psidialogs/__init__.py#L101-L113 | train |
ponty/psidialogs | psidialogs/__init__.py | ask_ok_cancel | def ask_ok_cancel(message='', default=0, title=''):
"""
Display a message with choices of OK and Cancel.
returned value:
OK -> True
Cancel -> False
:ref:`screenshots<ask_ok_cancel>`
:param message: message to be displayed.
:param title: window title
:param default: default button as boolean (OK=True, Cancel=False)
:rtype: bool
"""
return backend_api.opendialog("ask_ok_cancel", dict(message=message, default=default, title=title)) | python | def ask_ok_cancel(message='', default=0, title=''):
"""
Display a message with choices of OK and Cancel.
returned value:
OK -> True
Cancel -> False
:ref:`screenshots<ask_ok_cancel>`
:param message: message to be displayed.
:param title: window title
:param default: default button as boolean (OK=True, Cancel=False)
:rtype: bool
"""
return backend_api.opendialog("ask_ok_cancel", dict(message=message, default=default, title=title)) | [
"def",
"ask_ok_cancel",
"(",
"message",
"=",
"''",
",",
"default",
"=",
"0",
",",
"title",
"=",
"''",
")",
":",
"return",
"backend_api",
".",
"opendialog",
"(",
"\"ask_ok_cancel\"",
",",
"dict",
"(",
"message",
"=",
"message",
",",
"default",
"=",
"default",
",",
"title",
"=",
"title",
")",
")"
] | Display a message with choices of OK and Cancel.
returned value:
OK -> True
Cancel -> False
:ref:`screenshots<ask_ok_cancel>`
:param message: message to be displayed.
:param title: window title
:param default: default button as boolean (OK=True, Cancel=False)
:rtype: bool | [
"Display",
"a",
"message",
"with",
"choices",
"of",
"OK",
"and",
"Cancel",
"."
] | e385ab6b48cb43af52b810a1bf76a8135f4585b8 | https://github.com/ponty/psidialogs/blob/e385ab6b48cb43af52b810a1bf76a8135f4585b8/psidialogs/__init__.py#L151-L166 | train |
ponty/psidialogs | psidialogs/__init__.py | ask_yes_no | def ask_yes_no(message='', default=0, title=''):
"""
Display a message with choices of Yes and No.
returned value:
Yes -> True
No -> False
:ref:`screenshots<ask_yes_no>`
:param message: message to be displayed.
:param title: window title
:param default: default button as boolean (YES=True, NO=False)
:rtype: bool
"""
return backend_api.opendialog("ask_yes_no", dict(message=message, default=default, title=title)) | python | def ask_yes_no(message='', default=0, title=''):
"""
Display a message with choices of Yes and No.
returned value:
Yes -> True
No -> False
:ref:`screenshots<ask_yes_no>`
:param message: message to be displayed.
:param title: window title
:param default: default button as boolean (YES=True, NO=False)
:rtype: bool
"""
return backend_api.opendialog("ask_yes_no", dict(message=message, default=default, title=title)) | [
"def",
"ask_yes_no",
"(",
"message",
"=",
"''",
",",
"default",
"=",
"0",
",",
"title",
"=",
"''",
")",
":",
"return",
"backend_api",
".",
"opendialog",
"(",
"\"ask_yes_no\"",
",",
"dict",
"(",
"message",
"=",
"message",
",",
"default",
"=",
"default",
",",
"title",
"=",
"title",
")",
")"
] | Display a message with choices of Yes and No.
returned value:
Yes -> True
No -> False
:ref:`screenshots<ask_yes_no>`
:param message: message to be displayed.
:param title: window title
:param default: default button as boolean (YES=True, NO=False)
:rtype: bool | [
"Display",
"a",
"message",
"with",
"choices",
"of",
"Yes",
"and",
"No",
"."
] | e385ab6b48cb43af52b810a1bf76a8135f4585b8 | https://github.com/ponty/psidialogs/blob/e385ab6b48cb43af52b810a1bf76a8135f4585b8/psidialogs/__init__.py#L169-L184 | train |
inveniosoftware/invenio-webhooks | invenio_webhooks/ext.py | _WebhooksState.register | def register(self, receiver_id, receiver):
"""Register a receiver."""
assert receiver_id not in self.receivers
self.receivers[receiver_id] = receiver(receiver_id) | python | def register(self, receiver_id, receiver):
"""Register a receiver."""
assert receiver_id not in self.receivers
self.receivers[receiver_id] = receiver(receiver_id) | [
"def",
"register",
"(",
"self",
",",
"receiver_id",
",",
"receiver",
")",
":",
"assert",
"receiver_id",
"not",
"in",
"self",
".",
"receivers",
"self",
".",
"receivers",
"[",
"receiver_id",
"]",
"=",
"receiver",
"(",
"receiver_id",
")"
] | Register a receiver. | [
"Register",
"a",
"receiver",
"."
] | f407cb2245464543ee474a81189fb9d3978bdde5 | https://github.com/inveniosoftware/invenio-webhooks/blob/f407cb2245464543ee474a81189fb9d3978bdde5/invenio_webhooks/ext.py#L45-L48 | train |
rfverbruggen/rachiopy | rachiopy/schedulerule.py | Schedulerule.get | def get(self, sched_rule_id):
"""Retrieve the information for a scheduleRule entity."""
path = '/'.join(['schedulerule', sched_rule_id])
return self.rachio.get(path) | python | def get(self, sched_rule_id):
"""Retrieve the information for a scheduleRule entity."""
path = '/'.join(['schedulerule', sched_rule_id])
return self.rachio.get(path) | [
"def",
"get",
"(",
"self",
",",
"sched_rule_id",
")",
":",
"path",
"=",
"'/'",
".",
"join",
"(",
"[",
"'schedulerule'",
",",
"sched_rule_id",
"]",
")",
"return",
"self",
".",
"rachio",
".",
"get",
"(",
"path",
")"
] | Retrieve the information for a scheduleRule entity. | [
"Retrieve",
"the",
"information",
"for",
"a",
"scheduleRule",
"entity",
"."
] | c91abc9984f0f453e60fa905285c1b640c3390ae | https://github.com/rfverbruggen/rachiopy/blob/c91abc9984f0f453e60fa905285c1b640c3390ae/rachiopy/schedulerule.py#L33-L36 | train |
spotify/gordon-gcp | src/gordon_gcp/schema/parse.py | MessageParser.parse | def parse(self, message, schema):
"""Parse message according to schema.
`message` should already be validated against the given schema.
See :ref:`schemadef` for more information.
Args:
message (dict): message data to parse.
schema (str): valid message schema.
Returns:
(dict): parsed message
"""
func = {
'audit-log': self._parse_audit_log_msg,
'event': self._parse_event_msg,
}[schema]
return func(message) | python | def parse(self, message, schema):
"""Parse message according to schema.
`message` should already be validated against the given schema.
See :ref:`schemadef` for more information.
Args:
message (dict): message data to parse.
schema (str): valid message schema.
Returns:
(dict): parsed message
"""
func = {
'audit-log': self._parse_audit_log_msg,
'event': self._parse_event_msg,
}[schema]
return func(message) | [
"def",
"parse",
"(",
"self",
",",
"message",
",",
"schema",
")",
":",
"func",
"=",
"{",
"'audit-log'",
":",
"self",
".",
"_parse_audit_log_msg",
",",
"'event'",
":",
"self",
".",
"_parse_event_msg",
",",
"}",
"[",
"schema",
"]",
"return",
"func",
"(",
"message",
")"
] | Parse message according to schema.
`message` should already be validated against the given schema.
See :ref:`schemadef` for more information.
Args:
message (dict): message data to parse.
schema (str): valid message schema.
Returns:
(dict): parsed message | [
"Parse",
"message",
"according",
"to",
"schema",
"."
] | 5ab19e3c2fe6ace72ee91e2ef1a1326f90b805da | https://github.com/spotify/gordon-gcp/blob/5ab19e3c2fe6ace72ee91e2ef1a1326f90b805da/src/gordon_gcp/schema/parse.py#L69-L85 | train |
rfverbruggen/rachiopy | rachiopy/zone.py | Zone.start | def start(self, zone_id, duration):
"""Start a zone."""
path = 'zone/start'
payload = {'id': zone_id, 'duration': duration}
return self.rachio.put(path, payload) | python | def start(self, zone_id, duration):
"""Start a zone."""
path = 'zone/start'
payload = {'id': zone_id, 'duration': duration}
return self.rachio.put(path, payload) | [
"def",
"start",
"(",
"self",
",",
"zone_id",
",",
"duration",
")",
":",
"path",
"=",
"'zone/start'",
"payload",
"=",
"{",
"'id'",
":",
"zone_id",
",",
"'duration'",
":",
"duration",
"}",
"return",
"self",
".",
"rachio",
".",
"put",
"(",
"path",
",",
"payload",
")"
] | Start a zone. | [
"Start",
"a",
"zone",
"."
] | c91abc9984f0f453e60fa905285c1b640c3390ae | https://github.com/rfverbruggen/rachiopy/blob/c91abc9984f0f453e60fa905285c1b640c3390ae/rachiopy/zone.py#L11-L15 | train |
rfverbruggen/rachiopy | rachiopy/zone.py | Zone.startMultiple | def startMultiple(self, zones):
"""Start multiple zones."""
path = 'zone/start_multiple'
payload = {'zones': zones}
return self.rachio.put(path, payload) | python | def startMultiple(self, zones):
"""Start multiple zones."""
path = 'zone/start_multiple'
payload = {'zones': zones}
return self.rachio.put(path, payload) | [
"def",
"startMultiple",
"(",
"self",
",",
"zones",
")",
":",
"path",
"=",
"'zone/start_multiple'",
"payload",
"=",
"{",
"'zones'",
":",
"zones",
"}",
"return",
"self",
".",
"rachio",
".",
"put",
"(",
"path",
",",
"payload",
")"
] | Start multiple zones. | [
"Start",
"multiple",
"zones",
"."
] | c91abc9984f0f453e60fa905285c1b640c3390ae | https://github.com/rfverbruggen/rachiopy/blob/c91abc9984f0f453e60fa905285c1b640c3390ae/rachiopy/zone.py#L17-L21 | train |
rfverbruggen/rachiopy | rachiopy/zone.py | Zone.get | def get(self, zone_id):
"""Retrieve the information for a zone entity."""
path = '/'.join(['zone', zone_id])
return self.rachio.get(path) | python | def get(self, zone_id):
"""Retrieve the information for a zone entity."""
path = '/'.join(['zone', zone_id])
return self.rachio.get(path) | [
"def",
"get",
"(",
"self",
",",
"zone_id",
")",
":",
"path",
"=",
"'/'",
".",
"join",
"(",
"[",
"'zone'",
",",
"zone_id",
"]",
")",
"return",
"self",
".",
"rachio",
".",
"get",
"(",
"path",
")"
] | Retrieve the information for a zone entity. | [
"Retrieve",
"the",
"information",
"for",
"a",
"zone",
"entity",
"."
] | c91abc9984f0f453e60fa905285c1b640c3390ae | https://github.com/rfverbruggen/rachiopy/blob/c91abc9984f0f453e60fa905285c1b640c3390ae/rachiopy/zone.py#L27-L30 | train |
rfverbruggen/rachiopy | rachiopy/zone.py | ZoneSchedule.start | def start(self):
"""Start the schedule."""
zones = [{"id": data[0], "duration": data[1], "sortOrder": count}
for (count, data) in enumerate(self._zones, 1)]
self._api.startMultiple(zones) | python | def start(self):
"""Start the schedule."""
zones = [{"id": data[0], "duration": data[1], "sortOrder": count}
for (count, data) in enumerate(self._zones, 1)]
self._api.startMultiple(zones) | [
"def",
"start",
"(",
"self",
")",
":",
"zones",
"=",
"[",
"{",
"\"id\"",
":",
"data",
"[",
"0",
"]",
",",
"\"duration\"",
":",
"data",
"[",
"1",
"]",
",",
"\"sortOrder\"",
":",
"count",
"}",
"for",
"(",
"count",
",",
"data",
")",
"in",
"enumerate",
"(",
"self",
".",
"_zones",
",",
"1",
")",
"]",
"self",
".",
"_api",
".",
"startMultiple",
"(",
"zones",
")"
] | Start the schedule. | [
"Start",
"the",
"schedule",
"."
] | c91abc9984f0f453e60fa905285c1b640c3390ae | https://github.com/rfverbruggen/rachiopy/blob/c91abc9984f0f453e60fa905285c1b640c3390ae/rachiopy/zone.py#L45-L49 | train |
angvp/django-klingon | klingon/admin.py | TranslationInlineForm.clean_translation | def clean_translation(self):
"""
Do not allow translations longer than the max_lenght of the field to
be translated.
"""
translation = self.cleaned_data['translation']
if self.instance and self.instance.content_object:
# do not allow string longer than translatable field
obj = self.instance.content_object
field = obj._meta.get_field(self.instance.field)
max_length = field.max_length
if max_length and len(translation) > max_length:
raise forms.ValidationError(
_('The entered translation is too long. You entered '
'%(entered)s chars, max length is %(maxlength)s') % {
'entered': len(translation),
'maxlength': max_length,
}
)
else:
raise forms.ValidationError(
_('Can not store translation. First create all translation'
' for this object')
)
return translation | python | def clean_translation(self):
"""
Do not allow translations longer than the max_lenght of the field to
be translated.
"""
translation = self.cleaned_data['translation']
if self.instance and self.instance.content_object:
# do not allow string longer than translatable field
obj = self.instance.content_object
field = obj._meta.get_field(self.instance.field)
max_length = field.max_length
if max_length and len(translation) > max_length:
raise forms.ValidationError(
_('The entered translation is too long. You entered '
'%(entered)s chars, max length is %(maxlength)s') % {
'entered': len(translation),
'maxlength': max_length,
}
)
else:
raise forms.ValidationError(
_('Can not store translation. First create all translation'
' for this object')
)
return translation | [
"def",
"clean_translation",
"(",
"self",
")",
":",
"translation",
"=",
"self",
".",
"cleaned_data",
"[",
"'translation'",
"]",
"if",
"self",
".",
"instance",
"and",
"self",
".",
"instance",
".",
"content_object",
":",
"# do not allow string longer than translatable field",
"obj",
"=",
"self",
".",
"instance",
".",
"content_object",
"field",
"=",
"obj",
".",
"_meta",
".",
"get_field",
"(",
"self",
".",
"instance",
".",
"field",
")",
"max_length",
"=",
"field",
".",
"max_length",
"if",
"max_length",
"and",
"len",
"(",
"translation",
")",
">",
"max_length",
":",
"raise",
"forms",
".",
"ValidationError",
"(",
"_",
"(",
"'The entered translation is too long. You entered '",
"'%(entered)s chars, max length is %(maxlength)s'",
")",
"%",
"{",
"'entered'",
":",
"len",
"(",
"translation",
")",
",",
"'maxlength'",
":",
"max_length",
",",
"}",
")",
"else",
":",
"raise",
"forms",
".",
"ValidationError",
"(",
"_",
"(",
"'Can not store translation. First create all translation'",
"' for this object'",
")",
")",
"return",
"translation"
] | Do not allow translations longer than the max_lenght of the field to
be translated. | [
"Do",
"not",
"allow",
"translations",
"longer",
"than",
"the",
"max_lenght",
"of",
"the",
"field",
"to",
"be",
"translated",
"."
] | 6716fcb7e98d7d27d41c72c4036d3593f1cc04c2 | https://github.com/angvp/django-klingon/blob/6716fcb7e98d7d27d41c72c4036d3593f1cc04c2/klingon/admin.py#L54-L80 | train |
open-contracting/ocds-merge | ocdsmerge/merge.py | _get_merge_rules | def _get_merge_rules(properties, path=None):
"""
Yields merge rules as key-value pairs, in which the first element is a JSON path as a tuple, and the second element
is a list of merge properties whose values are `true`.
"""
if path is None:
path = ()
for key, value in properties.items():
new_path = path + (key,)
types = _get_types(value)
# `omitWhenMerged` supersedes all other rules.
# See http://standard.open-contracting.org/1.1-dev/en/schema/merging/#omit-when-merged
if value.get('omitWhenMerged') or value.get('mergeStrategy') == 'ocdsOmit':
yield (new_path, {'omitWhenMerged'})
# `wholeListMerge` supersedes any nested rules.
# See http://standard.open-contracting.org/1.1-dev/en/schema/merging/#whole-list-merge
elif 'array' in types and (value.get('wholeListMerge') or value.get('mergeStrategy') == 'ocdsVersion'):
yield (new_path, {'wholeListMerge'})
elif 'object' in types and 'properties' in value:
yield from _get_merge_rules(value['properties'], path=new_path)
elif 'array' in types and 'items' in value:
item_types = _get_types(value['items'])
# See http://standard.open-contracting.org/1.1-dev/en/schema/merging/#objects
if any(item_type != 'object' for item_type in item_types):
yield (new_path, {'wholeListMerge'})
elif 'object' in item_types and 'properties' in value['items']:
# See http://standard.open-contracting.org/1.1-dev/en/schema/merging/#whole-list-merge
if 'id' not in value['items']['properties']:
yield (new_path, {'wholeListMerge'})
else:
yield from _get_merge_rules(value['items']['properties'], path=new_path) | python | def _get_merge_rules(properties, path=None):
"""
Yields merge rules as key-value pairs, in which the first element is a JSON path as a tuple, and the second element
is a list of merge properties whose values are `true`.
"""
if path is None:
path = ()
for key, value in properties.items():
new_path = path + (key,)
types = _get_types(value)
# `omitWhenMerged` supersedes all other rules.
# See http://standard.open-contracting.org/1.1-dev/en/schema/merging/#omit-when-merged
if value.get('omitWhenMerged') or value.get('mergeStrategy') == 'ocdsOmit':
yield (new_path, {'omitWhenMerged'})
# `wholeListMerge` supersedes any nested rules.
# See http://standard.open-contracting.org/1.1-dev/en/schema/merging/#whole-list-merge
elif 'array' in types and (value.get('wholeListMerge') or value.get('mergeStrategy') == 'ocdsVersion'):
yield (new_path, {'wholeListMerge'})
elif 'object' in types and 'properties' in value:
yield from _get_merge_rules(value['properties'], path=new_path)
elif 'array' in types and 'items' in value:
item_types = _get_types(value['items'])
# See http://standard.open-contracting.org/1.1-dev/en/schema/merging/#objects
if any(item_type != 'object' for item_type in item_types):
yield (new_path, {'wholeListMerge'})
elif 'object' in item_types and 'properties' in value['items']:
# See http://standard.open-contracting.org/1.1-dev/en/schema/merging/#whole-list-merge
if 'id' not in value['items']['properties']:
yield (new_path, {'wholeListMerge'})
else:
yield from _get_merge_rules(value['items']['properties'], path=new_path) | [
"def",
"_get_merge_rules",
"(",
"properties",
",",
"path",
"=",
"None",
")",
":",
"if",
"path",
"is",
"None",
":",
"path",
"=",
"(",
")",
"for",
"key",
",",
"value",
"in",
"properties",
".",
"items",
"(",
")",
":",
"new_path",
"=",
"path",
"+",
"(",
"key",
",",
")",
"types",
"=",
"_get_types",
"(",
"value",
")",
"# `omitWhenMerged` supersedes all other rules.",
"# See http://standard.open-contracting.org/1.1-dev/en/schema/merging/#omit-when-merged",
"if",
"value",
".",
"get",
"(",
"'omitWhenMerged'",
")",
"or",
"value",
".",
"get",
"(",
"'mergeStrategy'",
")",
"==",
"'ocdsOmit'",
":",
"yield",
"(",
"new_path",
",",
"{",
"'omitWhenMerged'",
"}",
")",
"# `wholeListMerge` supersedes any nested rules.",
"# See http://standard.open-contracting.org/1.1-dev/en/schema/merging/#whole-list-merge",
"elif",
"'array'",
"in",
"types",
"and",
"(",
"value",
".",
"get",
"(",
"'wholeListMerge'",
")",
"or",
"value",
".",
"get",
"(",
"'mergeStrategy'",
")",
"==",
"'ocdsVersion'",
")",
":",
"yield",
"(",
"new_path",
",",
"{",
"'wholeListMerge'",
"}",
")",
"elif",
"'object'",
"in",
"types",
"and",
"'properties'",
"in",
"value",
":",
"yield",
"from",
"_get_merge_rules",
"(",
"value",
"[",
"'properties'",
"]",
",",
"path",
"=",
"new_path",
")",
"elif",
"'array'",
"in",
"types",
"and",
"'items'",
"in",
"value",
":",
"item_types",
"=",
"_get_types",
"(",
"value",
"[",
"'items'",
"]",
")",
"# See http://standard.open-contracting.org/1.1-dev/en/schema/merging/#objects",
"if",
"any",
"(",
"item_type",
"!=",
"'object'",
"for",
"item_type",
"in",
"item_types",
")",
":",
"yield",
"(",
"new_path",
",",
"{",
"'wholeListMerge'",
"}",
")",
"elif",
"'object'",
"in",
"item_types",
"and",
"'properties'",
"in",
"value",
"[",
"'items'",
"]",
":",
"# See http://standard.open-contracting.org/1.1-dev/en/schema/merging/#whole-list-merge",
"if",
"'id'",
"not",
"in",
"value",
"[",
"'items'",
"]",
"[",
"'properties'",
"]",
":",
"yield",
"(",
"new_path",
",",
"{",
"'wholeListMerge'",
"}",
")",
"else",
":",
"yield",
"from",
"_get_merge_rules",
"(",
"value",
"[",
"'items'",
"]",
"[",
"'properties'",
"]",
",",
"path",
"=",
"new_path",
")"
] | Yields merge rules as key-value pairs, in which the first element is a JSON path as a tuple, and the second element
is a list of merge properties whose values are `true`. | [
"Yields",
"merge",
"rules",
"as",
"key",
"-",
"value",
"pairs",
"in",
"which",
"the",
"first",
"element",
"is",
"a",
"JSON",
"path",
"as",
"a",
"tuple",
"and",
"the",
"second",
"element",
"is",
"a",
"list",
"of",
"merge",
"properties",
"whose",
"values",
"are",
"true",
"."
] | 09ef170b24f3fd13bdb1e33043d22de5f0448a9d | https://github.com/open-contracting/ocds-merge/blob/09ef170b24f3fd13bdb1e33043d22de5f0448a9d/ocdsmerge/merge.py#L60-L92 | train |
open-contracting/ocds-merge | ocdsmerge/merge.py | get_merge_rules | def get_merge_rules(schema=None):
"""
Returns merge rules as key-value pairs, in which the key is a JSON path as a tuple, and the value is a list of
merge properties whose values are `true`.
"""
schema = schema or get_release_schema_url(get_tags()[-1])
if isinstance(schema, dict):
deref_schema = jsonref.JsonRef.replace_refs(schema)
else:
deref_schema = _get_merge_rules_from_url_or_path(schema)
return dict(_get_merge_rules(deref_schema['properties'])) | python | def get_merge_rules(schema=None):
"""
Returns merge rules as key-value pairs, in which the key is a JSON path as a tuple, and the value is a list of
merge properties whose values are `true`.
"""
schema = schema or get_release_schema_url(get_tags()[-1])
if isinstance(schema, dict):
deref_schema = jsonref.JsonRef.replace_refs(schema)
else:
deref_schema = _get_merge_rules_from_url_or_path(schema)
return dict(_get_merge_rules(deref_schema['properties'])) | [
"def",
"get_merge_rules",
"(",
"schema",
"=",
"None",
")",
":",
"schema",
"=",
"schema",
"or",
"get_release_schema_url",
"(",
"get_tags",
"(",
")",
"[",
"-",
"1",
"]",
")",
"if",
"isinstance",
"(",
"schema",
",",
"dict",
")",
":",
"deref_schema",
"=",
"jsonref",
".",
"JsonRef",
".",
"replace_refs",
"(",
"schema",
")",
"else",
":",
"deref_schema",
"=",
"_get_merge_rules_from_url_or_path",
"(",
"schema",
")",
"return",
"dict",
"(",
"_get_merge_rules",
"(",
"deref_schema",
"[",
"'properties'",
"]",
")",
")"
] | Returns merge rules as key-value pairs, in which the key is a JSON path as a tuple, and the value is a list of
merge properties whose values are `true`. | [
"Returns",
"merge",
"rules",
"as",
"key",
"-",
"value",
"pairs",
"in",
"which",
"the",
"key",
"is",
"a",
"JSON",
"path",
"as",
"a",
"tuple",
"and",
"the",
"value",
"is",
"a",
"list",
"of",
"merge",
"properties",
"whose",
"values",
"are",
"true",
"."
] | 09ef170b24f3fd13bdb1e33043d22de5f0448a9d | https://github.com/open-contracting/ocds-merge/blob/09ef170b24f3fd13bdb1e33043d22de5f0448a9d/ocdsmerge/merge.py#L106-L116 | train |
open-contracting/ocds-merge | ocdsmerge/merge.py | unflatten | def unflatten(processed, merge_rules):
"""
Unflattens a processed object into a JSON object.
"""
unflattened = OrderedDict()
for key in processed:
current_node = unflattened
for end, part in enumerate(key, 1):
# If this is a path to an item of an array.
# See http://standard.open-contracting.org/1.1-dev/en/schema/merging/#identifier-merge
if isinstance(part, IdValue):
# If the `id` of an object in the array matches, change into it.
for node in current_node:
if isinstance(node, IdDict) and node.identifier == part.identifier:
current_node = node
break
# Otherwise, append a new object, and change into it.
else:
new_node = IdDict()
new_node.identifier = part.identifier
# If the original object had an `id` value, set it.
if part.original_value is not None:
new_node['id'] = part.original_value
current_node.append(new_node)
current_node = new_node
continue
# Otherwise, this is a path to a property of an object.
node = current_node.get(part)
# If this is a path to a node we visited before, change into it. If it's an `id` field, it's already been
# set to its original value.
if node is not None:
current_node = node
continue
# If this is a full path, copy the data.
if len(key) == end:
# Omit null'ed fields.
if processed[key] is not None:
current_node[part] = processed[key]
continue
# If the path is to a new array, start a new array, and change into it.
if isinstance(key[end], IdValue):
new_node = []
# If the path is to a new object, start a new object, and change into it.
else:
new_node = OrderedDict()
current_node[part] = new_node
current_node = new_node
return unflattened | python | def unflatten(processed, merge_rules):
"""
Unflattens a processed object into a JSON object.
"""
unflattened = OrderedDict()
for key in processed:
current_node = unflattened
for end, part in enumerate(key, 1):
# If this is a path to an item of an array.
# See http://standard.open-contracting.org/1.1-dev/en/schema/merging/#identifier-merge
if isinstance(part, IdValue):
# If the `id` of an object in the array matches, change into it.
for node in current_node:
if isinstance(node, IdDict) and node.identifier == part.identifier:
current_node = node
break
# Otherwise, append a new object, and change into it.
else:
new_node = IdDict()
new_node.identifier = part.identifier
# If the original object had an `id` value, set it.
if part.original_value is not None:
new_node['id'] = part.original_value
current_node.append(new_node)
current_node = new_node
continue
# Otherwise, this is a path to a property of an object.
node = current_node.get(part)
# If this is a path to a node we visited before, change into it. If it's an `id` field, it's already been
# set to its original value.
if node is not None:
current_node = node
continue
# If this is a full path, copy the data.
if len(key) == end:
# Omit null'ed fields.
if processed[key] is not None:
current_node[part] = processed[key]
continue
# If the path is to a new array, start a new array, and change into it.
if isinstance(key[end], IdValue):
new_node = []
# If the path is to a new object, start a new object, and change into it.
else:
new_node = OrderedDict()
current_node[part] = new_node
current_node = new_node
return unflattened | [
"def",
"unflatten",
"(",
"processed",
",",
"merge_rules",
")",
":",
"unflattened",
"=",
"OrderedDict",
"(",
")",
"for",
"key",
"in",
"processed",
":",
"current_node",
"=",
"unflattened",
"for",
"end",
",",
"part",
"in",
"enumerate",
"(",
"key",
",",
"1",
")",
":",
"# If this is a path to an item of an array.",
"# See http://standard.open-contracting.org/1.1-dev/en/schema/merging/#identifier-merge",
"if",
"isinstance",
"(",
"part",
",",
"IdValue",
")",
":",
"# If the `id` of an object in the array matches, change into it.",
"for",
"node",
"in",
"current_node",
":",
"if",
"isinstance",
"(",
"node",
",",
"IdDict",
")",
"and",
"node",
".",
"identifier",
"==",
"part",
".",
"identifier",
":",
"current_node",
"=",
"node",
"break",
"# Otherwise, append a new object, and change into it.",
"else",
":",
"new_node",
"=",
"IdDict",
"(",
")",
"new_node",
".",
"identifier",
"=",
"part",
".",
"identifier",
"# If the original object had an `id` value, set it.",
"if",
"part",
".",
"original_value",
"is",
"not",
"None",
":",
"new_node",
"[",
"'id'",
"]",
"=",
"part",
".",
"original_value",
"current_node",
".",
"append",
"(",
"new_node",
")",
"current_node",
"=",
"new_node",
"continue",
"# Otherwise, this is a path to a property of an object.",
"node",
"=",
"current_node",
".",
"get",
"(",
"part",
")",
"# If this is a path to a node we visited before, change into it. If it's an `id` field, it's already been",
"# set to its original value.",
"if",
"node",
"is",
"not",
"None",
":",
"current_node",
"=",
"node",
"continue",
"# If this is a full path, copy the data.",
"if",
"len",
"(",
"key",
")",
"==",
"end",
":",
"# Omit null'ed fields.",
"if",
"processed",
"[",
"key",
"]",
"is",
"not",
"None",
":",
"current_node",
"[",
"part",
"]",
"=",
"processed",
"[",
"key",
"]",
"continue",
"# If the path is to a new array, start a new array, and change into it.",
"if",
"isinstance",
"(",
"key",
"[",
"end",
"]",
",",
"IdValue",
")",
":",
"new_node",
"=",
"[",
"]",
"# If the path is to a new object, start a new object, and change into it.",
"else",
":",
"new_node",
"=",
"OrderedDict",
"(",
")",
"current_node",
"[",
"part",
"]",
"=",
"new_node",
"current_node",
"=",
"new_node",
"return",
"unflattened"
] | Unflattens a processed object into a JSON object. | [
"Unflattens",
"a",
"processed",
"object",
"into",
"a",
"JSON",
"object",
"."
] | 09ef170b24f3fd13bdb1e33043d22de5f0448a9d | https://github.com/open-contracting/ocds-merge/blob/09ef170b24f3fd13bdb1e33043d22de5f0448a9d/ocdsmerge/merge.py#L180-L234 | train |
open-contracting/ocds-merge | ocdsmerge/merge.py | merge | def merge(releases, schema=None, merge_rules=None):
"""
Merges a list of releases into a compiledRelease.
"""
if not merge_rules:
merge_rules = get_merge_rules(schema)
merged = OrderedDict({('tag',): ['compiled']})
for release in sorted(releases, key=lambda release: release['date']):
release = release.copy()
ocid = release['ocid']
date = release['date']
# Prior to OCDS 1.1.4, `tag` didn't set "omitWhenMerged": true.
release.pop('tag', None) # becomes ["compiled"]
flat = flatten(release, merge_rules)
processed = process_flattened(flat)
# Add an `id` and `date`.
merged[('id',)] = '{}-{}'.format(ocid, date)
merged[('date',)] = date
# In OCDS 1.0, `ocid` incorrectly sets "mergeStrategy": "ocdsOmit".
merged[('ocid',)] = ocid
merged.update(processed)
return unflatten(merged, merge_rules) | python | def merge(releases, schema=None, merge_rules=None):
"""
Merges a list of releases into a compiledRelease.
"""
if not merge_rules:
merge_rules = get_merge_rules(schema)
merged = OrderedDict({('tag',): ['compiled']})
for release in sorted(releases, key=lambda release: release['date']):
release = release.copy()
ocid = release['ocid']
date = release['date']
# Prior to OCDS 1.1.4, `tag` didn't set "omitWhenMerged": true.
release.pop('tag', None) # becomes ["compiled"]
flat = flatten(release, merge_rules)
processed = process_flattened(flat)
# Add an `id` and `date`.
merged[('id',)] = '{}-{}'.format(ocid, date)
merged[('date',)] = date
# In OCDS 1.0, `ocid` incorrectly sets "mergeStrategy": "ocdsOmit".
merged[('ocid',)] = ocid
merged.update(processed)
return unflatten(merged, merge_rules) | [
"def",
"merge",
"(",
"releases",
",",
"schema",
"=",
"None",
",",
"merge_rules",
"=",
"None",
")",
":",
"if",
"not",
"merge_rules",
":",
"merge_rules",
"=",
"get_merge_rules",
"(",
"schema",
")",
"merged",
"=",
"OrderedDict",
"(",
"{",
"(",
"'tag'",
",",
")",
":",
"[",
"'compiled'",
"]",
"}",
")",
"for",
"release",
"in",
"sorted",
"(",
"releases",
",",
"key",
"=",
"lambda",
"release",
":",
"release",
"[",
"'date'",
"]",
")",
":",
"release",
"=",
"release",
".",
"copy",
"(",
")",
"ocid",
"=",
"release",
"[",
"'ocid'",
"]",
"date",
"=",
"release",
"[",
"'date'",
"]",
"# Prior to OCDS 1.1.4, `tag` didn't set \"omitWhenMerged\": true.",
"release",
".",
"pop",
"(",
"'tag'",
",",
"None",
")",
"# becomes [\"compiled\"]",
"flat",
"=",
"flatten",
"(",
"release",
",",
"merge_rules",
")",
"processed",
"=",
"process_flattened",
"(",
"flat",
")",
"# Add an `id` and `date`.",
"merged",
"[",
"(",
"'id'",
",",
")",
"]",
"=",
"'{}-{}'",
".",
"format",
"(",
"ocid",
",",
"date",
")",
"merged",
"[",
"(",
"'date'",
",",
")",
"]",
"=",
"date",
"# In OCDS 1.0, `ocid` incorrectly sets \"mergeStrategy\": \"ocdsOmit\".",
"merged",
"[",
"(",
"'ocid'",
",",
")",
"]",
"=",
"ocid",
"merged",
".",
"update",
"(",
"processed",
")",
"return",
"unflatten",
"(",
"merged",
",",
"merge_rules",
")"
] | Merges a list of releases into a compiledRelease. | [
"Merges",
"a",
"list",
"of",
"releases",
"into",
"a",
"compiledRelease",
"."
] | 09ef170b24f3fd13bdb1e33043d22de5f0448a9d | https://github.com/open-contracting/ocds-merge/blob/09ef170b24f3fd13bdb1e33043d22de5f0448a9d/ocdsmerge/merge.py#L277-L305 | train |
open-contracting/ocds-merge | ocdsmerge/merge.py | merge_versioned | def merge_versioned(releases, schema=None, merge_rules=None):
"""
Merges a list of releases into a versionedRelease.
"""
if not merge_rules:
merge_rules = get_merge_rules(schema)
merged = OrderedDict()
for release in sorted(releases, key=lambda release: release['date']):
release = release.copy()
# Don't version the OCID.
ocid = release.pop('ocid')
merged[('ocid',)] = ocid
releaseID = release['id']
date = release['date']
# Prior to OCDS 1.1.4, `tag` didn't set "omitWhenMerged": true.
tag = release.pop('tag', None)
flat = flatten(release, merge_rules)
processed = process_flattened(flat)
for key, value in processed.items():
# If value is unchanged, don't add to history.
if key in merged and value == merged[key][-1]['value']:
continue
if key not in merged:
merged[key] = []
merged[key].append(OrderedDict([
('releaseID', releaseID),
('releaseDate', date),
('releaseTag', tag),
('value', value),
]))
return unflatten(merged, merge_rules) | python | def merge_versioned(releases, schema=None, merge_rules=None):
"""
Merges a list of releases into a versionedRelease.
"""
if not merge_rules:
merge_rules = get_merge_rules(schema)
merged = OrderedDict()
for release in sorted(releases, key=lambda release: release['date']):
release = release.copy()
# Don't version the OCID.
ocid = release.pop('ocid')
merged[('ocid',)] = ocid
releaseID = release['id']
date = release['date']
# Prior to OCDS 1.1.4, `tag` didn't set "omitWhenMerged": true.
tag = release.pop('tag', None)
flat = flatten(release, merge_rules)
processed = process_flattened(flat)
for key, value in processed.items():
# If value is unchanged, don't add to history.
if key in merged and value == merged[key][-1]['value']:
continue
if key not in merged:
merged[key] = []
merged[key].append(OrderedDict([
('releaseID', releaseID),
('releaseDate', date),
('releaseTag', tag),
('value', value),
]))
return unflatten(merged, merge_rules) | [
"def",
"merge_versioned",
"(",
"releases",
",",
"schema",
"=",
"None",
",",
"merge_rules",
"=",
"None",
")",
":",
"if",
"not",
"merge_rules",
":",
"merge_rules",
"=",
"get_merge_rules",
"(",
"schema",
")",
"merged",
"=",
"OrderedDict",
"(",
")",
"for",
"release",
"in",
"sorted",
"(",
"releases",
",",
"key",
"=",
"lambda",
"release",
":",
"release",
"[",
"'date'",
"]",
")",
":",
"release",
"=",
"release",
".",
"copy",
"(",
")",
"# Don't version the OCID.",
"ocid",
"=",
"release",
".",
"pop",
"(",
"'ocid'",
")",
"merged",
"[",
"(",
"'ocid'",
",",
")",
"]",
"=",
"ocid",
"releaseID",
"=",
"release",
"[",
"'id'",
"]",
"date",
"=",
"release",
"[",
"'date'",
"]",
"# Prior to OCDS 1.1.4, `tag` didn't set \"omitWhenMerged\": true.",
"tag",
"=",
"release",
".",
"pop",
"(",
"'tag'",
",",
"None",
")",
"flat",
"=",
"flatten",
"(",
"release",
",",
"merge_rules",
")",
"processed",
"=",
"process_flattened",
"(",
"flat",
")",
"for",
"key",
",",
"value",
"in",
"processed",
".",
"items",
"(",
")",
":",
"# If value is unchanged, don't add to history.",
"if",
"key",
"in",
"merged",
"and",
"value",
"==",
"merged",
"[",
"key",
"]",
"[",
"-",
"1",
"]",
"[",
"'value'",
"]",
":",
"continue",
"if",
"key",
"not",
"in",
"merged",
":",
"merged",
"[",
"key",
"]",
"=",
"[",
"]",
"merged",
"[",
"key",
"]",
".",
"append",
"(",
"OrderedDict",
"(",
"[",
"(",
"'releaseID'",
",",
"releaseID",
")",
",",
"(",
"'releaseDate'",
",",
"date",
")",
",",
"(",
"'releaseTag'",
",",
"tag",
")",
",",
"(",
"'value'",
",",
"value",
")",
",",
"]",
")",
")",
"return",
"unflatten",
"(",
"merged",
",",
"merge_rules",
")"
] | Merges a list of releases into a versionedRelease. | [
"Merges",
"a",
"list",
"of",
"releases",
"into",
"a",
"versionedRelease",
"."
] | 09ef170b24f3fd13bdb1e33043d22de5f0448a9d | https://github.com/open-contracting/ocds-merge/blob/09ef170b24f3fd13bdb1e33043d22de5f0448a9d/ocdsmerge/merge.py#L308-L346 | train |
F483/btctxstore | btctxstore/common.py | chunks | def chunks(items, size):
""" Split list into chunks of the given size.
Original order is preserved.
Example:
> chunks([1,2,3,4,5,6,7,8], 3)
[[1, 2, 3], [4, 5, 6], [7, 8]]
"""
return [items[i:i+size] for i in range(0, len(items), size)] | python | def chunks(items, size):
""" Split list into chunks of the given size.
Original order is preserved.
Example:
> chunks([1,2,3,4,5,6,7,8], 3)
[[1, 2, 3], [4, 5, 6], [7, 8]]
"""
return [items[i:i+size] for i in range(0, len(items), size)] | [
"def",
"chunks",
"(",
"items",
",",
"size",
")",
":",
"return",
"[",
"items",
"[",
"i",
":",
"i",
"+",
"size",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"items",
")",
",",
"size",
")",
"]"
] | Split list into chunks of the given size.
Original order is preserved.
Example:
> chunks([1,2,3,4,5,6,7,8], 3)
[[1, 2, 3], [4, 5, 6], [7, 8]] | [
"Split",
"list",
"into",
"chunks",
"of",
"the",
"given",
"size",
".",
"Original",
"order",
"is",
"preserved",
"."
] | 5790ace3a3d4c9bcc759e7c931fc4a57d40b6c25 | https://github.com/F483/btctxstore/blob/5790ace3a3d4c9bcc759e7c931fc4a57d40b6c25/btctxstore/common.py#L22-L30 | train |
rohankapoorcom/zm-py | zoneminder/zm.py | ZoneMinder.login | def login(self):
"""Login to the ZoneMinder API."""
_LOGGER.debug("Attempting to login to ZoneMinder")
login_post = {'view': 'console', 'action': 'login'}
if self._username:
login_post['username'] = self._username
if self._password:
login_post['password'] = self._password
req = requests.post(urljoin(self._server_url, 'index.php'),
data=login_post, verify=self._verify_ssl)
self._cookies = req.cookies
# Login calls returns a 200 response on both failure and success.
# The only way to tell if you logged in correctly is to issue an api
# call.
req = requests.get(
urljoin(self._server_url, 'api/host/getVersion.json'),
cookies=self._cookies,
timeout=ZoneMinder.DEFAULT_TIMEOUT,
verify=self._verify_ssl)
if not req.ok:
_LOGGER.error("Connection error logging into ZoneMinder")
return False
return True | python | def login(self):
"""Login to the ZoneMinder API."""
_LOGGER.debug("Attempting to login to ZoneMinder")
login_post = {'view': 'console', 'action': 'login'}
if self._username:
login_post['username'] = self._username
if self._password:
login_post['password'] = self._password
req = requests.post(urljoin(self._server_url, 'index.php'),
data=login_post, verify=self._verify_ssl)
self._cookies = req.cookies
# Login calls returns a 200 response on both failure and success.
# The only way to tell if you logged in correctly is to issue an api
# call.
req = requests.get(
urljoin(self._server_url, 'api/host/getVersion.json'),
cookies=self._cookies,
timeout=ZoneMinder.DEFAULT_TIMEOUT,
verify=self._verify_ssl)
if not req.ok:
_LOGGER.error("Connection error logging into ZoneMinder")
return False
return True | [
"def",
"login",
"(",
"self",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Attempting to login to ZoneMinder\"",
")",
"login_post",
"=",
"{",
"'view'",
":",
"'console'",
",",
"'action'",
":",
"'login'",
"}",
"if",
"self",
".",
"_username",
":",
"login_post",
"[",
"'username'",
"]",
"=",
"self",
".",
"_username",
"if",
"self",
".",
"_password",
":",
"login_post",
"[",
"'password'",
"]",
"=",
"self",
".",
"_password",
"req",
"=",
"requests",
".",
"post",
"(",
"urljoin",
"(",
"self",
".",
"_server_url",
",",
"'index.php'",
")",
",",
"data",
"=",
"login_post",
",",
"verify",
"=",
"self",
".",
"_verify_ssl",
")",
"self",
".",
"_cookies",
"=",
"req",
".",
"cookies",
"# Login calls returns a 200 response on both failure and success.",
"# The only way to tell if you logged in correctly is to issue an api",
"# call.",
"req",
"=",
"requests",
".",
"get",
"(",
"urljoin",
"(",
"self",
".",
"_server_url",
",",
"'api/host/getVersion.json'",
")",
",",
"cookies",
"=",
"self",
".",
"_cookies",
",",
"timeout",
"=",
"ZoneMinder",
".",
"DEFAULT_TIMEOUT",
",",
"verify",
"=",
"self",
".",
"_verify_ssl",
")",
"if",
"not",
"req",
".",
"ok",
":",
"_LOGGER",
".",
"error",
"(",
"\"Connection error logging into ZoneMinder\"",
")",
"return",
"False",
"return",
"True"
] | Login to the ZoneMinder API. | [
"Login",
"to",
"the",
"ZoneMinder",
"API",
"."
] | bd3a9f6b2f7b84b37589e2939f628b479a5531bf | https://github.com/rohankapoorcom/zm-py/blob/bd3a9f6b2f7b84b37589e2939f628b479a5531bf/zoneminder/zm.py#L35-L62 | train |
rohankapoorcom/zm-py | zoneminder/zm.py | ZoneMinder._zm_request | def _zm_request(self, method, api_url, data=None,
timeout=DEFAULT_TIMEOUT) -> dict:
"""Perform a request to the ZoneMinder API."""
try:
# Since the API uses sessions that expire, sometimes we need to
# re-auth if the call fails.
for _ in range(ZoneMinder.LOGIN_RETRIES):
req = requests.request(
method, urljoin(self._server_url, api_url), data=data,
cookies=self._cookies, timeout=timeout,
verify=self._verify_ssl)
if not req.ok:
self.login()
else:
break
else:
_LOGGER.error('Unable to get API response from ZoneMinder')
try:
return req.json()
except ValueError:
_LOGGER.exception('JSON decode exception caught while'
'attempting to decode "%s"', req.text)
return {}
except requests.exceptions.ConnectionError:
_LOGGER.exception('Unable to connect to ZoneMinder')
return {} | python | def _zm_request(self, method, api_url, data=None,
timeout=DEFAULT_TIMEOUT) -> dict:
"""Perform a request to the ZoneMinder API."""
try:
# Since the API uses sessions that expire, sometimes we need to
# re-auth if the call fails.
for _ in range(ZoneMinder.LOGIN_RETRIES):
req = requests.request(
method, urljoin(self._server_url, api_url), data=data,
cookies=self._cookies, timeout=timeout,
verify=self._verify_ssl)
if not req.ok:
self.login()
else:
break
else:
_LOGGER.error('Unable to get API response from ZoneMinder')
try:
return req.json()
except ValueError:
_LOGGER.exception('JSON decode exception caught while'
'attempting to decode "%s"', req.text)
return {}
except requests.exceptions.ConnectionError:
_LOGGER.exception('Unable to connect to ZoneMinder')
return {} | [
"def",
"_zm_request",
"(",
"self",
",",
"method",
",",
"api_url",
",",
"data",
"=",
"None",
",",
"timeout",
"=",
"DEFAULT_TIMEOUT",
")",
"->",
"dict",
":",
"try",
":",
"# Since the API uses sessions that expire, sometimes we need to",
"# re-auth if the call fails.",
"for",
"_",
"in",
"range",
"(",
"ZoneMinder",
".",
"LOGIN_RETRIES",
")",
":",
"req",
"=",
"requests",
".",
"request",
"(",
"method",
",",
"urljoin",
"(",
"self",
".",
"_server_url",
",",
"api_url",
")",
",",
"data",
"=",
"data",
",",
"cookies",
"=",
"self",
".",
"_cookies",
",",
"timeout",
"=",
"timeout",
",",
"verify",
"=",
"self",
".",
"_verify_ssl",
")",
"if",
"not",
"req",
".",
"ok",
":",
"self",
".",
"login",
"(",
")",
"else",
":",
"break",
"else",
":",
"_LOGGER",
".",
"error",
"(",
"'Unable to get API response from ZoneMinder'",
")",
"try",
":",
"return",
"req",
".",
"json",
"(",
")",
"except",
"ValueError",
":",
"_LOGGER",
".",
"exception",
"(",
"'JSON decode exception caught while'",
"'attempting to decode \"%s\"'",
",",
"req",
".",
"text",
")",
"return",
"{",
"}",
"except",
"requests",
".",
"exceptions",
".",
"ConnectionError",
":",
"_LOGGER",
".",
"exception",
"(",
"'Unable to connect to ZoneMinder'",
")",
"return",
"{",
"}"
] | Perform a request to the ZoneMinder API. | [
"Perform",
"a",
"request",
"to",
"the",
"ZoneMinder",
"API",
"."
] | bd3a9f6b2f7b84b37589e2939f628b479a5531bf | https://github.com/rohankapoorcom/zm-py/blob/bd3a9f6b2f7b84b37589e2939f628b479a5531bf/zoneminder/zm.py#L72-L100 | train |
rohankapoorcom/zm-py | zoneminder/zm.py | ZoneMinder.get_monitors | def get_monitors(self) -> List[Monitor]:
"""Get a list of Monitors from the ZoneMinder API."""
raw_monitors = self._zm_request('get', ZoneMinder.MONITOR_URL)
if not raw_monitors:
_LOGGER.warning("Could not fetch monitors from ZoneMinder")
return []
monitors = []
for raw_result in raw_monitors['monitors']:
_LOGGER.debug("Initializing camera %s",
raw_result['Monitor']['Id'])
monitors.append(Monitor(self, raw_result))
return monitors | python | def get_monitors(self) -> List[Monitor]:
"""Get a list of Monitors from the ZoneMinder API."""
raw_monitors = self._zm_request('get', ZoneMinder.MONITOR_URL)
if not raw_monitors:
_LOGGER.warning("Could not fetch monitors from ZoneMinder")
return []
monitors = []
for raw_result in raw_monitors['monitors']:
_LOGGER.debug("Initializing camera %s",
raw_result['Monitor']['Id'])
monitors.append(Monitor(self, raw_result))
return monitors | [
"def",
"get_monitors",
"(",
"self",
")",
"->",
"List",
"[",
"Monitor",
"]",
":",
"raw_monitors",
"=",
"self",
".",
"_zm_request",
"(",
"'get'",
",",
"ZoneMinder",
".",
"MONITOR_URL",
")",
"if",
"not",
"raw_monitors",
":",
"_LOGGER",
".",
"warning",
"(",
"\"Could not fetch monitors from ZoneMinder\"",
")",
"return",
"[",
"]",
"monitors",
"=",
"[",
"]",
"for",
"raw_result",
"in",
"raw_monitors",
"[",
"'monitors'",
"]",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Initializing camera %s\"",
",",
"raw_result",
"[",
"'Monitor'",
"]",
"[",
"'Id'",
"]",
")",
"monitors",
".",
"append",
"(",
"Monitor",
"(",
"self",
",",
"raw_result",
")",
")",
"return",
"monitors"
] | Get a list of Monitors from the ZoneMinder API. | [
"Get",
"a",
"list",
"of",
"Monitors",
"from",
"the",
"ZoneMinder",
"API",
"."
] | bd3a9f6b2f7b84b37589e2939f628b479a5531bf | https://github.com/rohankapoorcom/zm-py/blob/bd3a9f6b2f7b84b37589e2939f628b479a5531bf/zoneminder/zm.py#L102-L115 | train |
rohankapoorcom/zm-py | zoneminder/zm.py | ZoneMinder.get_run_states | def get_run_states(self) -> List[RunState]:
"""Get a list of RunStates from the ZoneMinder API."""
raw_states = self.get_state('api/states.json')
if not raw_states:
_LOGGER.warning("Could not fetch runstates from ZoneMinder")
return []
run_states = []
for i in raw_states['states']:
raw_state = i['State']
_LOGGER.info("Initializing runstate %s", raw_state['Id'])
run_states.append(RunState(self, raw_state))
return run_states | python | def get_run_states(self) -> List[RunState]:
"""Get a list of RunStates from the ZoneMinder API."""
raw_states = self.get_state('api/states.json')
if not raw_states:
_LOGGER.warning("Could not fetch runstates from ZoneMinder")
return []
run_states = []
for i in raw_states['states']:
raw_state = i['State']
_LOGGER.info("Initializing runstate %s", raw_state['Id'])
run_states.append(RunState(self, raw_state))
return run_states | [
"def",
"get_run_states",
"(",
"self",
")",
"->",
"List",
"[",
"RunState",
"]",
":",
"raw_states",
"=",
"self",
".",
"get_state",
"(",
"'api/states.json'",
")",
"if",
"not",
"raw_states",
":",
"_LOGGER",
".",
"warning",
"(",
"\"Could not fetch runstates from ZoneMinder\"",
")",
"return",
"[",
"]",
"run_states",
"=",
"[",
"]",
"for",
"i",
"in",
"raw_states",
"[",
"'states'",
"]",
":",
"raw_state",
"=",
"i",
"[",
"'State'",
"]",
"_LOGGER",
".",
"info",
"(",
"\"Initializing runstate %s\"",
",",
"raw_state",
"[",
"'Id'",
"]",
")",
"run_states",
".",
"append",
"(",
"RunState",
"(",
"self",
",",
"raw_state",
")",
")",
"return",
"run_states"
] | Get a list of RunStates from the ZoneMinder API. | [
"Get",
"a",
"list",
"of",
"RunStates",
"from",
"the",
"ZoneMinder",
"API",
"."
] | bd3a9f6b2f7b84b37589e2939f628b479a5531bf | https://github.com/rohankapoorcom/zm-py/blob/bd3a9f6b2f7b84b37589e2939f628b479a5531bf/zoneminder/zm.py#L117-L130 | train |
rohankapoorcom/zm-py | zoneminder/zm.py | ZoneMinder.get_active_state | def get_active_state(self) -> Optional[str]:
"""Get the name of the active run state from the ZoneMinder API."""
for state in self.get_run_states():
if state.active:
return state.name
return None | python | def get_active_state(self) -> Optional[str]:
"""Get the name of the active run state from the ZoneMinder API."""
for state in self.get_run_states():
if state.active:
return state.name
return None | [
"def",
"get_active_state",
"(",
"self",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"for",
"state",
"in",
"self",
".",
"get_run_states",
"(",
")",
":",
"if",
"state",
".",
"active",
":",
"return",
"state",
".",
"name",
"return",
"None"
] | Get the name of the active run state from the ZoneMinder API. | [
"Get",
"the",
"name",
"of",
"the",
"active",
"run",
"state",
"from",
"the",
"ZoneMinder",
"API",
"."
] | bd3a9f6b2f7b84b37589e2939f628b479a5531bf | https://github.com/rohankapoorcom/zm-py/blob/bd3a9f6b2f7b84b37589e2939f628b479a5531bf/zoneminder/zm.py#L132-L137 | train |
rohankapoorcom/zm-py | zoneminder/zm.py | ZoneMinder.set_active_state | def set_active_state(self, state_name):
"""
Set the ZoneMinder run state to the given state name, via ZM API.
Note that this is a long-running API call; ZoneMinder changes the state
of each camera in turn, and this GET does not receive a response until
all cameras have been updated. Even on a reasonably powerful machine,
this call can take ten (10) or more seconds **per camera**. This method
sets a timeout of 120, which should be adequate for most users.
"""
_LOGGER.info('Setting ZoneMinder run state to state %s', state_name)
return self._zm_request('GET',
'api/states/change/{}.json'.format(state_name),
timeout=120) | python | def set_active_state(self, state_name):
"""
Set the ZoneMinder run state to the given state name, via ZM API.
Note that this is a long-running API call; ZoneMinder changes the state
of each camera in turn, and this GET does not receive a response until
all cameras have been updated. Even on a reasonably powerful machine,
this call can take ten (10) or more seconds **per camera**. This method
sets a timeout of 120, which should be adequate for most users.
"""
_LOGGER.info('Setting ZoneMinder run state to state %s', state_name)
return self._zm_request('GET',
'api/states/change/{}.json'.format(state_name),
timeout=120) | [
"def",
"set_active_state",
"(",
"self",
",",
"state_name",
")",
":",
"_LOGGER",
".",
"info",
"(",
"'Setting ZoneMinder run state to state %s'",
",",
"state_name",
")",
"return",
"self",
".",
"_zm_request",
"(",
"'GET'",
",",
"'api/states/change/{}.json'",
".",
"format",
"(",
"state_name",
")",
",",
"timeout",
"=",
"120",
")"
] | Set the ZoneMinder run state to the given state name, via ZM API.
Note that this is a long-running API call; ZoneMinder changes the state
of each camera in turn, and this GET does not receive a response until
all cameras have been updated. Even on a reasonably powerful machine,
this call can take ten (10) or more seconds **per camera**. This method
sets a timeout of 120, which should be adequate for most users. | [
"Set",
"the",
"ZoneMinder",
"run",
"state",
"to",
"the",
"given",
"state",
"name",
"via",
"ZM",
"API",
"."
] | bd3a9f6b2f7b84b37589e2939f628b479a5531bf | https://github.com/rohankapoorcom/zm-py/blob/bd3a9f6b2f7b84b37589e2939f628b479a5531bf/zoneminder/zm.py#L139-L152 | train |
rohankapoorcom/zm-py | zoneminder/zm.py | ZoneMinder.is_available | def is_available(self) -> bool:
"""Indicate if this ZoneMinder service is currently available."""
status_response = self.get_state(
'api/host/daemonCheck.json'
)
if not status_response:
return False
return status_response.get('result') == 1 | python | def is_available(self) -> bool:
"""Indicate if this ZoneMinder service is currently available."""
status_response = self.get_state(
'api/host/daemonCheck.json'
)
if not status_response:
return False
return status_response.get('result') == 1 | [
"def",
"is_available",
"(",
"self",
")",
"->",
"bool",
":",
"status_response",
"=",
"self",
".",
"get_state",
"(",
"'api/host/daemonCheck.json'",
")",
"if",
"not",
"status_response",
":",
"return",
"False",
"return",
"status_response",
".",
"get",
"(",
"'result'",
")",
"==",
"1"
] | Indicate if this ZoneMinder service is currently available. | [
"Indicate",
"if",
"this",
"ZoneMinder",
"service",
"is",
"currently",
"available",
"."
] | bd3a9f6b2f7b84b37589e2939f628b479a5531bf | https://github.com/rohankapoorcom/zm-py/blob/bd3a9f6b2f7b84b37589e2939f628b479a5531bf/zoneminder/zm.py#L171-L180 | train |
rohankapoorcom/zm-py | zoneminder/zm.py | ZoneMinder._build_server_url | def _build_server_url(server_host, server_path) -> str:
"""Build the server url making sure it ends in a trailing slash."""
server_url = urljoin(server_host, server_path)
if server_url[-1] == '/':
return server_url
return '{}/'.format(server_url) | python | def _build_server_url(server_host, server_path) -> str:
"""Build the server url making sure it ends in a trailing slash."""
server_url = urljoin(server_host, server_path)
if server_url[-1] == '/':
return server_url
return '{}/'.format(server_url) | [
"def",
"_build_server_url",
"(",
"server_host",
",",
"server_path",
")",
"->",
"str",
":",
"server_url",
"=",
"urljoin",
"(",
"server_host",
",",
"server_path",
")",
"if",
"server_url",
"[",
"-",
"1",
"]",
"==",
"'/'",
":",
"return",
"server_url",
"return",
"'{}/'",
".",
"format",
"(",
"server_url",
")"
] | Build the server url making sure it ends in a trailing slash. | [
"Build",
"the",
"server",
"url",
"making",
"sure",
"it",
"ends",
"in",
"a",
"trailing",
"slash",
"."
] | bd3a9f6b2f7b84b37589e2939f628b479a5531bf | https://github.com/rohankapoorcom/zm-py/blob/bd3a9f6b2f7b84b37589e2939f628b479a5531bf/zoneminder/zm.py#L193-L198 | train |
rfverbruggen/rachiopy | rachiopy/flexschedulerule.py | FlexSchedulerule.get | def get(self, flex_sched_rule_id):
"""Retrieve the information for a flexscheduleRule entity."""
path = '/'.join(['flexschedulerule', flex_sched_rule_id])
return self.rachio.get(path) | python | def get(self, flex_sched_rule_id):
"""Retrieve the information for a flexscheduleRule entity."""
path = '/'.join(['flexschedulerule', flex_sched_rule_id])
return self.rachio.get(path) | [
"def",
"get",
"(",
"self",
",",
"flex_sched_rule_id",
")",
":",
"path",
"=",
"'/'",
".",
"join",
"(",
"[",
"'flexschedulerule'",
",",
"flex_sched_rule_id",
"]",
")",
"return",
"self",
".",
"rachio",
".",
"get",
"(",
"path",
")"
] | Retrieve the information for a flexscheduleRule entity. | [
"Retrieve",
"the",
"information",
"for",
"a",
"flexscheduleRule",
"entity",
"."
] | c91abc9984f0f453e60fa905285c1b640c3390ae | https://github.com/rfverbruggen/rachiopy/blob/c91abc9984f0f453e60fa905285c1b640c3390ae/rachiopy/flexschedulerule.py#L11-L14 | train |
gitenberg-dev/gitberg | gitenberg/workflow.py | upload_all_books | def upload_all_books(book_id_start, book_id_end, rdf_library=None):
""" Uses the fetch, make, push subcommands to
mirror Project Gutenberg to a github3 api
"""
# TODO refactor appname into variable
logger.info(
"starting a gitberg mass upload: {0} -> {1}".format(
book_id_start, book_id_end
)
)
for book_id in range(int(book_id_start), int(book_id_end) + 1):
cache = {}
errors = 0
try:
if int(book_id) in missing_pgid:
print(u'missing\t{}'.format(book_id))
continue
upload_book(book_id, rdf_library=rdf_library, cache=cache)
except Exception as e:
print(u'error\t{}'.format(book_id))
logger.error(u"Error processing: {}\r{}".format(book_id, e))
errors += 1
if errors > 10:
print('error limit reached!')
break | python | def upload_all_books(book_id_start, book_id_end, rdf_library=None):
""" Uses the fetch, make, push subcommands to
mirror Project Gutenberg to a github3 api
"""
# TODO refactor appname into variable
logger.info(
"starting a gitberg mass upload: {0} -> {1}".format(
book_id_start, book_id_end
)
)
for book_id in range(int(book_id_start), int(book_id_end) + 1):
cache = {}
errors = 0
try:
if int(book_id) in missing_pgid:
print(u'missing\t{}'.format(book_id))
continue
upload_book(book_id, rdf_library=rdf_library, cache=cache)
except Exception as e:
print(u'error\t{}'.format(book_id))
logger.error(u"Error processing: {}\r{}".format(book_id, e))
errors += 1
if errors > 10:
print('error limit reached!')
break | [
"def",
"upload_all_books",
"(",
"book_id_start",
",",
"book_id_end",
",",
"rdf_library",
"=",
"None",
")",
":",
"# TODO refactor appname into variable",
"logger",
".",
"info",
"(",
"\"starting a gitberg mass upload: {0} -> {1}\"",
".",
"format",
"(",
"book_id_start",
",",
"book_id_end",
")",
")",
"for",
"book_id",
"in",
"range",
"(",
"int",
"(",
"book_id_start",
")",
",",
"int",
"(",
"book_id_end",
")",
"+",
"1",
")",
":",
"cache",
"=",
"{",
"}",
"errors",
"=",
"0",
"try",
":",
"if",
"int",
"(",
"book_id",
")",
"in",
"missing_pgid",
":",
"print",
"(",
"u'missing\\t{}'",
".",
"format",
"(",
"book_id",
")",
")",
"continue",
"upload_book",
"(",
"book_id",
",",
"rdf_library",
"=",
"rdf_library",
",",
"cache",
"=",
"cache",
")",
"except",
"Exception",
"as",
"e",
":",
"print",
"(",
"u'error\\t{}'",
".",
"format",
"(",
"book_id",
")",
")",
"logger",
".",
"error",
"(",
"u\"Error processing: {}\\r{}\"",
".",
"format",
"(",
"book_id",
",",
"e",
")",
")",
"errors",
"+=",
"1",
"if",
"errors",
">",
"10",
":",
"print",
"(",
"'error limit reached!'",
")",
"break"
] | Uses the fetch, make, push subcommands to
mirror Project Gutenberg to a github3 api | [
"Uses",
"the",
"fetch",
"make",
"push",
"subcommands",
"to",
"mirror",
"Project",
"Gutenberg",
"to",
"a",
"github3",
"api"
] | 3f6db8b5a22ccdd2110d3199223c30db4e558b5c | https://github.com/gitenberg-dev/gitberg/blob/3f6db8b5a22ccdd2110d3199223c30db4e558b5c/gitenberg/workflow.py#L15-L41 | train |
gitenberg-dev/gitberg | gitenberg/workflow.py | upload_list | def upload_list(book_id_list, rdf_library=None):
""" Uses the fetch, make, push subcommands to add a list of pg books
"""
with open(book_id_list, 'r') as f:
cache = {}
for book_id in f:
book_id = book_id.strip()
try:
if int(book_id) in missing_pgid:
print(u'missing\t{}'.format(book_id))
continue
upload_book(book_id, rdf_library=rdf_library, cache=cache)
except Exception as e:
print(u'error\t{}'.format(book_id))
logger.error(u"Error processing: {}\r{}".format(book_id, e)) | python | def upload_list(book_id_list, rdf_library=None):
""" Uses the fetch, make, push subcommands to add a list of pg books
"""
with open(book_id_list, 'r') as f:
cache = {}
for book_id in f:
book_id = book_id.strip()
try:
if int(book_id) in missing_pgid:
print(u'missing\t{}'.format(book_id))
continue
upload_book(book_id, rdf_library=rdf_library, cache=cache)
except Exception as e:
print(u'error\t{}'.format(book_id))
logger.error(u"Error processing: {}\r{}".format(book_id, e)) | [
"def",
"upload_list",
"(",
"book_id_list",
",",
"rdf_library",
"=",
"None",
")",
":",
"with",
"open",
"(",
"book_id_list",
",",
"'r'",
")",
"as",
"f",
":",
"cache",
"=",
"{",
"}",
"for",
"book_id",
"in",
"f",
":",
"book_id",
"=",
"book_id",
".",
"strip",
"(",
")",
"try",
":",
"if",
"int",
"(",
"book_id",
")",
"in",
"missing_pgid",
":",
"print",
"(",
"u'missing\\t{}'",
".",
"format",
"(",
"book_id",
")",
")",
"continue",
"upload_book",
"(",
"book_id",
",",
"rdf_library",
"=",
"rdf_library",
",",
"cache",
"=",
"cache",
")",
"except",
"Exception",
"as",
"e",
":",
"print",
"(",
"u'error\\t{}'",
".",
"format",
"(",
"book_id",
")",
")",
"logger",
".",
"error",
"(",
"u\"Error processing: {}\\r{}\"",
".",
"format",
"(",
"book_id",
",",
"e",
")",
")"
] | Uses the fetch, make, push subcommands to add a list of pg books | [
"Uses",
"the",
"fetch",
"make",
"push",
"subcommands",
"to",
"add",
"a",
"list",
"of",
"pg",
"books"
] | 3f6db8b5a22ccdd2110d3199223c30db4e558b5c | https://github.com/gitenberg-dev/gitberg/blob/3f6db8b5a22ccdd2110d3199223c30db4e558b5c/gitenberg/workflow.py#L43-L57 | train |
angvp/django-klingon | klingon/models.py | Translatable.translate | def translate(self):
"""
Create all translations objects for this Translatable instance.
@rtype: list of Translation objects
@return: Returns a list of translations objects
"""
translations = []
for lang in settings.LANGUAGES:
# do not create an translations for default language.
# we will use the original model for this
if lang[0] == self._get_default_language():
continue
# create translations for all fields of each language
if self.translatable_slug is not None:
if self.translatable_slug not in self.translatable_fields:
self.translatable_fields = self.translatable_fields + (self.translatable_slug,)
for field in self.translatable_fields:
trans, created = Translation.objects.get_or_create(
object_id=self.id,
content_type=ContentType.objects.get_for_model(self),
field=field,
lang=lang[0],
)
translations.append(trans)
return translations | python | def translate(self):
"""
Create all translations objects for this Translatable instance.
@rtype: list of Translation objects
@return: Returns a list of translations objects
"""
translations = []
for lang in settings.LANGUAGES:
# do not create an translations for default language.
# we will use the original model for this
if lang[0] == self._get_default_language():
continue
# create translations for all fields of each language
if self.translatable_slug is not None:
if self.translatable_slug not in self.translatable_fields:
self.translatable_fields = self.translatable_fields + (self.translatable_slug,)
for field in self.translatable_fields:
trans, created = Translation.objects.get_or_create(
object_id=self.id,
content_type=ContentType.objects.get_for_model(self),
field=field,
lang=lang[0],
)
translations.append(trans)
return translations | [
"def",
"translate",
"(",
"self",
")",
":",
"translations",
"=",
"[",
"]",
"for",
"lang",
"in",
"settings",
".",
"LANGUAGES",
":",
"# do not create an translations for default language.",
"# we will use the original model for this",
"if",
"lang",
"[",
"0",
"]",
"==",
"self",
".",
"_get_default_language",
"(",
")",
":",
"continue",
"# create translations for all fields of each language",
"if",
"self",
".",
"translatable_slug",
"is",
"not",
"None",
":",
"if",
"self",
".",
"translatable_slug",
"not",
"in",
"self",
".",
"translatable_fields",
":",
"self",
".",
"translatable_fields",
"=",
"self",
".",
"translatable_fields",
"+",
"(",
"self",
".",
"translatable_slug",
",",
")",
"for",
"field",
"in",
"self",
".",
"translatable_fields",
":",
"trans",
",",
"created",
"=",
"Translation",
".",
"objects",
".",
"get_or_create",
"(",
"object_id",
"=",
"self",
".",
"id",
",",
"content_type",
"=",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"self",
")",
",",
"field",
"=",
"field",
",",
"lang",
"=",
"lang",
"[",
"0",
"]",
",",
")",
"translations",
".",
"append",
"(",
"trans",
")",
"return",
"translations"
] | Create all translations objects for this Translatable instance.
@rtype: list of Translation objects
@return: Returns a list of translations objects | [
"Create",
"all",
"translations",
"objects",
"for",
"this",
"Translatable",
"instance",
"."
] | 6716fcb7e98d7d27d41c72c4036d3593f1cc04c2 | https://github.com/angvp/django-klingon/blob/6716fcb7e98d7d27d41c72c4036d3593f1cc04c2/klingon/models.py#L57-L84 | train |
angvp/django-klingon | klingon/models.py | Translatable.translations_objects | def translations_objects(self, lang):
"""
Return the complete list of translation objects of a Translatable
instance
@type lang: string
@param lang: a string with the name of the language
@rtype: list of Translation
@return: Returns a list of translations objects
"""
return Translation.objects.filter(
object_id=self.id,
content_type=ContentType.objects.get_for_model(self),
lang=lang
) | python | def translations_objects(self, lang):
"""
Return the complete list of translation objects of a Translatable
instance
@type lang: string
@param lang: a string with the name of the language
@rtype: list of Translation
@return: Returns a list of translations objects
"""
return Translation.objects.filter(
object_id=self.id,
content_type=ContentType.objects.get_for_model(self),
lang=lang
) | [
"def",
"translations_objects",
"(",
"self",
",",
"lang",
")",
":",
"return",
"Translation",
".",
"objects",
".",
"filter",
"(",
"object_id",
"=",
"self",
".",
"id",
",",
"content_type",
"=",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"self",
")",
",",
"lang",
"=",
"lang",
")"
] | Return the complete list of translation objects of a Translatable
instance
@type lang: string
@param lang: a string with the name of the language
@rtype: list of Translation
@return: Returns a list of translations objects | [
"Return",
"the",
"complete",
"list",
"of",
"translation",
"objects",
"of",
"a",
"Translatable",
"instance"
] | 6716fcb7e98d7d27d41c72c4036d3593f1cc04c2 | https://github.com/angvp/django-klingon/blob/6716fcb7e98d7d27d41c72c4036d3593f1cc04c2/klingon/models.py#L86-L101 | train |
angvp/django-klingon | klingon/models.py | Translatable.translations | def translations(self, lang):
"""
Return the list of translation strings of a Translatable
instance in a dictionary form
@type lang: string
@param lang: a string with the name of the language
@rtype: python Dictionary
@return: Returns a all fieldname / translations (key / value)
"""
key = self._get_translations_cache_key(lang)
trans_dict = cache.get(key, {})
if self.translatable_slug is not None:
if self.translatable_slug not in self.translatable_fields:
self.translatable_fields = self.translatable_fields + (self.translatable_slug,)
if not trans_dict:
for field in self.translatable_fields:
# we use get_translation method to be sure that it will
# fall back and get the default value if needed
trans_dict[field] = self.get_translation(lang, field)
cache.set(key, trans_dict)
return trans_dict | python | def translations(self, lang):
"""
Return the list of translation strings of a Translatable
instance in a dictionary form
@type lang: string
@param lang: a string with the name of the language
@rtype: python Dictionary
@return: Returns a all fieldname / translations (key / value)
"""
key = self._get_translations_cache_key(lang)
trans_dict = cache.get(key, {})
if self.translatable_slug is not None:
if self.translatable_slug not in self.translatable_fields:
self.translatable_fields = self.translatable_fields + (self.translatable_slug,)
if not trans_dict:
for field in self.translatable_fields:
# we use get_translation method to be sure that it will
# fall back and get the default value if needed
trans_dict[field] = self.get_translation(lang, field)
cache.set(key, trans_dict)
return trans_dict | [
"def",
"translations",
"(",
"self",
",",
"lang",
")",
":",
"key",
"=",
"self",
".",
"_get_translations_cache_key",
"(",
"lang",
")",
"trans_dict",
"=",
"cache",
".",
"get",
"(",
"key",
",",
"{",
"}",
")",
"if",
"self",
".",
"translatable_slug",
"is",
"not",
"None",
":",
"if",
"self",
".",
"translatable_slug",
"not",
"in",
"self",
".",
"translatable_fields",
":",
"self",
".",
"translatable_fields",
"=",
"self",
".",
"translatable_fields",
"+",
"(",
"self",
".",
"translatable_slug",
",",
")",
"if",
"not",
"trans_dict",
":",
"for",
"field",
"in",
"self",
".",
"translatable_fields",
":",
"# we use get_translation method to be sure that it will",
"# fall back and get the default value if needed",
"trans_dict",
"[",
"field",
"]",
"=",
"self",
".",
"get_translation",
"(",
"lang",
",",
"field",
")",
"cache",
".",
"set",
"(",
"key",
",",
"trans_dict",
")",
"return",
"trans_dict"
] | Return the list of translation strings of a Translatable
instance in a dictionary form
@type lang: string
@param lang: a string with the name of the language
@rtype: python Dictionary
@return: Returns a all fieldname / translations (key / value) | [
"Return",
"the",
"list",
"of",
"translation",
"strings",
"of",
"a",
"Translatable",
"instance",
"in",
"a",
"dictionary",
"form"
] | 6716fcb7e98d7d27d41c72c4036d3593f1cc04c2 | https://github.com/angvp/django-klingon/blob/6716fcb7e98d7d27d41c72c4036d3593f1cc04c2/klingon/models.py#L103-L128 | train |
angvp/django-klingon | klingon/models.py | Translatable.get_translation_obj | def get_translation_obj(self, lang, field, create=False):
"""
Return the translation object of an specific field in a Translatable
istance
@type lang: string
@param lang: a string with the name of the language
@type field: string
@param field: a string with the name that we try to get
@rtype: Translation
@return: Returns a translation object
"""
trans = None
try:
trans = Translation.objects.get(
object_id=self.id,
content_type=ContentType.objects.get_for_model(self),
lang=lang,
field=field,
)
except Translation.DoesNotExist:
if create:
trans = Translation.objects.create(
object_id=self.id,
content_type=ContentType.objects.get_for_model(self),
lang=lang,
field=field,
)
return trans | python | def get_translation_obj(self, lang, field, create=False):
"""
Return the translation object of an specific field in a Translatable
istance
@type lang: string
@param lang: a string with the name of the language
@type field: string
@param field: a string with the name that we try to get
@rtype: Translation
@return: Returns a translation object
"""
trans = None
try:
trans = Translation.objects.get(
object_id=self.id,
content_type=ContentType.objects.get_for_model(self),
lang=lang,
field=field,
)
except Translation.DoesNotExist:
if create:
trans = Translation.objects.create(
object_id=self.id,
content_type=ContentType.objects.get_for_model(self),
lang=lang,
field=field,
)
return trans | [
"def",
"get_translation_obj",
"(",
"self",
",",
"lang",
",",
"field",
",",
"create",
"=",
"False",
")",
":",
"trans",
"=",
"None",
"try",
":",
"trans",
"=",
"Translation",
".",
"objects",
".",
"get",
"(",
"object_id",
"=",
"self",
".",
"id",
",",
"content_type",
"=",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"self",
")",
",",
"lang",
"=",
"lang",
",",
"field",
"=",
"field",
",",
")",
"except",
"Translation",
".",
"DoesNotExist",
":",
"if",
"create",
":",
"trans",
"=",
"Translation",
".",
"objects",
".",
"create",
"(",
"object_id",
"=",
"self",
".",
"id",
",",
"content_type",
"=",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"self",
")",
",",
"lang",
"=",
"lang",
",",
"field",
"=",
"field",
",",
")",
"return",
"trans"
] | Return the translation object of an specific field in a Translatable
istance
@type lang: string
@param lang: a string with the name of the language
@type field: string
@param field: a string with the name that we try to get
@rtype: Translation
@return: Returns a translation object | [
"Return",
"the",
"translation",
"object",
"of",
"an",
"specific",
"field",
"in",
"a",
"Translatable",
"istance"
] | 6716fcb7e98d7d27d41c72c4036d3593f1cc04c2 | https://github.com/angvp/django-klingon/blob/6716fcb7e98d7d27d41c72c4036d3593f1cc04c2/klingon/models.py#L130-L160 | train |
angvp/django-klingon | klingon/models.py | Translatable.get_translation | def get_translation(self, lang, field):
"""
Return the translation string of an specific field in a Translatable
istance
@type lang: string
@param lang: a string with the name of the language
@type field: string
@param field: a string with the name that we try to get
@rtype: string
@return: Returns a translation string
"""
# Read from cache
key = self._get_translation_cache_key(lang, field)
trans = cache.get(key, '')
if not trans:
trans_obj = self.get_translation_obj(lang, field)
trans = getattr(trans_obj, 'translation', '')
# if there's no translation text fall back to the model field
if not trans:
trans = getattr(self, field, '')
# update cache
cache.set(key, trans)
return trans | python | def get_translation(self, lang, field):
"""
Return the translation string of an specific field in a Translatable
istance
@type lang: string
@param lang: a string with the name of the language
@type field: string
@param field: a string with the name that we try to get
@rtype: string
@return: Returns a translation string
"""
# Read from cache
key = self._get_translation_cache_key(lang, field)
trans = cache.get(key, '')
if not trans:
trans_obj = self.get_translation_obj(lang, field)
trans = getattr(trans_obj, 'translation', '')
# if there's no translation text fall back to the model field
if not trans:
trans = getattr(self, field, '')
# update cache
cache.set(key, trans)
return trans | [
"def",
"get_translation",
"(",
"self",
",",
"lang",
",",
"field",
")",
":",
"# Read from cache",
"key",
"=",
"self",
".",
"_get_translation_cache_key",
"(",
"lang",
",",
"field",
")",
"trans",
"=",
"cache",
".",
"get",
"(",
"key",
",",
"''",
")",
"if",
"not",
"trans",
":",
"trans_obj",
"=",
"self",
".",
"get_translation_obj",
"(",
"lang",
",",
"field",
")",
"trans",
"=",
"getattr",
"(",
"trans_obj",
",",
"'translation'",
",",
"''",
")",
"# if there's no translation text fall back to the model field",
"if",
"not",
"trans",
":",
"trans",
"=",
"getattr",
"(",
"self",
",",
"field",
",",
"''",
")",
"# update cache",
"cache",
".",
"set",
"(",
"key",
",",
"trans",
")",
"return",
"trans"
] | Return the translation string of an specific field in a Translatable
istance
@type lang: string
@param lang: a string with the name of the language
@type field: string
@param field: a string with the name that we try to get
@rtype: string
@return: Returns a translation string | [
"Return",
"the",
"translation",
"string",
"of",
"an",
"specific",
"field",
"in",
"a",
"Translatable",
"istance"
] | 6716fcb7e98d7d27d41c72c4036d3593f1cc04c2 | https://github.com/angvp/django-klingon/blob/6716fcb7e98d7d27d41c72c4036d3593f1cc04c2/klingon/models.py#L162-L188 | train |
angvp/django-klingon | klingon/models.py | Translatable.set_translation | def set_translation(self, lang, field, text):
"""
Store a translation string in the specified field for a Translatable
istance
@type lang: string
@param lang: a string with the name of the language
@type field: string
@param field: a string with the name that we try to get
@type text: string
@param text: a string to be stored as translation of the field
"""
# Do not allow user to set a translations in the default language
auto_slug_obj = None
if lang == self._get_default_language():
raise CanNotTranslate(
_('You are not supposed to translate the default language. '
'Use the model fields for translations in default language')
)
# Get translation, if it does not exits create one
trans_obj = self.get_translation_obj(lang, field, create=True)
trans_obj.translation = text
trans_obj.save()
# check if the field has an autoslugfield and create the translation
if INSTALLED_AUTOSLUG:
if self.translatable_slug:
try:
auto_slug_obj = self._meta.get_field(self.translatable_slug).populate_from
except AttributeError:
pass
if auto_slug_obj:
tobj = self.get_translation_obj(lang, self.translatable_slug, create=True)
translation = self.get_translation(lang, auto_slug_obj)
tobj.translation = slugify(translation)
tobj.save()
# Update cache for this specif translations
key = self._get_translation_cache_key(lang, field)
cache.set(key, text)
# remove cache for translations dict
cache.delete(self._get_translations_cache_key(lang))
return trans_obj | python | def set_translation(self, lang, field, text):
"""
Store a translation string in the specified field for a Translatable
istance
@type lang: string
@param lang: a string with the name of the language
@type field: string
@param field: a string with the name that we try to get
@type text: string
@param text: a string to be stored as translation of the field
"""
# Do not allow user to set a translations in the default language
auto_slug_obj = None
if lang == self._get_default_language():
raise CanNotTranslate(
_('You are not supposed to translate the default language. '
'Use the model fields for translations in default language')
)
# Get translation, if it does not exits create one
trans_obj = self.get_translation_obj(lang, field, create=True)
trans_obj.translation = text
trans_obj.save()
# check if the field has an autoslugfield and create the translation
if INSTALLED_AUTOSLUG:
if self.translatable_slug:
try:
auto_slug_obj = self._meta.get_field(self.translatable_slug).populate_from
except AttributeError:
pass
if auto_slug_obj:
tobj = self.get_translation_obj(lang, self.translatable_slug, create=True)
translation = self.get_translation(lang, auto_slug_obj)
tobj.translation = slugify(translation)
tobj.save()
# Update cache for this specif translations
key = self._get_translation_cache_key(lang, field)
cache.set(key, text)
# remove cache for translations dict
cache.delete(self._get_translations_cache_key(lang))
return trans_obj | [
"def",
"set_translation",
"(",
"self",
",",
"lang",
",",
"field",
",",
"text",
")",
":",
"# Do not allow user to set a translations in the default language",
"auto_slug_obj",
"=",
"None",
"if",
"lang",
"==",
"self",
".",
"_get_default_language",
"(",
")",
":",
"raise",
"CanNotTranslate",
"(",
"_",
"(",
"'You are not supposed to translate the default language. '",
"'Use the model fields for translations in default language'",
")",
")",
"# Get translation, if it does not exits create one",
"trans_obj",
"=",
"self",
".",
"get_translation_obj",
"(",
"lang",
",",
"field",
",",
"create",
"=",
"True",
")",
"trans_obj",
".",
"translation",
"=",
"text",
"trans_obj",
".",
"save",
"(",
")",
"# check if the field has an autoslugfield and create the translation",
"if",
"INSTALLED_AUTOSLUG",
":",
"if",
"self",
".",
"translatable_slug",
":",
"try",
":",
"auto_slug_obj",
"=",
"self",
".",
"_meta",
".",
"get_field",
"(",
"self",
".",
"translatable_slug",
")",
".",
"populate_from",
"except",
"AttributeError",
":",
"pass",
"if",
"auto_slug_obj",
":",
"tobj",
"=",
"self",
".",
"get_translation_obj",
"(",
"lang",
",",
"self",
".",
"translatable_slug",
",",
"create",
"=",
"True",
")",
"translation",
"=",
"self",
".",
"get_translation",
"(",
"lang",
",",
"auto_slug_obj",
")",
"tobj",
".",
"translation",
"=",
"slugify",
"(",
"translation",
")",
"tobj",
".",
"save",
"(",
")",
"# Update cache for this specif translations",
"key",
"=",
"self",
".",
"_get_translation_cache_key",
"(",
"lang",
",",
"field",
")",
"cache",
".",
"set",
"(",
"key",
",",
"text",
")",
"# remove cache for translations dict",
"cache",
".",
"delete",
"(",
"self",
".",
"_get_translations_cache_key",
"(",
"lang",
")",
")",
"return",
"trans_obj"
] | Store a translation string in the specified field for a Translatable
istance
@type lang: string
@param lang: a string with the name of the language
@type field: string
@param field: a string with the name that we try to get
@type text: string
@param text: a string to be stored as translation of the field | [
"Store",
"a",
"translation",
"string",
"in",
"the",
"specified",
"field",
"for",
"a",
"Translatable",
"istance"
] | 6716fcb7e98d7d27d41c72c4036d3593f1cc04c2 | https://github.com/angvp/django-klingon/blob/6716fcb7e98d7d27d41c72c4036d3593f1cc04c2/klingon/models.py#L190-L237 | train |
angvp/django-klingon | klingon/models.py | Translatable.translations_link | def translations_link(self):
"""
Print on admin change list the link to see all translations for this object
@type text: string
@param text: a string with the html to link to the translations admin interface
"""
translation_type = ContentType.objects.get_for_model(Translation)
link = urlresolvers.reverse('admin:%s_%s_changelist' % (
translation_type.app_label,
translation_type.model),
)
object_type = ContentType.objects.get_for_model(self)
link += '?content_type__id__exact=%s&object_id=%s' % (object_type.id, self.id)
return '<a href="%s">translate</a>' % link | python | def translations_link(self):
"""
Print on admin change list the link to see all translations for this object
@type text: string
@param text: a string with the html to link to the translations admin interface
"""
translation_type = ContentType.objects.get_for_model(Translation)
link = urlresolvers.reverse('admin:%s_%s_changelist' % (
translation_type.app_label,
translation_type.model),
)
object_type = ContentType.objects.get_for_model(self)
link += '?content_type__id__exact=%s&object_id=%s' % (object_type.id, self.id)
return '<a href="%s">translate</a>' % link | [
"def",
"translations_link",
"(",
"self",
")",
":",
"translation_type",
"=",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"Translation",
")",
"link",
"=",
"urlresolvers",
".",
"reverse",
"(",
"'admin:%s_%s_changelist'",
"%",
"(",
"translation_type",
".",
"app_label",
",",
"translation_type",
".",
"model",
")",
",",
")",
"object_type",
"=",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"self",
")",
"link",
"+=",
"'?content_type__id__exact=%s&object_id=%s'",
"%",
"(",
"object_type",
".",
"id",
",",
"self",
".",
"id",
")",
"return",
"'<a href=\"%s\">translate</a>'",
"%",
"link"
] | Print on admin change list the link to see all translations for this object
@type text: string
@param text: a string with the html to link to the translations admin interface | [
"Print",
"on",
"admin",
"change",
"list",
"the",
"link",
"to",
"see",
"all",
"translations",
"for",
"this",
"object"
] | 6716fcb7e98d7d27d41c72c4036d3593f1cc04c2 | https://github.com/angvp/django-klingon/blob/6716fcb7e98d7d27d41c72c4036d3593f1cc04c2/klingon/models.py#L239-L254 | train |
indietyp/django-automated-logging | automated_logging/signals/database.py | comparison_callback | def comparison_callback(sender, instance, **kwargs):
"""Comparing old and new object to determin which fields changed how"""
if validate_instance(instance) and settings.AUTOMATED_LOGGING['to_database']:
try:
old = sender.objects.get(pk=instance.pk)
except Exception:
return None
try:
mdl = ContentType.objects.get_for_model(instance)
cur, ins = old.__dict__, instance.__dict__
old, new = {}, {}
for k in cur.keys():
# _ fields are not real model fields, only state or cache fields
# getting filtered
if re.match('(_)(.*?)', k):
continue
changed = False
if k in ins.keys():
if cur[k] != ins[k]:
changed = True
new[k] = ModelObject()
new[k].value = str(ins[k])
new[k].save()
try:
new[k].type = ContentType.objects.get_for_model(ins[k])
except Exception:
logger = logging.getLogger(__name__)
logger.debug('Could not dermin the content type of the field')
new[k].field = Field.objects.get_or_create(name=k, model=mdl)[0]
new[k].save()
else:
changed = True
if changed:
old[k] = ModelObject()
old[k].value = str(cur[k])
old[k].save()
try:
old[k].type = ContentType.objects.get_for_model(cur[k])
except Exception:
logger = logging.getLogger(__name__)
logger.debug('Could not dermin the content type of the field')
old[k].field = Field.objects.get_or_create(name=k, model=mdl)[0]
old[k].save()
if old or new:
changelog = ModelChangelog()
changelog.save()
changelog.modification = ModelModification()
changelog.modification.save()
changelog.modification.previously.add(*old.values())
changelog.modification.currently.add(*new.values())
changelog.information = ModelObject()
changelog.information.save()
changelog.information.value = repr(instance)
changelog.information.type = ContentType.objects.get_for_model(instance)
changelog.information.save()
changelog.save()
instance.al_chl = changelog
return instance
except Exception as e:
print(e)
logger = logging.getLogger(__name__)
logger.warning('automated_logging recorded an exception that should not have happended') | python | def comparison_callback(sender, instance, **kwargs):
"""Comparing old and new object to determin which fields changed how"""
if validate_instance(instance) and settings.AUTOMATED_LOGGING['to_database']:
try:
old = sender.objects.get(pk=instance.pk)
except Exception:
return None
try:
mdl = ContentType.objects.get_for_model(instance)
cur, ins = old.__dict__, instance.__dict__
old, new = {}, {}
for k in cur.keys():
# _ fields are not real model fields, only state or cache fields
# getting filtered
if re.match('(_)(.*?)', k):
continue
changed = False
if k in ins.keys():
if cur[k] != ins[k]:
changed = True
new[k] = ModelObject()
new[k].value = str(ins[k])
new[k].save()
try:
new[k].type = ContentType.objects.get_for_model(ins[k])
except Exception:
logger = logging.getLogger(__name__)
logger.debug('Could not dermin the content type of the field')
new[k].field = Field.objects.get_or_create(name=k, model=mdl)[0]
new[k].save()
else:
changed = True
if changed:
old[k] = ModelObject()
old[k].value = str(cur[k])
old[k].save()
try:
old[k].type = ContentType.objects.get_for_model(cur[k])
except Exception:
logger = logging.getLogger(__name__)
logger.debug('Could not dermin the content type of the field')
old[k].field = Field.objects.get_or_create(name=k, model=mdl)[0]
old[k].save()
if old or new:
changelog = ModelChangelog()
changelog.save()
changelog.modification = ModelModification()
changelog.modification.save()
changelog.modification.previously.add(*old.values())
changelog.modification.currently.add(*new.values())
changelog.information = ModelObject()
changelog.information.save()
changelog.information.value = repr(instance)
changelog.information.type = ContentType.objects.get_for_model(instance)
changelog.information.save()
changelog.save()
instance.al_chl = changelog
return instance
except Exception as e:
print(e)
logger = logging.getLogger(__name__)
logger.warning('automated_logging recorded an exception that should not have happended') | [
"def",
"comparison_callback",
"(",
"sender",
",",
"instance",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"validate_instance",
"(",
"instance",
")",
"and",
"settings",
".",
"AUTOMATED_LOGGING",
"[",
"'to_database'",
"]",
":",
"try",
":",
"old",
"=",
"sender",
".",
"objects",
".",
"get",
"(",
"pk",
"=",
"instance",
".",
"pk",
")",
"except",
"Exception",
":",
"return",
"None",
"try",
":",
"mdl",
"=",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"instance",
")",
"cur",
",",
"ins",
"=",
"old",
".",
"__dict__",
",",
"instance",
".",
"__dict__",
"old",
",",
"new",
"=",
"{",
"}",
",",
"{",
"}",
"for",
"k",
"in",
"cur",
".",
"keys",
"(",
")",
":",
"# _ fields are not real model fields, only state or cache fields",
"# getting filtered",
"if",
"re",
".",
"match",
"(",
"'(_)(.*?)'",
",",
"k",
")",
":",
"continue",
"changed",
"=",
"False",
"if",
"k",
"in",
"ins",
".",
"keys",
"(",
")",
":",
"if",
"cur",
"[",
"k",
"]",
"!=",
"ins",
"[",
"k",
"]",
":",
"changed",
"=",
"True",
"new",
"[",
"k",
"]",
"=",
"ModelObject",
"(",
")",
"new",
"[",
"k",
"]",
".",
"value",
"=",
"str",
"(",
"ins",
"[",
"k",
"]",
")",
"new",
"[",
"k",
"]",
".",
"save",
"(",
")",
"try",
":",
"new",
"[",
"k",
"]",
".",
"type",
"=",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"ins",
"[",
"k",
"]",
")",
"except",
"Exception",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"logger",
".",
"debug",
"(",
"'Could not dermin the content type of the field'",
")",
"new",
"[",
"k",
"]",
".",
"field",
"=",
"Field",
".",
"objects",
".",
"get_or_create",
"(",
"name",
"=",
"k",
",",
"model",
"=",
"mdl",
")",
"[",
"0",
"]",
"new",
"[",
"k",
"]",
".",
"save",
"(",
")",
"else",
":",
"changed",
"=",
"True",
"if",
"changed",
":",
"old",
"[",
"k",
"]",
"=",
"ModelObject",
"(",
")",
"old",
"[",
"k",
"]",
".",
"value",
"=",
"str",
"(",
"cur",
"[",
"k",
"]",
")",
"old",
"[",
"k",
"]",
".",
"save",
"(",
")",
"try",
":",
"old",
"[",
"k",
"]",
".",
"type",
"=",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"cur",
"[",
"k",
"]",
")",
"except",
"Exception",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"logger",
".",
"debug",
"(",
"'Could not dermin the content type of the field'",
")",
"old",
"[",
"k",
"]",
".",
"field",
"=",
"Field",
".",
"objects",
".",
"get_or_create",
"(",
"name",
"=",
"k",
",",
"model",
"=",
"mdl",
")",
"[",
"0",
"]",
"old",
"[",
"k",
"]",
".",
"save",
"(",
")",
"if",
"old",
"or",
"new",
":",
"changelog",
"=",
"ModelChangelog",
"(",
")",
"changelog",
".",
"save",
"(",
")",
"changelog",
".",
"modification",
"=",
"ModelModification",
"(",
")",
"changelog",
".",
"modification",
".",
"save",
"(",
")",
"changelog",
".",
"modification",
".",
"previously",
".",
"add",
"(",
"*",
"old",
".",
"values",
"(",
")",
")",
"changelog",
".",
"modification",
".",
"currently",
".",
"add",
"(",
"*",
"new",
".",
"values",
"(",
")",
")",
"changelog",
".",
"information",
"=",
"ModelObject",
"(",
")",
"changelog",
".",
"information",
".",
"save",
"(",
")",
"changelog",
".",
"information",
".",
"value",
"=",
"repr",
"(",
"instance",
")",
"changelog",
".",
"information",
".",
"type",
"=",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"instance",
")",
"changelog",
".",
"information",
".",
"save",
"(",
")",
"changelog",
".",
"save",
"(",
")",
"instance",
".",
"al_chl",
"=",
"changelog",
"return",
"instance",
"except",
"Exception",
"as",
"e",
":",
"print",
"(",
"e",
")",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"logger",
".",
"warning",
"(",
"'automated_logging recorded an exception that should not have happended'",
")"
] | Comparing old and new object to determin which fields changed how | [
"Comparing",
"old",
"and",
"new",
"object",
"to",
"determin",
"which",
"fields",
"changed",
"how"
] | 095dfc6df62dca45f7db4516bc35e52085d0a01c | https://github.com/indietyp/django-automated-logging/blob/095dfc6df62dca45f7db4516bc35e52085d0a01c/automated_logging/signals/database.py#L18-L92 | train |
indietyp/django-automated-logging | automated_logging/signals/database.py | save_callback | def save_callback(sender, instance, created, update_fields, **kwargs):
"""Save object & link logging entry"""
if validate_instance(instance):
status = 'add' if created is True else 'change'
change = ''
if status == 'change' and 'al_chl' in instance.__dict__.keys():
changelog = instance.al_chl.modification
change = ' to following changed: {}'.format(changelog)
processor(status, sender, instance, update_fields, addition=change) | python | def save_callback(sender, instance, created, update_fields, **kwargs):
"""Save object & link logging entry"""
if validate_instance(instance):
status = 'add' if created is True else 'change'
change = ''
if status == 'change' and 'al_chl' in instance.__dict__.keys():
changelog = instance.al_chl.modification
change = ' to following changed: {}'.format(changelog)
processor(status, sender, instance, update_fields, addition=change) | [
"def",
"save_callback",
"(",
"sender",
",",
"instance",
",",
"created",
",",
"update_fields",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"validate_instance",
"(",
"instance",
")",
":",
"status",
"=",
"'add'",
"if",
"created",
"is",
"True",
"else",
"'change'",
"change",
"=",
"''",
"if",
"status",
"==",
"'change'",
"and",
"'al_chl'",
"in",
"instance",
".",
"__dict__",
".",
"keys",
"(",
")",
":",
"changelog",
"=",
"instance",
".",
"al_chl",
".",
"modification",
"change",
"=",
"' to following changed: {}'",
".",
"format",
"(",
"changelog",
")",
"processor",
"(",
"status",
",",
"sender",
",",
"instance",
",",
"update_fields",
",",
"addition",
"=",
"change",
")"
] | Save object & link logging entry | [
"Save",
"object",
"&",
"link",
"logging",
"entry"
] | 095dfc6df62dca45f7db4516bc35e52085d0a01c | https://github.com/indietyp/django-automated-logging/blob/095dfc6df62dca45f7db4516bc35e52085d0a01c/automated_logging/signals/database.py#L97-L107 | train |
Xaroth/libzfs-python | libzfs/handle.py | LibZFSHandle.requires_refcount | def requires_refcount(cls, func):
"""
The ``requires_refcount`` decorator adds a check prior to call ``func`` to verify
that there is an active handle. if there is no such handle, a ``NoHandleException`` exception is thrown.
"""
@functools.wraps(func)
def requires_active_handle(*args, **kwargs):
if cls.refcount() == 0:
raise NoHandleException() # You probably want to encase your code in a 'with LibZFSHandle():' block...
return func(*args, **kwargs)
return requires_active_handle | python | def requires_refcount(cls, func):
"""
The ``requires_refcount`` decorator adds a check prior to call ``func`` to verify
that there is an active handle. if there is no such handle, a ``NoHandleException`` exception is thrown.
"""
@functools.wraps(func)
def requires_active_handle(*args, **kwargs):
if cls.refcount() == 0:
raise NoHandleException() # You probably want to encase your code in a 'with LibZFSHandle():' block...
return func(*args, **kwargs)
return requires_active_handle | [
"def",
"requires_refcount",
"(",
"cls",
",",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"requires_active_handle",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"cls",
".",
"refcount",
"(",
")",
"==",
"0",
":",
"raise",
"NoHandleException",
"(",
")",
"# You probably want to encase your code in a 'with LibZFSHandle():' block...",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"requires_active_handle"
] | The ``requires_refcount`` decorator adds a check prior to call ``func`` to verify
that there is an active handle. if there is no such handle, a ``NoHandleException`` exception is thrown. | [
"The",
"requires_refcount",
"decorator",
"adds",
"a",
"check",
"prior",
"to",
"call",
"func",
"to",
"verify",
"that",
"there",
"is",
"an",
"active",
"handle",
".",
"if",
"there",
"is",
"no",
"such",
"handle",
"a",
"NoHandleException",
"exception",
"is",
"thrown",
"."
] | 146e5f28de5971bb6eb64fd82b098c5f302f0b33 | https://github.com/Xaroth/libzfs-python/blob/146e5f28de5971bb6eb64fd82b098c5f302f0b33/libzfs/handle.py#L49-L59 | train |
Xaroth/libzfs-python | libzfs/handle.py | LibZFSHandle.auto | def auto(cls, func):
"""
The ``auto`` decorator wraps ``func`` in a context manager so that a handle is obtained.
.. note::
Please note, that most functions require the handle to continue being alive for future calls to data
retrieved from the function. In such cases, it's advisable to use the `requires_refcount` decorator, and
force the program using the library with obtaining a handle (and keeping it active.)
"""
@functools.wraps(func)
def auto_claim_handle(*args, **kwargs):
with cls():
return func(*args, **kwargs)
return auto_claim_handle | python | def auto(cls, func):
"""
The ``auto`` decorator wraps ``func`` in a context manager so that a handle is obtained.
.. note::
Please note, that most functions require the handle to continue being alive for future calls to data
retrieved from the function. In such cases, it's advisable to use the `requires_refcount` decorator, and
force the program using the library with obtaining a handle (and keeping it active.)
"""
@functools.wraps(func)
def auto_claim_handle(*args, **kwargs):
with cls():
return func(*args, **kwargs)
return auto_claim_handle | [
"def",
"auto",
"(",
"cls",
",",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"auto_claim_handle",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"cls",
"(",
")",
":",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"auto_claim_handle"
] | The ``auto`` decorator wraps ``func`` in a context manager so that a handle is obtained.
.. note::
Please note, that most functions require the handle to continue being alive for future calls to data
retrieved from the function. In such cases, it's advisable to use the `requires_refcount` decorator, and
force the program using the library with obtaining a handle (and keeping it active.) | [
"The",
"auto",
"decorator",
"wraps",
"func",
"in",
"a",
"context",
"manager",
"so",
"that",
"a",
"handle",
"is",
"obtained",
"."
] | 146e5f28de5971bb6eb64fd82b098c5f302f0b33 | https://github.com/Xaroth/libzfs-python/blob/146e5f28de5971bb6eb64fd82b098c5f302f0b33/libzfs/handle.py#L62-L75 | train |
spotify/gordon-gcp | src/gordon_gcp/plugins/janitor/__init__.py | get_gpubsub_publisher | def get_gpubsub_publisher(config, metrics, changes_channel, **kw):
"""Get a GPubsubPublisher client.
A factory function that validates configuration, creates an auth
and pubsub API client, and returns a Google Pub/Sub Publisher
provider.
Args:
config (dict): Google Cloud Pub/Sub-related configuration.
metrics (obj): :interface:`IMetricRelay` implementation.
changes_channel (asyncio.Queue): Queue to publish message to
make corrections to Cloud DNS.
kw (dict): Additional keyword arguments to pass to the
Publisher.
Returns:
A :class:`GPubsubPublisher` instance.
"""
builder = gpubsub_publisher.GPubsubPublisherBuilder(
config, metrics, changes_channel, **kw)
return builder.build_publisher() | python | def get_gpubsub_publisher(config, metrics, changes_channel, **kw):
"""Get a GPubsubPublisher client.
A factory function that validates configuration, creates an auth
and pubsub API client, and returns a Google Pub/Sub Publisher
provider.
Args:
config (dict): Google Cloud Pub/Sub-related configuration.
metrics (obj): :interface:`IMetricRelay` implementation.
changes_channel (asyncio.Queue): Queue to publish message to
make corrections to Cloud DNS.
kw (dict): Additional keyword arguments to pass to the
Publisher.
Returns:
A :class:`GPubsubPublisher` instance.
"""
builder = gpubsub_publisher.GPubsubPublisherBuilder(
config, metrics, changes_channel, **kw)
return builder.build_publisher() | [
"def",
"get_gpubsub_publisher",
"(",
"config",
",",
"metrics",
",",
"changes_channel",
",",
"*",
"*",
"kw",
")",
":",
"builder",
"=",
"gpubsub_publisher",
".",
"GPubsubPublisherBuilder",
"(",
"config",
",",
"metrics",
",",
"changes_channel",
",",
"*",
"*",
"kw",
")",
"return",
"builder",
".",
"build_publisher",
"(",
")"
] | Get a GPubsubPublisher client.
A factory function that validates configuration, creates an auth
and pubsub API client, and returns a Google Pub/Sub Publisher
provider.
Args:
config (dict): Google Cloud Pub/Sub-related configuration.
metrics (obj): :interface:`IMetricRelay` implementation.
changes_channel (asyncio.Queue): Queue to publish message to
make corrections to Cloud DNS.
kw (dict): Additional keyword arguments to pass to the
Publisher.
Returns:
A :class:`GPubsubPublisher` instance. | [
"Get",
"a",
"GPubsubPublisher",
"client",
"."
] | 5ab19e3c2fe6ace72ee91e2ef1a1326f90b805da | https://github.com/spotify/gordon-gcp/blob/5ab19e3c2fe6ace72ee91e2ef1a1326f90b805da/src/gordon_gcp/plugins/janitor/__init__.py#L34-L53 | train |
spotify/gordon-gcp | src/gordon_gcp/plugins/janitor/__init__.py | get_reconciler | def get_reconciler(config, metrics, rrset_channel, changes_channel, **kw):
"""Get a GDNSReconciler client.
A factory function that validates configuration, creates an auth
and :class:`GDNSClient` instance, and returns a GDNSReconciler
provider.
Args:
config (dict): Google Cloud Pub/Sub-related configuration.
metrics (obj): :interface:`IMetricRelay` implementation.
rrset_channel (asyncio.Queue): Queue from which to consume
record set messages to validate.
changes_channel (asyncio.Queue): Queue to publish message to
make corrections to Cloud DNS.
kw (dict): Additional keyword arguments to pass to the
Reconciler.
Returns:
A :class:`GDNSReconciler` instance.
"""
builder = reconciler.GDNSReconcilerBuilder(
config, metrics, rrset_channel, changes_channel, **kw)
return builder.build_reconciler() | python | def get_reconciler(config, metrics, rrset_channel, changes_channel, **kw):
"""Get a GDNSReconciler client.
A factory function that validates configuration, creates an auth
and :class:`GDNSClient` instance, and returns a GDNSReconciler
provider.
Args:
config (dict): Google Cloud Pub/Sub-related configuration.
metrics (obj): :interface:`IMetricRelay` implementation.
rrset_channel (asyncio.Queue): Queue from which to consume
record set messages to validate.
changes_channel (asyncio.Queue): Queue to publish message to
make corrections to Cloud DNS.
kw (dict): Additional keyword arguments to pass to the
Reconciler.
Returns:
A :class:`GDNSReconciler` instance.
"""
builder = reconciler.GDNSReconcilerBuilder(
config, metrics, rrset_channel, changes_channel, **kw)
return builder.build_reconciler() | [
"def",
"get_reconciler",
"(",
"config",
",",
"metrics",
",",
"rrset_channel",
",",
"changes_channel",
",",
"*",
"*",
"kw",
")",
":",
"builder",
"=",
"reconciler",
".",
"GDNSReconcilerBuilder",
"(",
"config",
",",
"metrics",
",",
"rrset_channel",
",",
"changes_channel",
",",
"*",
"*",
"kw",
")",
"return",
"builder",
".",
"build_reconciler",
"(",
")"
] | Get a GDNSReconciler client.
A factory function that validates configuration, creates an auth
and :class:`GDNSClient` instance, and returns a GDNSReconciler
provider.
Args:
config (dict): Google Cloud Pub/Sub-related configuration.
metrics (obj): :interface:`IMetricRelay` implementation.
rrset_channel (asyncio.Queue): Queue from which to consume
record set messages to validate.
changes_channel (asyncio.Queue): Queue to publish message to
make corrections to Cloud DNS.
kw (dict): Additional keyword arguments to pass to the
Reconciler.
Returns:
A :class:`GDNSReconciler` instance. | [
"Get",
"a",
"GDNSReconciler",
"client",
"."
] | 5ab19e3c2fe6ace72ee91e2ef1a1326f90b805da | https://github.com/spotify/gordon-gcp/blob/5ab19e3c2fe6ace72ee91e2ef1a1326f90b805da/src/gordon_gcp/plugins/janitor/__init__.py#L56-L77 | train |
spotify/gordon-gcp | src/gordon_gcp/plugins/janitor/__init__.py | get_authority | def get_authority(config, metrics, rrset_channel, **kwargs):
"""Get a GCEAuthority client.
A factory function that validates configuration and creates a
proper GCEAuthority.
Args:
config (dict): GCEAuthority related configuration.
metrics (obj): :interface:`IMetricRelay` implementation.
rrset_channel (asyncio.Queue): Queue used for sending messages
to the reconciler plugin.
kw (dict): Additional keyword arguments to pass to the
Authority.
Returns:
A :class:`GCEAuthority` instance.
"""
builder = authority.GCEAuthorityBuilder(
config, metrics, rrset_channel, **kwargs)
return builder.build_authority() | python | def get_authority(config, metrics, rrset_channel, **kwargs):
"""Get a GCEAuthority client.
A factory function that validates configuration and creates a
proper GCEAuthority.
Args:
config (dict): GCEAuthority related configuration.
metrics (obj): :interface:`IMetricRelay` implementation.
rrset_channel (asyncio.Queue): Queue used for sending messages
to the reconciler plugin.
kw (dict): Additional keyword arguments to pass to the
Authority.
Returns:
A :class:`GCEAuthority` instance.
"""
builder = authority.GCEAuthorityBuilder(
config, metrics, rrset_channel, **kwargs)
return builder.build_authority() | [
"def",
"get_authority",
"(",
"config",
",",
"metrics",
",",
"rrset_channel",
",",
"*",
"*",
"kwargs",
")",
":",
"builder",
"=",
"authority",
".",
"GCEAuthorityBuilder",
"(",
"config",
",",
"metrics",
",",
"rrset_channel",
",",
"*",
"*",
"kwargs",
")",
"return",
"builder",
".",
"build_authority",
"(",
")"
] | Get a GCEAuthority client.
A factory function that validates configuration and creates a
proper GCEAuthority.
Args:
config (dict): GCEAuthority related configuration.
metrics (obj): :interface:`IMetricRelay` implementation.
rrset_channel (asyncio.Queue): Queue used for sending messages
to the reconciler plugin.
kw (dict): Additional keyword arguments to pass to the
Authority.
Returns:
A :class:`GCEAuthority` instance. | [
"Get",
"a",
"GCEAuthority",
"client",
"."
] | 5ab19e3c2fe6ace72ee91e2ef1a1326f90b805da | https://github.com/spotify/gordon-gcp/blob/5ab19e3c2fe6ace72ee91e2ef1a1326f90b805da/src/gordon_gcp/plugins/janitor/__init__.py#L80-L98 | train |
spotify/gordon-gcp | src/gordon_gcp/clients/auth.py | GAuthClient.refresh_token | async def refresh_token(self):
"""Refresh oauth access token attached to this HTTP session.
Raises:
:exc:`.GCPAuthError`: if no token was found in the
response.
:exc:`.GCPHTTPError`: if any exception occurred,
specifically a :exc:`.GCPHTTPResponseError`, if the
exception is associated with a response status code.
"""
url, headers, body = self._setup_token_request()
request_id = uuid.uuid4()
logging.debug(_utils.REQ_LOG_FMT.format(
request_id=request_id, method='POST', url=url, kwargs=None))
async with self._session.post(url, headers=headers, data=body) as resp:
log_kw = {
'request_id': request_id,
'method': 'POST',
'url': resp.url,
'status': resp.status,
'reason': resp.reason,
}
logging.debug(_utils.RESP_LOG_FMT.format(**log_kw))
# avoid leaky abstractions and wrap http errors with our own
try:
resp.raise_for_status()
except aiohttp.ClientResponseError as e:
msg = f'[{request_id}] Issue connecting to {resp.url}: {e}'
logging.error(msg, exc_info=e)
raise exceptions.GCPHTTPResponseError(msg, resp.status)
response = await resp.json()
try:
self.token = response['access_token']
except KeyError:
msg = '[{request_id}] No access token in response.'
logging.error(msg)
raise exceptions.GCPAuthError(msg)
self.expiry = _client._parse_expiry(response) | python | async def refresh_token(self):
"""Refresh oauth access token attached to this HTTP session.
Raises:
:exc:`.GCPAuthError`: if no token was found in the
response.
:exc:`.GCPHTTPError`: if any exception occurred,
specifically a :exc:`.GCPHTTPResponseError`, if the
exception is associated with a response status code.
"""
url, headers, body = self._setup_token_request()
request_id = uuid.uuid4()
logging.debug(_utils.REQ_LOG_FMT.format(
request_id=request_id, method='POST', url=url, kwargs=None))
async with self._session.post(url, headers=headers, data=body) as resp:
log_kw = {
'request_id': request_id,
'method': 'POST',
'url': resp.url,
'status': resp.status,
'reason': resp.reason,
}
logging.debug(_utils.RESP_LOG_FMT.format(**log_kw))
# avoid leaky abstractions and wrap http errors with our own
try:
resp.raise_for_status()
except aiohttp.ClientResponseError as e:
msg = f'[{request_id}] Issue connecting to {resp.url}: {e}'
logging.error(msg, exc_info=e)
raise exceptions.GCPHTTPResponseError(msg, resp.status)
response = await resp.json()
try:
self.token = response['access_token']
except KeyError:
msg = '[{request_id}] No access token in response.'
logging.error(msg)
raise exceptions.GCPAuthError(msg)
self.expiry = _client._parse_expiry(response) | [
"async",
"def",
"refresh_token",
"(",
"self",
")",
":",
"url",
",",
"headers",
",",
"body",
"=",
"self",
".",
"_setup_token_request",
"(",
")",
"request_id",
"=",
"uuid",
".",
"uuid4",
"(",
")",
"logging",
".",
"debug",
"(",
"_utils",
".",
"REQ_LOG_FMT",
".",
"format",
"(",
"request_id",
"=",
"request_id",
",",
"method",
"=",
"'POST'",
",",
"url",
"=",
"url",
",",
"kwargs",
"=",
"None",
")",
")",
"async",
"with",
"self",
".",
"_session",
".",
"post",
"(",
"url",
",",
"headers",
"=",
"headers",
",",
"data",
"=",
"body",
")",
"as",
"resp",
":",
"log_kw",
"=",
"{",
"'request_id'",
":",
"request_id",
",",
"'method'",
":",
"'POST'",
",",
"'url'",
":",
"resp",
".",
"url",
",",
"'status'",
":",
"resp",
".",
"status",
",",
"'reason'",
":",
"resp",
".",
"reason",
",",
"}",
"logging",
".",
"debug",
"(",
"_utils",
".",
"RESP_LOG_FMT",
".",
"format",
"(",
"*",
"*",
"log_kw",
")",
")",
"# avoid leaky abstractions and wrap http errors with our own",
"try",
":",
"resp",
".",
"raise_for_status",
"(",
")",
"except",
"aiohttp",
".",
"ClientResponseError",
"as",
"e",
":",
"msg",
"=",
"f'[{request_id}] Issue connecting to {resp.url}: {e}'",
"logging",
".",
"error",
"(",
"msg",
",",
"exc_info",
"=",
"e",
")",
"raise",
"exceptions",
".",
"GCPHTTPResponseError",
"(",
"msg",
",",
"resp",
".",
"status",
")",
"response",
"=",
"await",
"resp",
".",
"json",
"(",
")",
"try",
":",
"self",
".",
"token",
"=",
"response",
"[",
"'access_token'",
"]",
"except",
"KeyError",
":",
"msg",
"=",
"'[{request_id}] No access token in response.'",
"logging",
".",
"error",
"(",
"msg",
")",
"raise",
"exceptions",
".",
"GCPAuthError",
"(",
"msg",
")",
"self",
".",
"expiry",
"=",
"_client",
".",
"_parse_expiry",
"(",
"response",
")"
] | Refresh oauth access token attached to this HTTP session.
Raises:
:exc:`.GCPAuthError`: if no token was found in the
response.
:exc:`.GCPHTTPError`: if any exception occurred,
specifically a :exc:`.GCPHTTPResponseError`, if the
exception is associated with a response status code. | [
"Refresh",
"oauth",
"access",
"token",
"attached",
"to",
"this",
"HTTP",
"session",
"."
] | 5ab19e3c2fe6ace72ee91e2ef1a1326f90b805da | https://github.com/spotify/gordon-gcp/blob/5ab19e3c2fe6ace72ee91e2ef1a1326f90b805da/src/gordon_gcp/clients/auth.py#L168-L208 | train |
rfverbruggen/rachiopy | rachiopy/device.py | Device.get | def get(self, dev_id):
"""Retrieve the information for a device entity."""
path = '/'.join(['device', dev_id])
return self.rachio.get(path) | python | def get(self, dev_id):
"""Retrieve the information for a device entity."""
path = '/'.join(['device', dev_id])
return self.rachio.get(path) | [
"def",
"get",
"(",
"self",
",",
"dev_id",
")",
":",
"path",
"=",
"'/'",
".",
"join",
"(",
"[",
"'device'",
",",
"dev_id",
"]",
")",
"return",
"self",
".",
"rachio",
".",
"get",
"(",
"path",
")"
] | Retrieve the information for a device entity. | [
"Retrieve",
"the",
"information",
"for",
"a",
"device",
"entity",
"."
] | c91abc9984f0f453e60fa905285c1b640c3390ae | https://github.com/rfverbruggen/rachiopy/blob/c91abc9984f0f453e60fa905285c1b640c3390ae/rachiopy/device.py#L11-L14 | train |
rfverbruggen/rachiopy | rachiopy/device.py | Device.getEvent | def getEvent(self, dev_id, starttime, endtime):
"""Retrieve events for a device entity."""
path = 'device/%s/event?startTime=%s&endTime=%s' % \
(dev_id, starttime, endtime)
return self.rachio.get(path) | python | def getEvent(self, dev_id, starttime, endtime):
"""Retrieve events for a device entity."""
path = 'device/%s/event?startTime=%s&endTime=%s' % \
(dev_id, starttime, endtime)
return self.rachio.get(path) | [
"def",
"getEvent",
"(",
"self",
",",
"dev_id",
",",
"starttime",
",",
"endtime",
")",
":",
"path",
"=",
"'device/%s/event?startTime=%s&endTime=%s'",
"%",
"(",
"dev_id",
",",
"starttime",
",",
"endtime",
")",
"return",
"self",
".",
"rachio",
".",
"get",
"(",
"path",
")"
] | Retrieve events for a device entity. | [
"Retrieve",
"events",
"for",
"a",
"device",
"entity",
"."
] | c91abc9984f0f453e60fa905285c1b640c3390ae | https://github.com/rfverbruggen/rachiopy/blob/c91abc9984f0f453e60fa905285c1b640c3390ae/rachiopy/device.py#L21-L25 | train |
rfverbruggen/rachiopy | rachiopy/device.py | Device.getForecast | def getForecast(self, dev_id, units):
"""Retrieve current and predicted forecast."""
assert units in ['US', 'METRIC'], 'units must be either US or METRIC'
path = 'device/%s/forecast?units=%s' % (dev_id, units)
return self.rachio.get(path) | python | def getForecast(self, dev_id, units):
"""Retrieve current and predicted forecast."""
assert units in ['US', 'METRIC'], 'units must be either US or METRIC'
path = 'device/%s/forecast?units=%s' % (dev_id, units)
return self.rachio.get(path) | [
"def",
"getForecast",
"(",
"self",
",",
"dev_id",
",",
"units",
")",
":",
"assert",
"units",
"in",
"[",
"'US'",
",",
"'METRIC'",
"]",
",",
"'units must be either US or METRIC'",
"path",
"=",
"'device/%s/forecast?units=%s'",
"%",
"(",
"dev_id",
",",
"units",
")",
"return",
"self",
".",
"rachio",
".",
"get",
"(",
"path",
")"
] | Retrieve current and predicted forecast. | [
"Retrieve",
"current",
"and",
"predicted",
"forecast",
"."
] | c91abc9984f0f453e60fa905285c1b640c3390ae | https://github.com/rfverbruggen/rachiopy/blob/c91abc9984f0f453e60fa905285c1b640c3390ae/rachiopy/device.py#L32-L36 | train |
rfverbruggen/rachiopy | rachiopy/device.py | Device.stopWater | def stopWater(self, dev_id):
"""Stop all watering on device."""
path = 'device/stop_water'
payload = {'id': dev_id}
return self.rachio.put(path, payload) | python | def stopWater(self, dev_id):
"""Stop all watering on device."""
path = 'device/stop_water'
payload = {'id': dev_id}
return self.rachio.put(path, payload) | [
"def",
"stopWater",
"(",
"self",
",",
"dev_id",
")",
":",
"path",
"=",
"'device/stop_water'",
"payload",
"=",
"{",
"'id'",
":",
"dev_id",
"}",
"return",
"self",
".",
"rachio",
".",
"put",
"(",
"path",
",",
"payload",
")"
] | Stop all watering on device. | [
"Stop",
"all",
"watering",
"on",
"device",
"."
] | c91abc9984f0f453e60fa905285c1b640c3390ae | https://github.com/rfverbruggen/rachiopy/blob/c91abc9984f0f453e60fa905285c1b640c3390ae/rachiopy/device.py#L38-L42 | train |
rfverbruggen/rachiopy | rachiopy/device.py | Device.rainDelay | def rainDelay(self, dev_id, duration):
"""Rain delay device."""
path = 'device/rain_delay'
payload = {'id': dev_id, 'duration': duration}
return self.rachio.put(path, payload) | python | def rainDelay(self, dev_id, duration):
"""Rain delay device."""
path = 'device/rain_delay'
payload = {'id': dev_id, 'duration': duration}
return self.rachio.put(path, payload) | [
"def",
"rainDelay",
"(",
"self",
",",
"dev_id",
",",
"duration",
")",
":",
"path",
"=",
"'device/rain_delay'",
"payload",
"=",
"{",
"'id'",
":",
"dev_id",
",",
"'duration'",
":",
"duration",
"}",
"return",
"self",
".",
"rachio",
".",
"put",
"(",
"path",
",",
"payload",
")"
] | Rain delay device. | [
"Rain",
"delay",
"device",
"."
] | c91abc9984f0f453e60fa905285c1b640c3390ae | https://github.com/rfverbruggen/rachiopy/blob/c91abc9984f0f453e60fa905285c1b640c3390ae/rachiopy/device.py#L44-L48 | train |
rfverbruggen/rachiopy | rachiopy/device.py | Device.on | def on(self, dev_id):
"""Turn ON all features of the device.
schedules, weather intelligence, water budget, etc.
"""
path = 'device/on'
payload = {'id': dev_id}
return self.rachio.put(path, payload) | python | def on(self, dev_id):
"""Turn ON all features of the device.
schedules, weather intelligence, water budget, etc.
"""
path = 'device/on'
payload = {'id': dev_id}
return self.rachio.put(path, payload) | [
"def",
"on",
"(",
"self",
",",
"dev_id",
")",
":",
"path",
"=",
"'device/on'",
"payload",
"=",
"{",
"'id'",
":",
"dev_id",
"}",
"return",
"self",
".",
"rachio",
".",
"put",
"(",
"path",
",",
"payload",
")"
] | Turn ON all features of the device.
schedules, weather intelligence, water budget, etc. | [
"Turn",
"ON",
"all",
"features",
"of",
"the",
"device",
"."
] | c91abc9984f0f453e60fa905285c1b640c3390ae | https://github.com/rfverbruggen/rachiopy/blob/c91abc9984f0f453e60fa905285c1b640c3390ae/rachiopy/device.py#L50-L57 | train |
rfverbruggen/rachiopy | rachiopy/device.py | Device.off | def off(self, dev_id):
"""Turn OFF all features of the device.
schedules, weather intelligence, water budget, etc.
"""
path = 'device/off'
payload = {'id': dev_id}
return self.rachio.put(path, payload) | python | def off(self, dev_id):
"""Turn OFF all features of the device.
schedules, weather intelligence, water budget, etc.
"""
path = 'device/off'
payload = {'id': dev_id}
return self.rachio.put(path, payload) | [
"def",
"off",
"(",
"self",
",",
"dev_id",
")",
":",
"path",
"=",
"'device/off'",
"payload",
"=",
"{",
"'id'",
":",
"dev_id",
"}",
"return",
"self",
".",
"rachio",
".",
"put",
"(",
"path",
",",
"payload",
")"
] | Turn OFF all features of the device.
schedules, weather intelligence, water budget, etc. | [
"Turn",
"OFF",
"all",
"features",
"of",
"the",
"device",
"."
] | c91abc9984f0f453e60fa905285c1b640c3390ae | https://github.com/rfverbruggen/rachiopy/blob/c91abc9984f0f453e60fa905285c1b640c3390ae/rachiopy/device.py#L59-L66 | train |
F483/btctxstore | btctxstore/api.py | BtcTxStore.create_wallet | def create_wallet(self, master_secret=b""):
"""Create a BIP0032-style hierarchical wallet.
@param: master_secret Create from master secret, otherwise random.
"""
master_secret = deserialize.bytes_str(master_secret)
bip32node = control.create_wallet(self.testnet,
master_secret=master_secret)
return bip32node.hwif(as_private=True) | python | def create_wallet(self, master_secret=b""):
"""Create a BIP0032-style hierarchical wallet.
@param: master_secret Create from master secret, otherwise random.
"""
master_secret = deserialize.bytes_str(master_secret)
bip32node = control.create_wallet(self.testnet,
master_secret=master_secret)
return bip32node.hwif(as_private=True) | [
"def",
"create_wallet",
"(",
"self",
",",
"master_secret",
"=",
"b\"\"",
")",
":",
"master_secret",
"=",
"deserialize",
".",
"bytes_str",
"(",
"master_secret",
")",
"bip32node",
"=",
"control",
".",
"create_wallet",
"(",
"self",
".",
"testnet",
",",
"master_secret",
"=",
"master_secret",
")",
"return",
"bip32node",
".",
"hwif",
"(",
"as_private",
"=",
"True",
")"
] | Create a BIP0032-style hierarchical wallet.
@param: master_secret Create from master secret, otherwise random. | [
"Create",
"a",
"BIP0032",
"-",
"style",
"hierarchical",
"wallet",
"."
] | 5790ace3a3d4c9bcc759e7c931fc4a57d40b6c25 | https://github.com/F483/btctxstore/blob/5790ace3a3d4c9bcc759e7c931fc4a57d40b6c25/btctxstore/api.py#L33-L41 | train |
F483/btctxstore | btctxstore/api.py | BtcTxStore.create_key | def create_key(self, master_secret=b""):
"""Create new private key and return in wif format.
@param: master_secret Create from master secret, otherwise random.
"""
master_secret = deserialize.bytes_str(master_secret)
bip32node = control.create_wallet(self.testnet,
master_secret=master_secret)
return bip32node.wif() | python | def create_key(self, master_secret=b""):
"""Create new private key and return in wif format.
@param: master_secret Create from master secret, otherwise random.
"""
master_secret = deserialize.bytes_str(master_secret)
bip32node = control.create_wallet(self.testnet,
master_secret=master_secret)
return bip32node.wif() | [
"def",
"create_key",
"(",
"self",
",",
"master_secret",
"=",
"b\"\"",
")",
":",
"master_secret",
"=",
"deserialize",
".",
"bytes_str",
"(",
"master_secret",
")",
"bip32node",
"=",
"control",
".",
"create_wallet",
"(",
"self",
".",
"testnet",
",",
"master_secret",
"=",
"master_secret",
")",
"return",
"bip32node",
".",
"wif",
"(",
")"
] | Create new private key and return in wif format.
@param: master_secret Create from master secret, otherwise random. | [
"Create",
"new",
"private",
"key",
"and",
"return",
"in",
"wif",
"format",
"."
] | 5790ace3a3d4c9bcc759e7c931fc4a57d40b6c25 | https://github.com/F483/btctxstore/blob/5790ace3a3d4c9bcc759e7c931fc4a57d40b6c25/btctxstore/api.py#L54-L62 | train |
F483/btctxstore | btctxstore/api.py | BtcTxStore.confirms | def confirms(self, txid):
"""Returns number of confirms or None if unpublished."""
txid = deserialize.txid(txid)
return self.service.confirms(txid) | python | def confirms(self, txid):
"""Returns number of confirms or None if unpublished."""
txid = deserialize.txid(txid)
return self.service.confirms(txid) | [
"def",
"confirms",
"(",
"self",
",",
"txid",
")",
":",
"txid",
"=",
"deserialize",
".",
"txid",
"(",
"txid",
")",
"return",
"self",
".",
"service",
".",
"confirms",
"(",
"txid",
")"
] | Returns number of confirms or None if unpublished. | [
"Returns",
"number",
"of",
"confirms",
"or",
"None",
"if",
"unpublished",
"."
] | 5790ace3a3d4c9bcc759e7c931fc4a57d40b6c25 | https://github.com/F483/btctxstore/blob/5790ace3a3d4c9bcc759e7c931fc4a57d40b6c25/btctxstore/api.py#L328-L331 | train |
rohankapoorcom/zm-py | zoneminder/monitor.py | TimePeriod.get_time_period | def get_time_period(value):
"""Get the corresponding TimePeriod from the value.
Example values: 'all', 'hour', 'day', 'week', or 'month'.
"""
for time_period in TimePeriod:
if time_period.period == value:
return time_period
raise ValueError('{} is not a valid TimePeriod'.format(value)) | python | def get_time_period(value):
"""Get the corresponding TimePeriod from the value.
Example values: 'all', 'hour', 'day', 'week', or 'month'.
"""
for time_period in TimePeriod:
if time_period.period == value:
return time_period
raise ValueError('{} is not a valid TimePeriod'.format(value)) | [
"def",
"get_time_period",
"(",
"value",
")",
":",
"for",
"time_period",
"in",
"TimePeriod",
":",
"if",
"time_period",
".",
"period",
"==",
"value",
":",
"return",
"time_period",
"raise",
"ValueError",
"(",
"'{} is not a valid TimePeriod'",
".",
"format",
"(",
"value",
")",
")"
] | Get the corresponding TimePeriod from the value.
Example values: 'all', 'hour', 'day', 'week', or 'month'. | [
"Get",
"the",
"corresponding",
"TimePeriod",
"from",
"the",
"value",
"."
] | bd3a9f6b2f7b84b37589e2939f628b479a5531bf | https://github.com/rohankapoorcom/zm-py/blob/bd3a9f6b2f7b84b37589e2939f628b479a5531bf/zoneminder/monitor.py#L41-L49 | train |
rohankapoorcom/zm-py | zoneminder/monitor.py | Monitor.update_monitor | def update_monitor(self):
"""Update the monitor and monitor status from the ZM server."""
result = self._client.get_state(self._monitor_url)
self._raw_result = result['monitor'] | python | def update_monitor(self):
"""Update the monitor and monitor status from the ZM server."""
result = self._client.get_state(self._monitor_url)
self._raw_result = result['monitor'] | [
"def",
"update_monitor",
"(",
"self",
")",
":",
"result",
"=",
"self",
".",
"_client",
".",
"get_state",
"(",
"self",
".",
"_monitor_url",
")",
"self",
".",
"_raw_result",
"=",
"result",
"[",
"'monitor'",
"]"
] | Update the monitor and monitor status from the ZM server. | [
"Update",
"the",
"monitor",
"and",
"monitor",
"status",
"from",
"the",
"ZM",
"server",
"."
] | bd3a9f6b2f7b84b37589e2939f628b479a5531bf | https://github.com/rohankapoorcom/zm-py/blob/bd3a9f6b2f7b84b37589e2939f628b479a5531bf/zoneminder/monitor.py#L86-L89 | train |
rohankapoorcom/zm-py | zoneminder/monitor.py | Monitor.function | def function(self, new_function):
"""Set the MonitorState of this Monitor."""
self._client.change_state(
self._monitor_url,
{'Monitor[Function]': new_function.value}) | python | def function(self, new_function):
"""Set the MonitorState of this Monitor."""
self._client.change_state(
self._monitor_url,
{'Monitor[Function]': new_function.value}) | [
"def",
"function",
"(",
"self",
",",
"new_function",
")",
":",
"self",
".",
"_client",
".",
"change_state",
"(",
"self",
".",
"_monitor_url",
",",
"{",
"'Monitor[Function]'",
":",
"new_function",
".",
"value",
"}",
")"
] | Set the MonitorState of this Monitor. | [
"Set",
"the",
"MonitorState",
"of",
"this",
"Monitor",
"."
] | bd3a9f6b2f7b84b37589e2939f628b479a5531bf | https://github.com/rohankapoorcom/zm-py/blob/bd3a9f6b2f7b84b37589e2939f628b479a5531bf/zoneminder/monitor.py#L99-L103 | train |
rohankapoorcom/zm-py | zoneminder/monitor.py | Monitor.is_recording | def is_recording(self) -> Optional[bool]:
"""Indicate if this Monitor is currently recording."""
status_response = self._client.get_state(
'api/monitors/alarm/id:{}/command:status.json'.format(
self._monitor_id
)
)
if not status_response:
_LOGGER.warning('Could not get status for monitor {}'.format(
self._monitor_id
))
return None
status = status_response.get('status')
# ZoneMinder API returns an empty string to indicate that this monitor
# cannot record right now
if status == '':
return False
return int(status) == STATE_ALARM | python | def is_recording(self) -> Optional[bool]:
"""Indicate if this Monitor is currently recording."""
status_response = self._client.get_state(
'api/monitors/alarm/id:{}/command:status.json'.format(
self._monitor_id
)
)
if not status_response:
_LOGGER.warning('Could not get status for monitor {}'.format(
self._monitor_id
))
return None
status = status_response.get('status')
# ZoneMinder API returns an empty string to indicate that this monitor
# cannot record right now
if status == '':
return False
return int(status) == STATE_ALARM | [
"def",
"is_recording",
"(",
"self",
")",
"->",
"Optional",
"[",
"bool",
"]",
":",
"status_response",
"=",
"self",
".",
"_client",
".",
"get_state",
"(",
"'api/monitors/alarm/id:{}/command:status.json'",
".",
"format",
"(",
"self",
".",
"_monitor_id",
")",
")",
"if",
"not",
"status_response",
":",
"_LOGGER",
".",
"warning",
"(",
"'Could not get status for monitor {}'",
".",
"format",
"(",
"self",
".",
"_monitor_id",
")",
")",
"return",
"None",
"status",
"=",
"status_response",
".",
"get",
"(",
"'status'",
")",
"# ZoneMinder API returns an empty string to indicate that this monitor",
"# cannot record right now",
"if",
"status",
"==",
"''",
":",
"return",
"False",
"return",
"int",
"(",
"status",
")",
"==",
"STATE_ALARM"
] | Indicate if this Monitor is currently recording. | [
"Indicate",
"if",
"this",
"Monitor",
"is",
"currently",
"recording",
"."
] | bd3a9f6b2f7b84b37589e2939f628b479a5531bf | https://github.com/rohankapoorcom/zm-py/blob/bd3a9f6b2f7b84b37589e2939f628b479a5531bf/zoneminder/monitor.py#L121-L140 | train |
rohankapoorcom/zm-py | zoneminder/monitor.py | Monitor.is_available | def is_available(self) -> bool:
"""Indicate if this Monitor is currently available."""
status_response = self._client.get_state(
'api/monitors/daemonStatus/id:{}/daemon:zmc.json'.format(
self._monitor_id
)
)
if not status_response:
_LOGGER.warning('Could not get availability for monitor {}'.format(
self._monitor_id
))
return False
# Monitor_Status was only added in ZM 1.32.3
monitor_status = self._raw_result.get('Monitor_Status', None)
capture_fps = monitor_status and monitor_status['CaptureFPS']
return status_response.get('status', False) and capture_fps != "0.00" | python | def is_available(self) -> bool:
"""Indicate if this Monitor is currently available."""
status_response = self._client.get_state(
'api/monitors/daemonStatus/id:{}/daemon:zmc.json'.format(
self._monitor_id
)
)
if not status_response:
_LOGGER.warning('Could not get availability for monitor {}'.format(
self._monitor_id
))
return False
# Monitor_Status was only added in ZM 1.32.3
monitor_status = self._raw_result.get('Monitor_Status', None)
capture_fps = monitor_status and monitor_status['CaptureFPS']
return status_response.get('status', False) and capture_fps != "0.00" | [
"def",
"is_available",
"(",
"self",
")",
"->",
"bool",
":",
"status_response",
"=",
"self",
".",
"_client",
".",
"get_state",
"(",
"'api/monitors/daemonStatus/id:{}/daemon:zmc.json'",
".",
"format",
"(",
"self",
".",
"_monitor_id",
")",
")",
"if",
"not",
"status_response",
":",
"_LOGGER",
".",
"warning",
"(",
"'Could not get availability for monitor {}'",
".",
"format",
"(",
"self",
".",
"_monitor_id",
")",
")",
"return",
"False",
"# Monitor_Status was only added in ZM 1.32.3",
"monitor_status",
"=",
"self",
".",
"_raw_result",
".",
"get",
"(",
"'Monitor_Status'",
",",
"None",
")",
"capture_fps",
"=",
"monitor_status",
"and",
"monitor_status",
"[",
"'CaptureFPS'",
"]",
"return",
"status_response",
".",
"get",
"(",
"'status'",
",",
"False",
")",
"and",
"capture_fps",
"!=",
"\"0.00\""
] | Indicate if this Monitor is currently available. | [
"Indicate",
"if",
"this",
"Monitor",
"is",
"currently",
"available",
"."
] | bd3a9f6b2f7b84b37589e2939f628b479a5531bf | https://github.com/rohankapoorcom/zm-py/blob/bd3a9f6b2f7b84b37589e2939f628b479a5531bf/zoneminder/monitor.py#L143-L161 | train |
rohankapoorcom/zm-py | zoneminder/monitor.py | Monitor.get_events | def get_events(self, time_period, include_archived=False) -> Optional[int]:
"""Get the number of events that have occurred on this Monitor.
Specifically only gets events that have occurred within the TimePeriod
provided.
"""
date_filter = '1%20{}'.format(time_period.period)
if time_period == TimePeriod.ALL:
# The consoleEvents API uses DATE_SUB, so give it
# something large
date_filter = '100%20year'
archived_filter = '/Archived=:0'
if include_archived:
archived_filter = ''
event = self._client.get_state(
'api/events/consoleEvents/{}{}.json'.format(
date_filter,
archived_filter
)
)
try:
events_by_monitor = event['results']
if isinstance(events_by_monitor, list):
return 0
return events_by_monitor.get(str(self._monitor_id), 0)
except (TypeError, KeyError, AttributeError):
return None | python | def get_events(self, time_period, include_archived=False) -> Optional[int]:
"""Get the number of events that have occurred on this Monitor.
Specifically only gets events that have occurred within the TimePeriod
provided.
"""
date_filter = '1%20{}'.format(time_period.period)
if time_period == TimePeriod.ALL:
# The consoleEvents API uses DATE_SUB, so give it
# something large
date_filter = '100%20year'
archived_filter = '/Archived=:0'
if include_archived:
archived_filter = ''
event = self._client.get_state(
'api/events/consoleEvents/{}{}.json'.format(
date_filter,
archived_filter
)
)
try:
events_by_monitor = event['results']
if isinstance(events_by_monitor, list):
return 0
return events_by_monitor.get(str(self._monitor_id), 0)
except (TypeError, KeyError, AttributeError):
return None | [
"def",
"get_events",
"(",
"self",
",",
"time_period",
",",
"include_archived",
"=",
"False",
")",
"->",
"Optional",
"[",
"int",
"]",
":",
"date_filter",
"=",
"'1%20{}'",
".",
"format",
"(",
"time_period",
".",
"period",
")",
"if",
"time_period",
"==",
"TimePeriod",
".",
"ALL",
":",
"# The consoleEvents API uses DATE_SUB, so give it",
"# something large",
"date_filter",
"=",
"'100%20year'",
"archived_filter",
"=",
"'/Archived=:0'",
"if",
"include_archived",
":",
"archived_filter",
"=",
"''",
"event",
"=",
"self",
".",
"_client",
".",
"get_state",
"(",
"'api/events/consoleEvents/{}{}.json'",
".",
"format",
"(",
"date_filter",
",",
"archived_filter",
")",
")",
"try",
":",
"events_by_monitor",
"=",
"event",
"[",
"'results'",
"]",
"if",
"isinstance",
"(",
"events_by_monitor",
",",
"list",
")",
":",
"return",
"0",
"return",
"events_by_monitor",
".",
"get",
"(",
"str",
"(",
"self",
".",
"_monitor_id",
")",
",",
"0",
")",
"except",
"(",
"TypeError",
",",
"KeyError",
",",
"AttributeError",
")",
":",
"return",
"None"
] | Get the number of events that have occurred on this Monitor.
Specifically only gets events that have occurred within the TimePeriod
provided. | [
"Get",
"the",
"number",
"of",
"events",
"that",
"have",
"occurred",
"on",
"this",
"Monitor",
"."
] | bd3a9f6b2f7b84b37589e2939f628b479a5531bf | https://github.com/rohankapoorcom/zm-py/blob/bd3a9f6b2f7b84b37589e2939f628b479a5531bf/zoneminder/monitor.py#L163-L192 | train |
rohankapoorcom/zm-py | zoneminder/monitor.py | Monitor._build_image_url | def _build_image_url(self, monitor, mode) -> str:
"""Build and return a ZoneMinder camera image url."""
query = urlencode({
'mode': mode,
'buffer': monitor['StreamReplayBuffer'],
'monitor': monitor['Id'],
})
url = '{zms_url}?{query}'.format(
zms_url=self._client.get_zms_url(), query=query)
_LOGGER.debug('Monitor %s %s URL (without auth): %s',
monitor['Id'], mode, url)
return self._client.get_url_with_auth(url) | python | def _build_image_url(self, monitor, mode) -> str:
"""Build and return a ZoneMinder camera image url."""
query = urlencode({
'mode': mode,
'buffer': monitor['StreamReplayBuffer'],
'monitor': monitor['Id'],
})
url = '{zms_url}?{query}'.format(
zms_url=self._client.get_zms_url(), query=query)
_LOGGER.debug('Monitor %s %s URL (without auth): %s',
monitor['Id'], mode, url)
return self._client.get_url_with_auth(url) | [
"def",
"_build_image_url",
"(",
"self",
",",
"monitor",
",",
"mode",
")",
"->",
"str",
":",
"query",
"=",
"urlencode",
"(",
"{",
"'mode'",
":",
"mode",
",",
"'buffer'",
":",
"monitor",
"[",
"'StreamReplayBuffer'",
"]",
",",
"'monitor'",
":",
"monitor",
"[",
"'Id'",
"]",
",",
"}",
")",
"url",
"=",
"'{zms_url}?{query}'",
".",
"format",
"(",
"zms_url",
"=",
"self",
".",
"_client",
".",
"get_zms_url",
"(",
")",
",",
"query",
"=",
"query",
")",
"_LOGGER",
".",
"debug",
"(",
"'Monitor %s %s URL (without auth): %s'",
",",
"monitor",
"[",
"'Id'",
"]",
",",
"mode",
",",
"url",
")",
"return",
"self",
".",
"_client",
".",
"get_url_with_auth",
"(",
"url",
")"
] | Build and return a ZoneMinder camera image url. | [
"Build",
"and",
"return",
"a",
"ZoneMinder",
"camera",
"image",
"url",
"."
] | bd3a9f6b2f7b84b37589e2939f628b479a5531bf | https://github.com/rohankapoorcom/zm-py/blob/bd3a9f6b2f7b84b37589e2939f628b479a5531bf/zoneminder/monitor.py#L194-L205 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.