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... | 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... | [
"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)
Re... | 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)
Re... | [
"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_di... | [
"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)
... | 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)
... | [
"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... | 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... | [
"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 = []
f... | 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 = []
f... | [
"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 (inclu... | 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 (inclu... | [
"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 ... | [
"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_R... | 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_R... | [
"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.descript... | 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.descript... | [
"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,
'... | 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,
'... | [
"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,
... | [
"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.
... | 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.
... | [
"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 ancho... | [
"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, __ = s... | 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, __ = s... | [
"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 = ge... | 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 = ge... | [
"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]
... | 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]
... | [
"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... | 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... | [
"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... | 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... | [
"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 consecu... | 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 consecu... | [
"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 thr... | [
"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.o... | 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.o... | [
"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... | [
"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,
'... | 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,
'... | [
"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,
... | [
"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)
r... | 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)
r... | [
"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)
:para... | 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)
:para... | [
"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... | [
"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]
anc... | 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]
anc... | [
"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 poi... | 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 poi... | [
"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 ... | [
"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 po... | 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 po... | [
"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": R... | 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": R... | [
"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.respo... | 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.respo... | [
"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_st... | 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_st... | [
"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.... | 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.... | [
"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))
... | 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))
... | [
"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_si... | 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_si... | [
"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 "intera... | 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 "intera... | [
"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 deb... | 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 deb... | [
"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 ... | [
"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 ... | 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 ... | [
"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
... | [
"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:
... | 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:
... | [
"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 ... | [
"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... | 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... | [
"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: Numbe... | [
"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
la... | 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
la... | [
"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
... | 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
... | [
"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... | 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... | [
"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 + ... | 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 + ... | [
"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) + n... | 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) + n... | [
"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. Continu... | 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. Continu... | [
"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 ... | 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 ... | [
"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 = Minimi... | 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 = Minimi... | [
"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)
# ... | 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)
# ... | [
"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 ch... | 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 ch... | [
"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__
... | 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__
... | [
"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, ... | 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, ... | [
"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
... | 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
... | [
"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(ob... | [
"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 ... | 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 ... | [
"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 (wri... | 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 (wri... | [
"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... | [
"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):
se... | 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):
se... | [
"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 ... | 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 ... | [
"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)
re... | 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)
re... | [
"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,
... | 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,
... | [
"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.proc... | 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.proc... | [
"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,
... | 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,
... | [
"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:
... | 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:
... | [
"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)
... | 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)
... | [
"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',
... | 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',
... | [
"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/c... | [
"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... | 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... | [
"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()
... | [
"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:
... | 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:
... | [
"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 sel... | 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 sel... | [
"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)
... | 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)
... | [
"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 += "/"
... | 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 += "/"
... | [
"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.
... | 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.
... | [
"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)
... | [
"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)
... | 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)
... | [
"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.
"""
... | 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.
"""
... | [
"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()
... | 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()
... | [
"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)
r... | 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)
r... | [
"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(v... | 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(v... | [
"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: inst... | 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: inst... | [
"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 am... | [
"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 Validation... | 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 Validation... | [
"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
:r... | [
"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)
ex... | 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)
ex... | [
"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... | 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... | [
"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/prev... | 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/prev... | [
"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_pr... | [
"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:
... | 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:
... | [
"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_sw... | 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_sw... | [
"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_s... | 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_s... | [
"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.se... | 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.se... | [
"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.