repository_name stringlengths 7 55 | func_path_in_repository stringlengths 4 223 | func_name stringlengths 1 134 | whole_func_string stringlengths 75 104k | language stringclasses 1
value | func_code_string stringlengths 75 104k | func_code_tokens listlengths 19 28.4k | func_documentation_string stringlengths 1 46.9k | func_documentation_tokens listlengths 1 1.97k | split_name stringclasses 1
value | func_code_url stringlengths 87 315 |
|---|---|---|---|---|---|---|---|---|---|---|
toumorokoshi/transmute-core | transmute_core/frameworks/aiohttp/swagger.py | create_swagger_json_handler | def create_swagger_json_handler(app, **kwargs):
"""
Create a handler that returns the swagger definition
for an application.
This method assumes the application is using the
TransmuteUrlDispatcher as the router.
"""
spec = get_swagger_spec(app).swagger_definition(**kwargs)
encoded_spec = json.dumps(spec).encode("UTF-8")
async def swagger(request):
return web.Response(
# we allow CORS, so this can be requested at swagger.io
headers={
"Access-Control-Allow-Origin": "*"
},
body=encoded_spec,
content_type="application/json",
)
return swagger | python | def create_swagger_json_handler(app, **kwargs):
"""
Create a handler that returns the swagger definition
for an application.
This method assumes the application is using the
TransmuteUrlDispatcher as the router.
"""
spec = get_swagger_spec(app).swagger_definition(**kwargs)
encoded_spec = json.dumps(spec).encode("UTF-8")
async def swagger(request):
return web.Response(
# we allow CORS, so this can be requested at swagger.io
headers={
"Access-Control-Allow-Origin": "*"
},
body=encoded_spec,
content_type="application/json",
)
return swagger | [
"def",
"create_swagger_json_handler",
"(",
"app",
",",
"*",
"*",
"kwargs",
")",
":",
"spec",
"=",
"get_swagger_spec",
"(",
"app",
")",
".",
"swagger_definition",
"(",
"*",
"*",
"kwargs",
")",
"encoded_spec",
"=",
"json",
".",
"dumps",
"(",
"spec",
")",
"... | Create a handler that returns the swagger definition
for an application.
This method assumes the application is using the
TransmuteUrlDispatcher as the router. | [
"Create",
"a",
"handler",
"that",
"returns",
"the",
"swagger",
"definition",
"for",
"an",
"application",
"."
] | train | https://github.com/toumorokoshi/transmute-core/blob/a2c26625d5d8bab37e00038f9d615a26167fc7f4/transmute_core/frameworks/aiohttp/swagger.py#L50-L72 |
LCAV/pylocus | pylocus/plots_cti.py | create_multispan_plots | def create_multispan_plots(tag_ids):
"""Create detail plots (first row) and total block(second row) of experiments.
Args:
tag_ids: list of tag-dictionaries, where the dictionaries must have fields 'name' (used for naming)
and 'id' (used for numbering axis_dict)
Returns:
Figure element fig, ax_dict containing the first row plots (accessed via id) and ax_total containing the
second row block.
"""
import matplotlib.gridspec as gridspec
fig = plt.figure()
nrows = 1
if len(tag_ids) > 1:
nrows = 2
fig.set_size_inches(10, 5*nrows)
gs = gridspec.GridSpec(nrows, len(tag_ids))
ax_list = [fig.add_subplot(g) for g in gs]
ax_dict = {}
for i, tag_dict in enumerate(tag_ids):
ax_dict[tag_dict['id']] = ax_list[i]
ax_dict[tag_dict['id']].set_title(
'System {} (id {})'.format(tag_dict['name'], tag_dict['id']))
if nrows > 1:
ax_total = plt.subplot(gs[1, :])
title = 'Combined {}'.format(tag_ids[0]['name'])
for i in range(1, len(tag_ids)):
title = title + ' and {}'.format(tag_ids[i]['name'])
ax_total.set_title(title)
gs.tight_layout(fig, rect=[0, 0.03, 1, 0.95])
return fig, ax_dict, ax_total
gs.tight_layout(fig, rect=[0, 0.03, 1, 0.95])
return fig, ax_dict, None | python | def create_multispan_plots(tag_ids):
"""Create detail plots (first row) and total block(second row) of experiments.
Args:
tag_ids: list of tag-dictionaries, where the dictionaries must have fields 'name' (used for naming)
and 'id' (used for numbering axis_dict)
Returns:
Figure element fig, ax_dict containing the first row plots (accessed via id) and ax_total containing the
second row block.
"""
import matplotlib.gridspec as gridspec
fig = plt.figure()
nrows = 1
if len(tag_ids) > 1:
nrows = 2
fig.set_size_inches(10, 5*nrows)
gs = gridspec.GridSpec(nrows, len(tag_ids))
ax_list = [fig.add_subplot(g) for g in gs]
ax_dict = {}
for i, tag_dict in enumerate(tag_ids):
ax_dict[tag_dict['id']] = ax_list[i]
ax_dict[tag_dict['id']].set_title(
'System {} (id {})'.format(tag_dict['name'], tag_dict['id']))
if nrows > 1:
ax_total = plt.subplot(gs[1, :])
title = 'Combined {}'.format(tag_ids[0]['name'])
for i in range(1, len(tag_ids)):
title = title + ' and {}'.format(tag_ids[i]['name'])
ax_total.set_title(title)
gs.tight_layout(fig, rect=[0, 0.03, 1, 0.95])
return fig, ax_dict, ax_total
gs.tight_layout(fig, rect=[0, 0.03, 1, 0.95])
return fig, ax_dict, None | [
"def",
"create_multispan_plots",
"(",
"tag_ids",
")",
":",
"import",
"matplotlib",
".",
"gridspec",
"as",
"gridspec",
"fig",
"=",
"plt",
".",
"figure",
"(",
")",
"nrows",
"=",
"1",
"if",
"len",
"(",
"tag_ids",
")",
">",
"1",
":",
"nrows",
"=",
"2",
"... | Create detail plots (first row) and total block(second row) of experiments.
Args:
tag_ids: list of tag-dictionaries, where the dictionaries must have fields 'name' (used for naming)
and 'id' (used for numbering axis_dict)
Returns:
Figure element fig, ax_dict containing the first row plots (accessed via id) and ax_total containing the
second row block. | [
"Create",
"detail",
"plots",
"(",
"first",
"row",
")",
"and",
"total",
"block",
"(",
"second",
"row",
")",
"of",
"experiments",
".",
"Args",
":",
"tag_ids",
":",
"list",
"of",
"tag",
"-",
"dictionaries",
"where",
"the",
"dictionaries",
"must",
"have",
"f... | train | https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/plots_cti.py#L207-L243 |
LCAV/pylocus | pylocus/basics_angles.py | change_angles | def change_angles(method, theta, tol=1e-10):
""" Function used by all angle conversion functions (from_x_to_x_pi(...))"""
try:
theta_new = np.zeros(theta.shape)
for i, thet in enumerate(theta):
try:
# theta is vector
theta_new[i] = method(thet, tol)
except:
# theta is matrix
for j, th in enumerate(thet):
try:
theta_new[i, j] = method(th, tol)
except:
# theta is tensor
for k, t in enumerate(th):
theta_new[i, j, k] = method(t, tol)
return theta_new
except:
return method(theta, tol) | python | def change_angles(method, theta, tol=1e-10):
""" Function used by all angle conversion functions (from_x_to_x_pi(...))"""
try:
theta_new = np.zeros(theta.shape)
for i, thet in enumerate(theta):
try:
# theta is vector
theta_new[i] = method(thet, tol)
except:
# theta is matrix
for j, th in enumerate(thet):
try:
theta_new[i, j] = method(th, tol)
except:
# theta is tensor
for k, t in enumerate(th):
theta_new[i, j, k] = method(t, tol)
return theta_new
except:
return method(theta, tol) | [
"def",
"change_angles",
"(",
"method",
",",
"theta",
",",
"tol",
"=",
"1e-10",
")",
":",
"try",
":",
"theta_new",
"=",
"np",
".",
"zeros",
"(",
"theta",
".",
"shape",
")",
"for",
"i",
",",
"thet",
"in",
"enumerate",
"(",
"theta",
")",
":",
"try",
... | Function used by all angle conversion functions (from_x_to_x_pi(...)) | [
"Function",
"used",
"by",
"all",
"angle",
"conversion",
"functions",
"(",
"from_x_to_x_pi",
"(",
"...",
"))"
] | train | https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/basics_angles.py#L7-L26 |
LCAV/pylocus | pylocus/basics_angles.py | rmse_2pi | def rmse_2pi(x, xhat):
''' Calcualte rmse between vector or matrix x and xhat, ignoring mod of 2pi.'''
real_diff = from_0_to_pi(x - xhat)
np.square(real_diff, out=real_diff)
sum_ = np.sum(real_diff)
return sqrt(sum_ / len(x)) | python | def rmse_2pi(x, xhat):
''' Calcualte rmse between vector or matrix x and xhat, ignoring mod of 2pi.'''
real_diff = from_0_to_pi(x - xhat)
np.square(real_diff, out=real_diff)
sum_ = np.sum(real_diff)
return sqrt(sum_ / len(x)) | [
"def",
"rmse_2pi",
"(",
"x",
",",
"xhat",
")",
":",
"real_diff",
"=",
"from_0_to_pi",
"(",
"x",
"-",
"xhat",
")",
"np",
".",
"square",
"(",
"real_diff",
",",
"out",
"=",
"real_diff",
")",
"sum_",
"=",
"np",
".",
"sum",
"(",
"real_diff",
")",
"retur... | Calcualte rmse between vector or matrix x and xhat, ignoring mod of 2pi. | [
"Calcualte",
"rmse",
"between",
"vector",
"or",
"matrix",
"x",
"and",
"xhat",
"ignoring",
"mod",
"of",
"2pi",
"."
] | train | https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/basics_angles.py#L68-L73 |
LCAV/pylocus | pylocus/basics_angles.py | get_point | def get_point(theta_ik, theta_jk, Pi, Pj):
""" Calculate coordinates of point Pk given two points Pi, Pj and inner angles. :param theta_ik: Inner angle at Pi to Pk.
:param theta_jk: Inner angle at Pj to Pk.
:param Pi: Coordinates of point Pi.
:param Pj: Coordinates of point Pj.
:return: Coordinate of point Pk.
"""
A = np.array([[sin(theta_ik), -cos(theta_ik)],
[sin(theta_jk), -cos(theta_jk)]])
B = np.array([[sin(theta_ik), -cos(theta_ik), 0, 0],
[0, 0, sin(theta_jk), -cos(theta_jk)]])
p = np.r_[Pi, Pj]
Pk = np.linalg.solve(A, np.dot(B, p))
return Pk | python | def get_point(theta_ik, theta_jk, Pi, Pj):
""" Calculate coordinates of point Pk given two points Pi, Pj and inner angles. :param theta_ik: Inner angle at Pi to Pk.
:param theta_jk: Inner angle at Pj to Pk.
:param Pi: Coordinates of point Pi.
:param Pj: Coordinates of point Pj.
:return: Coordinate of point Pk.
"""
A = np.array([[sin(theta_ik), -cos(theta_ik)],
[sin(theta_jk), -cos(theta_jk)]])
B = np.array([[sin(theta_ik), -cos(theta_ik), 0, 0],
[0, 0, sin(theta_jk), -cos(theta_jk)]])
p = np.r_[Pi, Pj]
Pk = np.linalg.solve(A, np.dot(B, p))
return Pk | [
"def",
"get_point",
"(",
"theta_ik",
",",
"theta_jk",
",",
"Pi",
",",
"Pj",
")",
":",
"A",
"=",
"np",
".",
"array",
"(",
"[",
"[",
"sin",
"(",
"theta_ik",
")",
",",
"-",
"cos",
"(",
"theta_ik",
")",
"]",
",",
"[",
"sin",
"(",
"theta_jk",
")",
... | Calculate coordinates of point Pk given two points Pi, Pj and inner angles. :param theta_ik: Inner angle at Pi to Pk.
:param theta_jk: Inner angle at Pj to Pk.
:param Pi: Coordinates of point Pi.
:param Pj: Coordinates of point Pj.
:return: Coordinate of point Pk. | [
"Calculate",
"coordinates",
"of",
"point",
"Pk",
"given",
"two",
"points",
"Pi",
"Pj",
"and",
"inner",
"angles",
".",
":",
"param",
"theta_ik",
":",
"Inner",
"angle",
"at",
"Pi",
"to",
"Pk",
".",
":",
"param",
"theta_jk",
":",
"Inner",
"angle",
"at",
"... | train | https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/basics_angles.py#L76-L90 |
toumorokoshi/transmute-core | transmute_core/contenttype_serializers/serializer_set.py | SerializerSet.keys | def keys(self):
"""
return a list of the content types this set supports.
this is not a complete list: serializers can accept more than
one content type. However, it is a good representation of the
class of content types supported.
"""
return_value = []
for s in self.serializers:
return_value += s.content_type
return return_value | python | def keys(self):
"""
return a list of the content types this set supports.
this is not a complete list: serializers can accept more than
one content type. However, it is a good representation of the
class of content types supported.
"""
return_value = []
for s in self.serializers:
return_value += s.content_type
return return_value | [
"def",
"keys",
"(",
"self",
")",
":",
"return_value",
"=",
"[",
"]",
"for",
"s",
"in",
"self",
".",
"serializers",
":",
"return_value",
"+=",
"s",
".",
"content_type",
"return",
"return_value"
] | return a list of the content types this set supports.
this is not a complete list: serializers can accept more than
one content type. However, it is a good representation of the
class of content types supported. | [
"return",
"a",
"list",
"of",
"the",
"content",
"types",
"this",
"set",
"supports",
"."
] | train | https://github.com/toumorokoshi/transmute-core/blob/a2c26625d5d8bab37e00038f9d615a26167fc7f4/transmute_core/contenttype_serializers/serializer_set.py#L41-L52 |
toumorokoshi/transmute-core | transmute_core/function/parameters.py | get_parameters | def get_parameters(signature, transmute_attrs, arguments_to_ignore=None):
"""given a function, categorize which arguments should be passed by
what types of parameters. The choices are:
* query parameters: passed in as query parameters in the url
* body parameters: retrieved from the request body (includes forms)
* header parameters: retrieved from the request header
* path parameters: retrieved from the uri path
The categorization is performed for an argument "arg" by:
1. examining the transmute parameters attached to the function (e.g.
func.transmute_query_parameters), and checking if "arg" is mentioned. If so,
it is added to the category.
2. If the argument is available in the path, it will be added
as a path parameter.
3. If the method of the function is GET and only GET, then "arg" will be
be added to the expected query parameters. Otherwise, "arg" will be added as
a body parameter.
"""
params = Parameters()
used_keys = set(arguments_to_ignore or [])
# examine what variables are categorized first.
for key in ["query", "header", "path"]:
param_set = getattr(params, key)
explicit_parameters = getattr(transmute_attrs, key + "_parameters")
used_keys |= load_parameters(
param_set, explicit_parameters, signature, transmute_attrs
)
body_parameters = transmute_attrs.body_parameters
if isinstance(body_parameters, str):
name = body_parameters
params.body = Param(
argument_name=name,
description=transmute_attrs.parameter_descriptions.get(name),
arginfo=signature.get_argument(name),
)
used_keys.add(name)
else:
used_keys |= load_parameters(
params.body, transmute_attrs.body_parameters, signature, transmute_attrs
)
# extract the parameters from the paths
for name in _extract_path_parameters_from_paths(transmute_attrs.paths):
params.path[name] = Param(
argument_name=name,
description=transmute_attrs.parameter_descriptions.get(name),
arginfo=signature.get_argument(name),
)
used_keys.add(name)
# check the method type, and decide if the parameters should be extracted
# from query parameters or the body
default_param_key = "query" if transmute_attrs.methods == set(["GET"]) else "body"
default_params = getattr(params, default_param_key)
# parse all positional params
for arginfo in signature:
if arginfo.name in used_keys:
continue
used_keys.add(arginfo.name)
default_params[arginfo.name] = Param(
arginfo.name,
description=transmute_attrs.parameter_descriptions.get(arginfo.name),
arginfo=arginfo,
)
return params | python | def get_parameters(signature, transmute_attrs, arguments_to_ignore=None):
"""given a function, categorize which arguments should be passed by
what types of parameters. The choices are:
* query parameters: passed in as query parameters in the url
* body parameters: retrieved from the request body (includes forms)
* header parameters: retrieved from the request header
* path parameters: retrieved from the uri path
The categorization is performed for an argument "arg" by:
1. examining the transmute parameters attached to the function (e.g.
func.transmute_query_parameters), and checking if "arg" is mentioned. If so,
it is added to the category.
2. If the argument is available in the path, it will be added
as a path parameter.
3. If the method of the function is GET and only GET, then "arg" will be
be added to the expected query parameters. Otherwise, "arg" will be added as
a body parameter.
"""
params = Parameters()
used_keys = set(arguments_to_ignore or [])
# examine what variables are categorized first.
for key in ["query", "header", "path"]:
param_set = getattr(params, key)
explicit_parameters = getattr(transmute_attrs, key + "_parameters")
used_keys |= load_parameters(
param_set, explicit_parameters, signature, transmute_attrs
)
body_parameters = transmute_attrs.body_parameters
if isinstance(body_parameters, str):
name = body_parameters
params.body = Param(
argument_name=name,
description=transmute_attrs.parameter_descriptions.get(name),
arginfo=signature.get_argument(name),
)
used_keys.add(name)
else:
used_keys |= load_parameters(
params.body, transmute_attrs.body_parameters, signature, transmute_attrs
)
# extract the parameters from the paths
for name in _extract_path_parameters_from_paths(transmute_attrs.paths):
params.path[name] = Param(
argument_name=name,
description=transmute_attrs.parameter_descriptions.get(name),
arginfo=signature.get_argument(name),
)
used_keys.add(name)
# check the method type, and decide if the parameters should be extracted
# from query parameters or the body
default_param_key = "query" if transmute_attrs.methods == set(["GET"]) else "body"
default_params = getattr(params, default_param_key)
# parse all positional params
for arginfo in signature:
if arginfo.name in used_keys:
continue
used_keys.add(arginfo.name)
default_params[arginfo.name] = Param(
arginfo.name,
description=transmute_attrs.parameter_descriptions.get(arginfo.name),
arginfo=arginfo,
)
return params | [
"def",
"get_parameters",
"(",
"signature",
",",
"transmute_attrs",
",",
"arguments_to_ignore",
"=",
"None",
")",
":",
"params",
"=",
"Parameters",
"(",
")",
"used_keys",
"=",
"set",
"(",
"arguments_to_ignore",
"or",
"[",
"]",
")",
"# examine what variables are cat... | given a function, categorize which arguments should be passed by
what types of parameters. The choices are:
* query parameters: passed in as query parameters in the url
* body parameters: retrieved from the request body (includes forms)
* header parameters: retrieved from the request header
* path parameters: retrieved from the uri path
The categorization is performed for an argument "arg" by:
1. examining the transmute parameters attached to the function (e.g.
func.transmute_query_parameters), and checking if "arg" is mentioned. If so,
it is added to the category.
2. If the argument is available in the path, it will be added
as a path parameter.
3. If the method of the function is GET and only GET, then "arg" will be
be added to the expected query parameters. Otherwise, "arg" will be added as
a body parameter. | [
"given",
"a",
"function",
"categorize",
"which",
"arguments",
"should",
"be",
"passed",
"by",
"what",
"types",
"of",
"parameters",
".",
"The",
"choices",
"are",
":"
] | train | https://github.com/toumorokoshi/transmute-core/blob/a2c26625d5d8bab37e00038f9d615a26167fc7f4/transmute_core/function/parameters.py#L6-L77 |
toumorokoshi/transmute-core | transmute_core/function/parameters.py | _extract_path_parameters_from_paths | def _extract_path_parameters_from_paths(paths):
"""
from a list of paths, return back a list of the
arguments present in those paths.
the arguments available in all of the paths must match: if not,
an exception will be raised.
"""
params = set()
for path in paths:
parts = PART_REGEX.split(path)
for p in parts:
match = PARAM_REGEX.match(p)
if match:
params.add(match.group("name"))
return params | python | def _extract_path_parameters_from_paths(paths):
"""
from a list of paths, return back a list of the
arguments present in those paths.
the arguments available in all of the paths must match: if not,
an exception will be raised.
"""
params = set()
for path in paths:
parts = PART_REGEX.split(path)
for p in parts:
match = PARAM_REGEX.match(p)
if match:
params.add(match.group("name"))
return params | [
"def",
"_extract_path_parameters_from_paths",
"(",
"paths",
")",
":",
"params",
"=",
"set",
"(",
")",
"for",
"path",
"in",
"paths",
":",
"parts",
"=",
"PART_REGEX",
".",
"split",
"(",
"path",
")",
"for",
"p",
"in",
"parts",
":",
"match",
"=",
"PARAM_REGE... | from a list of paths, return back a list of the
arguments present in those paths.
the arguments available in all of the paths must match: if not,
an exception will be raised. | [
"from",
"a",
"list",
"of",
"paths",
"return",
"back",
"a",
"list",
"of",
"the",
"arguments",
"present",
"in",
"those",
"paths",
"."
] | train | https://github.com/toumorokoshi/transmute-core/blob/a2c26625d5d8bab37e00038f9d615a26167fc7f4/transmute_core/function/parameters.py#L84-L99 |
toumorokoshi/transmute-core | transmute_core/http_parameters/swagger.py | _build_body_schema | def _build_body_schema(serializer, body_parameters):
""" body is built differently, since it's a single argument no matter what. """
description = ""
if isinstance(body_parameters, Param):
schema = serializer.to_json_schema(body_parameters.arginfo.type)
description = body_parameters.description
required = True
else:
if len(body_parameters) == 0:
return None
required = set()
body_properties = {}
for name, param in body_parameters.items():
arginfo = param.arginfo
body_properties[name] = serializer.to_json_schema(arginfo.type)
body_properties[name]["description"] = param.description
if arginfo.default is NoDefault:
required.add(name)
schema = {
"type": "object",
"required": list(required),
"properties": body_properties,
}
required = len(required) > 0
return BodyParameter(
{
"name": "body",
"description": description,
"required": required,
"schema": schema,
}
) | python | def _build_body_schema(serializer, body_parameters):
""" body is built differently, since it's a single argument no matter what. """
description = ""
if isinstance(body_parameters, Param):
schema = serializer.to_json_schema(body_parameters.arginfo.type)
description = body_parameters.description
required = True
else:
if len(body_parameters) == 0:
return None
required = set()
body_properties = {}
for name, param in body_parameters.items():
arginfo = param.arginfo
body_properties[name] = serializer.to_json_schema(arginfo.type)
body_properties[name]["description"] = param.description
if arginfo.default is NoDefault:
required.add(name)
schema = {
"type": "object",
"required": list(required),
"properties": body_properties,
}
required = len(required) > 0
return BodyParameter(
{
"name": "body",
"description": description,
"required": required,
"schema": schema,
}
) | [
"def",
"_build_body_schema",
"(",
"serializer",
",",
"body_parameters",
")",
":",
"description",
"=",
"\"\"",
"if",
"isinstance",
"(",
"body_parameters",
",",
"Param",
")",
":",
"schema",
"=",
"serializer",
".",
"to_json_schema",
"(",
"body_parameters",
".",
"ar... | body is built differently, since it's a single argument no matter what. | [
"body",
"is",
"built",
"differently",
"since",
"it",
"s",
"a",
"single",
"argument",
"no",
"matter",
"what",
"."
] | train | https://github.com/toumorokoshi/transmute-core/blob/a2c26625d5d8bab37e00038f9d615a26167fc7f4/transmute_core/http_parameters/swagger.py#L46-L77 |
d0ugal/python-rfxcom | rfxcom/protocol/wind.py | Wind.parse | def parse(self, data):
"""Parse a 17 bytes packet in the Wind format and return a
dictionary containing the data extracted. An example of a return value
would be:
.. code-block:: python
{
'id': "0x2EB2",
'packet_length': 16,
'packet_type': 86,
'packet_type_name': 'Wind sensors',
'sequence_number': 0,
'packet_subtype': 4,
'packet_subtype_name': "TFA",
'temperature': 17.3,
'direction': 120,
'wind_gust': 11,
'av_speed': 12,
'wind_chill': 10,
'signal_level': 9,
'battery_level': 6,
}
:param data: bytearray to be parsed
:type data: bytearray
:return: Data dictionary containing the parsed values
:rtype: dict
"""
self.validate_packet(data)
results = self.parse_header_part(data)
sub_type = results['packet_subtype']
id_ = self.dump_hex(data[4:6])
direction = data[6] * 256 + data[7]
if sub_type != 0x05:
av_speed = (data[8] * 256 + data[9]) * 0.1
else:
av_speed = '--??--'
gust = (data[10] * 256 + data[11]) * 0.1
if sub_type == 0x04:
temperature = ((data[12] & 0x7f) * 256 + data[13]) / 10
signbit = data[12] & 0x80
if signbit != 0:
temperature = -temperature
else:
temperature = '--??--'
if sub_type == 0x04:
wind_chill = ((data[14] & 0x7f) * 256 + data[15]) / 10
signbit = data[14] & 0x80
if signbit != 0:
wind_chill = -wind_chill
else:
wind_chill = '--??--'
sensor_specific = {
'id': id_,
'direction': direction,
'wind_gust': gust
}
if av_speed != '--??--':
sensor_specific['av_speed'] = av_speed
if temperature != '--??--':
sensor_specific['temperature'] = temperature
if wind_chill != '--??--':
sensor_specific['wind_chill'] = wind_chill
results.update(RfxPacketUtils.parse_signal_and_battery(data[16]))
results.update(sensor_specific)
return results | python | def parse(self, data):
"""Parse a 17 bytes packet in the Wind format and return a
dictionary containing the data extracted. An example of a return value
would be:
.. code-block:: python
{
'id': "0x2EB2",
'packet_length': 16,
'packet_type': 86,
'packet_type_name': 'Wind sensors',
'sequence_number': 0,
'packet_subtype': 4,
'packet_subtype_name': "TFA",
'temperature': 17.3,
'direction': 120,
'wind_gust': 11,
'av_speed': 12,
'wind_chill': 10,
'signal_level': 9,
'battery_level': 6,
}
:param data: bytearray to be parsed
:type data: bytearray
:return: Data dictionary containing the parsed values
:rtype: dict
"""
self.validate_packet(data)
results = self.parse_header_part(data)
sub_type = results['packet_subtype']
id_ = self.dump_hex(data[4:6])
direction = data[6] * 256 + data[7]
if sub_type != 0x05:
av_speed = (data[8] * 256 + data[9]) * 0.1
else:
av_speed = '--??--'
gust = (data[10] * 256 + data[11]) * 0.1
if sub_type == 0x04:
temperature = ((data[12] & 0x7f) * 256 + data[13]) / 10
signbit = data[12] & 0x80
if signbit != 0:
temperature = -temperature
else:
temperature = '--??--'
if sub_type == 0x04:
wind_chill = ((data[14] & 0x7f) * 256 + data[15]) / 10
signbit = data[14] & 0x80
if signbit != 0:
wind_chill = -wind_chill
else:
wind_chill = '--??--'
sensor_specific = {
'id': id_,
'direction': direction,
'wind_gust': gust
}
if av_speed != '--??--':
sensor_specific['av_speed'] = av_speed
if temperature != '--??--':
sensor_specific['temperature'] = temperature
if wind_chill != '--??--':
sensor_specific['wind_chill'] = wind_chill
results.update(RfxPacketUtils.parse_signal_and_battery(data[16]))
results.update(sensor_specific)
return results | [
"def",
"parse",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"validate_packet",
"(",
"data",
")",
"results",
"=",
"self",
".",
"parse_header_part",
"(",
"data",
")",
"sub_type",
"=",
"results",
"[",
"'packet_subtype'",
"]",
"id_",
"=",
"self",
".",
... | Parse a 17 bytes packet in the Wind format and return a
dictionary containing the data extracted. An example of a return value
would be:
.. code-block:: python
{
'id': "0x2EB2",
'packet_length': 16,
'packet_type': 86,
'packet_type_name': 'Wind sensors',
'sequence_number': 0,
'packet_subtype': 4,
'packet_subtype_name': "TFA",
'temperature': 17.3,
'direction': 120,
'wind_gust': 11,
'av_speed': 12,
'wind_chill': 10,
'signal_level': 9,
'battery_level': 6,
}
:param data: bytearray to be parsed
:type data: bytearray
:return: Data dictionary containing the parsed values
:rtype: dict | [
"Parse",
"a",
"17",
"bytes",
"packet",
"in",
"the",
"Wind",
"format",
"and",
"return",
"a",
"dictionary",
"containing",
"the",
"data",
"extracted",
".",
"An",
"example",
"of",
"a",
"return",
"value",
"would",
"be",
":"
] | train | https://github.com/d0ugal/python-rfxcom/blob/2eb87f85e5f5a04d00f32f25e0f010edfefbde0d/rfxcom/protocol/wind.py#L54-L128 |
LCAV/pylocus | pylocus/algorithms.py | procrustes | def procrustes(anchors, X, scale=True, print_out=False):
""" Fit X to anchors by applying optimal translation, rotation and reflection.
Given m >= d anchor nodes (anchors in R^(m x d)), return transformation
of coordinates X (output of EDM algorithm) optimally matching anchors in least squares sense.
:param anchors: Matrix of shape m x d, where m is number of anchors, d is dimension of setup.
:param X: Matrix of shape N x d, where the last m points will be used to find fit with the anchors.
:param scale: set to True if the point set should be scaled to match the anchors.
:return: the transformed vector X, the rotation matrix, translation vector, and scaling factor.
"""
def centralize(X):
n = X.shape[0]
ones = np.ones((n, 1))
return X - np.multiply(1 / n * np.dot(ones.T, X), ones)
m = anchors.shape[0]
N, d = X.shape
assert m >= d, 'Have to give at least d anchor nodes.'
X_m = X[N - m:, :]
ones = np.ones((m, 1))
mux = 1 / m * np.dot(ones.T, X_m)
muy = 1 / m * np.dot(ones.T, anchors)
sigmax = 1 / m * np.linalg.norm(X_m - mux)**2
sigmaxy = 1 / m * np.dot((anchors - muy).T, X_m - mux)
try:
U, D, VT = np.linalg.svd(sigmaxy)
except np.LinAlgError:
print('strange things are happening...')
print(sigmaxy)
print(np.linalg.matrix_rank(sigmaxy))
#this doesn't work and doesn't seem to be necessary! (why?)
# S = np.eye(D.shape[0])
# if (np.linalg.det(U)*np.linalg.det(VT.T) < 0):
# print('switching')
# S[-1,-1] = -1.0
# else:
# print('not switching')
# c = np.trace(np.dot(np.diag(D),S))/sigmax
# R = np.dot(U, np.dot(S,VT))
if (scale):
c = np.trace(np.diag(D)) / sigmax
else:
c = np.trace(np.diag(D)) / sigmax
if (print_out):
print('Optimal scale would be: {}. Setting it to 1 now.'.format(c))
c = 1.0
R = np.dot(U, VT)
t = muy.T - c * np.dot(R, mux.T)
X_transformed = (c * np.dot(R, (X - mux).T) + muy.T).T
return X_transformed, R, t, c | python | def procrustes(anchors, X, scale=True, print_out=False):
""" Fit X to anchors by applying optimal translation, rotation and reflection.
Given m >= d anchor nodes (anchors in R^(m x d)), return transformation
of coordinates X (output of EDM algorithm) optimally matching anchors in least squares sense.
:param anchors: Matrix of shape m x d, where m is number of anchors, d is dimension of setup.
:param X: Matrix of shape N x d, where the last m points will be used to find fit with the anchors.
:param scale: set to True if the point set should be scaled to match the anchors.
:return: the transformed vector X, the rotation matrix, translation vector, and scaling factor.
"""
def centralize(X):
n = X.shape[0]
ones = np.ones((n, 1))
return X - np.multiply(1 / n * np.dot(ones.T, X), ones)
m = anchors.shape[0]
N, d = X.shape
assert m >= d, 'Have to give at least d anchor nodes.'
X_m = X[N - m:, :]
ones = np.ones((m, 1))
mux = 1 / m * np.dot(ones.T, X_m)
muy = 1 / m * np.dot(ones.T, anchors)
sigmax = 1 / m * np.linalg.norm(X_m - mux)**2
sigmaxy = 1 / m * np.dot((anchors - muy).T, X_m - mux)
try:
U, D, VT = np.linalg.svd(sigmaxy)
except np.LinAlgError:
print('strange things are happening...')
print(sigmaxy)
print(np.linalg.matrix_rank(sigmaxy))
#this doesn't work and doesn't seem to be necessary! (why?)
# S = np.eye(D.shape[0])
# if (np.linalg.det(U)*np.linalg.det(VT.T) < 0):
# print('switching')
# S[-1,-1] = -1.0
# else:
# print('not switching')
# c = np.trace(np.dot(np.diag(D),S))/sigmax
# R = np.dot(U, np.dot(S,VT))
if (scale):
c = np.trace(np.diag(D)) / sigmax
else:
c = np.trace(np.diag(D)) / sigmax
if (print_out):
print('Optimal scale would be: {}. Setting it to 1 now.'.format(c))
c = 1.0
R = np.dot(U, VT)
t = muy.T - c * np.dot(R, mux.T)
X_transformed = (c * np.dot(R, (X - mux).T) + muy.T).T
return X_transformed, R, t, c | [
"def",
"procrustes",
"(",
"anchors",
",",
"X",
",",
"scale",
"=",
"True",
",",
"print_out",
"=",
"False",
")",
":",
"def",
"centralize",
"(",
"X",
")",
":",
"n",
"=",
"X",
".",
"shape",
"[",
"0",
"]",
"ones",
"=",
"np",
".",
"ones",
"(",
"(",
... | Fit X to anchors by applying optimal translation, rotation and reflection.
Given m >= d anchor nodes (anchors in R^(m x d)), return transformation
of coordinates X (output of EDM algorithm) optimally matching anchors in least squares sense.
:param anchors: Matrix of shape m x d, where m is number of anchors, d is dimension of setup.
:param X: Matrix of shape N x d, where the last m points will be used to find fit with the anchors.
:param scale: set to True if the point set should be scaled to match the anchors.
:return: the transformed vector X, the rotation matrix, translation vector, and scaling factor. | [
"Fit",
"X",
"to",
"anchors",
"by",
"applying",
"optimal",
"translation",
"rotation",
"and",
"reflection",
"."
] | train | https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/algorithms.py#L61-L112 |
LCAV/pylocus | pylocus/algorithms.py | reconstruct_emds | def reconstruct_emds(edm, Om, all_points, method=None, **kwargs):
""" Reconstruct point set using E(dge)-MDS.
"""
from .point_set import dm_from_edm
N = all_points.shape[0]
d = all_points.shape[1]
dm = dm_from_edm(edm)
if method is None:
from .mds import superMDS
Xhat, __ = superMDS(all_points[0, :], N, d, Om=Om, dm=dm)
else:
C = kwargs.get('C', None)
b = kwargs.get('b', None)
if C is None or b is None:
raise NameError(
'Need constraints C and b for reconstruct_emds in iterative mode.')
KE_noisy = np.multiply(np.outer(dm, dm), Om)
if method == 'iterative':
from .mds import iterativeEMDS
Xhat, __ = iterativeEMDS(
all_points[0, :], N, d, KE=KE_noisy, C=C, b=b)
elif method == 'relaxed':
from .mds import relaxedEMDS
Xhat, __ = relaxedEMDS(
all_points[0, :], N, d, KE=KE_noisy, C=C, b=b)
else:
raise NameError('Undefined method', method)
Y, R, t, c = procrustes(all_points, Xhat, scale=False)
return Y | python | def reconstruct_emds(edm, Om, all_points, method=None, **kwargs):
""" Reconstruct point set using E(dge)-MDS.
"""
from .point_set import dm_from_edm
N = all_points.shape[0]
d = all_points.shape[1]
dm = dm_from_edm(edm)
if method is None:
from .mds import superMDS
Xhat, __ = superMDS(all_points[0, :], N, d, Om=Om, dm=dm)
else:
C = kwargs.get('C', None)
b = kwargs.get('b', None)
if C is None or b is None:
raise NameError(
'Need constraints C and b for reconstruct_emds in iterative mode.')
KE_noisy = np.multiply(np.outer(dm, dm), Om)
if method == 'iterative':
from .mds import iterativeEMDS
Xhat, __ = iterativeEMDS(
all_points[0, :], N, d, KE=KE_noisy, C=C, b=b)
elif method == 'relaxed':
from .mds import relaxedEMDS
Xhat, __ = relaxedEMDS(
all_points[0, :], N, d, KE=KE_noisy, C=C, b=b)
else:
raise NameError('Undefined method', method)
Y, R, t, c = procrustes(all_points, Xhat, scale=False)
return Y | [
"def",
"reconstruct_emds",
"(",
"edm",
",",
"Om",
",",
"all_points",
",",
"method",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
".",
"point_set",
"import",
"dm_from_edm",
"N",
"=",
"all_points",
".",
"shape",
"[",
"0",
"]",
"d",
"=",
"all... | Reconstruct point set using E(dge)-MDS. | [
"Reconstruct",
"point",
"set",
"using",
"E",
"(",
"dge",
")",
"-",
"MDS",
"."
] | train | https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/algorithms.py#L115-L143 |
LCAV/pylocus | pylocus/algorithms.py | reconstruct_cdm | def reconstruct_cdm(dm, absolute_angles, all_points, W=None):
""" Reconstruct point set from angle and distance measurements, using coordinate difference matrices.
"""
from pylocus.point_set import dmi_from_V, sdm_from_dmi, get_V
from pylocus.mds import signedMDS
N = all_points.shape[0]
V = get_V(absolute_angles, dm)
dmx = dmi_from_V(V, 0)
dmy = dmi_from_V(V, 1)
sdmx = sdm_from_dmi(dmx, N)
sdmy = sdm_from_dmi(dmy, N)
points_x = signedMDS(sdmx, W)
points_y = signedMDS(sdmy, W)
Xhat = np.c_[points_x, points_y]
Y, R, t, c = procrustes(all_points, Xhat, scale=False)
return Y | python | def reconstruct_cdm(dm, absolute_angles, all_points, W=None):
""" Reconstruct point set from angle and distance measurements, using coordinate difference matrices.
"""
from pylocus.point_set import dmi_from_V, sdm_from_dmi, get_V
from pylocus.mds import signedMDS
N = all_points.shape[0]
V = get_V(absolute_angles, dm)
dmx = dmi_from_V(V, 0)
dmy = dmi_from_V(V, 1)
sdmx = sdm_from_dmi(dmx, N)
sdmy = sdm_from_dmi(dmy, N)
points_x = signedMDS(sdmx, W)
points_y = signedMDS(sdmy, W)
Xhat = np.c_[points_x, points_y]
Y, R, t, c = procrustes(all_points, Xhat, scale=False)
return Y | [
"def",
"reconstruct_cdm",
"(",
"dm",
",",
"absolute_angles",
",",
"all_points",
",",
"W",
"=",
"None",
")",
":",
"from",
"pylocus",
".",
"point_set",
"import",
"dmi_from_V",
",",
"sdm_from_dmi",
",",
"get_V",
"from",
"pylocus",
".",
"mds",
"import",
"signedM... | Reconstruct point set from angle and distance measurements, using coordinate difference matrices. | [
"Reconstruct",
"point",
"set",
"from",
"angle",
"and",
"distance",
"measurements",
"using",
"coordinate",
"difference",
"matrices",
"."
] | train | https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/algorithms.py#L146-L167 |
LCAV/pylocus | pylocus/algorithms.py | reconstruct_mds | def reconstruct_mds(edm, all_points, completion='optspace', mask=None, method='geometric', print_out=False, n=1):
""" Reconstruct point set using MDS and matrix completion algorithms.
"""
from .point_set import dm_from_edm
from .mds import MDS
N = all_points.shape[0]
d = all_points.shape[1]
if mask is not None:
edm_missing = np.multiply(edm, mask)
if completion == 'optspace':
from .edm_completion import optspace
edm_complete = optspace(edm_missing, d + 2)
elif completion == 'alternate':
from .edm_completion import rank_alternation
edm_complete, errs = rank_alternation(
edm_missing, d + 2, print_out=False, edm_true=edm)
else:
raise NameError('Unknown completion method {}'.format(completion))
if (print_out):
err = np.linalg.norm(edm_complete - edm)**2 / \
np.linalg.norm(edm)**2
print('{}: relative error:{}'.format(completion, err))
edm = edm_complete
Xhat = MDS(edm, d, method, False).T
Y, R, t, c = procrustes(all_points[n:], Xhat, True)
#Y, R, t, c = procrustes(all_points, Xhat, True)
return Y | python | def reconstruct_mds(edm, all_points, completion='optspace', mask=None, method='geometric', print_out=False, n=1):
""" Reconstruct point set using MDS and matrix completion algorithms.
"""
from .point_set import dm_from_edm
from .mds import MDS
N = all_points.shape[0]
d = all_points.shape[1]
if mask is not None:
edm_missing = np.multiply(edm, mask)
if completion == 'optspace':
from .edm_completion import optspace
edm_complete = optspace(edm_missing, d + 2)
elif completion == 'alternate':
from .edm_completion import rank_alternation
edm_complete, errs = rank_alternation(
edm_missing, d + 2, print_out=False, edm_true=edm)
else:
raise NameError('Unknown completion method {}'.format(completion))
if (print_out):
err = np.linalg.norm(edm_complete - edm)**2 / \
np.linalg.norm(edm)**2
print('{}: relative error:{}'.format(completion, err))
edm = edm_complete
Xhat = MDS(edm, d, method, False).T
Y, R, t, c = procrustes(all_points[n:], Xhat, True)
#Y, R, t, c = procrustes(all_points, Xhat, True)
return Y | [
"def",
"reconstruct_mds",
"(",
"edm",
",",
"all_points",
",",
"completion",
"=",
"'optspace'",
",",
"mask",
"=",
"None",
",",
"method",
"=",
"'geometric'",
",",
"print_out",
"=",
"False",
",",
"n",
"=",
"1",
")",
":",
"from",
".",
"point_set",
"import",
... | Reconstruct point set using MDS and matrix completion algorithms. | [
"Reconstruct",
"point",
"set",
"using",
"MDS",
"and",
"matrix",
"completion",
"algorithms",
"."
] | train | https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/algorithms.py#L170-L196 |
LCAV/pylocus | pylocus/algorithms.py | reconstruct_sdp | def reconstruct_sdp(edm, all_points, W=None, print_out=False, lamda=1000, **kwargs):
""" Reconstruct point set using semi-definite rank relaxation.
"""
from .edm_completion import semidefinite_relaxation
edm_complete = semidefinite_relaxation(
edm, lamda=lamda, W=W, print_out=print_out, **kwargs)
Xhat = reconstruct_mds(edm_complete, all_points, method='geometric')
return Xhat, edm_complete | python | def reconstruct_sdp(edm, all_points, W=None, print_out=False, lamda=1000, **kwargs):
""" Reconstruct point set using semi-definite rank relaxation.
"""
from .edm_completion import semidefinite_relaxation
edm_complete = semidefinite_relaxation(
edm, lamda=lamda, W=W, print_out=print_out, **kwargs)
Xhat = reconstruct_mds(edm_complete, all_points, method='geometric')
return Xhat, edm_complete | [
"def",
"reconstruct_sdp",
"(",
"edm",
",",
"all_points",
",",
"W",
"=",
"None",
",",
"print_out",
"=",
"False",
",",
"lamda",
"=",
"1000",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
".",
"edm_completion",
"import",
"semidefinite_relaxation",
"edm_complete",
... | Reconstruct point set using semi-definite rank relaxation. | [
"Reconstruct",
"point",
"set",
"using",
"semi",
"-",
"definite",
"rank",
"relaxation",
"."
] | train | https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/algorithms.py#L199-L206 |
LCAV/pylocus | pylocus/algorithms.py | reconstruct_srls | def reconstruct_srls(edm, all_points, W=None, print_out=False, n=1, rescale=False,
z=None):
""" Reconstruct point set using S(quared)R(ange)L(east)S(quares) method.
"""
from .lateration import SRLS, get_lateration_parameters
Y = all_points.copy()
indices = range(n)
for index in indices:
anchors, w, r2 = get_lateration_parameters(all_points, indices, index,
edm, W)
if print_out:
print('SRLS parameters:')
print('anchors', anchors)
print('w', w)
print('r2', r2)
srls = SRLS(anchors, w, r2, rescale, z, print_out)
if rescale:
srls = srls[0] # second element of output is the scale
Y[index, :] = srls
return Y | python | def reconstruct_srls(edm, all_points, W=None, print_out=False, n=1, rescale=False,
z=None):
""" Reconstruct point set using S(quared)R(ange)L(east)S(quares) method.
"""
from .lateration import SRLS, get_lateration_parameters
Y = all_points.copy()
indices = range(n)
for index in indices:
anchors, w, r2 = get_lateration_parameters(all_points, indices, index,
edm, W)
if print_out:
print('SRLS parameters:')
print('anchors', anchors)
print('w', w)
print('r2', r2)
srls = SRLS(anchors, w, r2, rescale, z, print_out)
if rescale:
srls = srls[0] # second element of output is the scale
Y[index, :] = srls
return Y | [
"def",
"reconstruct_srls",
"(",
"edm",
",",
"all_points",
",",
"W",
"=",
"None",
",",
"print_out",
"=",
"False",
",",
"n",
"=",
"1",
",",
"rescale",
"=",
"False",
",",
"z",
"=",
"None",
")",
":",
"from",
".",
"lateration",
"import",
"SRLS",
",",
"g... | Reconstruct point set using S(quared)R(ange)L(east)S(quares) method. | [
"Reconstruct",
"point",
"set",
"using",
"S",
"(",
"quared",
")",
"R",
"(",
"ange",
")",
"L",
"(",
"east",
")",
"S",
"(",
"quares",
")",
"method",
"."
] | train | https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/algorithms.py#L209-L229 |
LCAV/pylocus | pylocus/algorithms.py | reconstruct_acd | def reconstruct_acd(edm, X0, W=None, print_out=False, tol=1e-10, sweeps=10):
""" Reconstruct point set using alternating coordinate descent.
:param X0: Nxd matrix of starting points.
:param tol: Stopping criterion: if the stepsize in all coordinate directions
is less than tol for 2 consecutive sweeps, we stop.
:param sweep: Maximum number of sweeps. One sweep goes through all coordintaes and points once.
"""
def get_unique_delta(delta, i, coord, print_out=False):
delta_unique = delta.copy()
ftest = []
for de in delta_unique:
X_ktest = X_k.copy()
X_ktest[i, coord] += de
ftest.append(f(X_ktest, edm, W))
# choose delta_unique with lowest cost.
if print_out:
print(ftest)
print(delta_unique)
delta_unique = delta_unique[ftest == min(ftest)]
if print_out:
print(delta_unique)
if len(delta_unique) > 1:
# if multiple delta_uniques give the same cost, choose the biggest step.
delta_unique = max(delta_unique)
return delta_unique
def sweep():
for i in range(N):
loop_point(i)
def loop_coordinate(coord, i):
delta = get_step_size(i, coord, X_k, edm, W)
if len(delta) > 1:
delta_unique = get_unique_delta(delta, i, coord)
elif len(delta) == 1:
delta_unique = delta[0]
else:
print('Warning: did not find delta!', delta)
delta_unique = 0.0
try:
X_k[i, coord] += delta_unique
except:
get_unique_delta(delta, i, coord, print_out=True)
raise
cost_this = f(X_k, edm, W)
costs.append(cost_this)
if delta_unique <= tol:
coordinates_converged[i, coord] += 1
else:
if print_out:
print('======= coordinate {} of {} not yet converged'.format(coord, i))
coordinates_converged[i, coord] = 0
def loop_point(i):
coord_counter = 0
while not (coordinates_converged[i] >= 2).all():
if print_out:
print('==== point {}'.format(i))
coord_counter += 1
for coord in range(d):
if print_out:
print('======= coord {}'.format(coord))
loop_coordinate(coord, i)
if coord_counter > coord_n_it:
break
from .distributed_mds import get_step_size, f
N, d = X0.shape
if W is None:
W = np.ones((N, N)) - np.eye(N)
X_k = X0.copy()
costs = []
coordinates_converged = np.zeros(X_k.shape)
coord_n_it = 3
for sweep_counter in range(sweeps):
if print_out:
print('= sweep', sweep_counter)
sweep()
if (coordinates_converged >= 2).all():
if (print_out):
print('acd: all coordinates converged after {} sweeps.'.format(
sweep_counter))
return X_k, costs
if (print_out):
print('acd: did not converge after {} sweeps'.format(sweep_counter + 1))
return X_k, costs | python | def reconstruct_acd(edm, X0, W=None, print_out=False, tol=1e-10, sweeps=10):
""" Reconstruct point set using alternating coordinate descent.
:param X0: Nxd matrix of starting points.
:param tol: Stopping criterion: if the stepsize in all coordinate directions
is less than tol for 2 consecutive sweeps, we stop.
:param sweep: Maximum number of sweeps. One sweep goes through all coordintaes and points once.
"""
def get_unique_delta(delta, i, coord, print_out=False):
delta_unique = delta.copy()
ftest = []
for de in delta_unique:
X_ktest = X_k.copy()
X_ktest[i, coord] += de
ftest.append(f(X_ktest, edm, W))
# choose delta_unique with lowest cost.
if print_out:
print(ftest)
print(delta_unique)
delta_unique = delta_unique[ftest == min(ftest)]
if print_out:
print(delta_unique)
if len(delta_unique) > 1:
# if multiple delta_uniques give the same cost, choose the biggest step.
delta_unique = max(delta_unique)
return delta_unique
def sweep():
for i in range(N):
loop_point(i)
def loop_coordinate(coord, i):
delta = get_step_size(i, coord, X_k, edm, W)
if len(delta) > 1:
delta_unique = get_unique_delta(delta, i, coord)
elif len(delta) == 1:
delta_unique = delta[0]
else:
print('Warning: did not find delta!', delta)
delta_unique = 0.0
try:
X_k[i, coord] += delta_unique
except:
get_unique_delta(delta, i, coord, print_out=True)
raise
cost_this = f(X_k, edm, W)
costs.append(cost_this)
if delta_unique <= tol:
coordinates_converged[i, coord] += 1
else:
if print_out:
print('======= coordinate {} of {} not yet converged'.format(coord, i))
coordinates_converged[i, coord] = 0
def loop_point(i):
coord_counter = 0
while not (coordinates_converged[i] >= 2).all():
if print_out:
print('==== point {}'.format(i))
coord_counter += 1
for coord in range(d):
if print_out:
print('======= coord {}'.format(coord))
loop_coordinate(coord, i)
if coord_counter > coord_n_it:
break
from .distributed_mds import get_step_size, f
N, d = X0.shape
if W is None:
W = np.ones((N, N)) - np.eye(N)
X_k = X0.copy()
costs = []
coordinates_converged = np.zeros(X_k.shape)
coord_n_it = 3
for sweep_counter in range(sweeps):
if print_out:
print('= sweep', sweep_counter)
sweep()
if (coordinates_converged >= 2).all():
if (print_out):
print('acd: all coordinates converged after {} sweeps.'.format(
sweep_counter))
return X_k, costs
if (print_out):
print('acd: did not converge after {} sweeps'.format(sweep_counter + 1))
return X_k, costs | [
"def",
"reconstruct_acd",
"(",
"edm",
",",
"X0",
",",
"W",
"=",
"None",
",",
"print_out",
"=",
"False",
",",
"tol",
"=",
"1e-10",
",",
"sweeps",
"=",
"10",
")",
":",
"def",
"get_unique_delta",
"(",
"delta",
",",
"i",
",",
"coord",
",",
"print_out",
... | Reconstruct point set using alternating coordinate descent.
:param X0: Nxd matrix of starting points.
:param tol: Stopping criterion: if the stepsize in all coordinate directions
is less than tol for 2 consecutive sweeps, we stop.
:param sweep: Maximum number of sweeps. One sweep goes through all coordintaes and points once. | [
"Reconstruct",
"point",
"set",
"using",
"alternating",
"coordinate",
"descent",
"."
] | train | https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/algorithms.py#L232-L323 |
LCAV/pylocus | pylocus/algorithms.py | reconstruct_dwmds | def reconstruct_dwmds(edm, X0, W=None, n=None, r=None, X_bar=None, print_out=False, tol=1e-10, sweeps=100):
""" Reconstruct point set using d(istributed)w(eighted) MDS.
Refer to paper "Distributed Weighted-Multidimensional Scaling for Node Localization in Sensor Networks" for
implementation details (doi.org/10.1145/1138127.1138129)
:param X0: Nxd matrix of starting points.
:param n: Number of points of unknown position. The first n points in X0 and edm are considered unknown.
:param tol: Stopping criterion: when the cost is below this level, we stop.
:param sweeps: Maximum number of sweeps.
"""
from .basics import get_edm
from .distributed_mds import get_b, get_Si
N, d = X0.shape
if r is None and n is None:
raise ValueError('either r or n have to be given.')
elif n is None:
n = r.shape[0]
if W is None:
W = np.ones((N, N)) - np.eye(N)
X_k = X0.copy()
costs = []
# don't have to ignore i=j, because W[i,i] is zero.
a = np.sum(W[:n, :n], axis=1).flatten() + 2 * \
np.sum(W[:n, n:], axis=1).flatten()
if r is not None:
a += r.flatten()
for k in range(sweeps):
S = 0
for i in range(n):
edm_estimated = get_edm(X_k)
bi = get_b(i, edm_estimated, W, edm, n)
if r is not None and X_bar is not None:
X_k[i] = 1 / a[i] * (r[i] * X_bar[i, :] +
X_k.T.dot(bi).flatten())
Si = get_Si(i, edm_estimated, edm, W, n, r, X_bar[i], X_k[i])
else:
X_k[i] = 1 / a[i] * X_k.T.dot(bi).flatten()
Si = get_Si(i, edm_estimated, edm, W, n)
S += Si
costs.append(S)
if k > 1 and abs(costs[-1] - costs[-2]) < tol:
if (print_out):
print('dwMDS: converged after', k)
break
return X_k, costs | python | def reconstruct_dwmds(edm, X0, W=None, n=None, r=None, X_bar=None, print_out=False, tol=1e-10, sweeps=100):
""" Reconstruct point set using d(istributed)w(eighted) MDS.
Refer to paper "Distributed Weighted-Multidimensional Scaling for Node Localization in Sensor Networks" for
implementation details (doi.org/10.1145/1138127.1138129)
:param X0: Nxd matrix of starting points.
:param n: Number of points of unknown position. The first n points in X0 and edm are considered unknown.
:param tol: Stopping criterion: when the cost is below this level, we stop.
:param sweeps: Maximum number of sweeps.
"""
from .basics import get_edm
from .distributed_mds import get_b, get_Si
N, d = X0.shape
if r is None and n is None:
raise ValueError('either r or n have to be given.')
elif n is None:
n = r.shape[0]
if W is None:
W = np.ones((N, N)) - np.eye(N)
X_k = X0.copy()
costs = []
# don't have to ignore i=j, because W[i,i] is zero.
a = np.sum(W[:n, :n], axis=1).flatten() + 2 * \
np.sum(W[:n, n:], axis=1).flatten()
if r is not None:
a += r.flatten()
for k in range(sweeps):
S = 0
for i in range(n):
edm_estimated = get_edm(X_k)
bi = get_b(i, edm_estimated, W, edm, n)
if r is not None and X_bar is not None:
X_k[i] = 1 / a[i] * (r[i] * X_bar[i, :] +
X_k.T.dot(bi).flatten())
Si = get_Si(i, edm_estimated, edm, W, n, r, X_bar[i], X_k[i])
else:
X_k[i] = 1 / a[i] * X_k.T.dot(bi).flatten()
Si = get_Si(i, edm_estimated, edm, W, n)
S += Si
costs.append(S)
if k > 1 and abs(costs[-1] - costs[-2]) < tol:
if (print_out):
print('dwMDS: converged after', k)
break
return X_k, costs | [
"def",
"reconstruct_dwmds",
"(",
"edm",
",",
"X0",
",",
"W",
"=",
"None",
",",
"n",
"=",
"None",
",",
"r",
"=",
"None",
",",
"X_bar",
"=",
"None",
",",
"print_out",
"=",
"False",
",",
"tol",
"=",
"1e-10",
",",
"sweeps",
"=",
"100",
")",
":",
"f... | Reconstruct point set using d(istributed)w(eighted) MDS.
Refer to paper "Distributed Weighted-Multidimensional Scaling for Node Localization in Sensor Networks" for
implementation details (doi.org/10.1145/1138127.1138129)
:param X0: Nxd matrix of starting points.
:param n: Number of points of unknown position. The first n points in X0 and edm are considered unknown.
:param tol: Stopping criterion: when the cost is below this level, we stop.
:param sweeps: Maximum number of sweeps. | [
"Reconstruct",
"point",
"set",
"using",
"d",
"(",
"istributed",
")",
"w",
"(",
"eighted",
")",
"MDS",
"."
] | train | https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/algorithms.py#L326-L375 |
d0ugal/python-rfxcom | rfxcom/protocol/rain.py | Rain.parse | def parse(self, data):
"""Parse a 12 bytes packet in the Rain format and return a
dictionary containing the data extracted. An example of a return value
would be:
.. code-block:: python
{
'id': "0x2EB2",
'packet_length': 11,
'packet_type': 85,
'packet_type_name': 'Rain sensors',
'sequence_number': 0,
'packet_subtype': 1,
'packet_subtype_name': "RGR126/682/918",
'rain_rate': 5,
'rain_total': 130.0,
'signal_level': 9,
'battery_level': 6,
}
:param data: bytearray to be parsed
:type data: bytearray
:return: Data dictionary containing the parsed values
:rtype: dict
"""
self.validate_packet(data)
results = self.parse_header_part(data)
sub_type = results['packet_subtype']
id_ = self.dump_hex(data[4:6])
rain_rate_high = data[6]
rain_rate_low = data[7]
if sub_type == 0x01:
rain_rate = rain_rate_high * 0x100 + rain_rate_low
elif sub_type == 0x02:
rain_rate = float(rain_rate_high * 0x100 + rain_rate_low) / 100
else:
rain_rate = '--??--'
rain_total1 = data[8]
rain_total2 = data[9]
rain_total3 = data[10]
if sub_type != 0x06:
rain_total = float(
rain_total1 * 0x1000 + rain_total2 * 0x100 + rain_total3) / 10
else:
rain_total = '--??--'
sensor_specific = {
'id': id_
}
if rain_rate != '--??--':
sensor_specific['rain_rate'] = rain_rate
if rain_total != '--??--':
sensor_specific['rain_total'] = rain_total
results.update(RfxPacketUtils.parse_signal_and_battery(data[11]))
results.update(sensor_specific)
return results | python | def parse(self, data):
"""Parse a 12 bytes packet in the Rain format and return a
dictionary containing the data extracted. An example of a return value
would be:
.. code-block:: python
{
'id': "0x2EB2",
'packet_length': 11,
'packet_type': 85,
'packet_type_name': 'Rain sensors',
'sequence_number': 0,
'packet_subtype': 1,
'packet_subtype_name': "RGR126/682/918",
'rain_rate': 5,
'rain_total': 130.0,
'signal_level': 9,
'battery_level': 6,
}
:param data: bytearray to be parsed
:type data: bytearray
:return: Data dictionary containing the parsed values
:rtype: dict
"""
self.validate_packet(data)
results = self.parse_header_part(data)
sub_type = results['packet_subtype']
id_ = self.dump_hex(data[4:6])
rain_rate_high = data[6]
rain_rate_low = data[7]
if sub_type == 0x01:
rain_rate = rain_rate_high * 0x100 + rain_rate_low
elif sub_type == 0x02:
rain_rate = float(rain_rate_high * 0x100 + rain_rate_low) / 100
else:
rain_rate = '--??--'
rain_total1 = data[8]
rain_total2 = data[9]
rain_total3 = data[10]
if sub_type != 0x06:
rain_total = float(
rain_total1 * 0x1000 + rain_total2 * 0x100 + rain_total3) / 10
else:
rain_total = '--??--'
sensor_specific = {
'id': id_
}
if rain_rate != '--??--':
sensor_specific['rain_rate'] = rain_rate
if rain_total != '--??--':
sensor_specific['rain_total'] = rain_total
results.update(RfxPacketUtils.parse_signal_and_battery(data[11]))
results.update(sensor_specific)
return results | [
"def",
"parse",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"validate_packet",
"(",
"data",
")",
"results",
"=",
"self",
".",
"parse_header_part",
"(",
"data",
")",
"sub_type",
"=",
"results",
"[",
"'packet_subtype'",
"]",
"id_",
"=",
"self",
".",
... | Parse a 12 bytes packet in the Rain format and return a
dictionary containing the data extracted. An example of a return value
would be:
.. code-block:: python
{
'id': "0x2EB2",
'packet_length': 11,
'packet_type': 85,
'packet_type_name': 'Rain sensors',
'sequence_number': 0,
'packet_subtype': 1,
'packet_subtype_name': "RGR126/682/918",
'rain_rate': 5,
'rain_total': 130.0,
'signal_level': 9,
'battery_level': 6,
}
:param data: bytearray to be parsed
:type data: bytearray
:return: Data dictionary containing the parsed values
:rtype: dict | [
"Parse",
"a",
"12",
"bytes",
"packet",
"in",
"the",
"Rain",
"format",
"and",
"return",
"a",
"dictionary",
"containing",
"the",
"data",
"extracted",
".",
"An",
"example",
"of",
"a",
"return",
"value",
"would",
"be",
":"
] | train | https://github.com/d0ugal/python-rfxcom/blob/2eb87f85e5f5a04d00f32f25e0f010edfefbde0d/rfxcom/protocol/rain.py#L52-L115 |
LCAV/pylocus | pylocus/lateration.py | get_lateration_parameters | def get_lateration_parameters(all_points, indices, index, edm, W=None):
""" Get parameters relevant for lateration from full all_points, edm and W.
"""
if W is None:
W = np.ones(edm.shape)
# delete points that are not considered anchors
anchors = np.delete(all_points, indices, axis=0)
r2 = np.delete(edm[index, :], indices)
w = np.delete(W[index, :], indices)
# set w to zero where measurements are invalid
if np.isnan(r2).any():
nan_measurements = np.where(np.isnan(r2))[0]
r2[nan_measurements] = 0.0
w[nan_measurements] = 0.0
if np.isnan(w).any():
nan_measurements = np.where(np.isnan(w))[0]
r2[nan_measurements] = 0.0
w[nan_measurements] = 0.0
# delete anchors where weight is zero to avoid ill-conditioning
missing_anchors = np.where(w == 0.0)[0]
w = np.asarray(np.delete(w, missing_anchors))
r2 = np.asarray(np.delete(r2, missing_anchors))
w.resize(edm.shape[0] - len(indices) - len(missing_anchors), 1)
r2.resize(edm.shape[0] - len(indices) - len(missing_anchors), 1)
anchors = np.delete(anchors, missing_anchors, axis=0)
assert w.shape[0] == anchors.shape[0]
assert np.isnan(w).any() == False
assert np.isnan(r2).any() == False
return anchors, w, r2 | python | def get_lateration_parameters(all_points, indices, index, edm, W=None):
""" Get parameters relevant for lateration from full all_points, edm and W.
"""
if W is None:
W = np.ones(edm.shape)
# delete points that are not considered anchors
anchors = np.delete(all_points, indices, axis=0)
r2 = np.delete(edm[index, :], indices)
w = np.delete(W[index, :], indices)
# set w to zero where measurements are invalid
if np.isnan(r2).any():
nan_measurements = np.where(np.isnan(r2))[0]
r2[nan_measurements] = 0.0
w[nan_measurements] = 0.0
if np.isnan(w).any():
nan_measurements = np.where(np.isnan(w))[0]
r2[nan_measurements] = 0.0
w[nan_measurements] = 0.0
# delete anchors where weight is zero to avoid ill-conditioning
missing_anchors = np.where(w == 0.0)[0]
w = np.asarray(np.delete(w, missing_anchors))
r2 = np.asarray(np.delete(r2, missing_anchors))
w.resize(edm.shape[0] - len(indices) - len(missing_anchors), 1)
r2.resize(edm.shape[0] - len(indices) - len(missing_anchors), 1)
anchors = np.delete(anchors, missing_anchors, axis=0)
assert w.shape[0] == anchors.shape[0]
assert np.isnan(w).any() == False
assert np.isnan(r2).any() == False
return anchors, w, r2 | [
"def",
"get_lateration_parameters",
"(",
"all_points",
",",
"indices",
",",
"index",
",",
"edm",
",",
"W",
"=",
"None",
")",
":",
"if",
"W",
"is",
"None",
":",
"W",
"=",
"np",
".",
"ones",
"(",
"edm",
".",
"shape",
")",
"# delete points that are not cons... | Get parameters relevant for lateration from full all_points, edm and W. | [
"Get",
"parameters",
"relevant",
"for",
"lateration",
"from",
"full",
"all_points",
"edm",
"and",
"W",
"."
] | train | https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/lateration.py#L11-L42 |
LCAV/pylocus | pylocus/lateration.py | SRLS | def SRLS(anchors, w, r2, rescale=False, z=None, print_out=False):
'''Squared range least squares (SRLS)
Algorithm written by A.Beck, P.Stoica in "Approximate and Exact solutions of Source Localization Problems".
:param anchors: anchor points (Nxd)
:param w: weights for the measurements (Nx1)
:param r2: squared distances from anchors to point x. (Nx1)
:param rescale: Optional parameter. When set to True, the algorithm will
also identify if there is a global scaling of the measurements. Such a
situation arise for example when the measurement units of the distance is
unknown and different from that of the anchors locations (e.g. anchors are
in meters, distance in centimeters).
:param z: Optional parameter. Use to fix the z-coordinate of localized point.
:param print_out: Optional parameter, prints extra information.
:return: estimated position of point x.
'''
def y_hat(_lambda):
lhs = ATA + _lambda * D
assert A.shape[0] == b.shape[0]
assert A.shape[1] == f.shape[0], 'A {}, f {}'.format(A.shape, f.shape)
rhs = (np.dot(A.T, b) - _lambda * f).reshape((-1,))
assert lhs.shape[0] == rhs.shape[0], 'lhs {}, rhs {}'.format(
lhs.shape, rhs.shape)
try:
return np.linalg.solve(lhs, rhs)
except:
return np.zeros((lhs.shape[1],))
def phi(_lambda):
yhat = y_hat(_lambda).reshape((-1, 1))
sol = np.dot(yhat.T, np.dot(D, yhat)) + 2 * np.dot(f.T, yhat)
return sol.flatten()
def phi_prime(_lambda):
# TODO: test this.
B = np.linalg.inv(ATA + _lambda * D)
C = A.T.dot(b) - _lambda*f
y_prime = -B.dot(D.dot(B.dot(C)) - f)
y = y_hat(_lambda)
return 2*y.T.dot(D).dot(y_prime) + 2*f.T.dot(y_prime)
from scipy import optimize
from scipy.linalg import sqrtm
n, d = anchors.shape
assert r2.shape[1] == 1 and r2.shape[0] == n, 'r2 has to be of shape Nx1'
assert w.shape[1] == 1 and w.shape[0] == n, 'w has to be of shape Nx1'
if z is not None:
assert d == 3, 'Dimension of problem has to be 3 for fixing z.'
if rescale and z is not None:
raise NotImplementedError('Cannot run rescale for fixed z.')
if rescale and n < d + 2:
raise ValueError(
'A minimum of d + 2 ranges are necessary for rescaled ranging.')
elif n < d + 1 and z is None:
raise ValueError(
'A minimum of d + 1 ranges are necessary for ranging.')
elif n < d:
raise ValueError(
'A minimum of d ranges are necessary for ranging.')
Sigma = np.diagflat(np.power(w, 0.5))
if rescale:
A = np.c_[-2 * anchors, np.ones((n, 1)), -r2]
else:
if z is None:
A = np.c_[-2 * anchors, np.ones((n, 1))]
else:
A = np.c_[-2 * anchors[:, :2], np.ones((n, 1))]
A = Sigma.dot(A)
if rescale:
b = - np.power(np.linalg.norm(anchors, axis=1), 2).reshape(r2.shape)
else:
b = r2 - np.power(np.linalg.norm(anchors, axis=1), 2).reshape(r2.shape)
if z is not None:
b = b + 2 * anchors[:, 2].reshape((-1, 1)) * z - z**2
b = Sigma.dot(b)
ATA = np.dot(A.T, A)
if rescale:
D = np.zeros((d + 2, d + 2))
D[:d, :d] = np.eye(d)
else:
if z is None:
D = np.zeros((d + 1, d + 1))
else:
D = np.zeros((d, d))
D[:-1, :-1] = np.eye(D.shape[0]-1)
if rescale:
f = np.c_[np.zeros((1, d)), -0.5, 0.].T
elif z is None:
f = np.c_[np.zeros((1, d)), -0.5].T
else:
f = np.c_[np.zeros((1, 2)), -0.5].T
eig = np.sort(np.real(eigvalsh(a=D, b=ATA)))
if (print_out):
print('ATA:', ATA)
print('rank:', np.linalg.matrix_rank(A))
print('eigvals:', eigvals(ATA))
print('condition number:', np.linalg.cond(ATA))
print('generalized eigenvalues:', eig)
#eps = 0.01
if eig[-1] > 1e-10:
lower_bound = - 1.0 / eig[-1]
else:
print('Warning: biggest eigenvalue is zero!')
lower_bound = -1e-5
inf = 1e5
xtol = 1e-12
lambda_opt = 0
# We will look for the zero of phi between lower_bound and inf.
# Therefore, the two have to be of different signs.
if (phi(lower_bound) > 0) and (phi(inf) < 0):
# brentq is considered the best rootfinding routine.
try:
lambda_opt = optimize.brentq(phi, lower_bound, inf, xtol=xtol)
except:
print('SRLS error: brentq did not converge even though we found an estimate for lower and upper bonud. Setting lambda to 0.')
else:
try:
lambda_opt = optimize.newton(phi, lower_bound, fprime=phi_prime, maxiter=1000, tol=xtol, verbose=True)
assert phi(lambda_opt) < xtol, 'did not find solution of phi(lambda)=0:={}'.format(phi(lambda_opt))
except:
print('SRLS error: newton did not converge. Setting lambda to 0.')
if (print_out):
print('phi(lower_bound)', phi(lower_bound))
print('phi(inf)', phi(inf))
print('phi(lambda_opt)', phi(lambda_opt))
pos_definite = ATA + lambda_opt*D
eig = np.sort(np.real(eigvals(pos_definite)))
print('should be strictly bigger than 0:', eig)
# Compute best estimate
yhat = y_hat(lambda_opt)
if print_out and rescale:
print('Scaling factor :', yhat[-1])
if rescale:
return yhat[:d], yhat[-1]
elif z is None:
return yhat[:d]
else:
return np.r_[yhat[0], yhat[1], z] | python | def SRLS(anchors, w, r2, rescale=False, z=None, print_out=False):
'''Squared range least squares (SRLS)
Algorithm written by A.Beck, P.Stoica in "Approximate and Exact solutions of Source Localization Problems".
:param anchors: anchor points (Nxd)
:param w: weights for the measurements (Nx1)
:param r2: squared distances from anchors to point x. (Nx1)
:param rescale: Optional parameter. When set to True, the algorithm will
also identify if there is a global scaling of the measurements. Such a
situation arise for example when the measurement units of the distance is
unknown and different from that of the anchors locations (e.g. anchors are
in meters, distance in centimeters).
:param z: Optional parameter. Use to fix the z-coordinate of localized point.
:param print_out: Optional parameter, prints extra information.
:return: estimated position of point x.
'''
def y_hat(_lambda):
lhs = ATA + _lambda * D
assert A.shape[0] == b.shape[0]
assert A.shape[1] == f.shape[0], 'A {}, f {}'.format(A.shape, f.shape)
rhs = (np.dot(A.T, b) - _lambda * f).reshape((-1,))
assert lhs.shape[0] == rhs.shape[0], 'lhs {}, rhs {}'.format(
lhs.shape, rhs.shape)
try:
return np.linalg.solve(lhs, rhs)
except:
return np.zeros((lhs.shape[1],))
def phi(_lambda):
yhat = y_hat(_lambda).reshape((-1, 1))
sol = np.dot(yhat.T, np.dot(D, yhat)) + 2 * np.dot(f.T, yhat)
return sol.flatten()
def phi_prime(_lambda):
# TODO: test this.
B = np.linalg.inv(ATA + _lambda * D)
C = A.T.dot(b) - _lambda*f
y_prime = -B.dot(D.dot(B.dot(C)) - f)
y = y_hat(_lambda)
return 2*y.T.dot(D).dot(y_prime) + 2*f.T.dot(y_prime)
from scipy import optimize
from scipy.linalg import sqrtm
n, d = anchors.shape
assert r2.shape[1] == 1 and r2.shape[0] == n, 'r2 has to be of shape Nx1'
assert w.shape[1] == 1 and w.shape[0] == n, 'w has to be of shape Nx1'
if z is not None:
assert d == 3, 'Dimension of problem has to be 3 for fixing z.'
if rescale and z is not None:
raise NotImplementedError('Cannot run rescale for fixed z.')
if rescale and n < d + 2:
raise ValueError(
'A minimum of d + 2 ranges are necessary for rescaled ranging.')
elif n < d + 1 and z is None:
raise ValueError(
'A minimum of d + 1 ranges are necessary for ranging.')
elif n < d:
raise ValueError(
'A minimum of d ranges are necessary for ranging.')
Sigma = np.diagflat(np.power(w, 0.5))
if rescale:
A = np.c_[-2 * anchors, np.ones((n, 1)), -r2]
else:
if z is None:
A = np.c_[-2 * anchors, np.ones((n, 1))]
else:
A = np.c_[-2 * anchors[:, :2], np.ones((n, 1))]
A = Sigma.dot(A)
if rescale:
b = - np.power(np.linalg.norm(anchors, axis=1), 2).reshape(r2.shape)
else:
b = r2 - np.power(np.linalg.norm(anchors, axis=1), 2).reshape(r2.shape)
if z is not None:
b = b + 2 * anchors[:, 2].reshape((-1, 1)) * z - z**2
b = Sigma.dot(b)
ATA = np.dot(A.T, A)
if rescale:
D = np.zeros((d + 2, d + 2))
D[:d, :d] = np.eye(d)
else:
if z is None:
D = np.zeros((d + 1, d + 1))
else:
D = np.zeros((d, d))
D[:-1, :-1] = np.eye(D.shape[0]-1)
if rescale:
f = np.c_[np.zeros((1, d)), -0.5, 0.].T
elif z is None:
f = np.c_[np.zeros((1, d)), -0.5].T
else:
f = np.c_[np.zeros((1, 2)), -0.5].T
eig = np.sort(np.real(eigvalsh(a=D, b=ATA)))
if (print_out):
print('ATA:', ATA)
print('rank:', np.linalg.matrix_rank(A))
print('eigvals:', eigvals(ATA))
print('condition number:', np.linalg.cond(ATA))
print('generalized eigenvalues:', eig)
#eps = 0.01
if eig[-1] > 1e-10:
lower_bound = - 1.0 / eig[-1]
else:
print('Warning: biggest eigenvalue is zero!')
lower_bound = -1e-5
inf = 1e5
xtol = 1e-12
lambda_opt = 0
# We will look for the zero of phi between lower_bound and inf.
# Therefore, the two have to be of different signs.
if (phi(lower_bound) > 0) and (phi(inf) < 0):
# brentq is considered the best rootfinding routine.
try:
lambda_opt = optimize.brentq(phi, lower_bound, inf, xtol=xtol)
except:
print('SRLS error: brentq did not converge even though we found an estimate for lower and upper bonud. Setting lambda to 0.')
else:
try:
lambda_opt = optimize.newton(phi, lower_bound, fprime=phi_prime, maxiter=1000, tol=xtol, verbose=True)
assert phi(lambda_opt) < xtol, 'did not find solution of phi(lambda)=0:={}'.format(phi(lambda_opt))
except:
print('SRLS error: newton did not converge. Setting lambda to 0.')
if (print_out):
print('phi(lower_bound)', phi(lower_bound))
print('phi(inf)', phi(inf))
print('phi(lambda_opt)', phi(lambda_opt))
pos_definite = ATA + lambda_opt*D
eig = np.sort(np.real(eigvals(pos_definite)))
print('should be strictly bigger than 0:', eig)
# Compute best estimate
yhat = y_hat(lambda_opt)
if print_out and rescale:
print('Scaling factor :', yhat[-1])
if rescale:
return yhat[:d], yhat[-1]
elif z is None:
return yhat[:d]
else:
return np.r_[yhat[0], yhat[1], z] | [
"def",
"SRLS",
"(",
"anchors",
",",
"w",
",",
"r2",
",",
"rescale",
"=",
"False",
",",
"z",
"=",
"None",
",",
"print_out",
"=",
"False",
")",
":",
"def",
"y_hat",
"(",
"_lambda",
")",
":",
"lhs",
"=",
"ATA",
"+",
"_lambda",
"*",
"D",
"assert",
... | Squared range least squares (SRLS)
Algorithm written by A.Beck, P.Stoica in "Approximate and Exact solutions of Source Localization Problems".
:param anchors: anchor points (Nxd)
:param w: weights for the measurements (Nx1)
:param r2: squared distances from anchors to point x. (Nx1)
:param rescale: Optional parameter. When set to True, the algorithm will
also identify if there is a global scaling of the measurements. Such a
situation arise for example when the measurement units of the distance is
unknown and different from that of the anchors locations (e.g. anchors are
in meters, distance in centimeters).
:param z: Optional parameter. Use to fix the z-coordinate of localized point.
:param print_out: Optional parameter, prints extra information.
:return: estimated position of point x. | [
"Squared",
"range",
"least",
"squares",
"(",
"SRLS",
")"
] | train | https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/lateration.py#L45-L201 |
LCAV/pylocus | pylocus/lateration.py | PozyxLS | def PozyxLS(anchors, W, r2, print_out=False):
''' Algorithm used by pozyx (https://www.pozyx.io/Documentation/how_does_positioning_work)
:param anchors: anchor points
:param r2: squared distances from anchors to point x.
:returns: estimated position of point x.
'''
N = anchors.shape[0]
anchors_term = np.sum(np.power(anchors[:-1], 2), axis=1)
last_term = np.sum(np.power(anchors[-1], 2))
b = r2[:-1] - anchors_term + last_term - r2[-1]
A = -2 * (anchors[:-1] - anchors[-1])
x, res, rank, s = np.linalg.lstsq(A, b)
return x | python | def PozyxLS(anchors, W, r2, print_out=False):
''' Algorithm used by pozyx (https://www.pozyx.io/Documentation/how_does_positioning_work)
:param anchors: anchor points
:param r2: squared distances from anchors to point x.
:returns: estimated position of point x.
'''
N = anchors.shape[0]
anchors_term = np.sum(np.power(anchors[:-1], 2), axis=1)
last_term = np.sum(np.power(anchors[-1], 2))
b = r2[:-1] - anchors_term + last_term - r2[-1]
A = -2 * (anchors[:-1] - anchors[-1])
x, res, rank, s = np.linalg.lstsq(A, b)
return x | [
"def",
"PozyxLS",
"(",
"anchors",
",",
"W",
",",
"r2",
",",
"print_out",
"=",
"False",
")",
":",
"N",
"=",
"anchors",
".",
"shape",
"[",
"0",
"]",
"anchors_term",
"=",
"np",
".",
"sum",
"(",
"np",
".",
"power",
"(",
"anchors",
"[",
":",
"-",
"1... | Algorithm used by pozyx (https://www.pozyx.io/Documentation/how_does_positioning_work)
:param anchors: anchor points
:param r2: squared distances from anchors to point x.
:returns: estimated position of point x. | [
"Algorithm",
"used",
"by",
"pozyx",
"(",
"https",
":",
"//",
"www",
".",
"pozyx",
".",
"io",
"/",
"Documentation",
"/",
"how_does_positioning_work",
")"
] | train | https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/lateration.py#L204-L218 |
LCAV/pylocus | pylocus/lateration.py | RLS | def RLS(anchors, W, r, print_out=False, grid=None, num_points=10):
""" Range least squares (RLS) using grid search.
Algorithm written by A.Beck, P.Stoica in "Approximate and Exact solutions of Source Localization Problems".
:param anchors: anchor points
:param r2: squared distances from anchors to point x.
:param grid: where to search for solution. (min, max) where min and max are
lists of d elements, d being the dimension of the setup. If not given, the
search is conducted within the space covered by the anchors.
:param num_points: number of grid points per direction.
:return: estimated position of point x.
"""
def cost_function(arr):
X = np.c_[arr]
r_measured = np.linalg.norm(anchors - X)
mse = np.linalg.norm(r_measured - r)**2
return mse
if grid is None:
grid = [np.min(anchors, axis=0), np.max(anchors, axis=0)]
d = anchors.shape[1]
x = np.linspace(grid[0][0], grid[1][0], num_points)
y = np.linspace(grid[0][1], grid[1][1], num_points)
if d == 2:
errors_test = np.zeros((num_points, num_points))
for i, xs in enumerate(x):
for j, ys in enumerate(y):
errors_test[i, j] = cost_function((xs, ys))
min_idx = errors_test.argmin()
min_idx_multi = np.unravel_index(min_idx, errors_test.shape)
xhat = np.c_[x[min_idx_multi[0]], y[min_idx_multi[1]]]
elif d == 3:
z = np.linspace(grid[0][2], grid[1][2], num_points)
errors_test = np.zeros((num_points, num_points, num_points))
# TODO: make this more efficient.
#xx, yy, zz= np.meshgrid(x, y, z)
for i, xs in enumerate(x):
for j, ys in enumerate(y):
for k, zs in enumerate(z):
errors_test[i, j, k] = cost_function((xs, ys, zs))
min_idx = errors_test.argmin()
min_idx_multi = np.unravel_index(min_idx, errors_test.shape)
xhat = np.c_[x[min_idx_multi[0]],
y[min_idx_multi[1]], z[min_idx_multi[2]]]
else:
raise ValueError('Non-supported number of dimensions.')
return xhat[0] | python | def RLS(anchors, W, r, print_out=False, grid=None, num_points=10):
""" Range least squares (RLS) using grid search.
Algorithm written by A.Beck, P.Stoica in "Approximate and Exact solutions of Source Localization Problems".
:param anchors: anchor points
:param r2: squared distances from anchors to point x.
:param grid: where to search for solution. (min, max) where min and max are
lists of d elements, d being the dimension of the setup. If not given, the
search is conducted within the space covered by the anchors.
:param num_points: number of grid points per direction.
:return: estimated position of point x.
"""
def cost_function(arr):
X = np.c_[arr]
r_measured = np.linalg.norm(anchors - X)
mse = np.linalg.norm(r_measured - r)**2
return mse
if grid is None:
grid = [np.min(anchors, axis=0), np.max(anchors, axis=0)]
d = anchors.shape[1]
x = np.linspace(grid[0][0], grid[1][0], num_points)
y = np.linspace(grid[0][1], grid[1][1], num_points)
if d == 2:
errors_test = np.zeros((num_points, num_points))
for i, xs in enumerate(x):
for j, ys in enumerate(y):
errors_test[i, j] = cost_function((xs, ys))
min_idx = errors_test.argmin()
min_idx_multi = np.unravel_index(min_idx, errors_test.shape)
xhat = np.c_[x[min_idx_multi[0]], y[min_idx_multi[1]]]
elif d == 3:
z = np.linspace(grid[0][2], grid[1][2], num_points)
errors_test = np.zeros((num_points, num_points, num_points))
# TODO: make this more efficient.
#xx, yy, zz= np.meshgrid(x, y, z)
for i, xs in enumerate(x):
for j, ys in enumerate(y):
for k, zs in enumerate(z):
errors_test[i, j, k] = cost_function((xs, ys, zs))
min_idx = errors_test.argmin()
min_idx_multi = np.unravel_index(min_idx, errors_test.shape)
xhat = np.c_[x[min_idx_multi[0]],
y[min_idx_multi[1]], z[min_idx_multi[2]]]
else:
raise ValueError('Non-supported number of dimensions.')
return xhat[0] | [
"def",
"RLS",
"(",
"anchors",
",",
"W",
",",
"r",
",",
"print_out",
"=",
"False",
",",
"grid",
"=",
"None",
",",
"num_points",
"=",
"10",
")",
":",
"def",
"cost_function",
"(",
"arr",
")",
":",
"X",
"=",
"np",
".",
"c_",
"[",
"arr",
"]",
"r_mea... | Range least squares (RLS) using grid search.
Algorithm written by A.Beck, P.Stoica in "Approximate and Exact solutions of Source Localization Problems".
:param anchors: anchor points
:param r2: squared distances from anchors to point x.
:param grid: where to search for solution. (min, max) where min and max are
lists of d elements, d being the dimension of the setup. If not given, the
search is conducted within the space covered by the anchors.
:param num_points: number of grid points per direction.
:return: estimated position of point x. | [
"Range",
"least",
"squares",
"(",
"RLS",
")",
"using",
"grid",
"search",
"."
] | train | https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/lateration.py#L221-L271 |
LCAV/pylocus | pylocus/lateration.py | RLS_SDR | def RLS_SDR(anchors, W, r, print_out=False):
""" Range least squares (RLS) using SDR.
Algorithm cited by A.Beck, P.Stoica in "Approximate and Exact solutions of Source Localization Problems".
:param anchors: anchor points
:param r2: squared distances from anchors to point x.
:return: estimated position of point x.
"""
from pylocus.basics import low_rank_approximation, eigendecomp
from pylocus.mds import x_from_eigendecomp
m = anchors.shape[0]
d = anchors.shape[1]
G = Variable(m + 1, m + 1)
X = Variable(d + 1, d + 1)
constraints = [G[m, m] == 1.0,
X[d, d] == 1.0,
G >> 0, X >> 0,
G == G.T, X == X.T]
for i in range(m):
Ci = np.eye(d + 1)
Ci[:-1, -1] = -anchors[i]
Ci[-1, :-1] = -anchors[i].T
Ci[-1, -1] = np.linalg.norm(anchors[i])**2
constraints.append(G[i, i] == trace(Ci * X))
obj = Minimize(trace(G) - 2 * sum_entries(mul_elemwise(r, G[m, :-1].T)))
prob = Problem(obj, constraints)
## Solution
total = prob.solve(verbose=True)
rank_G = np.linalg.matrix_rank(G.value)
rank_X = np.linalg.matrix_rank(X.value)
if rank_G > 1:
u, s, v = np.linalg.svd(G.value, full_matrices=False)
print('optimal G is not of rank 1!')
print(s)
if rank_X > 1:
u, s, v = np.linalg.svd(X.value, full_matrices=False)
print('optimal X is not of rank 1!')
print(s)
factor, u = eigendecomp(X.value, 1)
xhat = x_from_eigendecomp(factor, u, 1)
return xhat | python | def RLS_SDR(anchors, W, r, print_out=False):
""" Range least squares (RLS) using SDR.
Algorithm cited by A.Beck, P.Stoica in "Approximate and Exact solutions of Source Localization Problems".
:param anchors: anchor points
:param r2: squared distances from anchors to point x.
:return: estimated position of point x.
"""
from pylocus.basics import low_rank_approximation, eigendecomp
from pylocus.mds import x_from_eigendecomp
m = anchors.shape[0]
d = anchors.shape[1]
G = Variable(m + 1, m + 1)
X = Variable(d + 1, d + 1)
constraints = [G[m, m] == 1.0,
X[d, d] == 1.0,
G >> 0, X >> 0,
G == G.T, X == X.T]
for i in range(m):
Ci = np.eye(d + 1)
Ci[:-1, -1] = -anchors[i]
Ci[-1, :-1] = -anchors[i].T
Ci[-1, -1] = np.linalg.norm(anchors[i])**2
constraints.append(G[i, i] == trace(Ci * X))
obj = Minimize(trace(G) - 2 * sum_entries(mul_elemwise(r, G[m, :-1].T)))
prob = Problem(obj, constraints)
## Solution
total = prob.solve(verbose=True)
rank_G = np.linalg.matrix_rank(G.value)
rank_X = np.linalg.matrix_rank(X.value)
if rank_G > 1:
u, s, v = np.linalg.svd(G.value, full_matrices=False)
print('optimal G is not of rank 1!')
print(s)
if rank_X > 1:
u, s, v = np.linalg.svd(X.value, full_matrices=False)
print('optimal X is not of rank 1!')
print(s)
factor, u = eigendecomp(X.value, 1)
xhat = x_from_eigendecomp(factor, u, 1)
return xhat | [
"def",
"RLS_SDR",
"(",
"anchors",
",",
"W",
",",
"r",
",",
"print_out",
"=",
"False",
")",
":",
"from",
"pylocus",
".",
"basics",
"import",
"low_rank_approximation",
",",
"eigendecomp",
"from",
"pylocus",
".",
"mds",
"import",
"x_from_eigendecomp",
"m",
"=",... | Range least squares (RLS) using SDR.
Algorithm cited by A.Beck, P.Stoica in "Approximate and Exact solutions of Source Localization Problems".
:param anchors: anchor points
:param r2: squared distances from anchors to point x.
:return: estimated position of point x. | [
"Range",
"least",
"squares",
"(",
"RLS",
")",
"using",
"SDR",
"."
] | train | https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/lateration.py#L274-L321 |
toumorokoshi/transmute-core | transmute_core/attributes/__init__.py | TransmuteAttributes._join_parameters | def _join_parameters(base, nxt):
""" join parameters from the lhs to the rhs, if compatible. """
if nxt is None:
return base
if isinstance(base, set) and isinstance(nxt, set):
return base | nxt
else:
return nxt | python | def _join_parameters(base, nxt):
""" join parameters from the lhs to the rhs, if compatible. """
if nxt is None:
return base
if isinstance(base, set) and isinstance(nxt, set):
return base | nxt
else:
return nxt | [
"def",
"_join_parameters",
"(",
"base",
",",
"nxt",
")",
":",
"if",
"nxt",
"is",
"None",
":",
"return",
"base",
"if",
"isinstance",
"(",
"base",
",",
"set",
")",
"and",
"isinstance",
"(",
"nxt",
",",
"set",
")",
":",
"return",
"base",
"|",
"nxt",
"... | join parameters from the lhs to the rhs, if compatible. | [
"join",
"parameters",
"from",
"the",
"lhs",
"to",
"the",
"rhs",
"if",
"compatible",
"."
] | train | https://github.com/toumorokoshi/transmute-core/blob/a2c26625d5d8bab37e00038f9d615a26167fc7f4/transmute_core/attributes/__init__.py#L99-L106 |
toumorokoshi/transmute-core | transmute_core/function/transmute_function.py | TransmuteFunction.get_swagger_operation | def get_swagger_operation(self, context=default_context):
"""
get the swagger_schema operation representation.
"""
consumes = produces = context.contenttype_serializers.keys()
parameters = get_swagger_parameters(self.parameters, context)
responses = {
"400": Response(
{
"description": "invalid input received",
"schema": Schema(
{
"title": "FailureObject",
"type": "object",
"properties": {
"success": {"type": "boolean"},
"result": {"type": "string"},
},
"required": ["success", "result"],
}
),
}
)
}
for code, details in self.response_types.items():
responses[str(code)] = details.swagger_definition(context)
return Operation(
{
"summary": self.summary,
"description": self.description,
"consumes": consumes,
"produces": produces,
"parameters": parameters,
"responses": responses,
"operationId": self.raw_func.__name__,
"tags": self.tags,
}
) | python | def get_swagger_operation(self, context=default_context):
"""
get the swagger_schema operation representation.
"""
consumes = produces = context.contenttype_serializers.keys()
parameters = get_swagger_parameters(self.parameters, context)
responses = {
"400": Response(
{
"description": "invalid input received",
"schema": Schema(
{
"title": "FailureObject",
"type": "object",
"properties": {
"success": {"type": "boolean"},
"result": {"type": "string"},
},
"required": ["success", "result"],
}
),
}
)
}
for code, details in self.response_types.items():
responses[str(code)] = details.swagger_definition(context)
return Operation(
{
"summary": self.summary,
"description": self.description,
"consumes": consumes,
"produces": produces,
"parameters": parameters,
"responses": responses,
"operationId": self.raw_func.__name__,
"tags": self.tags,
}
) | [
"def",
"get_swagger_operation",
"(",
"self",
",",
"context",
"=",
"default_context",
")",
":",
"consumes",
"=",
"produces",
"=",
"context",
".",
"contenttype_serializers",
".",
"keys",
"(",
")",
"parameters",
"=",
"get_swagger_parameters",
"(",
"self",
".",
"par... | get the swagger_schema operation representation. | [
"get",
"the",
"swagger_schema",
"operation",
"representation",
"."
] | train | https://github.com/toumorokoshi/transmute-core/blob/a2c26625d5d8bab37e00038f9d615a26167fc7f4/transmute_core/function/transmute_function.py#L89-L128 |
toumorokoshi/transmute-core | transmute_core/function/transmute_function.py | TransmuteFunction.process_result | def process_result(self, context, result_body, exc, content_type):
"""
given an result body and an exception object,
return the appropriate result object,
or raise an exception.
"""
return process_result(self, context, result_body, exc, content_type) | python | def process_result(self, context, result_body, exc, content_type):
"""
given an result body and an exception object,
return the appropriate result object,
or raise an exception.
"""
return process_result(self, context, result_body, exc, content_type) | [
"def",
"process_result",
"(",
"self",
",",
"context",
",",
"result_body",
",",
"exc",
",",
"content_type",
")",
":",
"return",
"process_result",
"(",
"self",
",",
"context",
",",
"result_body",
",",
"exc",
",",
"content_type",
")"
] | given an result body and an exception object,
return the appropriate result object,
or raise an exception. | [
"given",
"an",
"result",
"body",
"and",
"an",
"exception",
"object",
"return",
"the",
"appropriate",
"result",
"object",
"or",
"raise",
"an",
"exception",
"."
] | train | https://github.com/toumorokoshi/transmute-core/blob/a2c26625d5d8bab37e00038f9d615a26167fc7f4/transmute_core/function/transmute_function.py#L130-L136 |
toumorokoshi/transmute-core | transmute_core/function/transmute_function.py | TransmuteFunction._parse_response_types | def _parse_response_types(argspec, attrs):
"""
from the given parameters, return back the response type dictionaries.
"""
return_type = argspec.annotations.get("return") or None
type_description = attrs.parameter_descriptions.get("return", "")
response_types = attrs.response_types.copy()
if return_type or len(response_types) == 0:
response_types[attrs.success_code] = ResponseType(
type=return_type,
type_description=type_description,
description="success",
)
return response_types | python | def _parse_response_types(argspec, attrs):
"""
from the given parameters, return back the response type dictionaries.
"""
return_type = argspec.annotations.get("return") or None
type_description = attrs.parameter_descriptions.get("return", "")
response_types = attrs.response_types.copy()
if return_type or len(response_types) == 0:
response_types[attrs.success_code] = ResponseType(
type=return_type,
type_description=type_description,
description="success",
)
return response_types | [
"def",
"_parse_response_types",
"(",
"argspec",
",",
"attrs",
")",
":",
"return_type",
"=",
"argspec",
".",
"annotations",
".",
"get",
"(",
"\"return\"",
")",
"or",
"None",
"type_description",
"=",
"attrs",
".",
"parameter_descriptions",
".",
"get",
"(",
"\"re... | from the given parameters, return back the response type dictionaries. | [
"from",
"the",
"given",
"parameters",
"return",
"back",
"the",
"response",
"type",
"dictionaries",
"."
] | train | https://github.com/toumorokoshi/transmute-core/blob/a2c26625d5d8bab37e00038f9d615a26167fc7f4/transmute_core/function/transmute_function.py#L152-L165 |
toumorokoshi/transmute-core | transmute_core/swagger/__init__.py | generate_swagger_html | def generate_swagger_html(swagger_static_root, swagger_json_url):
"""
given a root directory for the swagger statics, and
a swagger json path, return back a swagger html designed
to use those values.
"""
tmpl = _get_template("swagger.html")
return tmpl.render(
swagger_root=swagger_static_root, swagger_json_url=swagger_json_url
) | python | def generate_swagger_html(swagger_static_root, swagger_json_url):
"""
given a root directory for the swagger statics, and
a swagger json path, return back a swagger html designed
to use those values.
"""
tmpl = _get_template("swagger.html")
return tmpl.render(
swagger_root=swagger_static_root, swagger_json_url=swagger_json_url
) | [
"def",
"generate_swagger_html",
"(",
"swagger_static_root",
",",
"swagger_json_url",
")",
":",
"tmpl",
"=",
"_get_template",
"(",
"\"swagger.html\"",
")",
"return",
"tmpl",
".",
"render",
"(",
"swagger_root",
"=",
"swagger_static_root",
",",
"swagger_json_url",
"=",
... | given a root directory for the swagger statics, and
a swagger json path, return back a swagger html designed
to use those values. | [
"given",
"a",
"root",
"directory",
"for",
"the",
"swagger",
"statics",
"and",
"a",
"swagger",
"json",
"path",
"return",
"back",
"a",
"swagger",
"html",
"designed",
"to",
"use",
"those",
"values",
"."
] | train | https://github.com/toumorokoshi/transmute-core/blob/a2c26625d5d8bab37e00038f9d615a26167fc7f4/transmute_core/swagger/__init__.py#L10-L19 |
toumorokoshi/transmute-core | transmute_core/swagger/__init__.py | SwaggerSpec.add_func | def add_func(self, transmute_func, transmute_context):
""" add a transmute function's swagger definition to the spec """
swagger_path = transmute_func.get_swagger_path(transmute_context)
for p in transmute_func.paths:
self.add_path(p, swagger_path) | python | def add_func(self, transmute_func, transmute_context):
""" add a transmute function's swagger definition to the spec """
swagger_path = transmute_func.get_swagger_path(transmute_context)
for p in transmute_func.paths:
self.add_path(p, swagger_path) | [
"def",
"add_func",
"(",
"self",
",",
"transmute_func",
",",
"transmute_context",
")",
":",
"swagger_path",
"=",
"transmute_func",
".",
"get_swagger_path",
"(",
"transmute_context",
")",
"for",
"p",
"in",
"transmute_func",
".",
"paths",
":",
"self",
".",
"add_pat... | add a transmute function's swagger definition to the spec | [
"add",
"a",
"transmute",
"function",
"s",
"swagger",
"definition",
"to",
"the",
"spec"
] | train | https://github.com/toumorokoshi/transmute-core/blob/a2c26625d5d8bab37e00038f9d615a26167fc7f4/transmute_core/swagger/__init__.py#L53-L57 |
toumorokoshi/transmute-core | transmute_core/swagger/__init__.py | SwaggerSpec.add_path | def add_path(self, path, path_item):
""" for a given path, add the path items. """
if path not in self._swagger:
self._swagger[path] = path_item
else:
for method, definition in path_item.items():
if definition is not None:
setattr(self._swagger[path], method, definition) | python | def add_path(self, path, path_item):
""" for a given path, add the path items. """
if path not in self._swagger:
self._swagger[path] = path_item
else:
for method, definition in path_item.items():
if definition is not None:
setattr(self._swagger[path], method, definition) | [
"def",
"add_path",
"(",
"self",
",",
"path",
",",
"path_item",
")",
":",
"if",
"path",
"not",
"in",
"self",
".",
"_swagger",
":",
"self",
".",
"_swagger",
"[",
"path",
"]",
"=",
"path_item",
"else",
":",
"for",
"method",
",",
"definition",
"in",
"pat... | for a given path, add the path items. | [
"for",
"a",
"given",
"path",
"add",
"the",
"path",
"items",
"."
] | train | https://github.com/toumorokoshi/transmute-core/blob/a2c26625d5d8bab37e00038f9d615a26167fc7f4/transmute_core/swagger/__init__.py#L59-L66 |
toumorokoshi/transmute-core | transmute_core/swagger/__init__.py | SwaggerSpec.swagger_definition | def swagger_definition(self, base_path=None, **kwargs):
"""
return a valid swagger spec, with the values passed.
"""
return Swagger(
{
"info": Info(
{
key: kwargs.get(key, self.DEFAULT_INFO.get(key))
for key in Info.fields.keys()
if key in kwargs or key in self.DEFAULT_INFO
}
),
"paths": self.paths,
"swagger": "2.0",
"basePath": base_path,
}
).to_primitive() | python | def swagger_definition(self, base_path=None, **kwargs):
"""
return a valid swagger spec, with the values passed.
"""
return Swagger(
{
"info": Info(
{
key: kwargs.get(key, self.DEFAULT_INFO.get(key))
for key in Info.fields.keys()
if key in kwargs or key in self.DEFAULT_INFO
}
),
"paths": self.paths,
"swagger": "2.0",
"basePath": base_path,
}
).to_primitive() | [
"def",
"swagger_definition",
"(",
"self",
",",
"base_path",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"Swagger",
"(",
"{",
"\"info\"",
":",
"Info",
"(",
"{",
"key",
":",
"kwargs",
".",
"get",
"(",
"key",
",",
"self",
".",
"DEFAULT_INF... | return a valid swagger spec, with the values passed. | [
"return",
"a",
"valid",
"swagger",
"spec",
"with",
"the",
"values",
"passed",
"."
] | train | https://github.com/toumorokoshi/transmute-core/blob/a2c26625d5d8bab37e00038f9d615a26167fc7f4/transmute_core/swagger/__init__.py#L76-L93 |
agoragames/chai | chai/spy.py | Spy._call_spy | def _call_spy(self, *args, **kwargs):
'''
Wrapper to call the spied-on function. Operates similar to
Expectation.test.
'''
if self._spy_side_effect:
if self._spy_side_effect_args or self._spy_side_effect_kwargs:
self._spy_side_effect(
*self._spy_side_effect_args,
**self._spy_side_effect_kwargs)
else:
self._spy_side_effect(*args, **kwargs)
return_value = self._stub.call_orig(*args, **kwargs)
if self._spy_return:
self._spy_return(return_value)
return return_value | python | def _call_spy(self, *args, **kwargs):
'''
Wrapper to call the spied-on function. Operates similar to
Expectation.test.
'''
if self._spy_side_effect:
if self._spy_side_effect_args or self._spy_side_effect_kwargs:
self._spy_side_effect(
*self._spy_side_effect_args,
**self._spy_side_effect_kwargs)
else:
self._spy_side_effect(*args, **kwargs)
return_value = self._stub.call_orig(*args, **kwargs)
if self._spy_return:
self._spy_return(return_value)
return return_value | [
"def",
"_call_spy",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"_spy_side_effect",
":",
"if",
"self",
".",
"_spy_side_effect_args",
"or",
"self",
".",
"_spy_side_effect_kwargs",
":",
"self",
".",
"_spy_side_effect",
... | Wrapper to call the spied-on function. Operates similar to
Expectation.test. | [
"Wrapper",
"to",
"call",
"the",
"spied",
"-",
"on",
"function",
".",
"Operates",
"similar",
"to",
"Expectation",
".",
"test",
"."
] | train | https://github.com/agoragames/chai/blob/8148d7b7754226b0d1cabfc2af10cd912612abdc/chai/spy.py#L24-L41 |
agoragames/chai | chai/spy.py | Spy.side_effect | def side_effect(self, func, *args, **kwargs):
'''
Wrap side effects for spies.
'''
self._spy_side_effect = func
self._spy_side_effect_args = args
self._spy_side_effect_kwargs = kwargs
return self | python | def side_effect(self, func, *args, **kwargs):
'''
Wrap side effects for spies.
'''
self._spy_side_effect = func
self._spy_side_effect_args = args
self._spy_side_effect_kwargs = kwargs
return self | [
"def",
"side_effect",
"(",
"self",
",",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_spy_side_effect",
"=",
"func",
"self",
".",
"_spy_side_effect_args",
"=",
"args",
"self",
".",
"_spy_side_effect_kwargs",
"=",
"kwargs",
"re... | Wrap side effects for spies. | [
"Wrap",
"side",
"effects",
"for",
"spies",
"."
] | train | https://github.com/agoragames/chai/blob/8148d7b7754226b0d1cabfc2af10cd912612abdc/chai/spy.py#L43-L50 |
dhondta/tinyscript | tinyscript/interact.py | set_interact_items | def set_interact_items(glob):
"""
This function prepares the interaction items for inclusion in main script's
global scope.
:param glob: main script's global scope dictionary reference
"""
a, l = glob['args'], glob['logger']
enabled = getattr(a, a._collisions.get("interact") or "interact", False)
if enabled:
readline.parse_and_bind('tab: complete')
# InteractiveConsole as defined in the code module, but handling a banner
# using the logging of tinyscript
class InteractiveConsole(BaseInteractiveConsole, object):
def __init__(self, banner=None, namespace=None, filename='<console>',
exitmsg=None):
if enabled:
self.banner = banner
self.exitmsg = exitmsg
ns = glob
ns.update(namespace or {})
super(InteractiveConsole, self).__init__(locals=ns,
filename=filename)
def __enter__(self):
if enabled and self.banner is not None:
l.interact(self.banner)
return self
def __exit__(self, *args):
if enabled and self.exitmsg is not None:
l.interact(self.exitmsg)
def interact(self, *args, **kwargs):
if enabled:
super(InteractiveConsole, self).interact(*args, **kwargs)
glob['InteractiveConsole'] = InteractiveConsole
def interact(banner=None, readfunc=None, namespace=None, exitmsg=None):
if enabled:
if banner is not None:
l.interact(banner)
ns = glob
ns.update(namespace or {})
base_interact(readfunc=readfunc, local=ns)
if exitmsg is not None:
l.interact(exitmsg)
glob['interact'] = interact
glob['compile_command'] = compile_command if enabled else \
lambda *a, **kw: None
# ConsoleSocket for handling duplicating std*** to a socket for the
# RemoteInteractiveConsole
host = getattr(a, a._collisions.get("host") or "host", None)
port = getattr(a, a._collisions.get("port") or "port", None)
# custom socket, for handling the bindings of stdXXX through a socket
class ConsoleSocket(socket.socket):
def readline(self, nbytes=2048):
return self.recv(nbytes)
def write(self, *args, **kwargs):
return self.send(*args, **kwargs)
# RemoteInteractiveConsole as defined in the code module, but handling
# interaction through a socket
class RemoteInteractiveConsole(InteractiveConsole):
def __init__(self, *args, **kwargs):
if enabled:
# open a socket
self.socket = ConsoleSocket()
self.socket.connect((str(host), port))
# save STDIN, STDOUT and STDERR
self.__stdin = sys.stdin
self.__stdout = sys.stdout
self.__stderr = sys.stderr
# rebind STDIN, STDOUT and STDERR to the socket
sys.stdin = sys.stdout = sys.stderr = self.socket
# now initialize the interactive console
super(RemoteInteractiveConsole, self).__init__(*args, **kwargs)
def __exit__(self, *args):
if enabled:
super(RemoteInteractiveConsole, self).__exit__(*args)
self.socket.close()
self.close()
def close(self):
if enabled:
# restore STDIN, STDOUT and STDERR
sys.stdin = self.__stdin
sys.stdout = self.__stdout
sys.stderr = self.__stderr
glob['RemoteInteractiveConsole'] = RemoteInteractiveConsole | python | def set_interact_items(glob):
"""
This function prepares the interaction items for inclusion in main script's
global scope.
:param glob: main script's global scope dictionary reference
"""
a, l = glob['args'], glob['logger']
enabled = getattr(a, a._collisions.get("interact") or "interact", False)
if enabled:
readline.parse_and_bind('tab: complete')
# InteractiveConsole as defined in the code module, but handling a banner
# using the logging of tinyscript
class InteractiveConsole(BaseInteractiveConsole, object):
def __init__(self, banner=None, namespace=None, filename='<console>',
exitmsg=None):
if enabled:
self.banner = banner
self.exitmsg = exitmsg
ns = glob
ns.update(namespace or {})
super(InteractiveConsole, self).__init__(locals=ns,
filename=filename)
def __enter__(self):
if enabled and self.banner is not None:
l.interact(self.banner)
return self
def __exit__(self, *args):
if enabled and self.exitmsg is not None:
l.interact(self.exitmsg)
def interact(self, *args, **kwargs):
if enabled:
super(InteractiveConsole, self).interact(*args, **kwargs)
glob['InteractiveConsole'] = InteractiveConsole
def interact(banner=None, readfunc=None, namespace=None, exitmsg=None):
if enabled:
if banner is not None:
l.interact(banner)
ns = glob
ns.update(namespace or {})
base_interact(readfunc=readfunc, local=ns)
if exitmsg is not None:
l.interact(exitmsg)
glob['interact'] = interact
glob['compile_command'] = compile_command if enabled else \
lambda *a, **kw: None
# ConsoleSocket for handling duplicating std*** to a socket for the
# RemoteInteractiveConsole
host = getattr(a, a._collisions.get("host") or "host", None)
port = getattr(a, a._collisions.get("port") or "port", None)
# custom socket, for handling the bindings of stdXXX through a socket
class ConsoleSocket(socket.socket):
def readline(self, nbytes=2048):
return self.recv(nbytes)
def write(self, *args, **kwargs):
return self.send(*args, **kwargs)
# RemoteInteractiveConsole as defined in the code module, but handling
# interaction through a socket
class RemoteInteractiveConsole(InteractiveConsole):
def __init__(self, *args, **kwargs):
if enabled:
# open a socket
self.socket = ConsoleSocket()
self.socket.connect((str(host), port))
# save STDIN, STDOUT and STDERR
self.__stdin = sys.stdin
self.__stdout = sys.stdout
self.__stderr = sys.stderr
# rebind STDIN, STDOUT and STDERR to the socket
sys.stdin = sys.stdout = sys.stderr = self.socket
# now initialize the interactive console
super(RemoteInteractiveConsole, self).__init__(*args, **kwargs)
def __exit__(self, *args):
if enabled:
super(RemoteInteractiveConsole, self).__exit__(*args)
self.socket.close()
self.close()
def close(self):
if enabled:
# restore STDIN, STDOUT and STDERR
sys.stdin = self.__stdin
sys.stdout = self.__stdout
sys.stderr = self.__stderr
glob['RemoteInteractiveConsole'] = RemoteInteractiveConsole | [
"def",
"set_interact_items",
"(",
"glob",
")",
":",
"a",
",",
"l",
"=",
"glob",
"[",
"'args'",
"]",
",",
"glob",
"[",
"'logger'",
"]",
"enabled",
"=",
"getattr",
"(",
"a",
",",
"a",
".",
"_collisions",
".",
"get",
"(",
"\"interact\"",
")",
"or",
"\... | This function prepares the interaction items for inclusion in main script's
global scope.
:param glob: main script's global scope dictionary reference | [
"This",
"function",
"prepares",
"the",
"interaction",
"items",
"for",
"inclusion",
"in",
"main",
"script",
"s",
"global",
"scope",
".",
":",
"param",
"glob",
":",
"main",
"script",
"s",
"global",
"scope",
"dictionary",
"reference"
] | train | https://github.com/dhondta/tinyscript/blob/624a0718db698899e7bc3ba6ac694baed251e81d/tinyscript/interact.py#L16-L114 |
dhondta/tinyscript | tinyscript/loglib.py | configure_logger | def configure_logger(glob, multi_level,
relative=False, logfile=None, syslog=False):
"""
Logger configuration function for setting either a simple debug mode or a
multi-level one.
:param glob: globals dictionary
:param multi_level: boolean telling if multi-level debug is to be considered
:param relative: use relative time for the logging messages
:param logfile: log file to be saved (None means do not log to file)
:param syslog: enable logging to /var/log/syslog
"""
levels = [logging.ERROR, logging.WARNING, logging.INFO, logging.DEBUG] \
if multi_level else [logging.INFO, logging.DEBUG]
try:
verbose = min(int(glob['args'].verbose), 3)
except AttributeError:
verbose = 0
glob['args']._debug_level = dl = levels[verbose]
logger.handlers = []
glob['logger'] = logger
handler = logging.StreamHandler()
formatter = logging.Formatter(glob['LOG_FORMAT'], glob['DATE_FORMAT'])
handler.setFormatter(formatter)
glob['logger'].addHandler(handler)
glob['logger'].setLevel(dl)
if relative:
coloredlogs.ColoredFormatter = RelativeTimeColoredFormatter
coloredlogs.install(dl,
logger=glob['logger'],
fmt=glob['LOG_FORMAT'],
datefmt=glob['DATE_FORMAT'],
milliseconds=glob['TIME_MILLISECONDS'],
syslog=syslog,
stream=logfile) | python | def configure_logger(glob, multi_level,
relative=False, logfile=None, syslog=False):
"""
Logger configuration function for setting either a simple debug mode or a
multi-level one.
:param glob: globals dictionary
:param multi_level: boolean telling if multi-level debug is to be considered
:param relative: use relative time for the logging messages
:param logfile: log file to be saved (None means do not log to file)
:param syslog: enable logging to /var/log/syslog
"""
levels = [logging.ERROR, logging.WARNING, logging.INFO, logging.DEBUG] \
if multi_level else [logging.INFO, logging.DEBUG]
try:
verbose = min(int(glob['args'].verbose), 3)
except AttributeError:
verbose = 0
glob['args']._debug_level = dl = levels[verbose]
logger.handlers = []
glob['logger'] = logger
handler = logging.StreamHandler()
formatter = logging.Formatter(glob['LOG_FORMAT'], glob['DATE_FORMAT'])
handler.setFormatter(formatter)
glob['logger'].addHandler(handler)
glob['logger'].setLevel(dl)
if relative:
coloredlogs.ColoredFormatter = RelativeTimeColoredFormatter
coloredlogs.install(dl,
logger=glob['logger'],
fmt=glob['LOG_FORMAT'],
datefmt=glob['DATE_FORMAT'],
milliseconds=glob['TIME_MILLISECONDS'],
syslog=syslog,
stream=logfile) | [
"def",
"configure_logger",
"(",
"glob",
",",
"multi_level",
",",
"relative",
"=",
"False",
",",
"logfile",
"=",
"None",
",",
"syslog",
"=",
"False",
")",
":",
"levels",
"=",
"[",
"logging",
".",
"ERROR",
",",
"logging",
".",
"WARNING",
",",
"logging",
... | Logger configuration function for setting either a simple debug mode or a
multi-level one.
:param glob: globals dictionary
:param multi_level: boolean telling if multi-level debug is to be considered
:param relative: use relative time for the logging messages
:param logfile: log file to be saved (None means do not log to file)
:param syslog: enable logging to /var/log/syslog | [
"Logger",
"configuration",
"function",
"for",
"setting",
"either",
"a",
"simple",
"debug",
"mode",
"or",
"a",
"multi",
"-",
"level",
"one",
".",
":",
"param",
"glob",
":",
"globals",
"dictionary",
":",
"param",
"multi_level",
":",
"boolean",
"telling",
"if",... | train | https://github.com/dhondta/tinyscript/blob/624a0718db698899e7bc3ba6ac694baed251e81d/tinyscript/loglib.py#L74-L108 |
toumorokoshi/transmute-core | transmute_core/handler.py | process_result | def process_result(transmute_func, context, result, exc, content_type):
"""
process a result:
transmute_func: the transmute_func function that returned the response.
context: the transmute_context to use.
result: the return value of the function, which will be serialized and
returned back in the API.
exc: the exception object. For Python 2, the traceback should
be attached via the __traceback__ attribute. This is done automatically
in Python 3.
content_type: the content type that request is requesting for a return type.
(e.g. application/json)
"""
if isinstance(result, Response):
response = result
else:
response = Response(
result=result, code=transmute_func.success_code, success=True
)
if exc:
if isinstance(exc, APIException):
response.result = str(exc)
response.success = False
response.code = exc.code
else:
reraise(type(exc), exc, getattr(exc, "__traceback__", None))
else:
return_type = transmute_func.get_response_by_code(response.code)
if return_type:
response.result = context.serializers.dump(return_type, response.result)
try:
content_type = str(content_type)
serializer = context.contenttype_serializers[content_type]
except NoSerializerFound:
serializer = context.contenttype_serializers.default
content_type = serializer.main_type
if response.success:
result = context.response_shape.create_body(attr.asdict(response))
response.result = result
else:
response.result = attr.asdict(response)
body = serializer.dump(response.result)
# keeping the return type a dict to
# reduce performance overhead.
return {
"body": body,
"code": response.code,
"content-type": content_type,
"headers": response.headers,
} | python | def process_result(transmute_func, context, result, exc, content_type):
"""
process a result:
transmute_func: the transmute_func function that returned the response.
context: the transmute_context to use.
result: the return value of the function, which will be serialized and
returned back in the API.
exc: the exception object. For Python 2, the traceback should
be attached via the __traceback__ attribute. This is done automatically
in Python 3.
content_type: the content type that request is requesting for a return type.
(e.g. application/json)
"""
if isinstance(result, Response):
response = result
else:
response = Response(
result=result, code=transmute_func.success_code, success=True
)
if exc:
if isinstance(exc, APIException):
response.result = str(exc)
response.success = False
response.code = exc.code
else:
reraise(type(exc), exc, getattr(exc, "__traceback__", None))
else:
return_type = transmute_func.get_response_by_code(response.code)
if return_type:
response.result = context.serializers.dump(return_type, response.result)
try:
content_type = str(content_type)
serializer = context.contenttype_serializers[content_type]
except NoSerializerFound:
serializer = context.contenttype_serializers.default
content_type = serializer.main_type
if response.success:
result = context.response_shape.create_body(attr.asdict(response))
response.result = result
else:
response.result = attr.asdict(response)
body = serializer.dump(response.result)
# keeping the return type a dict to
# reduce performance overhead.
return {
"body": body,
"code": response.code,
"content-type": content_type,
"headers": response.headers,
} | [
"def",
"process_result",
"(",
"transmute_func",
",",
"context",
",",
"result",
",",
"exc",
",",
"content_type",
")",
":",
"if",
"isinstance",
"(",
"result",
",",
"Response",
")",
":",
"response",
"=",
"result",
"else",
":",
"response",
"=",
"Response",
"("... | process a result:
transmute_func: the transmute_func function that returned the response.
context: the transmute_context to use.
result: the return value of the function, which will be serialized and
returned back in the API.
exc: the exception object. For Python 2, the traceback should
be attached via the __traceback__ attribute. This is done automatically
in Python 3.
content_type: the content type that request is requesting for a return type.
(e.g. application/json) | [
"process",
"a",
"result",
":"
] | train | https://github.com/toumorokoshi/transmute-core/blob/a2c26625d5d8bab37e00038f9d615a26167fc7f4/transmute_core/handler.py#L10-L64 |
LCAV/pylocus | pylocus/opt_space.py | opt_space | def opt_space(M_E, r=None, niter=50, tol=1e-6, print_out=False):
'''
Implementation of the OptSpace matrix completion algorithm.
An algorithm for Matrix Reconstruction from a partially revealed set.
Sparse treatment of matrices are removed because of indexing problems in Python.
Args:
M_E: 2D numpy array; The partially revealed matrix.
Matrix with zeroes at the unrevealed indices.
r: The rank to be used for reconstruction. If left empty, the rank is guessed in the program.
niter: Maximum number of iterations.
tol: Stop iterations if norm((XSY' - M_E) * E, 'fro') / sqrt(|E|) < tol, where
E_{ij} = 1 if M_{ij} is revealed and zero otherwise,
|E| is the size of the revealed set.
Returns: The following
X: A M_E.shape[0]xr numpy array
S: An rxr numpy array
Y: A M_E.shape[1]xr numpy matrix such that M_hat = X*S*Y'
errs: A vector containing norm((XSY' - M_E) * E, 'fro') / sqrt(|E|) at each iteration.
'''
n, m = M_E.shape
# construct the revealed set
E = np.zeros(M_E.shape)
E[np.nonzero(M_E)] = 1
eps = np.count_nonzero(E) / np.sqrt(m * n)
if r is None:
print('Rank not specified. Trying to guess ...')
r = guess_rank(M_E)
print('Using Rank : %d' % r)
m0 = 10000
rho = 0
rescal_param = np.sqrt(np.count_nonzero(
E) * r / np.linalg.norm(M_E, ord='fro')**2)
M_E = M_E * rescal_param
if print_out:
print('Trimming ...')
M_Et = copy.deepcopy(M_E)
d = E.sum(0)
d_ = np.mean(d)
for col in range(m):
if E[:, col].sum() > 2 * d_:
nonzero_ind_list = np.nonzero(E[:, col])
p = np.random.permutation(len(nonzero_ind_list))
M_Et[nonzero_ind_list[p[np.ceil(2 * d_):]], col] = 0
d = E.sum(1)
d_ = np.mean(d)
for row in range(n):
if E[row, :].sum() > 2 * d_:
nonzero_ind_list = np.nonzero(E[row, :])
p = np.random.permutation(len(nonzero_ind_list))
M_Et[nonzero_ind_list[row, p[np.ceil(2 * d_):]]] = 0
if print_out:
print('Sparse SVD ...')
X0, S0, Y0 = svds_descending(M_Et, r)
del M_Et
# Initial Guess
X0 = X0 * np.sqrt(n)
Y0 = Y0 * np.sqrt(m)
S0 = S0 / eps
if print_out:
print('Iteration\tFit Error')
# Gradient Descent
X = copy.deepcopy(X0)
Y = copy.deepcopy(Y0)
S = getoptS(X, Y, M_E, E)
errs = [None] * (niter + 1)
errs[0] = np.linalg.norm(
(M_E - np.dot(np.dot(X, S), Y.T)) * E, ord='fro') / np.sqrt(np.count_nonzero(E))
if print_out:
print('0\t\t\t%e' % errs[0])
for i in range(niter):
# Compute the Gradient
W, Z = gradF_t(X, Y, S, M_E, E, m0, rho)
# Line search for the optimum jump length
t = getoptT(X, W, Y, Z, S, M_E, E, m0, rho)
X = X + t * W
Y = Y + t * Z
S = getoptS(X, Y, M_E, E)
# Compute the distortion
errs[i + 1] = np.linalg.norm((M_E - np.dot(np.dot(X, S), Y.T))
* E, ord='fro') / np.sqrt(np.count_nonzero(E))
if print_out:
print('%d\t\t\t%e' % (i + 1, errs[i + 1]))
if abs(errs[i + 1] - errs[i]) < tol:
break
S = S / rescal_param
return X, S, Y, errs | python | def opt_space(M_E, r=None, niter=50, tol=1e-6, print_out=False):
'''
Implementation of the OptSpace matrix completion algorithm.
An algorithm for Matrix Reconstruction from a partially revealed set.
Sparse treatment of matrices are removed because of indexing problems in Python.
Args:
M_E: 2D numpy array; The partially revealed matrix.
Matrix with zeroes at the unrevealed indices.
r: The rank to be used for reconstruction. If left empty, the rank is guessed in the program.
niter: Maximum number of iterations.
tol: Stop iterations if norm((XSY' - M_E) * E, 'fro') / sqrt(|E|) < tol, where
E_{ij} = 1 if M_{ij} is revealed and zero otherwise,
|E| is the size of the revealed set.
Returns: The following
X: A M_E.shape[0]xr numpy array
S: An rxr numpy array
Y: A M_E.shape[1]xr numpy matrix such that M_hat = X*S*Y'
errs: A vector containing norm((XSY' - M_E) * E, 'fro') / sqrt(|E|) at each iteration.
'''
n, m = M_E.shape
# construct the revealed set
E = np.zeros(M_E.shape)
E[np.nonzero(M_E)] = 1
eps = np.count_nonzero(E) / np.sqrt(m * n)
if r is None:
print('Rank not specified. Trying to guess ...')
r = guess_rank(M_E)
print('Using Rank : %d' % r)
m0 = 10000
rho = 0
rescal_param = np.sqrt(np.count_nonzero(
E) * r / np.linalg.norm(M_E, ord='fro')**2)
M_E = M_E * rescal_param
if print_out:
print('Trimming ...')
M_Et = copy.deepcopy(M_E)
d = E.sum(0)
d_ = np.mean(d)
for col in range(m):
if E[:, col].sum() > 2 * d_:
nonzero_ind_list = np.nonzero(E[:, col])
p = np.random.permutation(len(nonzero_ind_list))
M_Et[nonzero_ind_list[p[np.ceil(2 * d_):]], col] = 0
d = E.sum(1)
d_ = np.mean(d)
for row in range(n):
if E[row, :].sum() > 2 * d_:
nonzero_ind_list = np.nonzero(E[row, :])
p = np.random.permutation(len(nonzero_ind_list))
M_Et[nonzero_ind_list[row, p[np.ceil(2 * d_):]]] = 0
if print_out:
print('Sparse SVD ...')
X0, S0, Y0 = svds_descending(M_Et, r)
del M_Et
# Initial Guess
X0 = X0 * np.sqrt(n)
Y0 = Y0 * np.sqrt(m)
S0 = S0 / eps
if print_out:
print('Iteration\tFit Error')
# Gradient Descent
X = copy.deepcopy(X0)
Y = copy.deepcopy(Y0)
S = getoptS(X, Y, M_E, E)
errs = [None] * (niter + 1)
errs[0] = np.linalg.norm(
(M_E - np.dot(np.dot(X, S), Y.T)) * E, ord='fro') / np.sqrt(np.count_nonzero(E))
if print_out:
print('0\t\t\t%e' % errs[0])
for i in range(niter):
# Compute the Gradient
W, Z = gradF_t(X, Y, S, M_E, E, m0, rho)
# Line search for the optimum jump length
t = getoptT(X, W, Y, Z, S, M_E, E, m0, rho)
X = X + t * W
Y = Y + t * Z
S = getoptS(X, Y, M_E, E)
# Compute the distortion
errs[i + 1] = np.linalg.norm((M_E - np.dot(np.dot(X, S), Y.T))
* E, ord='fro') / np.sqrt(np.count_nonzero(E))
if print_out:
print('%d\t\t\t%e' % (i + 1, errs[i + 1]))
if abs(errs[i + 1] - errs[i]) < tol:
break
S = S / rescal_param
return X, S, Y, errs | [
"def",
"opt_space",
"(",
"M_E",
",",
"r",
"=",
"None",
",",
"niter",
"=",
"50",
",",
"tol",
"=",
"1e-6",
",",
"print_out",
"=",
"False",
")",
":",
"n",
",",
"m",
"=",
"M_E",
".",
"shape",
"# construct the revealed set\r",
"E",
"=",
"np",
".",
"zero... | Implementation of the OptSpace matrix completion algorithm.
An algorithm for Matrix Reconstruction from a partially revealed set.
Sparse treatment of matrices are removed because of indexing problems in Python.
Args:
M_E: 2D numpy array; The partially revealed matrix.
Matrix with zeroes at the unrevealed indices.
r: The rank to be used for reconstruction. If left empty, the rank is guessed in the program.
niter: Maximum number of iterations.
tol: Stop iterations if norm((XSY' - M_E) * E, 'fro') / sqrt(|E|) < tol, where
E_{ij} = 1 if M_{ij} is revealed and zero otherwise,
|E| is the size of the revealed set.
Returns: The following
X: A M_E.shape[0]xr numpy array
S: An rxr numpy array
Y: A M_E.shape[1]xr numpy matrix such that M_hat = X*S*Y'
errs: A vector containing norm((XSY' - M_E) * E, 'fro') / sqrt(|E|) at each iteration. | [
"Implementation",
"of",
"the",
"OptSpace",
"matrix",
"completion",
"algorithm",
".",
"An",
"algorithm",
"for",
"Matrix",
"Reconstruction",
"from",
"a",
"partially",
"revealed",
"set",
".",
"Sparse",
"treatment",
"of",
"matrices",
"are",
"removed",
"because",
"of",... | train | https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/opt_space.py#L17-L121 |
LCAV/pylocus | pylocus/opt_space.py | svds_descending | def svds_descending(M, k):
'''
In contrast to MATLAB, numpy's svds() arranges the singular
values in ascending order. In order to have matching codes,
we wrap it around by a function which re-sorts the singular
values and singular vectors.
Args:
M: 2D numpy array; the matrix whose SVD is to be computed.
k: Number of singular values to be computed.
Returns:
u, s, vt = svds(M, k=k)
'''
u, s, vt = svds(M, k=k)
# reverse columns of u
u = u[:, ::-1]
# reverse s
s = s[::-1]
# reverse rows of vt
vt = vt[::-1, :]
return u, np.diag(s), vt.T | python | def svds_descending(M, k):
'''
In contrast to MATLAB, numpy's svds() arranges the singular
values in ascending order. In order to have matching codes,
we wrap it around by a function which re-sorts the singular
values and singular vectors.
Args:
M: 2D numpy array; the matrix whose SVD is to be computed.
k: Number of singular values to be computed.
Returns:
u, s, vt = svds(M, k=k)
'''
u, s, vt = svds(M, k=k)
# reverse columns of u
u = u[:, ::-1]
# reverse s
s = s[::-1]
# reverse rows of vt
vt = vt[::-1, :]
return u, np.diag(s), vt.T | [
"def",
"svds_descending",
"(",
"M",
",",
"k",
")",
":",
"u",
",",
"s",
",",
"vt",
"=",
"svds",
"(",
"M",
",",
"k",
"=",
"k",
")",
"# reverse columns of u\r",
"u",
"=",
"u",
"[",
":",
",",
":",
":",
"-",
"1",
"]",
"# reverse s\r",
"s",
"=",
"s... | In contrast to MATLAB, numpy's svds() arranges the singular
values in ascending order. In order to have matching codes,
we wrap it around by a function which re-sorts the singular
values and singular vectors.
Args:
M: 2D numpy array; the matrix whose SVD is to be computed.
k: Number of singular values to be computed.
Returns:
u, s, vt = svds(M, k=k) | [
"In",
"contrast",
"to",
"MATLAB",
"numpy",
"s",
"svds",
"()",
"arranges",
"the",
"singular",
"values",
"in",
"ascending",
"order",
".",
"In",
"order",
"to",
"have",
"matching",
"codes",
"we",
"wrap",
"it",
"around",
"by",
"a",
"function",
"which",
"re",
... | train | https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/opt_space.py#L124-L144 |
LCAV/pylocus | pylocus/opt_space.py | guess_rank | def guess_rank(M_E):
'''Guess the rank of the incomplete matrix '''
n, m = M_E.shape
epsilon = np.count_nonzero(M_E) / np.sqrt(m * n)
_, S0, _ = svds_descending(M_E, min(100, max(M_E.shape) - 1))
S0 = np.diag(S0)
S1 = S0[:-1] - S0[1:]
S1_ = S1 / np.mean(S1[-10:])
r1 = 0
lam = 0.05
cost = [None] * len(S1_)
while r1 <= 0:
for idx in range(len(S1_)):
cost[idx] = lam * max(S1_[idx:]) + idx
i2 = np.argmin(cost)
r1 = np.max(i2)
lam += 0.05
cost = [None] * (len(S0) - 1)
for idx in range(len(S0) - 1):
cost[idx] = (S0[idx + 1] + np.sqrt(idx * epsilon)
* S0[0] / epsilon) / S0[idx]
i2 = np.argmin(cost)
r2 = np.max(i2 + 1)
r = max([r1, r2])
return r | python | def guess_rank(M_E):
'''Guess the rank of the incomplete matrix '''
n, m = M_E.shape
epsilon = np.count_nonzero(M_E) / np.sqrt(m * n)
_, S0, _ = svds_descending(M_E, min(100, max(M_E.shape) - 1))
S0 = np.diag(S0)
S1 = S0[:-1] - S0[1:]
S1_ = S1 / np.mean(S1[-10:])
r1 = 0
lam = 0.05
cost = [None] * len(S1_)
while r1 <= 0:
for idx in range(len(S1_)):
cost[idx] = lam * max(S1_[idx:]) + idx
i2 = np.argmin(cost)
r1 = np.max(i2)
lam += 0.05
cost = [None] * (len(S0) - 1)
for idx in range(len(S0) - 1):
cost[idx] = (S0[idx + 1] + np.sqrt(idx * epsilon)
* S0[0] / epsilon) / S0[idx]
i2 = np.argmin(cost)
r2 = np.max(i2 + 1)
r = max([r1, r2])
return r | [
"def",
"guess_rank",
"(",
"M_E",
")",
":",
"n",
",",
"m",
"=",
"M_E",
".",
"shape",
"epsilon",
"=",
"np",
".",
"count_nonzero",
"(",
"M_E",
")",
"/",
"np",
".",
"sqrt",
"(",
"m",
"*",
"n",
")",
"_",
",",
"S0",
",",
"_",
"=",
"svds_descending",
... | Guess the rank of the incomplete matrix | [
"Guess",
"the",
"rank",
"of",
"the",
"incomplete",
"matrix"
] | train | https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/opt_space.py#L147-L174 |
LCAV/pylocus | pylocus/opt_space.py | F_t | def F_t(X, Y, S, M_E, E, m0, rho):
''' Compute the distortion '''
r = X.shape[1]
out1 = (((np.dot(np.dot(X, S), Y.T) - M_E) * E)**2).sum() / 2
out2 = rho * G(Y, m0, r)
out3 = rho * G(X, m0, r)
return out1 + out2 + out3 | python | def F_t(X, Y, S, M_E, E, m0, rho):
''' Compute the distortion '''
r = X.shape[1]
out1 = (((np.dot(np.dot(X, S), Y.T) - M_E) * E)**2).sum() / 2
out2 = rho * G(Y, m0, r)
out3 = rho * G(X, m0, r)
return out1 + out2 + out3 | [
"def",
"F_t",
"(",
"X",
",",
"Y",
",",
"S",
",",
"M_E",
",",
"E",
",",
"m0",
",",
"rho",
")",
":",
"r",
"=",
"X",
".",
"shape",
"[",
"1",
"]",
"out1",
"=",
"(",
"(",
"(",
"np",
".",
"dot",
"(",
"np",
".",
"dot",
"(",
"X",
",",
"S",
... | Compute the distortion | [
"Compute",
"the",
"distortion"
] | train | https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/opt_space.py#L177-L184 |
LCAV/pylocus | pylocus/opt_space.py | gradF_t | def gradF_t(X, Y, S, M_E, E, m0, rho):
''' Compute the gradient.
'''
n, r = X.shape
m, r = Y.shape
XS = np.dot(X, S)
YS = np.dot(Y, S.T)
XSY = np.dot(XS, Y.T)
Qx = np.dot(np.dot(X.T, ((M_E - XSY) * E)), YS) / n
Qy = np.dot(np.dot(Y.T, ((M_E - XSY) * E).T), XS) / m
W = np.dot((XSY - M_E) * E, YS) + np.dot(X, Qx) + rho * Gp(X, m0, r)
Z = np.dot(((XSY - M_E) * E).T, XS) + np.dot(Y, Qy) + rho * Gp(Y, m0, r)
return W, Z | python | def gradF_t(X, Y, S, M_E, E, m0, rho):
''' Compute the gradient.
'''
n, r = X.shape
m, r = Y.shape
XS = np.dot(X, S)
YS = np.dot(Y, S.T)
XSY = np.dot(XS, Y.T)
Qx = np.dot(np.dot(X.T, ((M_E - XSY) * E)), YS) / n
Qy = np.dot(np.dot(Y.T, ((M_E - XSY) * E).T), XS) / m
W = np.dot((XSY - M_E) * E, YS) + np.dot(X, Qx) + rho * Gp(X, m0, r)
Z = np.dot(((XSY - M_E) * E).T, XS) + np.dot(Y, Qy) + rho * Gp(Y, m0, r)
return W, Z | [
"def",
"gradF_t",
"(",
"X",
",",
"Y",
",",
"S",
",",
"M_E",
",",
"E",
",",
"m0",
",",
"rho",
")",
":",
"n",
",",
"r",
"=",
"X",
".",
"shape",
"m",
",",
"r",
"=",
"Y",
".",
"shape",
"XS",
"=",
"np",
".",
"dot",
"(",
"X",
",",
"S",
")",... | Compute the gradient. | [
"Compute",
"the",
"gradient",
"."
] | train | https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/opt_space.py#L195-L211 |
LCAV/pylocus | pylocus/opt_space.py | getoptS | def getoptS(X, Y, M_E, E):
''' Find Sopt given X, Y
'''
n, r = X.shape
C = np.dot(np.dot(X.T, M_E), Y)
C = C.flatten()
A = np.zeros((r * r, r * r))
for i in range(r):
for j in range(r):
ind = j * r + i
temp = np.dot(
np.dot(X.T, np.dot(X[:, i, None], Y[:, j, None].T) * E), Y)
A[:, ind] = temp.flatten()
S = np.linalg.solve(A, C)
return np.reshape(S, (r, r)).T | python | def getoptS(X, Y, M_E, E):
''' Find Sopt given X, Y
'''
n, r = X.shape
C = np.dot(np.dot(X.T, M_E), Y)
C = C.flatten()
A = np.zeros((r * r, r * r))
for i in range(r):
for j in range(r):
ind = j * r + i
temp = np.dot(
np.dot(X.T, np.dot(X[:, i, None], Y[:, j, None].T) * E), Y)
A[:, ind] = temp.flatten()
S = np.linalg.solve(A, C)
return np.reshape(S, (r, r)).T | [
"def",
"getoptS",
"(",
"X",
",",
"Y",
",",
"M_E",
",",
"E",
")",
":",
"n",
",",
"r",
"=",
"X",
".",
"shape",
"C",
"=",
"np",
".",
"dot",
"(",
"np",
".",
"dot",
"(",
"X",
".",
"T",
",",
"M_E",
")",
",",
"Y",
")",
"C",
"=",
"C",
".",
... | Find Sopt given X, Y | [
"Find",
"Sopt",
"given",
"X",
"Y"
] | train | https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/opt_space.py#L222-L239 |
LCAV/pylocus | pylocus/opt_space.py | getoptT | def getoptT(X, W, Y, Z, S, M_E, E, m0, rho):
''' Perform line search
'''
iter_max = 20
norm2WZ = np.linalg.norm(W, ord='fro')**2 + np.linalg.norm(Z, ord='fro')**2
f = np.zeros(iter_max + 1)
f[0] = F_t(X, Y, S, M_E, E, m0, rho)
t = -1e-1
for i in range(iter_max):
f[i + 1] = F_t(X + t * W, Y + t * Z, S, M_E, E, m0, rho)
if f[i + 1] - f[0] <= 0.5 * t * norm2WZ:
return t
t /= 2
return t | python | def getoptT(X, W, Y, Z, S, M_E, E, m0, rho):
''' Perform line search
'''
iter_max = 20
norm2WZ = np.linalg.norm(W, ord='fro')**2 + np.linalg.norm(Z, ord='fro')**2
f = np.zeros(iter_max + 1)
f[0] = F_t(X, Y, S, M_E, E, m0, rho)
t = -1e-1
for i in range(iter_max):
f[i + 1] = F_t(X + t * W, Y + t * Z, S, M_E, E, m0, rho)
if f[i + 1] - f[0] <= 0.5 * t * norm2WZ:
return t
t /= 2
return t | [
"def",
"getoptT",
"(",
"X",
",",
"W",
",",
"Y",
",",
"Z",
",",
"S",
",",
"M_E",
",",
"E",
",",
"m0",
",",
"rho",
")",
":",
"iter_max",
"=",
"20",
"norm2WZ",
"=",
"np",
".",
"linalg",
".",
"norm",
"(",
"W",
",",
"ord",
"=",
"'fro'",
")",
"... | Perform line search | [
"Perform",
"line",
"search"
] | train | https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/opt_space.py#L242-L257 |
LCAV/pylocus | pylocus/mds.py | MDS | def MDS(D, dim, method='simple', theta=False):
""" recover points from euclidean distance matrix using classic MDS algorithm.
"""
N = D.shape[0]
if method == 'simple':
d1 = D[0, :]
# buf_ = d1 * np.ones([1, N]).T + (np.ones([N, 1]) * d1).T
buf_ = np.broadcast_to(d1, D.shape) + np.broadcast_to(d1[:, np.newaxis], D.shape)
np.subtract(D, buf_, out=buf_)
G = buf_ # G = (D - d1 * np.ones([1, N]).T - (np.ones([N, 1]) * d1).T)
elif method == 'advanced':
# s1T = np.vstack([np.ones([1, N]), np.zeros([N - 1, N])])
s1T = np.zeros_like(D)
s1T[0, :] = 1
np.subtract(np.identity(N), s1T, out = s1T)
G = np.dot(np.dot(s1T.T, D), s1T)
elif method == 'geometric':
J = np.identity(N) + np.full((N, N), -1.0 / float(N))
G = np.dot(np.dot(J, D), J)
else:
print('Unknown method {} in MDS'.format(method))
G *= -0.5
factor, u = eigendecomp(G, dim)
if (theta):
return theta_from_eigendecomp(factor, u)
else:
return x_from_eigendecomp(factor, u, dim) | python | def MDS(D, dim, method='simple', theta=False):
""" recover points from euclidean distance matrix using classic MDS algorithm.
"""
N = D.shape[0]
if method == 'simple':
d1 = D[0, :]
# buf_ = d1 * np.ones([1, N]).T + (np.ones([N, 1]) * d1).T
buf_ = np.broadcast_to(d1, D.shape) + np.broadcast_to(d1[:, np.newaxis], D.shape)
np.subtract(D, buf_, out=buf_)
G = buf_ # G = (D - d1 * np.ones([1, N]).T - (np.ones([N, 1]) * d1).T)
elif method == 'advanced':
# s1T = np.vstack([np.ones([1, N]), np.zeros([N - 1, N])])
s1T = np.zeros_like(D)
s1T[0, :] = 1
np.subtract(np.identity(N), s1T, out = s1T)
G = np.dot(np.dot(s1T.T, D), s1T)
elif method == 'geometric':
J = np.identity(N) + np.full((N, N), -1.0 / float(N))
G = np.dot(np.dot(J, D), J)
else:
print('Unknown method {} in MDS'.format(method))
G *= -0.5
factor, u = eigendecomp(G, dim)
if (theta):
return theta_from_eigendecomp(factor, u)
else:
return x_from_eigendecomp(factor, u, dim) | [
"def",
"MDS",
"(",
"D",
",",
"dim",
",",
"method",
"=",
"'simple'",
",",
"theta",
"=",
"False",
")",
":",
"N",
"=",
"D",
".",
"shape",
"[",
"0",
"]",
"if",
"method",
"==",
"'simple'",
":",
"d1",
"=",
"D",
"[",
"0",
",",
":",
"]",
"# buf_ = d1... | recover points from euclidean distance matrix using classic MDS algorithm. | [
"recover",
"points",
"from",
"euclidean",
"distance",
"matrix",
"using",
"classic",
"MDS",
"algorithm",
"."
] | train | https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/mds.py#L22-L48 |
LCAV/pylocus | pylocus/mds.py | superMDS | def superMDS(X0, N, d, **kwargs):
""" Find the set of points from an edge kernel.
"""
Om = kwargs.get('Om', None)
dm = kwargs.get('dm', None)
if Om is not None and dm is not None:
KE = kwargs.get('KE', None)
if KE is not None:
print('superMDS: KE and Om, dm given. Continuing with Om, dm')
factor, u = eigendecomp(Om, d)
uhat = u[:, :d]
lambdahat = np.diag(factor[:d])
diag_dm = np.diag(dm)
Vhat = np.dot(diag_dm, np.dot(uhat, lambdahat))
elif Om is None or dm is None:
KE = kwargs.get('KE', None)
if KE is None:
raise NameError('Either KE or Om and dm have to be given.')
factor, u = eigendecomp(KE, d)
lambda_ = np.diag(factor)
Vhat = np.dot(u, lambda_)[:, :d]
C_inv = -np.eye(N)
C_inv[0, 0] = 1.0
C_inv[:, 0] = 1.0
b = np.zeros((C_inv.shape[1], d))
b[0, :] = X0
b[1:, :] = Vhat[:N - 1, :]
Xhat = np.dot(C_inv, b)
return Xhat, Vhat | python | def superMDS(X0, N, d, **kwargs):
""" Find the set of points from an edge kernel.
"""
Om = kwargs.get('Om', None)
dm = kwargs.get('dm', None)
if Om is not None and dm is not None:
KE = kwargs.get('KE', None)
if KE is not None:
print('superMDS: KE and Om, dm given. Continuing with Om, dm')
factor, u = eigendecomp(Om, d)
uhat = u[:, :d]
lambdahat = np.diag(factor[:d])
diag_dm = np.diag(dm)
Vhat = np.dot(diag_dm, np.dot(uhat, lambdahat))
elif Om is None or dm is None:
KE = kwargs.get('KE', None)
if KE is None:
raise NameError('Either KE or Om and dm have to be given.')
factor, u = eigendecomp(KE, d)
lambda_ = np.diag(factor)
Vhat = np.dot(u, lambda_)[:, :d]
C_inv = -np.eye(N)
C_inv[0, 0] = 1.0
C_inv[:, 0] = 1.0
b = np.zeros((C_inv.shape[1], d))
b[0, :] = X0
b[1:, :] = Vhat[:N - 1, :]
Xhat = np.dot(C_inv, b)
return Xhat, Vhat | [
"def",
"superMDS",
"(",
"X0",
",",
"N",
",",
"d",
",",
"*",
"*",
"kwargs",
")",
":",
"Om",
"=",
"kwargs",
".",
"get",
"(",
"'Om'",
",",
"None",
")",
"dm",
"=",
"kwargs",
".",
"get",
"(",
"'dm'",
",",
"None",
")",
"if",
"Om",
"is",
"not",
"N... | Find the set of points from an edge kernel. | [
"Find",
"the",
"set",
"of",
"points",
"from",
"an",
"edge",
"kernel",
"."
] | train | https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/mds.py#L51-L80 |
LCAV/pylocus | pylocus/mds.py | iterativeEMDS | def iterativeEMDS(X0, N, d, C, b, max_it=10, print_out=False, **kwargs):
""" Find the set of points from an edge kernel with geometric constraints, using iterative projection
"""
from pylocus.basics import mse, projection
KE = kwargs.get('KE', None)
KE_projected = KE.copy()
d = len(X0)
for i in range(max_it):
# projection on constraints
KE_projected, cost, __ = projection(KE_projected, C, b)
rank = np.linalg.matrix_rank(KE_projected)
# rank 2 decomposition
Xhat_KE, Vhat_KE = superMDS(X0, N, d, KE=KE_projected)
KE_projected = Vhat_KE.dot(Vhat_KE.T)
error = mse(C.dot(KE_projected), b)
if (print_out):
print('cost={:2.2e},error={:2.2e}, rank={}'.format(
cost, error, rank))
if cost < 1e-20 and error < 1e-20 and rank == d:
if (print_out):
print('converged after {} iterations'.format(i))
return Xhat_KE, Vhat_KE
print('iterativeMDS did not converge!')
return None, None | python | def iterativeEMDS(X0, N, d, C, b, max_it=10, print_out=False, **kwargs):
""" Find the set of points from an edge kernel with geometric constraints, using iterative projection
"""
from pylocus.basics import mse, projection
KE = kwargs.get('KE', None)
KE_projected = KE.copy()
d = len(X0)
for i in range(max_it):
# projection on constraints
KE_projected, cost, __ = projection(KE_projected, C, b)
rank = np.linalg.matrix_rank(KE_projected)
# rank 2 decomposition
Xhat_KE, Vhat_KE = superMDS(X0, N, d, KE=KE_projected)
KE_projected = Vhat_KE.dot(Vhat_KE.T)
error = mse(C.dot(KE_projected), b)
if (print_out):
print('cost={:2.2e},error={:2.2e}, rank={}'.format(
cost, error, rank))
if cost < 1e-20 and error < 1e-20 and rank == d:
if (print_out):
print('converged after {} iterations'.format(i))
return Xhat_KE, Vhat_KE
print('iterativeMDS did not converge!')
return None, None | [
"def",
"iterativeEMDS",
"(",
"X0",
",",
"N",
",",
"d",
",",
"C",
",",
"b",
",",
"max_it",
"=",
"10",
",",
"print_out",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"pylocus",
".",
"basics",
"import",
"mse",
",",
"projection",
"KE",
"=... | Find the set of points from an edge kernel with geometric constraints, using iterative projection | [
"Find",
"the",
"set",
"of",
"points",
"from",
"an",
"edge",
"kernel",
"with",
"geometric",
"constraints",
"using",
"iterative",
"projection"
] | train | https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/mds.py#L83-L109 |
LCAV/pylocus | pylocus/mds.py | relaxedEMDS | def relaxedEMDS(X0, N, d, C, b, KE, print_out=False, lamda=10):
""" Find the set of points from an edge kernel with geometric constraints, using convex rank relaxation.
"""
E = C.shape[1]
X = Variable((E, E), PSD=True)
constraints = [C[i, :] * X == b[i] for i in range(C.shape[0])]
obj = Minimize(trace(X) + lamda * norm(KE - X))
prob = Problem(obj, constraints)
try:
# CVXOPT is more accurate than SCS, even though slower.
total_cost = prob.solve(solver='CVXOPT', verbose=print_out)
except:
try:
print('CVXOPT with default cholesky failed. Trying kktsolver...')
# kktsolver is more robust than default (cholesky), even though slower.
total_cost = prob.solve(
solver='CVXOPT', verbose=print_out, kktsolver="robust")
except:
try:
print('CVXOPT with robust kktsovler failed. Trying SCS...')
# SCS is fast and robust, but inaccurate (last choice).
total_cost = prob.solve(solver='SCS', verbose=print_out)
except:
print('SCS and CVXOPT solver with default and kktsolver failed .')
if print_out:
print('status:', prob.status)
Xhat_KE, Vhat_KE = superMDS(X0, N, d, KE=X.value)
return Xhat_KE, Vhat_KE | python | def relaxedEMDS(X0, N, d, C, b, KE, print_out=False, lamda=10):
""" Find the set of points from an edge kernel with geometric constraints, using convex rank relaxation.
"""
E = C.shape[1]
X = Variable((E, E), PSD=True)
constraints = [C[i, :] * X == b[i] for i in range(C.shape[0])]
obj = Minimize(trace(X) + lamda * norm(KE - X))
prob = Problem(obj, constraints)
try:
# CVXOPT is more accurate than SCS, even though slower.
total_cost = prob.solve(solver='CVXOPT', verbose=print_out)
except:
try:
print('CVXOPT with default cholesky failed. Trying kktsolver...')
# kktsolver is more robust than default (cholesky), even though slower.
total_cost = prob.solve(
solver='CVXOPT', verbose=print_out, kktsolver="robust")
except:
try:
print('CVXOPT with robust kktsovler failed. Trying SCS...')
# SCS is fast and robust, but inaccurate (last choice).
total_cost = prob.solve(solver='SCS', verbose=print_out)
except:
print('SCS and CVXOPT solver with default and kktsolver failed .')
if print_out:
print('status:', prob.status)
Xhat_KE, Vhat_KE = superMDS(X0, N, d, KE=X.value)
return Xhat_KE, Vhat_KE | [
"def",
"relaxedEMDS",
"(",
"X0",
",",
"N",
",",
"d",
",",
"C",
",",
"b",
",",
"KE",
",",
"print_out",
"=",
"False",
",",
"lamda",
"=",
"10",
")",
":",
"E",
"=",
"C",
".",
"shape",
"[",
"1",
"]",
"X",
"=",
"Variable",
"(",
"(",
"E",
",",
"... | Find the set of points from an edge kernel with geometric constraints, using convex rank relaxation. | [
"Find",
"the",
"set",
"of",
"points",
"from",
"an",
"edge",
"kernel",
"with",
"geometric",
"constraints",
"using",
"convex",
"rank",
"relaxation",
"."
] | train | https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/mds.py#L112-L142 |
LCAV/pylocus | pylocus/mds.py | signedMDS | def signedMDS(cdm, W=None):
""" Find the set of points from a cdm.
"""
N = cdm.shape[0]
D_sym = (cdm - cdm.T)
D_sym /= 2
if W is None:
x_est = np.mean(D_sym, axis=1)
x_est -= np.min(x_est)
return x_est
W_sub = W[1:, 1:]
sum_W = np.sum(W[1:, :], axis=1)
# A = np.eye(N, N-1, k=-1) - W_sub.astype(np.int) / sum_W[:, None]
A = np.eye(N - 1) - W_sub.astype(np.int) / 1. / sum_W[:, None]
d = (np.sum(D_sym[1:, :] * W[1:, :], axis=1) / 1. / sum_W)
x_est = np.linalg.lstsq(A, d)[0]
x_est = np.r_[[0], x_est]
x_est -= np.min(x_est)
return x_est, A, np.linalg.pinv(A) | python | def signedMDS(cdm, W=None):
""" Find the set of points from a cdm.
"""
N = cdm.shape[0]
D_sym = (cdm - cdm.T)
D_sym /= 2
if W is None:
x_est = np.mean(D_sym, axis=1)
x_est -= np.min(x_est)
return x_est
W_sub = W[1:, 1:]
sum_W = np.sum(W[1:, :], axis=1)
# A = np.eye(N, N-1, k=-1) - W_sub.astype(np.int) / sum_W[:, None]
A = np.eye(N - 1) - W_sub.astype(np.int) / 1. / sum_W[:, None]
d = (np.sum(D_sym[1:, :] * W[1:, :], axis=1) / 1. / sum_W)
x_est = np.linalg.lstsq(A, d)[0]
x_est = np.r_[[0], x_est]
x_est -= np.min(x_est)
return x_est, A, np.linalg.pinv(A) | [
"def",
"signedMDS",
"(",
"cdm",
",",
"W",
"=",
"None",
")",
":",
"N",
"=",
"cdm",
".",
"shape",
"[",
"0",
"]",
"D_sym",
"=",
"(",
"cdm",
"-",
"cdm",
".",
"T",
")",
"D_sym",
"/=",
"2",
"if",
"W",
"is",
"None",
":",
"x_est",
"=",
"np",
".",
... | Find the set of points from a cdm. | [
"Find",
"the",
"set",
"of",
"points",
"from",
"a",
"cdm",
"."
] | train | https://github.com/LCAV/pylocus/blob/c56a38c251d8a435caf4641a8ae6027ecba2c8c6/pylocus/mds.py#L145-L170 |
agoragames/chai | chai/stub.py | _stub_attr | def _stub_attr(obj, attr_name):
'''
Stub an attribute of an object. Will return an existing stub if
there already is one.
'''
# Annoying circular reference requires importing here. Would like to see
# this cleaned up. @AW
from .mock import Mock
# Check to see if this a property, this check is only for when dealing
# with an instance. getattr will work for classes.
is_property = False
if not inspect.isclass(obj) and not inspect.ismodule(obj):
# It's possible that the attribute is defined after initialization, and
# so is not on the class itself.
attr = getattr(obj.__class__, attr_name, None)
if isinstance(attr, property):
is_property = True
if not is_property:
attr = getattr(obj, attr_name)
# Return an existing stub
if isinstance(attr, Stub):
return attr
# If a Mock object, stub its __call__
if isinstance(attr, Mock):
return stub(attr.__call__)
if isinstance(attr, property):
return StubProperty(obj, attr_name)
# Sadly, builtin functions and methods have the same type, so we have to
# use the same stub class even though it's a bit ugly
if inspect.ismodule(obj) and isinstance(attr, (types.FunctionType,
types.BuiltinFunctionType,
types.BuiltinMethodType)):
return StubFunction(obj, attr_name)
# In python3 unbound methods are treated as functions with no reference
# back to the parent class and no im_* fields. We can still make unbound
# methods work by passing these through to the stub
if inspect.isclass(obj) and isinstance(attr, types.FunctionType):
return StubUnboundMethod(obj, attr_name)
# I thought that types.UnboundMethodType differentiated these cases but
# apparently not.
if isinstance(attr, types.MethodType):
# Handle differently if unbound because it's an implicit "any instance"
if getattr(attr, 'im_self', None) is None:
# Handle the python3 case and py2 filter
if hasattr(attr, '__self__'):
if attr.__self__ is not None:
return StubMethod(obj, attr_name)
if sys.version_info.major == 2:
return StubUnboundMethod(attr)
else:
return StubMethod(obj, attr_name)
if isinstance(attr, (types.BuiltinFunctionType, types.BuiltinMethodType)):
return StubFunction(obj, attr_name)
# What an absurd type this is ....
if type(attr).__name__ == 'method-wrapper':
return StubMethodWrapper(attr)
# This is also slot_descriptor
if type(attr).__name__ == 'wrapper_descriptor':
return StubWrapperDescriptor(obj, attr_name)
raise UnsupportedStub(
"can't stub %s(%s) of %s", attr_name, type(attr), obj) | python | def _stub_attr(obj, attr_name):
'''
Stub an attribute of an object. Will return an existing stub if
there already is one.
'''
# Annoying circular reference requires importing here. Would like to see
# this cleaned up. @AW
from .mock import Mock
# Check to see if this a property, this check is only for when dealing
# with an instance. getattr will work for classes.
is_property = False
if not inspect.isclass(obj) and not inspect.ismodule(obj):
# It's possible that the attribute is defined after initialization, and
# so is not on the class itself.
attr = getattr(obj.__class__, attr_name, None)
if isinstance(attr, property):
is_property = True
if not is_property:
attr = getattr(obj, attr_name)
# Return an existing stub
if isinstance(attr, Stub):
return attr
# If a Mock object, stub its __call__
if isinstance(attr, Mock):
return stub(attr.__call__)
if isinstance(attr, property):
return StubProperty(obj, attr_name)
# Sadly, builtin functions and methods have the same type, so we have to
# use the same stub class even though it's a bit ugly
if inspect.ismodule(obj) and isinstance(attr, (types.FunctionType,
types.BuiltinFunctionType,
types.BuiltinMethodType)):
return StubFunction(obj, attr_name)
# In python3 unbound methods are treated as functions with no reference
# back to the parent class and no im_* fields. We can still make unbound
# methods work by passing these through to the stub
if inspect.isclass(obj) and isinstance(attr, types.FunctionType):
return StubUnboundMethod(obj, attr_name)
# I thought that types.UnboundMethodType differentiated these cases but
# apparently not.
if isinstance(attr, types.MethodType):
# Handle differently if unbound because it's an implicit "any instance"
if getattr(attr, 'im_self', None) is None:
# Handle the python3 case and py2 filter
if hasattr(attr, '__self__'):
if attr.__self__ is not None:
return StubMethod(obj, attr_name)
if sys.version_info.major == 2:
return StubUnboundMethod(attr)
else:
return StubMethod(obj, attr_name)
if isinstance(attr, (types.BuiltinFunctionType, types.BuiltinMethodType)):
return StubFunction(obj, attr_name)
# What an absurd type this is ....
if type(attr).__name__ == 'method-wrapper':
return StubMethodWrapper(attr)
# This is also slot_descriptor
if type(attr).__name__ == 'wrapper_descriptor':
return StubWrapperDescriptor(obj, attr_name)
raise UnsupportedStub(
"can't stub %s(%s) of %s", attr_name, type(attr), obj) | [
"def",
"_stub_attr",
"(",
"obj",
",",
"attr_name",
")",
":",
"# Annoying circular reference requires importing here. Would like to see",
"# this cleaned up. @AW",
"from",
".",
"mock",
"import",
"Mock",
"# Check to see if this a property, this check is only for when dealing",
"# with ... | Stub an attribute of an object. Will return an existing stub if
there already is one. | [
"Stub",
"an",
"attribute",
"of",
"an",
"object",
".",
"Will",
"return",
"an",
"existing",
"stub",
"if",
"there",
"already",
"is",
"one",
"."
] | train | https://github.com/agoragames/chai/blob/8148d7b7754226b0d1cabfc2af10cd912612abdc/chai/stub.py#L32-L105 |
agoragames/chai | chai/stub.py | _stub_obj | def _stub_obj(obj):
'''
Stub an object directly.
'''
# Annoying circular reference requires importing here. Would like to see
# this cleaned up. @AW
from .mock import Mock
# Return an existing stub
if isinstance(obj, Stub):
return obj
# If a Mock object, stub its __call__
if isinstance(obj, Mock):
return stub(obj.__call__)
# If passed-in a type, assume that we're going to stub out the creation.
# See StubNew for the awesome sauce.
# if isinstance(obj, types.TypeType):
if hasattr(types, 'TypeType') and isinstance(obj, types.TypeType):
return StubNew(obj)
elif hasattr(__builtins__, 'type') and \
isinstance(obj, __builtins__.type):
return StubNew(obj)
elif inspect.isclass(obj):
return StubNew(obj)
# I thought that types.UnboundMethodType differentiated these cases but
# apparently not.
if isinstance(obj, types.MethodType):
# Handle differently if unbound because it's an implicit "any instance"
if getattr(obj, 'im_self', None) is None:
# Handle the python3 case and py2 filter
if hasattr(obj, '__self__'):
if obj.__self__ is not None:
return StubMethod(obj)
if sys.version_info.major == 2:
return StubUnboundMethod(obj)
else:
return StubMethod(obj)
# These aren't in the types library
if type(obj).__name__ == 'method-wrapper':
return StubMethodWrapper(obj)
if type(obj).__name__ == 'wrapper_descriptor':
raise UnsupportedStub(
"must call stub(obj,'%s') for slot wrapper on %s",
obj.__name__, obj.__objclass__.__name__)
# (Mostly) Lastly, look for properties.
# First look for the situation where there's a reference back to the
# property.
prop = obj
if isinstance(getattr(obj, '__self__', None), property):
obj = prop.__self__
# Once we've found a property, we have to figure out how to reference
# back to the owning class. This is a giant pain and we have to use gc
# to find out where it comes from. This code is dense but resolves to
# something like this:
# >>> gc.get_referrers( foo.x )
# [{'__dict__': <attribute '__dict__' of 'foo' objects>,
# 'x': <property object at 0x7f68c99a16d8>,
# '__module__': '__main__',
# '__weakref__': <attribute '__weakref__' of 'foo' objects>,
# '__doc__': None}]
if isinstance(obj, property):
klass, attr = None, None
for ref in gc.get_referrers(obj):
if klass and attr:
break
if isinstance(ref, dict) and ref.get('prop', None) is obj:
klass = getattr(
ref.get('__dict__', None), '__objclass__', None)
for name, val in getattr(klass, '__dict__', {}).items():
if val is obj:
attr = name
break
# In the case of PyPy, we have to check all types that refer to
# the property, and see if any of their attrs are the property
elif isinstance(ref, type):
# Use dir as a means to quickly walk through the class tree
for name in dir(ref):
if getattr(ref, name) == obj:
klass = ref
attr = name
break
if klass and attr:
rval = stub(klass, attr)
if prop != obj:
return stub(rval, prop.__name__)
return rval
# If a function and it has an associated module, we can mock directly.
# Note that this *must* be after properties, otherwise it conflicts with
# stubbing out the deleter methods and such
# Sadly, builtin functions and methods have the same type, so we have to
# use the same stub class even though it's a bit ugly
if isinstance(obj, (types.FunctionType, types.BuiltinFunctionType,
types.BuiltinMethodType)) and hasattr(obj, '__module__'):
return StubFunction(obj)
raise UnsupportedStub("can't stub %s", obj) | python | def _stub_obj(obj):
'''
Stub an object directly.
'''
# Annoying circular reference requires importing here. Would like to see
# this cleaned up. @AW
from .mock import Mock
# Return an existing stub
if isinstance(obj, Stub):
return obj
# If a Mock object, stub its __call__
if isinstance(obj, Mock):
return stub(obj.__call__)
# If passed-in a type, assume that we're going to stub out the creation.
# See StubNew for the awesome sauce.
# if isinstance(obj, types.TypeType):
if hasattr(types, 'TypeType') and isinstance(obj, types.TypeType):
return StubNew(obj)
elif hasattr(__builtins__, 'type') and \
isinstance(obj, __builtins__.type):
return StubNew(obj)
elif inspect.isclass(obj):
return StubNew(obj)
# I thought that types.UnboundMethodType differentiated these cases but
# apparently not.
if isinstance(obj, types.MethodType):
# Handle differently if unbound because it's an implicit "any instance"
if getattr(obj, 'im_self', None) is None:
# Handle the python3 case and py2 filter
if hasattr(obj, '__self__'):
if obj.__self__ is not None:
return StubMethod(obj)
if sys.version_info.major == 2:
return StubUnboundMethod(obj)
else:
return StubMethod(obj)
# These aren't in the types library
if type(obj).__name__ == 'method-wrapper':
return StubMethodWrapper(obj)
if type(obj).__name__ == 'wrapper_descriptor':
raise UnsupportedStub(
"must call stub(obj,'%s') for slot wrapper on %s",
obj.__name__, obj.__objclass__.__name__)
# (Mostly) Lastly, look for properties.
# First look for the situation where there's a reference back to the
# property.
prop = obj
if isinstance(getattr(obj, '__self__', None), property):
obj = prop.__self__
# Once we've found a property, we have to figure out how to reference
# back to the owning class. This is a giant pain and we have to use gc
# to find out where it comes from. This code is dense but resolves to
# something like this:
# >>> gc.get_referrers( foo.x )
# [{'__dict__': <attribute '__dict__' of 'foo' objects>,
# 'x': <property object at 0x7f68c99a16d8>,
# '__module__': '__main__',
# '__weakref__': <attribute '__weakref__' of 'foo' objects>,
# '__doc__': None}]
if isinstance(obj, property):
klass, attr = None, None
for ref in gc.get_referrers(obj):
if klass and attr:
break
if isinstance(ref, dict) and ref.get('prop', None) is obj:
klass = getattr(
ref.get('__dict__', None), '__objclass__', None)
for name, val in getattr(klass, '__dict__', {}).items():
if val is obj:
attr = name
break
# In the case of PyPy, we have to check all types that refer to
# the property, and see if any of their attrs are the property
elif isinstance(ref, type):
# Use dir as a means to quickly walk through the class tree
for name in dir(ref):
if getattr(ref, name) == obj:
klass = ref
attr = name
break
if klass and attr:
rval = stub(klass, attr)
if prop != obj:
return stub(rval, prop.__name__)
return rval
# If a function and it has an associated module, we can mock directly.
# Note that this *must* be after properties, otherwise it conflicts with
# stubbing out the deleter methods and such
# Sadly, builtin functions and methods have the same type, so we have to
# use the same stub class even though it's a bit ugly
if isinstance(obj, (types.FunctionType, types.BuiltinFunctionType,
types.BuiltinMethodType)) and hasattr(obj, '__module__'):
return StubFunction(obj)
raise UnsupportedStub("can't stub %s", obj) | [
"def",
"_stub_obj",
"(",
"obj",
")",
":",
"# Annoying circular reference requires importing here. Would like to see",
"# this cleaned up. @AW",
"from",
".",
"mock",
"import",
"Mock",
"# Return an existing stub",
"if",
"isinstance",
"(",
"obj",
",",
"Stub",
")",
":",
"retu... | Stub an object directly. | [
"Stub",
"an",
"object",
"directly",
"."
] | train | https://github.com/agoragames/chai/blob/8148d7b7754226b0d1cabfc2af10cd912612abdc/chai/stub.py#L108-L212 |
agoragames/chai | chai/stub.py | Stub.unmet_expectations | def unmet_expectations(self):
'''
Assert that all expectations on the stub have been met.
'''
unmet = []
for exp in self._expectations:
if not exp.closed(with_counts=True):
unmet.append(ExpectationNotSatisfied(exp))
return unmet | python | def unmet_expectations(self):
'''
Assert that all expectations on the stub have been met.
'''
unmet = []
for exp in self._expectations:
if not exp.closed(with_counts=True):
unmet.append(ExpectationNotSatisfied(exp))
return unmet | [
"def",
"unmet_expectations",
"(",
"self",
")",
":",
"unmet",
"=",
"[",
"]",
"for",
"exp",
"in",
"self",
".",
"_expectations",
":",
"if",
"not",
"exp",
".",
"closed",
"(",
"with_counts",
"=",
"True",
")",
":",
"unmet",
".",
"append",
"(",
"ExpectationNo... | Assert that all expectations on the stub have been met. | [
"Assert",
"that",
"all",
"expectations",
"on",
"the",
"stub",
"have",
"been",
"met",
"."
] | train | https://github.com/agoragames/chai/blob/8148d7b7754226b0d1cabfc2af10cd912612abdc/chai/stub.py#L238-L246 |
agoragames/chai | chai/stub.py | Stub.teardown | def teardown(self):
'''
Clean up all expectations and restore the original attribute of the
mocked object.
'''
if not self._torn:
self._expectations = []
self._torn = True
self._teardown() | python | def teardown(self):
'''
Clean up all expectations and restore the original attribute of the
mocked object.
'''
if not self._torn:
self._expectations = []
self._torn = True
self._teardown() | [
"def",
"teardown",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_torn",
":",
"self",
".",
"_expectations",
"=",
"[",
"]",
"self",
".",
"_torn",
"=",
"True",
"self",
".",
"_teardown",
"(",
")"
] | Clean up all expectations and restore the original attribute of the
mocked object. | [
"Clean",
"up",
"all",
"expectations",
"and",
"restore",
"the",
"original",
"attribute",
"of",
"the",
"mocked",
"object",
"."
] | train | https://github.com/agoragames/chai/blob/8148d7b7754226b0d1cabfc2af10cd912612abdc/chai/stub.py#L248-L256 |
agoragames/chai | chai/stub.py | Stub.expect | def expect(self):
'''
Add an expectation to this stub. Return the expectation.
'''
exp = Expectation(self)
self._expectations.append(exp)
return exp | python | def expect(self):
'''
Add an expectation to this stub. Return the expectation.
'''
exp = Expectation(self)
self._expectations.append(exp)
return exp | [
"def",
"expect",
"(",
"self",
")",
":",
"exp",
"=",
"Expectation",
"(",
"self",
")",
"self",
".",
"_expectations",
".",
"append",
"(",
"exp",
")",
"return",
"exp"
] | Add an expectation to this stub. Return the expectation. | [
"Add",
"an",
"expectation",
"to",
"this",
"stub",
".",
"Return",
"the",
"expectation",
"."
] | train | https://github.com/agoragames/chai/blob/8148d7b7754226b0d1cabfc2af10cd912612abdc/chai/stub.py#L263-L269 |
agoragames/chai | chai/stub.py | Stub.spy | def spy(self):
'''
Add a spy to this stub. Return the spy.
'''
spy = Spy(self)
self._expectations.append(spy)
return spy | python | def spy(self):
'''
Add a spy to this stub. Return the spy.
'''
spy = Spy(self)
self._expectations.append(spy)
return spy | [
"def",
"spy",
"(",
"self",
")",
":",
"spy",
"=",
"Spy",
"(",
"self",
")",
"self",
".",
"_expectations",
".",
"append",
"(",
"spy",
")",
"return",
"spy"
] | Add a spy to this stub. Return the spy. | [
"Add",
"a",
"spy",
"to",
"this",
"stub",
".",
"Return",
"the",
"spy",
"."
] | train | https://github.com/agoragames/chai/blob/8148d7b7754226b0d1cabfc2af10cd912612abdc/chai/stub.py#L271-L277 |
agoragames/chai | chai/stub.py | StubMethod.call_orig | def call_orig(self, *args, **kwargs):
'''
Calls the original function.
'''
if hasattr(self._obj, '__self__') and \
inspect.isclass(self._obj.__self__) and \
self._obj.__self__ is self._instance:
return self._obj.__func__(self._instance, *args, **kwargs)
elif hasattr(self._obj, 'im_self') and \
inspect.isclass(self._obj.im_self) and \
self._obj.im_self is self._instance:
return self._obj.im_func(self._instance, *args, **kwargs)
else:
return self._obj(*args, **kwargs) | python | def call_orig(self, *args, **kwargs):
'''
Calls the original function.
'''
if hasattr(self._obj, '__self__') and \
inspect.isclass(self._obj.__self__) and \
self._obj.__self__ is self._instance:
return self._obj.__func__(self._instance, *args, **kwargs)
elif hasattr(self._obj, 'im_self') and \
inspect.isclass(self._obj.im_self) and \
self._obj.im_self is self._instance:
return self._obj.im_func(self._instance, *args, **kwargs)
else:
return self._obj(*args, **kwargs) | [
"def",
"call_orig",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"hasattr",
"(",
"self",
".",
"_obj",
",",
"'__self__'",
")",
"and",
"inspect",
".",
"isclass",
"(",
"self",
".",
"_obj",
".",
"__self__",
")",
"and",
"self"... | Calls the original function. | [
"Calls",
"the",
"original",
"function",
"."
] | train | https://github.com/agoragames/chai/blob/8148d7b7754226b0d1cabfc2af10cd912612abdc/chai/stub.py#L407-L420 |
agoragames/chai | chai/stub.py | StubMethod._teardown | def _teardown(self):
'''
Put the original method back in place. This will also handle the
special case when it putting back a class method.
The following code snippet best describe why it fails using settar,
the class method would be replaced with a bound method not a class
method.
>>> class Example(object):
... @classmethod
... def a_classmethod(self):
... pass
...
>>> Example.__dict__['a_classmethod']
<classmethod object at 0x7f5e6c298be8>
>>> orig = getattr(Example, 'a_classmethod')
>>> orig
<bound method type.a_classmethod of <class '__main__.Example'>>
>>> setattr(Example, 'a_classmethod', orig)
>>> Example.__dict__['a_classmethod']
<bound method type.a_classmethod of <class '__main__.Example'>>
The only way to figure out if this is a class method is to check and
see if the bound method im_self is a class, if so then we need to wrap
the function object (im_func) with class method before setting it back
on the class.
'''
# Figure out if this is a class method and we're unstubbing it on the
# class to which it belongs. This addresses an edge case where a
# module can expose a method of an instance. e.g gevent.
if hasattr(self._obj, '__self__') and \
inspect.isclass(self._obj.__self__) and \
self._obj.__self__ is self._instance:
setattr(
self._instance, self._attr, classmethod(self._obj.__func__))
elif hasattr(self._obj, 'im_self') and \
inspect.isclass(self._obj.im_self) and \
self._obj.im_self is self._instance:
# Wrap it and set it back on the class
setattr(self._instance, self._attr, classmethod(self._obj.im_func))
else:
setattr(self._instance, self._attr, self._obj) | python | def _teardown(self):
'''
Put the original method back in place. This will also handle the
special case when it putting back a class method.
The following code snippet best describe why it fails using settar,
the class method would be replaced with a bound method not a class
method.
>>> class Example(object):
... @classmethod
... def a_classmethod(self):
... pass
...
>>> Example.__dict__['a_classmethod']
<classmethod object at 0x7f5e6c298be8>
>>> orig = getattr(Example, 'a_classmethod')
>>> orig
<bound method type.a_classmethod of <class '__main__.Example'>>
>>> setattr(Example, 'a_classmethod', orig)
>>> Example.__dict__['a_classmethod']
<bound method type.a_classmethod of <class '__main__.Example'>>
The only way to figure out if this is a class method is to check and
see if the bound method im_self is a class, if so then we need to wrap
the function object (im_func) with class method before setting it back
on the class.
'''
# Figure out if this is a class method and we're unstubbing it on the
# class to which it belongs. This addresses an edge case where a
# module can expose a method of an instance. e.g gevent.
if hasattr(self._obj, '__self__') and \
inspect.isclass(self._obj.__self__) and \
self._obj.__self__ is self._instance:
setattr(
self._instance, self._attr, classmethod(self._obj.__func__))
elif hasattr(self._obj, 'im_self') and \
inspect.isclass(self._obj.im_self) and \
self._obj.im_self is self._instance:
# Wrap it and set it back on the class
setattr(self._instance, self._attr, classmethod(self._obj.im_func))
else:
setattr(self._instance, self._attr, self._obj) | [
"def",
"_teardown",
"(",
"self",
")",
":",
"# Figure out if this is a class method and we're unstubbing it on the",
"# class to which it belongs. This addresses an edge case where a",
"# module can expose a method of an instance. e.g gevent.",
"if",
"hasattr",
"(",
"self",
".",
"_obj",
... | Put the original method back in place. This will also handle the
special case when it putting back a class method.
The following code snippet best describe why it fails using settar,
the class method would be replaced with a bound method not a class
method.
>>> class Example(object):
... @classmethod
... def a_classmethod(self):
... pass
...
>>> Example.__dict__['a_classmethod']
<classmethod object at 0x7f5e6c298be8>
>>> orig = getattr(Example, 'a_classmethod')
>>> orig
<bound method type.a_classmethod of <class '__main__.Example'>>
>>> setattr(Example, 'a_classmethod', orig)
>>> Example.__dict__['a_classmethod']
<bound method type.a_classmethod of <class '__main__.Example'>>
The only way to figure out if this is a class method is to check and
see if the bound method im_self is a class, if so then we need to wrap
the function object (im_func) with class method before setting it back
on the class. | [
"Put",
"the",
"original",
"method",
"back",
"in",
"place",
".",
"This",
"will",
"also",
"handle",
"the",
"special",
"case",
"when",
"it",
"putting",
"back",
"a",
"class",
"method",
"."
] | train | https://github.com/agoragames/chai/blob/8148d7b7754226b0d1cabfc2af10cd912612abdc/chai/stub.py#L422-L464 |
agoragames/chai | chai/stub.py | StubFunction._teardown | def _teardown(self):
'''
Replace the original method.
'''
if not self._was_object_method:
setattr(self._instance, self._attr, self._obj)
else:
delattr(self._instance, self._attr) | python | def _teardown(self):
'''
Replace the original method.
'''
if not self._was_object_method:
setattr(self._instance, self._attr, self._obj)
else:
delattr(self._instance, self._attr) | [
"def",
"_teardown",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_was_object_method",
":",
"setattr",
"(",
"self",
".",
"_instance",
",",
"self",
".",
"_attr",
",",
"self",
".",
"_obj",
")",
"else",
":",
"delattr",
"(",
"self",
".",
"_instance",
... | Replace the original method. | [
"Replace",
"the",
"original",
"method",
"."
] | train | https://github.com/agoragames/chai/blob/8148d7b7754226b0d1cabfc2af10cd912612abdc/chai/stub.py#L518-L525 |
agoragames/chai | chai/stub.py | StubNew.call_orig | def call_orig(self, *args, **kwargs):
'''
Calls the original function. Simulates __new__ and __init__ together.
'''
rval = super(StubNew, self).call_orig(self._type)
rval.__init__(*args, **kwargs)
return rval | python | def call_orig(self, *args, **kwargs):
'''
Calls the original function. Simulates __new__ and __init__ together.
'''
rval = super(StubNew, self).call_orig(self._type)
rval.__init__(*args, **kwargs)
return rval | [
"def",
"call_orig",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"rval",
"=",
"super",
"(",
"StubNew",
",",
"self",
")",
".",
"call_orig",
"(",
"self",
".",
"_type",
")",
"rval",
".",
"__init__",
"(",
"*",
"args",
",",
"*",
... | Calls the original function. Simulates __new__ and __init__ together. | [
"Calls",
"the",
"original",
"function",
".",
"Simulates",
"__new__",
"and",
"__init__",
"together",
"."
] | train | https://github.com/agoragames/chai/blob/8148d7b7754226b0d1cabfc2af10cd912612abdc/chai/stub.py#L568-L574 |
agoragames/chai | chai/stub.py | StubNew._teardown | def _teardown(self):
'''
Overload so that we can clear out the cache after a test run.
'''
# __new__ is a super-special case in that even when stubbing a class
# which implements its own __new__ and subclasses object, the
# "Class.__new__" reference is a staticmethod and not a method (or
# function). That confuses the "was_object_method" logic in
# StubFunction which then fails to delattr and from then on the class
# is corrupted. So skip that teardown and use a __new__-specific case.
setattr(self._instance, self._attr, staticmethod(self._new))
StubNew._cache.pop(self._type) | python | def _teardown(self):
'''
Overload so that we can clear out the cache after a test run.
'''
# __new__ is a super-special case in that even when stubbing a class
# which implements its own __new__ and subclasses object, the
# "Class.__new__" reference is a staticmethod and not a method (or
# function). That confuses the "was_object_method" logic in
# StubFunction which then fails to delattr and from then on the class
# is corrupted. So skip that teardown and use a __new__-specific case.
setattr(self._instance, self._attr, staticmethod(self._new))
StubNew._cache.pop(self._type) | [
"def",
"_teardown",
"(",
"self",
")",
":",
"# __new__ is a super-special case in that even when stubbing a class",
"# which implements its own __new__ and subclasses object, the",
"# \"Class.__new__\" reference is a staticmethod and not a method (or",
"# function). That confuses the \"was_object_m... | Overload so that we can clear out the cache after a test run. | [
"Overload",
"so",
"that",
"we",
"can",
"clear",
"out",
"the",
"cache",
"after",
"a",
"test",
"run",
"."
] | train | https://github.com/agoragames/chai/blob/8148d7b7754226b0d1cabfc2af10cd912612abdc/chai/stub.py#L576-L587 |
agoragames/chai | chai/stub.py | StubWrapperDescriptor.call_orig | def call_orig(self, *args, **kwargs):
'''
Calls the original function.
'''
return self._orig(self._obj, *args, **kwargs) | python | def call_orig(self, *args, **kwargs):
'''
Calls the original function.
'''
return self._orig(self._obj, *args, **kwargs) | [
"def",
"call_orig",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_orig",
"(",
"self",
".",
"_obj",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Calls the original function. | [
"Calls",
"the",
"original",
"function",
"."
] | train | https://github.com/agoragames/chai/blob/8148d7b7754226b0d1cabfc2af10cd912612abdc/chai/stub.py#L686-L690 |
d0ugal/python-rfxcom | rfxcom/transport/asyncio.py | AsyncioTransport._setup | def _setup(self):
"""Performs the RFXtrx initialisation protocol in a Future.
Currently this is the rough workflow of the interactions with the
RFXtrx. We also do a few extra things - flush the buffer, and attach
readers/writers to the asyncio loop.
1. Write a RESET packet (write all zeros)
2. Wait at least 50ms and less than 9000ms
3. Write the STATUS packet to verify the device is up.
4. Receive status response
5. Write the MODE packet to enable or disabled the required protocols.
"""
self.log.info("Adding reader to prepare to receive.")
self.loop.add_reader(self.dev.fd, self.read)
self.log.info("Flushing the RFXtrx buffer.")
self.flushSerialInput()
self.log.info("Writing the reset packet to the RFXtrx. (blocking)")
yield from self.sendRESET()
self.log.info("Wating 0.4s")
yield from asyncio.sleep(0.4)
self.log.info("Write the status packet (blocking)")
yield from self.sendSTATUS()
# TODO receive status response, compare it with the needed MODE and
# request a new MODE if required. Currently MODE is always sent.
self.log.info("Adding mode packet to the write queue (blocking)")
yield from self.sendMODE() | python | def _setup(self):
"""Performs the RFXtrx initialisation protocol in a Future.
Currently this is the rough workflow of the interactions with the
RFXtrx. We also do a few extra things - flush the buffer, and attach
readers/writers to the asyncio loop.
1. Write a RESET packet (write all zeros)
2. Wait at least 50ms and less than 9000ms
3. Write the STATUS packet to verify the device is up.
4. Receive status response
5. Write the MODE packet to enable or disabled the required protocols.
"""
self.log.info("Adding reader to prepare to receive.")
self.loop.add_reader(self.dev.fd, self.read)
self.log.info("Flushing the RFXtrx buffer.")
self.flushSerialInput()
self.log.info("Writing the reset packet to the RFXtrx. (blocking)")
yield from self.sendRESET()
self.log.info("Wating 0.4s")
yield from asyncio.sleep(0.4)
self.log.info("Write the status packet (blocking)")
yield from self.sendSTATUS()
# TODO receive status response, compare it with the needed MODE and
# request a new MODE if required. Currently MODE is always sent.
self.log.info("Adding mode packet to the write queue (blocking)")
yield from self.sendMODE() | [
"def",
"_setup",
"(",
"self",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"\"Adding reader to prepare to receive.\"",
")",
"self",
".",
"loop",
".",
"add_reader",
"(",
"self",
".",
"dev",
".",
"fd",
",",
"self",
".",
"read",
")",
"self",
".",
"log"... | Performs the RFXtrx initialisation protocol in a Future.
Currently this is the rough workflow of the interactions with the
RFXtrx. We also do a few extra things - flush the buffer, and attach
readers/writers to the asyncio loop.
1. Write a RESET packet (write all zeros)
2. Wait at least 50ms and less than 9000ms
3. Write the STATUS packet to verify the device is up.
4. Receive status response
5. Write the MODE packet to enable or disabled the required protocols. | [
"Performs",
"the",
"RFXtrx",
"initialisation",
"protocol",
"in",
"a",
"Future",
"."
] | train | https://github.com/d0ugal/python-rfxcom/blob/2eb87f85e5f5a04d00f32f25e0f010edfefbde0d/rfxcom/transport/asyncio.py#L23-L55 |
d0ugal/python-rfxcom | rfxcom/transport/asyncio.py | AsyncioTransport.do_callback | def do_callback(self, pkt):
"""Add the callback to the event loop, we use call soon because we just
want it to be called at some point, but don't care when particularly.
"""
callback, parser = self.get_callback_parser(pkt)
if asyncio.iscoroutinefunction(callback):
self.loop.call_soon_threadsafe(self._do_async_callback,
callback, parser)
else:
self.loop.call_soon(callback, parser) | python | def do_callback(self, pkt):
"""Add the callback to the event loop, we use call soon because we just
want it to be called at some point, but don't care when particularly.
"""
callback, parser = self.get_callback_parser(pkt)
if asyncio.iscoroutinefunction(callback):
self.loop.call_soon_threadsafe(self._do_async_callback,
callback, parser)
else:
self.loop.call_soon(callback, parser) | [
"def",
"do_callback",
"(",
"self",
",",
"pkt",
")",
":",
"callback",
",",
"parser",
"=",
"self",
".",
"get_callback_parser",
"(",
"pkt",
")",
"if",
"asyncio",
".",
"iscoroutinefunction",
"(",
"callback",
")",
":",
"self",
".",
"loop",
".",
"call_soon_threa... | Add the callback to the event loop, we use call soon because we just
want it to be called at some point, but don't care when particularly. | [
"Add",
"the",
"callback",
"to",
"the",
"event",
"loop",
"we",
"use",
"call",
"soon",
"because",
"we",
"just",
"want",
"it",
"to",
"be",
"called",
"at",
"some",
"point",
"but",
"don",
"t",
"care",
"when",
"particularly",
"."
] | train | https://github.com/d0ugal/python-rfxcom/blob/2eb87f85e5f5a04d00f32f25e0f010edfefbde0d/rfxcom/transport/asyncio.py#L73-L83 |
d0ugal/python-rfxcom | rfxcom/transport/asyncio.py | AsyncioTransport.read | def read(self):
"""We have been called to read! As a consumer, continue to read for
the length of the packet and then pass to the callback.
"""
data = self.dev.read()
if len(data) == 0:
self.log.warning("READ : Nothing received")
return
if data == b'\x00':
self.log.warning("READ : Empty packet (Got \\x00)")
return
pkt = bytearray(data)
data = self.dev.read(pkt[0])
pkt.extend(bytearray(data))
self.log.info("READ : %s" % self.format_packet(pkt))
self.do_callback(pkt)
return pkt | python | def read(self):
"""We have been called to read! As a consumer, continue to read for
the length of the packet and then pass to the callback.
"""
data = self.dev.read()
if len(data) == 0:
self.log.warning("READ : Nothing received")
return
if data == b'\x00':
self.log.warning("READ : Empty packet (Got \\x00)")
return
pkt = bytearray(data)
data = self.dev.read(pkt[0])
pkt.extend(bytearray(data))
self.log.info("READ : %s" % self.format_packet(pkt))
self.do_callback(pkt)
return pkt | [
"def",
"read",
"(",
"self",
")",
":",
"data",
"=",
"self",
".",
"dev",
".",
"read",
"(",
")",
"if",
"len",
"(",
"data",
")",
"==",
"0",
":",
"self",
".",
"log",
".",
"warning",
"(",
"\"READ : Nothing received\"",
")",
"return",
"if",
"data",
"==",
... | We have been called to read! As a consumer, continue to read for
the length of the packet and then pass to the callback. | [
"We",
"have",
"been",
"called",
"to",
"read!",
"As",
"a",
"consumer",
"continue",
"to",
"read",
"for",
"the",
"length",
"of",
"the",
"packet",
"and",
"then",
"pass",
"to",
"the",
"callback",
"."
] | train | https://github.com/d0ugal/python-rfxcom/blob/2eb87f85e5f5a04d00f32f25e0f010edfefbde0d/rfxcom/transport/asyncio.py#L93-L114 |
zencoder/zencoder-py | zencoder/core.py | HTTPBackend.delete | def delete(self, url, params=None):
""" Executes an HTTP DELETE request for the given URL.
``params`` should be a dictionary
"""
response = self.http.delete(url,
params=params,
**self.requests_params)
return self.process(response) | python | def delete(self, url, params=None):
""" Executes an HTTP DELETE request for the given URL.
``params`` should be a dictionary
"""
response = self.http.delete(url,
params=params,
**self.requests_params)
return self.process(response) | [
"def",
"delete",
"(",
"self",
",",
"url",
",",
"params",
"=",
"None",
")",
":",
"response",
"=",
"self",
".",
"http",
".",
"delete",
"(",
"url",
",",
"params",
"=",
"params",
",",
"*",
"*",
"self",
".",
"requests_params",
")",
"return",
"self",
"."... | Executes an HTTP DELETE request for the given URL.
``params`` should be a dictionary | [
"Executes",
"an",
"HTTP",
"DELETE",
"request",
"for",
"the",
"given",
"URL",
"."
] | train | https://github.com/zencoder/zencoder-py/blob/9d762e33e2bb2edadb0e5da0bb80a61e27636426/zencoder/core.py#L82-L90 |
zencoder/zencoder-py | zencoder/core.py | HTTPBackend.get | def get(self, url, data=None):
""" Executes an HTTP GET request for the given URL.
``data`` should be a dictionary of url parameters
"""
response = self.http.get(url,
headers=self.headers,
params=data,
**self.requests_params)
return self.process(response) | python | def get(self, url, data=None):
""" Executes an HTTP GET request for the given URL.
``data`` should be a dictionary of url parameters
"""
response = self.http.get(url,
headers=self.headers,
params=data,
**self.requests_params)
return self.process(response) | [
"def",
"get",
"(",
"self",
",",
"url",
",",
"data",
"=",
"None",
")",
":",
"response",
"=",
"self",
".",
"http",
".",
"get",
"(",
"url",
",",
"headers",
"=",
"self",
".",
"headers",
",",
"params",
"=",
"data",
",",
"*",
"*",
"self",
".",
"reque... | Executes an HTTP GET request for the given URL.
``data`` should be a dictionary of url parameters | [
"Executes",
"an",
"HTTP",
"GET",
"request",
"for",
"the",
"given",
"URL",
"."
] | train | https://github.com/zencoder/zencoder-py/blob/9d762e33e2bb2edadb0e5da0bb80a61e27636426/zencoder/core.py#L92-L101 |
zencoder/zencoder-py | zencoder/core.py | HTTPBackend.post | def post(self, url, body=None):
""" Executes an HTTP POST request for the given URL. """
response = self.http.post(url,
headers=self.headers,
data=body,
**self.requests_params)
return self.process(response) | python | def post(self, url, body=None):
""" Executes an HTTP POST request for the given URL. """
response = self.http.post(url,
headers=self.headers,
data=body,
**self.requests_params)
return self.process(response) | [
"def",
"post",
"(",
"self",
",",
"url",
",",
"body",
"=",
"None",
")",
":",
"response",
"=",
"self",
".",
"http",
".",
"post",
"(",
"url",
",",
"headers",
"=",
"self",
".",
"headers",
",",
"data",
"=",
"body",
",",
"*",
"*",
"self",
".",
"reque... | Executes an HTTP POST request for the given URL. | [
"Executes",
"an",
"HTTP",
"POST",
"request",
"for",
"the",
"given",
"URL",
"."
] | train | https://github.com/zencoder/zencoder-py/blob/9d762e33e2bb2edadb0e5da0bb80a61e27636426/zencoder/core.py#L103-L110 |
zencoder/zencoder-py | zencoder/core.py | HTTPBackend.put | def put(self, url, data=None, body=None):
""" Executes an HTTP PUT request for the given URL. """
response = self.http.put(url,
headers=self.headers,
data=body,
params=data,
**self.requests_params)
return self.process(response) | python | def put(self, url, data=None, body=None):
""" Executes an HTTP PUT request for the given URL. """
response = self.http.put(url,
headers=self.headers,
data=body,
params=data,
**self.requests_params)
return self.process(response) | [
"def",
"put",
"(",
"self",
",",
"url",
",",
"data",
"=",
"None",
",",
"body",
"=",
"None",
")",
":",
"response",
"=",
"self",
".",
"http",
".",
"put",
"(",
"url",
",",
"headers",
"=",
"self",
".",
"headers",
",",
"data",
"=",
"body",
",",
"para... | Executes an HTTP PUT request for the given URL. | [
"Executes",
"an",
"HTTP",
"PUT",
"request",
"for",
"the",
"given",
"URL",
"."
] | train | https://github.com/zencoder/zencoder-py/blob/9d762e33e2bb2edadb0e5da0bb80a61e27636426/zencoder/core.py#L112-L120 |
zencoder/zencoder-py | zencoder/core.py | HTTPBackend.process | def process(self, response):
""" Returns HTTP backend agnostic ``Response`` data. """
try:
code = response.status_code
# 204 - No Content
if code == 204:
body = None
# add an error message to 402 errors
elif code == 402:
body = {
"message": "Payment Required",
"status": "error"
}
else:
body = response.json()
return Response(code, body, response.content, response)
except ValueError:
raise ZencoderResponseError(response, response.content) | python | def process(self, response):
""" Returns HTTP backend agnostic ``Response`` data. """
try:
code = response.status_code
# 204 - No Content
if code == 204:
body = None
# add an error message to 402 errors
elif code == 402:
body = {
"message": "Payment Required",
"status": "error"
}
else:
body = response.json()
return Response(code, body, response.content, response)
except ValueError:
raise ZencoderResponseError(response, response.content) | [
"def",
"process",
"(",
"self",
",",
"response",
")",
":",
"try",
":",
"code",
"=",
"response",
".",
"status_code",
"# 204 - No Content",
"if",
"code",
"==",
"204",
":",
"body",
"=",
"None",
"# add an error message to 402 errors",
"elif",
"code",
"==",
"402",
... | Returns HTTP backend agnostic ``Response`` data. | [
"Returns",
"HTTP",
"backend",
"agnostic",
"Response",
"data",
"."
] | train | https://github.com/zencoder/zencoder-py/blob/9d762e33e2bb2edadb0e5da0bb80a61e27636426/zencoder/core.py#L122-L142 |
zencoder/zencoder-py | zencoder/core.py | Account.create | def create(self, email, tos=1, options=None):
""" Creates an account with Zencoder, no API Key necessary.
https://app.zencoder.com/docs/api/accounts/create
"""
data = {'email': email,
'terms_of_service': str(tos)}
if options:
data.update(options)
return self.post(self.base_url, body=json.dumps(data)) | python | def create(self, email, tos=1, options=None):
""" Creates an account with Zencoder, no API Key necessary.
https://app.zencoder.com/docs/api/accounts/create
"""
data = {'email': email,
'terms_of_service': str(tos)}
if options:
data.update(options)
return self.post(self.base_url, body=json.dumps(data)) | [
"def",
"create",
"(",
"self",
",",
"email",
",",
"tos",
"=",
"1",
",",
"options",
"=",
"None",
")",
":",
"data",
"=",
"{",
"'email'",
":",
"email",
",",
"'terms_of_service'",
":",
"str",
"(",
"tos",
")",
"}",
"if",
"options",
":",
"data",
".",
"u... | Creates an account with Zencoder, no API Key necessary.
https://app.zencoder.com/docs/api/accounts/create | [
"Creates",
"an",
"account",
"with",
"Zencoder",
"no",
"API",
"Key",
"necessary",
"."
] | train | https://github.com/zencoder/zencoder-py/blob/9d762e33e2bb2edadb0e5da0bb80a61e27636426/zencoder/core.py#L230-L241 |
zencoder/zencoder-py | zencoder/core.py | Job.create | def create(self, input=None, live_stream=False, outputs=None, options=None):
""" Creates a transcoding job. Here are some examples::
job.create('s3://zencodertesting/test.mov')
job.create(live_stream=True)
job.create(input='http://example.com/input.mov',
outputs=({'label': 'test output'},))
https://app.zencoder.com/docs/api/jobs/create
"""
data = {"input": input, "test": self.test}
if outputs:
data['outputs'] = outputs
if options:
data.update(options)
if live_stream:
data['live_stream'] = live_stream
return self.post(self.base_url, body=json.dumps(data)) | python | def create(self, input=None, live_stream=False, outputs=None, options=None):
""" Creates a transcoding job. Here are some examples::
job.create('s3://zencodertesting/test.mov')
job.create(live_stream=True)
job.create(input='http://example.com/input.mov',
outputs=({'label': 'test output'},))
https://app.zencoder.com/docs/api/jobs/create
"""
data = {"input": input, "test": self.test}
if outputs:
data['outputs'] = outputs
if options:
data.update(options)
if live_stream:
data['live_stream'] = live_stream
return self.post(self.base_url, body=json.dumps(data)) | [
"def",
"create",
"(",
"self",
",",
"input",
"=",
"None",
",",
"live_stream",
"=",
"False",
",",
"outputs",
"=",
"None",
",",
"options",
"=",
"None",
")",
":",
"data",
"=",
"{",
"\"input\"",
":",
"input",
",",
"\"test\"",
":",
"self",
".",
"test",
"... | Creates a transcoding job. Here are some examples::
job.create('s3://zencodertesting/test.mov')
job.create(live_stream=True)
job.create(input='http://example.com/input.mov',
outputs=({'label': 'test output'},))
https://app.zencoder.com/docs/api/jobs/create | [
"Creates",
"a",
"transcoding",
"job",
".",
"Here",
"are",
"some",
"examples",
"::"
] | train | https://github.com/zencoder/zencoder-py/blob/9d762e33e2bb2edadb0e5da0bb80a61e27636426/zencoder/core.py#L329-L350 |
zencoder/zencoder-py | zencoder/core.py | Job.list | def list(self, page=1, per_page=50):
""" Lists Jobs.
https://app.zencoder.com/docs/api/jobs/list
"""
data = {"page": page,
"per_page": per_page}
return self.get(self.base_url, data=data) | python | def list(self, page=1, per_page=50):
""" Lists Jobs.
https://app.zencoder.com/docs/api/jobs/list
"""
data = {"page": page,
"per_page": per_page}
return self.get(self.base_url, data=data) | [
"def",
"list",
"(",
"self",
",",
"page",
"=",
"1",
",",
"per_page",
"=",
"50",
")",
":",
"data",
"=",
"{",
"\"page\"",
":",
"page",
",",
"\"per_page\"",
":",
"per_page",
"}",
"return",
"self",
".",
"get",
"(",
"self",
".",
"base_url",
",",
"data",
... | Lists Jobs.
https://app.zencoder.com/docs/api/jobs/list | [
"Lists",
"Jobs",
"."
] | train | https://github.com/zencoder/zencoder-py/blob/9d762e33e2bb2edadb0e5da0bb80a61e27636426/zencoder/core.py#L352-L360 |
zencoder/zencoder-py | zencoder/core.py | Job.resubmit | def resubmit(self, job_id):
""" Resubmits the given ``job_id``.
https://app.zencoder.com/docs/api/jobs/resubmit
"""
url = self.base_url + '/%s/resubmit' % str(job_id)
return self.put(url) | python | def resubmit(self, job_id):
""" Resubmits the given ``job_id``.
https://app.zencoder.com/docs/api/jobs/resubmit
"""
url = self.base_url + '/%s/resubmit' % str(job_id)
return self.put(url) | [
"def",
"resubmit",
"(",
"self",
",",
"job_id",
")",
":",
"url",
"=",
"self",
".",
"base_url",
"+",
"'/%s/resubmit'",
"%",
"str",
"(",
"job_id",
")",
"return",
"self",
".",
"put",
"(",
"url",
")"
] | Resubmits the given ``job_id``.
https://app.zencoder.com/docs/api/jobs/resubmit | [
"Resubmits",
"the",
"given",
"job_id",
"."
] | train | https://github.com/zencoder/zencoder-py/blob/9d762e33e2bb2edadb0e5da0bb80a61e27636426/zencoder/core.py#L378-L385 |
zencoder/zencoder-py | zencoder/core.py | Job.cancel | def cancel(self, job_id):
""" Cancels the given ``job_id``.
https://app.zencoder.com/docs/api/jobs/cancel
"""
if self.version == 'v1':
verb = self.get
else:
verb = self.put
url = self.base_url + '/%s/cancel' % str(job_id)
return verb(url) | python | def cancel(self, job_id):
""" Cancels the given ``job_id``.
https://app.zencoder.com/docs/api/jobs/cancel
"""
if self.version == 'v1':
verb = self.get
else:
verb = self.put
url = self.base_url + '/%s/cancel' % str(job_id)
return verb(url) | [
"def",
"cancel",
"(",
"self",
",",
"job_id",
")",
":",
"if",
"self",
".",
"version",
"==",
"'v1'",
":",
"verb",
"=",
"self",
".",
"get",
"else",
":",
"verb",
"=",
"self",
".",
"put",
"url",
"=",
"self",
".",
"base_url",
"+",
"'/%s/cancel'",
"%",
... | Cancels the given ``job_id``.
https://app.zencoder.com/docs/api/jobs/cancel | [
"Cancels",
"the",
"given",
"job_id",
"."
] | train | https://github.com/zencoder/zencoder-py/blob/9d762e33e2bb2edadb0e5da0bb80a61e27636426/zencoder/core.py#L387-L399 |
zencoder/zencoder-py | zencoder/core.py | Report.minutes | def minutes(self, start_date=None, end_date=None, grouping=None):
""" Gets a detailed Report of encoded minutes and billable minutes for a
date range.
**Warning**: ``start_date`` and ``end_date`` must be ``datetime.date`` objects.
Example::
import datetime
start = datetime.date(2012, 12, 31)
end = datetime.today()
data = z.report.minutes(start, end)
https://app.zencoder.com/docs/api/reports/minutes
"""
data = self.__format(start_date, end_date)
url = self.base_url + '/minutes'
return self.get(url, data=data) | python | def minutes(self, start_date=None, end_date=None, grouping=None):
""" Gets a detailed Report of encoded minutes and billable minutes for a
date range.
**Warning**: ``start_date`` and ``end_date`` must be ``datetime.date`` objects.
Example::
import datetime
start = datetime.date(2012, 12, 31)
end = datetime.today()
data = z.report.minutes(start, end)
https://app.zencoder.com/docs/api/reports/minutes
"""
data = self.__format(start_date, end_date)
url = self.base_url + '/minutes'
return self.get(url, data=data) | [
"def",
"minutes",
"(",
"self",
",",
"start_date",
"=",
"None",
",",
"end_date",
"=",
"None",
",",
"grouping",
"=",
"None",
")",
":",
"data",
"=",
"self",
".",
"__format",
"(",
"start_date",
",",
"end_date",
")",
"url",
"=",
"self",
".",
"base_url",
"... | Gets a detailed Report of encoded minutes and billable minutes for a
date range.
**Warning**: ``start_date`` and ``end_date`` must be ``datetime.date`` objects.
Example::
import datetime
start = datetime.date(2012, 12, 31)
end = datetime.today()
data = z.report.minutes(start, end)
https://app.zencoder.com/docs/api/reports/minutes | [
"Gets",
"a",
"detailed",
"Report",
"of",
"encoded",
"minutes",
"and",
"billable",
"minutes",
"for",
"a",
"date",
"range",
"."
] | train | https://github.com/zencoder/zencoder-py/blob/9d762e33e2bb2edadb0e5da0bb80a61e27636426/zencoder/core.py#L442-L462 |
toumorokoshi/transmute-core | transmute_core/frameworks/flask/route.py | route | def route(app_or_blueprint, context=default_context, **kwargs):
""" attach a transmute route. """
def decorator(fn):
fn = describe(**kwargs)(fn)
transmute_func = TransmuteFunction(fn)
routes, handler = create_routes_and_handler(transmute_func, context)
for r in routes:
# push swagger info.
if not hasattr(app_or_blueprint, SWAGGER_ATTR_NAME):
setattr(app_or_blueprint, SWAGGER_ATTR_NAME, SwaggerSpec())
swagger_obj = getattr(app_or_blueprint, SWAGGER_ATTR_NAME)
swagger_obj.add_func(transmute_func, context)
app_or_blueprint.route(r, methods=transmute_func.methods)(handler)
return handler
return decorator | python | def route(app_or_blueprint, context=default_context, **kwargs):
""" attach a transmute route. """
def decorator(fn):
fn = describe(**kwargs)(fn)
transmute_func = TransmuteFunction(fn)
routes, handler = create_routes_and_handler(transmute_func, context)
for r in routes:
# push swagger info.
if not hasattr(app_or_blueprint, SWAGGER_ATTR_NAME):
setattr(app_or_blueprint, SWAGGER_ATTR_NAME, SwaggerSpec())
swagger_obj = getattr(app_or_blueprint, SWAGGER_ATTR_NAME)
swagger_obj.add_func(transmute_func, context)
app_or_blueprint.route(r, methods=transmute_func.methods)(handler)
return handler
return decorator | [
"def",
"route",
"(",
"app_or_blueprint",
",",
"context",
"=",
"default_context",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"decorator",
"(",
"fn",
")",
":",
"fn",
"=",
"describe",
"(",
"*",
"*",
"kwargs",
")",
"(",
"fn",
")",
"transmute_func",
"=",
"... | attach a transmute route. | [
"attach",
"a",
"transmute",
"route",
"."
] | train | https://github.com/toumorokoshi/transmute-core/blob/a2c26625d5d8bab37e00038f9d615a26167fc7f4/transmute_core/frameworks/flask/route.py#L9-L23 |
agoragames/chai | chai/chai.py | ChaiBase.stub | def stub(self, obj, attr=None):
'''
Stub an object. If attr is not None, will attempt to stub that
attribute on the object. Only required for modules and other rare
cases where we can't determine the binding from the object.
'''
s = stub(obj, attr)
if s not in self._stubs:
self._stubs.append(s)
return s | python | def stub(self, obj, attr=None):
'''
Stub an object. If attr is not None, will attempt to stub that
attribute on the object. Only required for modules and other rare
cases where we can't determine the binding from the object.
'''
s = stub(obj, attr)
if s not in self._stubs:
self._stubs.append(s)
return s | [
"def",
"stub",
"(",
"self",
",",
"obj",
",",
"attr",
"=",
"None",
")",
":",
"s",
"=",
"stub",
"(",
"obj",
",",
"attr",
")",
"if",
"s",
"not",
"in",
"self",
".",
"_stubs",
":",
"self",
".",
"_stubs",
".",
"append",
"(",
"s",
")",
"return",
"s"... | Stub an object. If attr is not None, will attempt to stub that
attribute on the object. Only required for modules and other rare
cases where we can't determine the binding from the object. | [
"Stub",
"an",
"object",
".",
"If",
"attr",
"is",
"not",
"None",
"will",
"attempt",
"to",
"stub",
"that",
"attribute",
"on",
"the",
"object",
".",
"Only",
"required",
"for",
"modules",
"and",
"other",
"rare",
"cases",
"where",
"we",
"can",
"t",
"determine... | train | https://github.com/agoragames/chai/blob/8148d7b7754226b0d1cabfc2af10cd912612abdc/chai/chai.py#L207-L216 |
agoragames/chai | chai/chai.py | ChaiBase.mock | def mock(self, obj=None, attr=None, **kwargs):
'''
Return a mock object.
'''
rval = Mock(**kwargs)
if obj is not None and attr is not None:
rval._object = obj
rval._attr = attr
if hasattr(obj, attr):
orig = getattr(obj, attr)
self._mocks.append((obj, attr, orig))
setattr(obj, attr, rval)
else:
self._mocks.append((obj, attr))
setattr(obj, attr, rval)
return rval | python | def mock(self, obj=None, attr=None, **kwargs):
'''
Return a mock object.
'''
rval = Mock(**kwargs)
if obj is not None and attr is not None:
rval._object = obj
rval._attr = attr
if hasattr(obj, attr):
orig = getattr(obj, attr)
self._mocks.append((obj, attr, orig))
setattr(obj, attr, rval)
else:
self._mocks.append((obj, attr))
setattr(obj, attr, rval)
return rval | [
"def",
"mock",
"(",
"self",
",",
"obj",
"=",
"None",
",",
"attr",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"rval",
"=",
"Mock",
"(",
"*",
"*",
"kwargs",
")",
"if",
"obj",
"is",
"not",
"None",
"and",
"attr",
"is",
"not",
"None",
":",
"r... | Return a mock object. | [
"Return",
"a",
"mock",
"object",
"."
] | train | https://github.com/agoragames/chai/blob/8148d7b7754226b0d1cabfc2af10cd912612abdc/chai/chai.py#L232-L248 |
paylogic/halogen | halogen/vnd/error.py | Error.from_validation_exception | def from_validation_exception(cls, exception, **kwargs):
"""Create an error from validation exception."""
errors = []
def flatten(error, path=""):
if isinstance(error, halogen.exceptions.ValidationError):
if not path.endswith("/"):
path += "/"
if error.attr is not None:
path += error.attr
elif error.index is not None:
path += six.text_type(error.index)
for e in error.errors:
flatten(e, path)
else:
message = error
if isinstance(error, Exception):
try:
message = error.message
except AttributeError:
message = six.text_type(error)
# TODO: i18n
errors.append(Error(message=message, path=path))
flatten(exception)
message = kwargs.pop("message", "Validation error.")
return cls(message=message, errors=sorted(errors, key=lambda error: error.path or ""), **kwargs) | python | def from_validation_exception(cls, exception, **kwargs):
"""Create an error from validation exception."""
errors = []
def flatten(error, path=""):
if isinstance(error, halogen.exceptions.ValidationError):
if not path.endswith("/"):
path += "/"
if error.attr is not None:
path += error.attr
elif error.index is not None:
path += six.text_type(error.index)
for e in error.errors:
flatten(e, path)
else:
message = error
if isinstance(error, Exception):
try:
message = error.message
except AttributeError:
message = six.text_type(error)
# TODO: i18n
errors.append(Error(message=message, path=path))
flatten(exception)
message = kwargs.pop("message", "Validation error.")
return cls(message=message, errors=sorted(errors, key=lambda error: error.path or ""), **kwargs) | [
"def",
"from_validation_exception",
"(",
"cls",
",",
"exception",
",",
"*",
"*",
"kwargs",
")",
":",
"errors",
"=",
"[",
"]",
"def",
"flatten",
"(",
"error",
",",
"path",
"=",
"\"\"",
")",
":",
"if",
"isinstance",
"(",
"error",
",",
"halogen",
".",
"... | Create an error from validation exception. | [
"Create",
"an",
"error",
"from",
"validation",
"exception",
"."
] | train | https://github.com/paylogic/halogen/blob/2dec0a67c506d02d1f51915fa7163f59764a0bde/halogen/vnd/error.py#L26-L53 |
toumorokoshi/transmute-core | transmute_core/contenttype_serializers/yaml_serializer.py | YamlSerializer.load | def load(raw_bytes):
"""
given a bytes object, should return a base python data
structure that represents the object.
"""
try:
return yaml.load(raw_bytes)
except yaml.scanner.ScannerError as e:
raise SerializationException(str(e)) | python | def load(raw_bytes):
"""
given a bytes object, should return a base python data
structure that represents the object.
"""
try:
return yaml.load(raw_bytes)
except yaml.scanner.ScannerError as e:
raise SerializationException(str(e)) | [
"def",
"load",
"(",
"raw_bytes",
")",
":",
"try",
":",
"return",
"yaml",
".",
"load",
"(",
"raw_bytes",
")",
"except",
"yaml",
".",
"scanner",
".",
"ScannerError",
"as",
"e",
":",
"raise",
"SerializationException",
"(",
"str",
"(",
"e",
")",
")"
] | given a bytes object, should return a base python data
structure that represents the object. | [
"given",
"a",
"bytes",
"object",
"should",
"return",
"a",
"base",
"python",
"data",
"structure",
"that",
"represents",
"the",
"object",
"."
] | train | https://github.com/toumorokoshi/transmute-core/blob/a2c26625d5d8bab37e00038f9d615a26167fc7f4/transmute_core/contenttype_serializers/yaml_serializer.py#L24-L32 |
toumorokoshi/transmute-core | transmute_core/frameworks/aiohttp/url_dispatcher.py | TransmuteUrlDispatcher.add_transmute_route | def add_transmute_route(self, *args):
"""
two formats are accepted, for transmute routes. One allows
for a more traditional aiohttp syntax, while the other
allows for a flask-like variant.
.. code-block:: python
# if the path and method are not added in describe.
add_transmute_route("GET", "/route", fn)
# if the path and method are already added in describe
add_transmute_route(fn)
"""
if len(args) == 1:
fn = args[0]
elif len(args) == 3:
methods, paths, fn = args
fn = describe(methods=methods, paths=paths)(fn)
else:
raise ValueError(
"expected one or three arguments for add_transmute_route!"
)
add_route(self._app, fn, context=self._transmute_context) | python | def add_transmute_route(self, *args):
"""
two formats are accepted, for transmute routes. One allows
for a more traditional aiohttp syntax, while the other
allows for a flask-like variant.
.. code-block:: python
# if the path and method are not added in describe.
add_transmute_route("GET", "/route", fn)
# if the path and method are already added in describe
add_transmute_route(fn)
"""
if len(args) == 1:
fn = args[0]
elif len(args) == 3:
methods, paths, fn = args
fn = describe(methods=methods, paths=paths)(fn)
else:
raise ValueError(
"expected one or three arguments for add_transmute_route!"
)
add_route(self._app, fn, context=self._transmute_context) | [
"def",
"add_transmute_route",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
"==",
"1",
":",
"fn",
"=",
"args",
"[",
"0",
"]",
"elif",
"len",
"(",
"args",
")",
"==",
"3",
":",
"methods",
",",
"paths",
",",
"fn",
"=",
... | two formats are accepted, for transmute routes. One allows
for a more traditional aiohttp syntax, while the other
allows for a flask-like variant.
.. code-block:: python
# if the path and method are not added in describe.
add_transmute_route("GET", "/route", fn)
# if the path and method are already added in describe
add_transmute_route(fn) | [
"two",
"formats",
"are",
"accepted",
"for",
"transmute",
"routes",
".",
"One",
"allows",
"for",
"a",
"more",
"traditional",
"aiohttp",
"syntax",
"while",
"the",
"other",
"allows",
"for",
"a",
"flask",
"-",
"like",
"variant",
"."
] | train | https://github.com/toumorokoshi/transmute-core/blob/a2c26625d5d8bab37e00038f9d615a26167fc7f4/transmute_core/frameworks/aiohttp/url_dispatcher.py#L33-L57 |
toumorokoshi/transmute-core | transmute_core/object_serializers/cattrs_serializer/__init__.py | CattrsSerializer.can_handle | def can_handle(self, cls):
"""
this will theoretically be compatible with everything,
as cattrs can handle many basic types as well.
"""
# cattrs uses a Singledispatch like function
# under the hood.
f = self._cattrs_converter._structure_func.dispatch(cls)
return f != self._cattrs_converter._structure_default | python | def can_handle(self, cls):
"""
this will theoretically be compatible with everything,
as cattrs can handle many basic types as well.
"""
# cattrs uses a Singledispatch like function
# under the hood.
f = self._cattrs_converter._structure_func.dispatch(cls)
return f != self._cattrs_converter._structure_default | [
"def",
"can_handle",
"(",
"self",
",",
"cls",
")",
":",
"# cattrs uses a Singledispatch like function",
"# under the hood.",
"f",
"=",
"self",
".",
"_cattrs_converter",
".",
"_structure_func",
".",
"dispatch",
"(",
"cls",
")",
"return",
"f",
"!=",
"self",
".",
"... | this will theoretically be compatible with everything,
as cattrs can handle many basic types as well. | [
"this",
"will",
"theoretically",
"be",
"compatible",
"with",
"everything",
"as",
"cattrs",
"can",
"handle",
"many",
"basic",
"types",
"as",
"well",
"."
] | train | https://github.com/toumorokoshi/transmute-core/blob/a2c26625d5d8bab37e00038f9d615a26167fc7f4/transmute_core/object_serializers/cattrs_serializer/__init__.py#L17-L25 |
toumorokoshi/transmute-core | transmute_core/object_serializers/cattrs_serializer/__init__.py | CattrsSerializer.load | def load(self, model, value):
"""
Converts unstructured data into structured data, recursively.
"""
try:
return self._cattrs_converter.structure(value, model)
except (ValueError, TypeError) as e:
raise SerializationException(str(e)) | python | def load(self, model, value):
"""
Converts unstructured data into structured data, recursively.
"""
try:
return self._cattrs_converter.structure(value, model)
except (ValueError, TypeError) as e:
raise SerializationException(str(e)) | [
"def",
"load",
"(",
"self",
",",
"model",
",",
"value",
")",
":",
"try",
":",
"return",
"self",
".",
"_cattrs_converter",
".",
"structure",
"(",
"value",
",",
"model",
")",
"except",
"(",
"ValueError",
",",
"TypeError",
")",
"as",
"e",
":",
"raise",
... | Converts unstructured data into structured data, recursively. | [
"Converts",
"unstructured",
"data",
"into",
"structured",
"data",
"recursively",
"."
] | train | https://github.com/toumorokoshi/transmute-core/blob/a2c26625d5d8bab37e00038f9d615a26167fc7f4/transmute_core/object_serializers/cattrs_serializer/__init__.py#L27-L34 |
toumorokoshi/transmute-core | transmute_core/object_serializers/cattrs_serializer/__init__.py | CattrsSerializer.dump | def dump(self, model, value):
"""
Convert attrs data into unstructured data with basic types, recursively:
- attrs classes => dictionaries
- Enumeration => values
- Other types are let through without conversion,
such as, int, boolean, dict, other classes.
"""
try:
return self._cattrs_converter.unstructure(value)
except (ValueError, TypeError) as e:
raise SerializationException(str(e)) | python | def dump(self, model, value):
"""
Convert attrs data into unstructured data with basic types, recursively:
- attrs classes => dictionaries
- Enumeration => values
- Other types are let through without conversion,
such as, int, boolean, dict, other classes.
"""
try:
return self._cattrs_converter.unstructure(value)
except (ValueError, TypeError) as e:
raise SerializationException(str(e)) | [
"def",
"dump",
"(",
"self",
",",
"model",
",",
"value",
")",
":",
"try",
":",
"return",
"self",
".",
"_cattrs_converter",
".",
"unstructure",
"(",
"value",
")",
"except",
"(",
"ValueError",
",",
"TypeError",
")",
"as",
"e",
":",
"raise",
"SerializationEx... | Convert attrs data into unstructured data with basic types, recursively:
- attrs classes => dictionaries
- Enumeration => values
- Other types are let through without conversion,
such as, int, boolean, dict, other classes. | [
"Convert",
"attrs",
"data",
"into",
"unstructured",
"data",
"with",
"basic",
"types",
"recursively",
":"
] | train | https://github.com/toumorokoshi/transmute-core/blob/a2c26625d5d8bab37e00038f9d615a26167fc7f4/transmute_core/object_serializers/cattrs_serializer/__init__.py#L36-L48 |
inveniosoftware/invenio-previewer | invenio_previewer/utils.py | detect_encoding | def detect_encoding(fp, default=None):
"""Detect the cahracter encoding of a file.
:param fp: Open Python file pointer.
:param default: Fallback encoding to use.
:returns: The detected encoding.
.. note:: The file pointer is returned at its original read position.
"""
init_pos = fp.tell()
try:
sample = fp.read(
current_app.config.get('PREVIEWER_CHARDET_BYTES', 1024))
# Result contains 'confidence' and 'encoding'
result = cchardet.detect(sample)
threshold = current_app.config.get('PREVIEWER_CHARDET_CONFIDENCE', 0.9)
if result.get('confidence', 0) > threshold:
return result.get('encoding', default)
else:
return default
except Exception:
current_app.logger.warning('Encoding detection failed.', exc_info=True)
return default
finally:
fp.seek(init_pos) | python | def detect_encoding(fp, default=None):
"""Detect the cahracter encoding of a file.
:param fp: Open Python file pointer.
:param default: Fallback encoding to use.
:returns: The detected encoding.
.. note:: The file pointer is returned at its original read position.
"""
init_pos = fp.tell()
try:
sample = fp.read(
current_app.config.get('PREVIEWER_CHARDET_BYTES', 1024))
# Result contains 'confidence' and 'encoding'
result = cchardet.detect(sample)
threshold = current_app.config.get('PREVIEWER_CHARDET_CONFIDENCE', 0.9)
if result.get('confidence', 0) > threshold:
return result.get('encoding', default)
else:
return default
except Exception:
current_app.logger.warning('Encoding detection failed.', exc_info=True)
return default
finally:
fp.seek(init_pos) | [
"def",
"detect_encoding",
"(",
"fp",
",",
"default",
"=",
"None",
")",
":",
"init_pos",
"=",
"fp",
".",
"tell",
"(",
")",
"try",
":",
"sample",
"=",
"fp",
".",
"read",
"(",
"current_app",
".",
"config",
".",
"get",
"(",
"'PREVIEWER_CHARDET_BYTES'",
","... | Detect the cahracter encoding of a file.
:param fp: Open Python file pointer.
:param default: Fallback encoding to use.
:returns: The detected encoding.
.. note:: The file pointer is returned at its original read position. | [
"Detect",
"the",
"cahracter",
"encoding",
"of",
"a",
"file",
"."
] | train | https://github.com/inveniosoftware/invenio-previewer/blob/558fd22e0f29cc8cd7a6999abd4febcf6b248c49/invenio_previewer/utils.py#L15-L39 |
paylogic/halogen | halogen/types.py | Type.deserialize | def deserialize(self, value, **kwargs):
"""Deserialization of value.
:return: Deserialized value.
:raises: :class:`halogen.exception.ValidationError` exception if value is not valid.
"""
for validator in self.validators:
validator.validate(value, **kwargs)
return value | python | def deserialize(self, value, **kwargs):
"""Deserialization of value.
:return: Deserialized value.
:raises: :class:`halogen.exception.ValidationError` exception if value is not valid.
"""
for validator in self.validators:
validator.validate(value, **kwargs)
return value | [
"def",
"deserialize",
"(",
"self",
",",
"value",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"validator",
"in",
"self",
".",
"validators",
":",
"validator",
".",
"validate",
"(",
"value",
",",
"*",
"*",
"kwargs",
")",
"return",
"value"
] | Deserialization of value.
:return: Deserialized value.
:raises: :class:`halogen.exception.ValidationError` exception if value is not valid. | [
"Deserialization",
"of",
"value",
"."
] | train | https://github.com/paylogic/halogen/blob/2dec0a67c506d02d1f51915fa7163f59764a0bde/halogen/types.py#L29-L38 |
paylogic/halogen | halogen/types.py | Type.is_type | def is_type(value):
"""Determine if value is an instance or subclass of the class Type."""
if isinstance(value, type):
return issubclass(value, Type)
return isinstance(value, Type) | python | def is_type(value):
"""Determine if value is an instance or subclass of the class Type."""
if isinstance(value, type):
return issubclass(value, Type)
return isinstance(value, Type) | [
"def",
"is_type",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"type",
")",
":",
"return",
"issubclass",
"(",
"value",
",",
"Type",
")",
"return",
"isinstance",
"(",
"value",
",",
"Type",
")"
] | Determine if value is an instance or subclass of the class Type. | [
"Determine",
"if",
"value",
"is",
"an",
"instance",
"or",
"subclass",
"of",
"the",
"class",
"Type",
"."
] | train | https://github.com/paylogic/halogen/blob/2dec0a67c506d02d1f51915fa7163f59764a0bde/halogen/types.py#L41-L45 |
paylogic/halogen | halogen/types.py | List.serialize | def serialize(self, value, **kwargs):
"""Serialize every item of the list."""
return [self.item_type.serialize(val, **kwargs) for val in value] | python | def serialize(self, value, **kwargs):
"""Serialize every item of the list."""
return [self.item_type.serialize(val, **kwargs) for val in value] | [
"def",
"serialize",
"(",
"self",
",",
"value",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"[",
"self",
".",
"item_type",
".",
"serialize",
"(",
"val",
",",
"*",
"*",
"kwargs",
")",
"for",
"val",
"in",
"value",
"]"
] | Serialize every item of the list. | [
"Serialize",
"every",
"item",
"of",
"the",
"list",
"."
] | train | https://github.com/paylogic/halogen/blob/2dec0a67c506d02d1f51915fa7163f59764a0bde/halogen/types.py#L61-L63 |
paylogic/halogen | halogen/types.py | List.deserialize | def deserialize(self, value, **kwargs):
"""Deserialize every item of the list."""
if self.allow_scalar and not isinstance(value, (list, tuple)):
value = [value]
value = super(List, self).deserialize(value)
result = []
errors = []
for index, val in enumerate(value):
try:
result.append(self.item_type.deserialize(val, **kwargs))
except ValidationError as exc:
exc.index = index
errors.append(exc)
if errors:
raise ValidationError(errors)
return result | python | def deserialize(self, value, **kwargs):
"""Deserialize every item of the list."""
if self.allow_scalar and not isinstance(value, (list, tuple)):
value = [value]
value = super(List, self).deserialize(value)
result = []
errors = []
for index, val in enumerate(value):
try:
result.append(self.item_type.deserialize(val, **kwargs))
except ValidationError as exc:
exc.index = index
errors.append(exc)
if errors:
raise ValidationError(errors)
return result | [
"def",
"deserialize",
"(",
"self",
",",
"value",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"allow_scalar",
"and",
"not",
"isinstance",
"(",
"value",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"value",
"=",
"[",
"value",
"]",
"value"... | Deserialize every item of the list. | [
"Deserialize",
"every",
"item",
"of",
"the",
"list",
"."
] | train | https://github.com/paylogic/halogen/blob/2dec0a67c506d02d1f51915fa7163f59764a0bde/halogen/types.py#L65-L81 |
paylogic/halogen | halogen/types.py | ISOUTCDateTime.format_as_utc | def format_as_utc(self, value):
"""Format UTC times."""
if isinstance(value, datetime.datetime):
if value.tzinfo is not None:
value = value.astimezone(pytz.UTC)
value = value.replace(microsecond=0)
return value.isoformat().replace('+00:00', 'Z') | python | def format_as_utc(self, value):
"""Format UTC times."""
if isinstance(value, datetime.datetime):
if value.tzinfo is not None:
value = value.astimezone(pytz.UTC)
value = value.replace(microsecond=0)
return value.isoformat().replace('+00:00', 'Z') | [
"def",
"format_as_utc",
"(",
"self",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"datetime",
".",
"datetime",
")",
":",
"if",
"value",
".",
"tzinfo",
"is",
"not",
"None",
":",
"value",
"=",
"value",
".",
"astimezone",
"(",
"pytz",
... | Format UTC times. | [
"Format",
"UTC",
"times",
"."
] | train | https://github.com/paylogic/halogen/blob/2dec0a67c506d02d1f51915fa7163f59764a0bde/halogen/types.py#L110-L116 |
paylogic/halogen | halogen/types.py | Amount.amount_object_to_dict | def amount_object_to_dict(self, amount):
"""Return the dictionary representation of an Amount object.
Amount object must have amount and currency properties and as_tuple method which will return (currency, amount)
and as_quantized method to quantize amount property.
:param amount: instance of Amount object
:return: dict with amount and currency keys.
"""
currency, amount = (
amount.as_quantized(digits=2).as_tuple()
if not isinstance(amount, dict)
else (amount["currency"], amount["amount"])
)
if currency not in self.currencies:
raise ValueError(self.err_unknown_currency.format(currency=currency))
return {
"amount": str(amount),
"currency": str(currency),
} | python | def amount_object_to_dict(self, amount):
"""Return the dictionary representation of an Amount object.
Amount object must have amount and currency properties and as_tuple method which will return (currency, amount)
and as_quantized method to quantize amount property.
:param amount: instance of Amount object
:return: dict with amount and currency keys.
"""
currency, amount = (
amount.as_quantized(digits=2).as_tuple()
if not isinstance(amount, dict)
else (amount["currency"], amount["amount"])
)
if currency not in self.currencies:
raise ValueError(self.err_unknown_currency.format(currency=currency))
return {
"amount": str(amount),
"currency": str(currency),
} | [
"def",
"amount_object_to_dict",
"(",
"self",
",",
"amount",
")",
":",
"currency",
",",
"amount",
"=",
"(",
"amount",
".",
"as_quantized",
"(",
"digits",
"=",
"2",
")",
".",
"as_tuple",
"(",
")",
"if",
"not",
"isinstance",
"(",
"amount",
",",
"dict",
")... | Return the dictionary representation of an Amount object.
Amount object must have amount and currency properties and as_tuple method which will return (currency, amount)
and as_quantized method to quantize amount property.
:param amount: instance of Amount object
:return: dict with amount and currency keys. | [
"Return",
"the",
"dictionary",
"representation",
"of",
"an",
"Amount",
"object",
"."
] | train | https://github.com/paylogic/halogen/blob/2dec0a67c506d02d1f51915fa7163f59764a0bde/halogen/types.py#L205-L225 |
paylogic/halogen | halogen/types.py | Amount.deserialize | def deserialize(self, value, **kwargs):
"""Deserialize the amount.
:param value: Amount in CURRENCYAMOUNT or {"currency": CURRENCY, "amount": AMOUNT} format. For example EUR35.50
or {"currency": "EUR", "amount": "35.50"}
:return: A paylogic Amount object.
:raises ValidationError: when amount can"t be deserialzied
:raises ValidationError: when amount has more than 2 decimal places
"""
if value is None:
return None
if isinstance(value, six.string_types):
currency = value[:3]
amount = value[3:]
elif isinstance(value, dict):
if set(value.keys()) != set(("currency", "amount")):
raise ValueError("Amount object has to have currency and amount fields.")
amount = value["amount"]
currency = value["currency"]
else:
raise ValueError("Value cannot be parsed to Amount.")
if currency not in self.currencies:
raise ValueError(self.err_unknown_currency.format(currency=currency))
try:
amount = decimal.Decimal(amount).normalize()
except decimal.InvalidOperation:
raise ValueError(u"'{amount}' cannot be parsed to decimal.".format(amount=amount))
if amount.as_tuple().exponent < - 2:
raise ValueError(u"'{amount}' has more than 2 decimal places.".format(amount=amount))
value = self.amount_class(currency=currency, amount=amount)
return super(Amount, self).deserialize(value) | python | def deserialize(self, value, **kwargs):
"""Deserialize the amount.
:param value: Amount in CURRENCYAMOUNT or {"currency": CURRENCY, "amount": AMOUNT} format. For example EUR35.50
or {"currency": "EUR", "amount": "35.50"}
:return: A paylogic Amount object.
:raises ValidationError: when amount can"t be deserialzied
:raises ValidationError: when amount has more than 2 decimal places
"""
if value is None:
return None
if isinstance(value, six.string_types):
currency = value[:3]
amount = value[3:]
elif isinstance(value, dict):
if set(value.keys()) != set(("currency", "amount")):
raise ValueError("Amount object has to have currency and amount fields.")
amount = value["amount"]
currency = value["currency"]
else:
raise ValueError("Value cannot be parsed to Amount.")
if currency not in self.currencies:
raise ValueError(self.err_unknown_currency.format(currency=currency))
try:
amount = decimal.Decimal(amount).normalize()
except decimal.InvalidOperation:
raise ValueError(u"'{amount}' cannot be parsed to decimal.".format(amount=amount))
if amount.as_tuple().exponent < - 2:
raise ValueError(u"'{amount}' has more than 2 decimal places.".format(amount=amount))
value = self.amount_class(currency=currency, amount=amount)
return super(Amount, self).deserialize(value) | [
"def",
"deserialize",
"(",
"self",
",",
"value",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"None",
"if",
"isinstance",
"(",
"value",
",",
"six",
".",
"string_types",
")",
":",
"currency",
"=",
"value",
"[",
":",
... | Deserialize the amount.
:param value: Amount in CURRENCYAMOUNT or {"currency": CURRENCY, "amount": AMOUNT} format. For example EUR35.50
or {"currency": "EUR", "amount": "35.50"}
:return: A paylogic Amount object.
:raises ValidationError: when amount can"t be deserialzied
:raises ValidationError: when amount has more than 2 decimal places | [
"Deserialize",
"the",
"amount",
"."
] | train | https://github.com/paylogic/halogen/blob/2dec0a67c506d02d1f51915fa7163f59764a0bde/halogen/types.py#L238-L274 |
toumorokoshi/transmute-core | transmute_core/contenttype_serializers/json_serializer.py | JsonSerializer.load | def load(raw_bytes):
"""
given a bytes object, should return a base python data
structure that represents the object.
"""
try:
if not isinstance(raw_bytes, string_type):
raw_bytes = raw_bytes.decode()
return json.loads(raw_bytes)
except ValueError as e:
raise SerializationException(str(e)) | python | def load(raw_bytes):
"""
given a bytes object, should return a base python data
structure that represents the object.
"""
try:
if not isinstance(raw_bytes, string_type):
raw_bytes = raw_bytes.decode()
return json.loads(raw_bytes)
except ValueError as e:
raise SerializationException(str(e)) | [
"def",
"load",
"(",
"raw_bytes",
")",
":",
"try",
":",
"if",
"not",
"isinstance",
"(",
"raw_bytes",
",",
"string_type",
")",
":",
"raw_bytes",
"=",
"raw_bytes",
".",
"decode",
"(",
")",
"return",
"json",
".",
"loads",
"(",
"raw_bytes",
")",
"except",
"... | given a bytes object, should return a base python data
structure that represents the object. | [
"given",
"a",
"bytes",
"object",
"should",
"return",
"a",
"base",
"python",
"data",
"structure",
"that",
"represents",
"the",
"object",
"."
] | train | https://github.com/toumorokoshi/transmute-core/blob/a2c26625d5d8bab37e00038f9d615a26167fc7f4/transmute_core/contenttype_serializers/json_serializer.py#L25-L35 |
toumorokoshi/transmute-core | transmute_core/frameworks/aiohttp/route.py | add_route | def add_route(app, fn, context=default_context):
"""
a decorator that adds a transmute route to the application.
"""
transmute_func = TransmuteFunction(
fn,
args_not_from_request=["request"]
)
handler = create_handler(transmute_func, context=context)
get_swagger_spec(app).add_func(transmute_func, context)
for p in transmute_func.paths:
aiohttp_path = _convert_to_aiohttp_path(p)
resource = app.router.add_resource(aiohttp_path)
for method in transmute_func.methods:
resource.add_route(method, handler) | python | def add_route(app, fn, context=default_context):
"""
a decorator that adds a transmute route to the application.
"""
transmute_func = TransmuteFunction(
fn,
args_not_from_request=["request"]
)
handler = create_handler(transmute_func, context=context)
get_swagger_spec(app).add_func(transmute_func, context)
for p in transmute_func.paths:
aiohttp_path = _convert_to_aiohttp_path(p)
resource = app.router.add_resource(aiohttp_path)
for method in transmute_func.methods:
resource.add_route(method, handler) | [
"def",
"add_route",
"(",
"app",
",",
"fn",
",",
"context",
"=",
"default_context",
")",
":",
"transmute_func",
"=",
"TransmuteFunction",
"(",
"fn",
",",
"args_not_from_request",
"=",
"[",
"\"request\"",
"]",
")",
"handler",
"=",
"create_handler",
"(",
"transmu... | a decorator that adds a transmute route to the application. | [
"a",
"decorator",
"that",
"adds",
"a",
"transmute",
"route",
"to",
"the",
"application",
"."
] | train | https://github.com/toumorokoshi/transmute-core/blob/a2c26625d5d8bab37e00038f9d615a26167fc7f4/transmute_core/frameworks/aiohttp/route.py#L6-L21 |
inveniosoftware/invenio-previewer | invenio_previewer/views.py | preview | def preview(pid, record, template=None, **kwargs):
"""Preview file for given record.
Plug this method into your ``RECORDS_UI_ENDPOINTS`` configuration:
.. code-block:: python
RECORDS_UI_ENDPOINTS = dict(
recid=dict(
# ...
route='/records/<pid_value/preview/<path:filename>',
view_imp='invenio_previewer.views.preview',
record_class='invenio_records_files.api:Record',
)
)
"""
# Get file from record
fileobj = current_previewer.record_file_factory(
pid, record, request.view_args.get(
'filename', request.args.get('filename', type=str))
)
if not fileobj:
abort(404)
# Try to see if specific previewer is requested?
try:
file_previewer = fileobj['previewer']
except KeyError:
file_previewer = None
# Find a suitable previewer
fileobj = PreviewFile(pid, record, fileobj)
for plugin in current_previewer.iter_previewers(
previewers=[file_previewer] if file_previewer else None):
if plugin.can_preview(fileobj):
try:
return plugin.preview(fileobj)
except Exception:
current_app.logger.warning(
('Preview failed for {key}, in {pid_type}:{pid_value}'
.format(key=fileobj.file.key,
pid_type=fileobj.pid.pid_type,
pid_value=fileobj.pid.pid_value)),
exc_info=True)
return default.preview(fileobj) | python | def preview(pid, record, template=None, **kwargs):
"""Preview file for given record.
Plug this method into your ``RECORDS_UI_ENDPOINTS`` configuration:
.. code-block:: python
RECORDS_UI_ENDPOINTS = dict(
recid=dict(
# ...
route='/records/<pid_value/preview/<path:filename>',
view_imp='invenio_previewer.views.preview',
record_class='invenio_records_files.api:Record',
)
)
"""
# Get file from record
fileobj = current_previewer.record_file_factory(
pid, record, request.view_args.get(
'filename', request.args.get('filename', type=str))
)
if not fileobj:
abort(404)
# Try to see if specific previewer is requested?
try:
file_previewer = fileobj['previewer']
except KeyError:
file_previewer = None
# Find a suitable previewer
fileobj = PreviewFile(pid, record, fileobj)
for plugin in current_previewer.iter_previewers(
previewers=[file_previewer] if file_previewer else None):
if plugin.can_preview(fileobj):
try:
return plugin.preview(fileobj)
except Exception:
current_app.logger.warning(
('Preview failed for {key}, in {pid_type}:{pid_value}'
.format(key=fileobj.file.key,
pid_type=fileobj.pid.pid_type,
pid_value=fileobj.pid.pid_value)),
exc_info=True)
return default.preview(fileobj) | [
"def",
"preview",
"(",
"pid",
",",
"record",
",",
"template",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# Get file from record",
"fileobj",
"=",
"current_previewer",
".",
"record_file_factory",
"(",
"pid",
",",
"record",
",",
"request",
".",
"view_arg... | Preview file for given record.
Plug this method into your ``RECORDS_UI_ENDPOINTS`` configuration:
.. code-block:: python
RECORDS_UI_ENDPOINTS = dict(
recid=dict(
# ...
route='/records/<pid_value/preview/<path:filename>',
view_imp='invenio_previewer.views.preview',
record_class='invenio_records_files.api:Record',
)
) | [
"Preview",
"file",
"for",
"given",
"record",
"."
] | train | https://github.com/inveniosoftware/invenio-previewer/blob/558fd22e0f29cc8cd7a6999abd4febcf6b248c49/invenio_previewer/views.py#L28-L72 |
dhondta/tinyscript | tinyscript/template.py | new | def new(template, target=None, name=None):
"""
Function for creating a template script or tool.
:param template: template to be used ; one of TEMPLATES
:param target: type of script/tool to be created
:param name: name of the new script/tool
"""
if template not in TEMPLATES:
raise ValueError("Template argument must be one of the followings: {}"
.format(", ".join(TEMPLATES)))
if target is not None and target not in TARGETS.keys():
raise ValueError("Target argument must be one of the followings: {}"
.format(TARGETS.keys()))
name = name or template
if NAME_REGEX.match(name) is None:
raise ValueError("Invalid {} name".format(template))
with open("{}.py".format(name), 'w') as f:
target_imp = "" if target is None else "from {} import {}\n" \
.format(*target.split('.'))
main = MAIN.format(base=TARGETS.get(target) or "")
if template == "script":
f.write(SHEBANG + IMPORTS.format(target=target_imp) + "\n\n" + main)
elif template == "tool":
f.write(SHEBANG + TOOL_METADATA + TOOL_SECTIONS \
.format(imports=IMPORTS.format(target=target_imp)) + main) | python | def new(template, target=None, name=None):
"""
Function for creating a template script or tool.
:param template: template to be used ; one of TEMPLATES
:param target: type of script/tool to be created
:param name: name of the new script/tool
"""
if template not in TEMPLATES:
raise ValueError("Template argument must be one of the followings: {}"
.format(", ".join(TEMPLATES)))
if target is not None and target not in TARGETS.keys():
raise ValueError("Target argument must be one of the followings: {}"
.format(TARGETS.keys()))
name = name or template
if NAME_REGEX.match(name) is None:
raise ValueError("Invalid {} name".format(template))
with open("{}.py".format(name), 'w') as f:
target_imp = "" if target is None else "from {} import {}\n" \
.format(*target.split('.'))
main = MAIN.format(base=TARGETS.get(target) or "")
if template == "script":
f.write(SHEBANG + IMPORTS.format(target=target_imp) + "\n\n" + main)
elif template == "tool":
f.write(SHEBANG + TOOL_METADATA + TOOL_SECTIONS \
.format(imports=IMPORTS.format(target=target_imp)) + main) | [
"def",
"new",
"(",
"template",
",",
"target",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"if",
"template",
"not",
"in",
"TEMPLATES",
":",
"raise",
"ValueError",
"(",
"\"Template argument must be one of the followings: {}\"",
".",
"format",
"(",
"\", \"",
... | Function for creating a template script or tool.
:param template: template to be used ; one of TEMPLATES
:param target: type of script/tool to be created
:param name: name of the new script/tool | [
"Function",
"for",
"creating",
"a",
"template",
"script",
"or",
"tool",
".",
":",
"param",
"template",
":",
"template",
"to",
"be",
"used",
";",
"one",
"of",
"TEMPLATES",
":",
"param",
"target",
":",
"type",
"of",
"script",
"/",
"tool",
"to",
"be",
"cr... | train | https://github.com/dhondta/tinyscript/blob/624a0718db698899e7bc3ba6ac694baed251e81d/tinyscript/template.py#L78-L103 |
toumorokoshi/transmute-core | transmute_core/frameworks/flask/swagger.py | add_swagger | def add_swagger(app, json_route, html_route, **kwargs):
"""
a convenience method for both adding a swagger.json route,
as well as adding a page showing the html documentation
"""
app.route(json_route)(create_swagger_json_handler(app, **kwargs))
add_swagger_api_route(app, html_route, json_route) | python | def add_swagger(app, json_route, html_route, **kwargs):
"""
a convenience method for both adding a swagger.json route,
as well as adding a page showing the html documentation
"""
app.route(json_route)(create_swagger_json_handler(app, **kwargs))
add_swagger_api_route(app, html_route, json_route) | [
"def",
"add_swagger",
"(",
"app",
",",
"json_route",
",",
"html_route",
",",
"*",
"*",
"kwargs",
")",
":",
"app",
".",
"route",
"(",
"json_route",
")",
"(",
"create_swagger_json_handler",
"(",
"app",
",",
"*",
"*",
"kwargs",
")",
")",
"add_swagger_api_rout... | a convenience method for both adding a swagger.json route,
as well as adding a page showing the html documentation | [
"a",
"convenience",
"method",
"for",
"both",
"adding",
"a",
"swagger",
".",
"json",
"route",
"as",
"well",
"as",
"adding",
"a",
"page",
"showing",
"the",
"html",
"documentation"
] | train | https://github.com/toumorokoshi/transmute-core/blob/a2c26625d5d8bab37e00038f9d615a26167fc7f4/transmute_core/frameworks/flask/swagger.py#L14-L20 |
toumorokoshi/transmute-core | transmute_core/frameworks/flask/swagger.py | add_swagger_api_route | def add_swagger_api_route(app, target_route, swagger_json_route):
"""
mount a swagger statics page.
app: the flask app object
target_route: the path to mount the statics page.
swagger_json_route: the path where the swagger json definitions is
expected to be.
"""
static_root = get_swagger_static_root()
swagger_body = generate_swagger_html(
STATIC_ROOT, swagger_json_route
).encode("utf-8")
def swagger_ui():
return Response(swagger_body, content_type="text/html")
blueprint = Blueprint('swagger', __name__,
static_url_path=STATIC_ROOT,
static_folder=static_root)
app.route(target_route)(swagger_ui)
app.register_blueprint(blueprint) | python | def add_swagger_api_route(app, target_route, swagger_json_route):
"""
mount a swagger statics page.
app: the flask app object
target_route: the path to mount the statics page.
swagger_json_route: the path where the swagger json definitions is
expected to be.
"""
static_root = get_swagger_static_root()
swagger_body = generate_swagger_html(
STATIC_ROOT, swagger_json_route
).encode("utf-8")
def swagger_ui():
return Response(swagger_body, content_type="text/html")
blueprint = Blueprint('swagger', __name__,
static_url_path=STATIC_ROOT,
static_folder=static_root)
app.route(target_route)(swagger_ui)
app.register_blueprint(blueprint) | [
"def",
"add_swagger_api_route",
"(",
"app",
",",
"target_route",
",",
"swagger_json_route",
")",
":",
"static_root",
"=",
"get_swagger_static_root",
"(",
")",
"swagger_body",
"=",
"generate_swagger_html",
"(",
"STATIC_ROOT",
",",
"swagger_json_route",
")",
".",
"encod... | mount a swagger statics page.
app: the flask app object
target_route: the path to mount the statics page.
swagger_json_route: the path where the swagger json definitions is
expected to be. | [
"mount",
"a",
"swagger",
"statics",
"page",
"."
] | train | https://github.com/toumorokoshi/transmute-core/blob/a2c26625d5d8bab37e00038f9d615a26167fc7f4/transmute_core/frameworks/flask/swagger.py#L23-L44 |
toumorokoshi/transmute-core | transmute_core/frameworks/flask/swagger.py | create_swagger_json_handler | def create_swagger_json_handler(app, **kwargs):
"""
Create a handler that returns the swagger definition
for an application.
This method assumes the application is using the
TransmuteUrlDispatcher as the router.
"""
spec = getattr(app, SWAGGER_ATTR_NAME, SwaggerSpec())
_add_blueprint_specs(app, spec)
spec_dict = spec.swagger_definition(**kwargs)
encoded_spec = json.dumps(spec_dict).encode("UTF-8")
def swagger():
return Response(
encoded_spec,
# we allow CORS, so this can be requested at swagger.io
headers={
"Access-Control-Allow-Origin": "*"
},
content_type="application/json",
)
return swagger | python | def create_swagger_json_handler(app, **kwargs):
"""
Create a handler that returns the swagger definition
for an application.
This method assumes the application is using the
TransmuteUrlDispatcher as the router.
"""
spec = getattr(app, SWAGGER_ATTR_NAME, SwaggerSpec())
_add_blueprint_specs(app, spec)
spec_dict = spec.swagger_definition(**kwargs)
encoded_spec = json.dumps(spec_dict).encode("UTF-8")
def swagger():
return Response(
encoded_spec,
# we allow CORS, so this can be requested at swagger.io
headers={
"Access-Control-Allow-Origin": "*"
},
content_type="application/json",
)
return swagger | [
"def",
"create_swagger_json_handler",
"(",
"app",
",",
"*",
"*",
"kwargs",
")",
":",
"spec",
"=",
"getattr",
"(",
"app",
",",
"SWAGGER_ATTR_NAME",
",",
"SwaggerSpec",
"(",
")",
")",
"_add_blueprint_specs",
"(",
"app",
",",
"spec",
")",
"spec_dict",
"=",
"s... | Create a handler that returns the swagger definition
for an application.
This method assumes the application is using the
TransmuteUrlDispatcher as the router. | [
"Create",
"a",
"handler",
"that",
"returns",
"the",
"swagger",
"definition",
"for",
"an",
"application",
"."
] | train | https://github.com/toumorokoshi/transmute-core/blob/a2c26625d5d8bab37e00038f9d615a26167fc7f4/transmute_core/frameworks/flask/swagger.py#L47-L71 |
inveniosoftware/invenio-previewer | examples/app.py | fixtures | def fixtures():
"""Command for working with test data."""
temp_path = os.path.join(os.path.dirname(__file__), 'temp')
demo_files_path = os.path.join(os.path.dirname(__file__), 'demo_files')
# Create location
loc = Location(name='local', uri=temp_path, default=True)
db.session.add(loc)
db.session.commit()
# Example files from the data folder
demo_files = (
'markdown.md',
'csvfile.csv',
'zipfile.zip',
'jsonfile.json',
'xmlfile.xml',
'notebook.ipynb',
'jpgfile.jpg',
'pngfile.png',
)
rec_uuid = uuid4()
provider = RecordIdProvider.create(object_type='rec', object_uuid=rec_uuid)
data = {
'pid_value': provider.pid.pid_value,
}
record = Record.create(data, id_=rec_uuid)
bucket = Bucket.create()
RecordsBuckets.create(record=record.model, bucket=bucket)
# Add files to the record
for f in demo_files:
with open(os.path.join(demo_files_path, f), 'rb') as fp:
record.files[f] = fp
record.files.flush()
record.commit()
db.session.commit() | python | def fixtures():
"""Command for working with test data."""
temp_path = os.path.join(os.path.dirname(__file__), 'temp')
demo_files_path = os.path.join(os.path.dirname(__file__), 'demo_files')
# Create location
loc = Location(name='local', uri=temp_path, default=True)
db.session.add(loc)
db.session.commit()
# Example files from the data folder
demo_files = (
'markdown.md',
'csvfile.csv',
'zipfile.zip',
'jsonfile.json',
'xmlfile.xml',
'notebook.ipynb',
'jpgfile.jpg',
'pngfile.png',
)
rec_uuid = uuid4()
provider = RecordIdProvider.create(object_type='rec', object_uuid=rec_uuid)
data = {
'pid_value': provider.pid.pid_value,
}
record = Record.create(data, id_=rec_uuid)
bucket = Bucket.create()
RecordsBuckets.create(record=record.model, bucket=bucket)
# Add files to the record
for f in demo_files:
with open(os.path.join(demo_files_path, f), 'rb') as fp:
record.files[f] = fp
record.files.flush()
record.commit()
db.session.commit() | [
"def",
"fixtures",
"(",
")",
":",
"temp_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"'temp'",
")",
"demo_files_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
... | Command for working with test data. | [
"Command",
"for",
"working",
"with",
"test",
"data",
"."
] | train | https://github.com/inveniosoftware/invenio-previewer/blob/558fd22e0f29cc8cd7a6999abd4febcf6b248c49/examples/app.py#L87-L126 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.