repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
Jaymon/endpoints | endpoints/http.py | Request.body | def body(self):
"""return the raw version of the body"""
body = None
if self.body_input:
body = self.body_input.read(int(self.get_header('content-length', -1)))
return body | python | def body(self):
"""return the raw version of the body"""
body = None
if self.body_input:
body = self.body_input.read(int(self.get_header('content-length', -1)))
return body | [
"def",
"body",
"(",
"self",
")",
":",
"body",
"=",
"None",
"if",
"self",
".",
"body_input",
":",
"body",
"=",
"self",
".",
"body_input",
".",
"read",
"(",
"int",
"(",
"self",
".",
"get_header",
"(",
"'content-length'",
",",
"-",
"1",
")",
")",
")",... | return the raw version of the body | [
"return",
"the",
"raw",
"version",
"of",
"the",
"body"
] | train | https://github.com/Jaymon/endpoints/blob/2f1c4ae2c69a168e69447d3d8395ada7becaa5fb/endpoints/http.py#L1004-L1010 |
Jaymon/endpoints | endpoints/http.py | Request.body_kwargs | def body_kwargs(self):
"""
the request body, if this is a POST request
this tries to do the right thing with the body, so if you have set the body and
the content type is json, then it will return the body json decoded, if you need
the original string body, use body
exa... | python | def body_kwargs(self):
"""
the request body, if this is a POST request
this tries to do the right thing with the body, so if you have set the body and
the content type is json, then it will return the body json decoded, if you need
the original string body, use body
exa... | [
"def",
"body_kwargs",
"(",
"self",
")",
":",
"body_kwargs",
"=",
"{",
"}",
"ct",
"=",
"self",
".",
"get_header",
"(",
"\"content-type\"",
")",
"if",
"ct",
":",
"ct",
"=",
"ct",
".",
"lower",
"(",
")",
"if",
"ct",
".",
"rfind",
"(",
"\"json\"",
")",... | the request body, if this is a POST request
this tries to do the right thing with the body, so if you have set the body and
the content type is json, then it will return the body json decoded, if you need
the original string body, use body
example --
self.body = '{"foo":{"... | [
"the",
"request",
"body",
"if",
"this",
"is",
"a",
"POST",
"request"
] | train | https://github.com/Jaymon/endpoints/blob/2f1c4ae2c69a168e69447d3d8395ada7becaa5fb/endpoints/http.py#L1021-L1059 |
Jaymon/endpoints | endpoints/http.py | Request.kwargs | def kwargs(self):
"""combine GET and POST params to be passed to the controller"""
kwargs = dict(self.query_kwargs)
kwargs.update(self.body_kwargs)
return kwargs | python | def kwargs(self):
"""combine GET and POST params to be passed to the controller"""
kwargs = dict(self.query_kwargs)
kwargs.update(self.body_kwargs)
return kwargs | [
"def",
"kwargs",
"(",
"self",
")",
":",
"kwargs",
"=",
"dict",
"(",
"self",
".",
"query_kwargs",
")",
"kwargs",
".",
"update",
"(",
"self",
".",
"body_kwargs",
")",
"return",
"kwargs"
] | combine GET and POST params to be passed to the controller | [
"combine",
"GET",
"and",
"POST",
"params",
"to",
"be",
"passed",
"to",
"the",
"controller"
] | train | https://github.com/Jaymon/endpoints/blob/2f1c4ae2c69a168e69447d3d8395ada7becaa5fb/endpoints/http.py#L1068-L1073 |
Jaymon/endpoints | endpoints/http.py | Request.version | def version(self, content_type="*/*"):
"""
versioning is based off of this post
http://urthen.github.io/2013/05/09/ways-to-version-your-api/
"""
v = ""
accept_header = self.get_header('accept', "")
if accept_header:
a = AcceptHeader(accept_header)
... | python | def version(self, content_type="*/*"):
"""
versioning is based off of this post
http://urthen.github.io/2013/05/09/ways-to-version-your-api/
"""
v = ""
accept_header = self.get_header('accept', "")
if accept_header:
a = AcceptHeader(accept_header)
... | [
"def",
"version",
"(",
"self",
",",
"content_type",
"=",
"\"*/*\"",
")",
":",
"v",
"=",
"\"\"",
"accept_header",
"=",
"self",
".",
"get_header",
"(",
"'accept'",
",",
"\"\"",
")",
"if",
"accept_header",
":",
"a",
"=",
"AcceptHeader",
"(",
"accept_header",
... | versioning is based off of this post
http://urthen.github.io/2013/05/09/ways-to-version-your-api/ | [
"versioning",
"is",
"based",
"off",
"of",
"this",
"post",
"http",
":",
"//",
"urthen",
".",
"github",
".",
"io",
"/",
"2013",
"/",
"05",
"/",
"09",
"/",
"ways",
"-",
"to",
"-",
"version",
"-",
"your",
"-",
"api",
"/"
] | train | https://github.com/Jaymon/endpoints/blob/2f1c4ae2c69a168e69447d3d8395ada7becaa5fb/endpoints/http.py#L1079-L1092 |
Jaymon/endpoints | endpoints/http.py | Request.get_auth_bearer | def get_auth_bearer(self):
"""return the bearer token in the authorization header if it exists"""
access_token = ''
auth_header = self.get_header('authorization')
if auth_header:
m = re.search(r"^Bearer\s+(\S+)$", auth_header, re.I)
if m: access_token = m.group(1)... | python | def get_auth_bearer(self):
"""return the bearer token in the authorization header if it exists"""
access_token = ''
auth_header = self.get_header('authorization')
if auth_header:
m = re.search(r"^Bearer\s+(\S+)$", auth_header, re.I)
if m: access_token = m.group(1)... | [
"def",
"get_auth_bearer",
"(",
"self",
")",
":",
"access_token",
"=",
"''",
"auth_header",
"=",
"self",
".",
"get_header",
"(",
"'authorization'",
")",
"if",
"auth_header",
":",
"m",
"=",
"re",
".",
"search",
"(",
"r\"^Bearer\\s+(\\S+)$\"",
",",
"auth_header",... | return the bearer token in the authorization header if it exists | [
"return",
"the",
"bearer",
"token",
"in",
"the",
"authorization",
"header",
"if",
"it",
"exists"
] | train | https://github.com/Jaymon/endpoints/blob/2f1c4ae2c69a168e69447d3d8395ada7becaa5fb/endpoints/http.py#L1103-L1111 |
Jaymon/endpoints | endpoints/http.py | Request.get_auth_basic | def get_auth_basic(self):
"""return the username and password of a basic auth header if it exists"""
username = ''
password = ''
auth_header = self.get_header('authorization')
if auth_header:
m = re.search(r"^Basic\s+(\S+)$", auth_header, re.I)
if m:
... | python | def get_auth_basic(self):
"""return the username and password of a basic auth header if it exists"""
username = ''
password = ''
auth_header = self.get_header('authorization')
if auth_header:
m = re.search(r"^Basic\s+(\S+)$", auth_header, re.I)
if m:
... | [
"def",
"get_auth_basic",
"(",
"self",
")",
":",
"username",
"=",
"''",
"password",
"=",
"''",
"auth_header",
"=",
"self",
".",
"get_header",
"(",
"'authorization'",
")",
"if",
"auth_header",
":",
"m",
"=",
"re",
".",
"search",
"(",
"r\"^Basic\\s+(\\S+)$\"",
... | return the username and password of a basic auth header if it exists | [
"return",
"the",
"username",
"and",
"password",
"of",
"a",
"basic",
"auth",
"header",
"if",
"it",
"exists"
] | train | https://github.com/Jaymon/endpoints/blob/2f1c4ae2c69a168e69447d3d8395ada7becaa5fb/endpoints/http.py#L1113-L1124 |
Jaymon/endpoints | endpoints/http.py | Response.code | def code(self):
"""the http status code to return to the client, by default, 200 if a body is present otherwise 204"""
code = getattr(self, '_code', None)
if not code:
if self.has_body():
code = 200
else:
code = 204
return code | python | def code(self):
"""the http status code to return to the client, by default, 200 if a body is present otherwise 204"""
code = getattr(self, '_code', None)
if not code:
if self.has_body():
code = 200
else:
code = 204
return code | [
"def",
"code",
"(",
"self",
")",
":",
"code",
"=",
"getattr",
"(",
"self",
",",
"'_code'",
",",
"None",
")",
"if",
"not",
"code",
":",
"if",
"self",
".",
"has_body",
"(",
")",
":",
"code",
"=",
"200",
"else",
":",
"code",
"=",
"204",
"return",
... | the http status code to return to the client, by default, 200 if a body is present otherwise 204 | [
"the",
"http",
"status",
"code",
"to",
"return",
"to",
"the",
"client",
"by",
"default",
"200",
"if",
"a",
"body",
"is",
"present",
"otherwise",
"204"
] | train | https://github.com/Jaymon/endpoints/blob/2f1c4ae2c69a168e69447d3d8395ada7becaa5fb/endpoints/http.py#L1144-L1153 |
Jaymon/endpoints | endpoints/http.py | Response.normalize_body | def normalize_body(self, b):
"""return the body as a string, formatted to the appropriate content type
:param b: mixed, the current raw body
:returns: unicode string
"""
if b is None: return ''
if self.is_json():
# TODO ???
# I don't like this, i... | python | def normalize_body(self, b):
"""return the body as a string, formatted to the appropriate content type
:param b: mixed, the current raw body
:returns: unicode string
"""
if b is None: return ''
if self.is_json():
# TODO ???
# I don't like this, i... | [
"def",
"normalize_body",
"(",
"self",
",",
"b",
")",
":",
"if",
"b",
"is",
"None",
":",
"return",
"''",
"if",
"self",
".",
"is_json",
"(",
")",
":",
"# TODO ???",
"# I don't like this, if we have a content type but it isn't one",
"# of the supported ones we were retur... | return the body as a string, formatted to the appropriate content type
:param b: mixed, the current raw body
:returns: unicode string | [
"return",
"the",
"body",
"as",
"a",
"string",
"formatted",
"to",
"the",
"appropriate",
"content",
"type"
] | train | https://github.com/Jaymon/endpoints/blob/2f1c4ae2c69a168e69447d3d8395ada7becaa5fb/endpoints/http.py#L1218-L1240 |
Jaymon/endpoints | endpoints/decorators/base.py | TargetDecorator.normalize_target_params | def normalize_target_params(self, request, controller_args, controller_kwargs):
"""get params ready for calling target
this method exists because child classes might only really need certain params
passed to the method, this allows the child classes to decided what their
target methods ... | python | def normalize_target_params(self, request, controller_args, controller_kwargs):
"""get params ready for calling target
this method exists because child classes might only really need certain params
passed to the method, this allows the child classes to decided what their
target methods ... | [
"def",
"normalize_target_params",
"(",
"self",
",",
"request",
",",
"controller_args",
",",
"controller_kwargs",
")",
":",
"return",
"[",
"]",
",",
"dict",
"(",
"request",
"=",
"request",
",",
"controller_args",
"=",
"controller_args",
",",
"controller_kwargs",
... | get params ready for calling target
this method exists because child classes might only really need certain params
passed to the method, this allows the child classes to decided what their
target methods need
:param request: the http.Request instance for this specific request
:... | [
"get",
"params",
"ready",
"for",
"calling",
"target"
] | train | https://github.com/Jaymon/endpoints/blob/2f1c4ae2c69a168e69447d3d8395ada7becaa5fb/endpoints/decorators/base.py#L19-L37 |
Jaymon/endpoints | endpoints/decorators/base.py | TargetDecorator.handle_target | def handle_target(self, request, controller_args, controller_kwargs):
"""Internal method for this class
handles normalizing the passed in values from the decorator using
.normalize_target_params() and then passes them to the set .target()
"""
try:
param_args, param_k... | python | def handle_target(self, request, controller_args, controller_kwargs):
"""Internal method for this class
handles normalizing the passed in values from the decorator using
.normalize_target_params() and then passes them to the set .target()
"""
try:
param_args, param_k... | [
"def",
"handle_target",
"(",
"self",
",",
"request",
",",
"controller_args",
",",
"controller_kwargs",
")",
":",
"try",
":",
"param_args",
",",
"param_kwargs",
"=",
"self",
".",
"normalize_target_params",
"(",
"request",
"=",
"request",
",",
"controller_args",
"... | Internal method for this class
handles normalizing the passed in values from the decorator using
.normalize_target_params() and then passes them to the set .target() | [
"Internal",
"method",
"for",
"this",
"class"
] | train | https://github.com/Jaymon/endpoints/blob/2f1c4ae2c69a168e69447d3d8395ada7becaa5fb/endpoints/decorators/base.py#L50-L70 |
Jaymon/endpoints | endpoints/decorators/base.py | TargetDecorator.decorate | def decorate(self, func, target, *anoop, **kwnoop):
"""decorate the passed in func calling target when func is called
:param func: the function being decorated
:param target: the target that will be run when func is called
:returns: the decorated func
"""
if target:
... | python | def decorate(self, func, target, *anoop, **kwnoop):
"""decorate the passed in func calling target when func is called
:param func: the function being decorated
:param target: the target that will be run when func is called
:returns: the decorated func
"""
if target:
... | [
"def",
"decorate",
"(",
"self",
",",
"func",
",",
"target",
",",
"*",
"anoop",
",",
"*",
"*",
"kwnoop",
")",
":",
"if",
"target",
":",
"self",
".",
"target",
"=",
"target",
"def",
"decorated",
"(",
"decorated_self",
",",
"*",
"args",
",",
"*",
"*",... | decorate the passed in func calling target when func is called
:param func: the function being decorated
:param target: the target that will be run when func is called
:returns: the decorated func | [
"decorate",
"the",
"passed",
"in",
"func",
"calling",
"target",
"when",
"func",
"is",
"called"
] | train | https://github.com/Jaymon/endpoints/blob/2f1c4ae2c69a168e69447d3d8395ada7becaa5fb/endpoints/decorators/base.py#L72-L90 |
Jaymon/endpoints | endpoints/decorators/__init__.py | param.normalize_flags | def normalize_flags(self, flags):
"""normalize the flags to make sure needed values are there
after this method is called self.flags is available
:param flags: the flags that will be normalized
"""
flags['type'] = flags.get('type', None)
paction = flags.get('action', 's... | python | def normalize_flags(self, flags):
"""normalize the flags to make sure needed values are there
after this method is called self.flags is available
:param flags: the flags that will be normalized
"""
flags['type'] = flags.get('type', None)
paction = flags.get('action', 's... | [
"def",
"normalize_flags",
"(",
"self",
",",
"flags",
")",
":",
"flags",
"[",
"'type'",
"]",
"=",
"flags",
".",
"get",
"(",
"'type'",
",",
"None",
")",
"paction",
"=",
"flags",
".",
"get",
"(",
"'action'",
",",
"'store'",
")",
"if",
"paction",
"==",
... | normalize the flags to make sure needed values are there
after this method is called self.flags is available
:param flags: the flags that will be normalized | [
"normalize",
"the",
"flags",
"to",
"make",
"sure",
"needed",
"values",
"are",
"there"
] | train | https://github.com/Jaymon/endpoints/blob/2f1c4ae2c69a168e69447d3d8395ada7becaa5fb/endpoints/decorators/__init__.py#L259-L280 |
Jaymon/endpoints | endpoints/decorators/__init__.py | param.normalize_type | def normalize_type(self, names):
"""Decide if this param is an arg or a kwarg and set appropriate internal flags"""
self.name = names[0]
self.is_kwarg = False
self.is_arg = False
self.names = []
try:
# http://stackoverflow.com/a/16488383/5006 uses ask forgive... | python | def normalize_type(self, names):
"""Decide if this param is an arg or a kwarg and set appropriate internal flags"""
self.name = names[0]
self.is_kwarg = False
self.is_arg = False
self.names = []
try:
# http://stackoverflow.com/a/16488383/5006 uses ask forgive... | [
"def",
"normalize_type",
"(",
"self",
",",
"names",
")",
":",
"self",
".",
"name",
"=",
"names",
"[",
"0",
"]",
"self",
".",
"is_kwarg",
"=",
"False",
"self",
".",
"is_arg",
"=",
"False",
"self",
".",
"names",
"=",
"[",
"]",
"try",
":",
"# http://s... | Decide if this param is an arg or a kwarg and set appropriate internal flags | [
"Decide",
"if",
"this",
"param",
"is",
"an",
"arg",
"or",
"a",
"kwarg",
"and",
"set",
"appropriate",
"internal",
"flags"
] | train | https://github.com/Jaymon/endpoints/blob/2f1c4ae2c69a168e69447d3d8395ada7becaa5fb/endpoints/decorators/__init__.py#L282-L298 |
Jaymon/endpoints | endpoints/decorators/__init__.py | param.normalize_param | def normalize_param(self, slf, args, kwargs):
"""this is where all the magic happens, this will try and find the param and
put its value in kwargs if it has a default and stuff"""
if self.is_kwarg:
kwargs = self.normalize_kwarg(slf.request, kwargs)
else:
args = se... | python | def normalize_param(self, slf, args, kwargs):
"""this is where all the magic happens, this will try and find the param and
put its value in kwargs if it has a default and stuff"""
if self.is_kwarg:
kwargs = self.normalize_kwarg(slf.request, kwargs)
else:
args = se... | [
"def",
"normalize_param",
"(",
"self",
",",
"slf",
",",
"args",
",",
"kwargs",
")",
":",
"if",
"self",
".",
"is_kwarg",
":",
"kwargs",
"=",
"self",
".",
"normalize_kwarg",
"(",
"slf",
".",
"request",
",",
"kwargs",
")",
"else",
":",
"args",
"=",
"sel... | this is where all the magic happens, this will try and find the param and
put its value in kwargs if it has a default and stuff | [
"this",
"is",
"where",
"all",
"the",
"magic",
"happens",
"this",
"will",
"try",
"and",
"find",
"the",
"param",
"and",
"put",
"its",
"value",
"in",
"kwargs",
"if",
"it",
"has",
"a",
"default",
"and",
"stuff"
] | train | https://github.com/Jaymon/endpoints/blob/2f1c4ae2c69a168e69447d3d8395ada7becaa5fb/endpoints/decorators/__init__.py#L314-L321 |
Jaymon/endpoints | endpoints/decorators/__init__.py | param.find_kwarg | def find_kwarg(self, request, names, required, default, kwargs):
"""actually try to retrieve names key from params dict
:param request: the current request instance, handy for child classes
:param names: the names this kwarg can be
:param required: True if a name has to be found in kwar... | python | def find_kwarg(self, request, names, required, default, kwargs):
"""actually try to retrieve names key from params dict
:param request: the current request instance, handy for child classes
:param names: the names this kwarg can be
:param required: True if a name has to be found in kwar... | [
"def",
"find_kwarg",
"(",
"self",
",",
"request",
",",
"names",
",",
"required",
",",
"default",
",",
"kwargs",
")",
":",
"val",
"=",
"default",
"found_name",
"=",
"''",
"for",
"name",
"in",
"names",
":",
"if",
"name",
"in",
"kwargs",
":",
"val",
"="... | actually try to retrieve names key from params dict
:param request: the current request instance, handy for child classes
:param names: the names this kwarg can be
:param required: True if a name has to be found in kwargs
:param default: the default value if name isn't found
:pa... | [
"actually",
"try",
"to",
"retrieve",
"names",
"key",
"from",
"params",
"dict"
] | train | https://github.com/Jaymon/endpoints/blob/2f1c4ae2c69a168e69447d3d8395ada7becaa5fb/endpoints/decorators/__init__.py#L355-L376 |
Jaymon/endpoints | endpoints/decorators/__init__.py | param.normalize_val | def normalize_val(self, request, val):
"""This will take the value and make sure it meets expectations
:param request: the current request instance
:param val: the raw value pulled from kwargs or args
:returns: val that has met all param checks
:raises: ValueError if val fails a... | python | def normalize_val(self, request, val):
"""This will take the value and make sure it meets expectations
:param request: the current request instance
:param val: the raw value pulled from kwargs or args
:returns: val that has met all param checks
:raises: ValueError if val fails a... | [
"def",
"normalize_val",
"(",
"self",
",",
"request",
",",
"val",
")",
":",
"flags",
"=",
"self",
".",
"flags",
"paction",
"=",
"flags",
"[",
"'action'",
"]",
"ptype",
"=",
"flags",
"[",
"'type'",
"]",
"pchoices",
"=",
"flags",
".",
"get",
"(",
"'choi... | This will take the value and make sure it meets expectations
:param request: the current request instance
:param val: the raw value pulled from kwargs or args
:returns: val that has met all param checks
:raises: ValueError if val fails any checks | [
"This",
"will",
"take",
"the",
"value",
"and",
"make",
"sure",
"it",
"meets",
"expectations"
] | train | https://github.com/Jaymon/endpoints/blob/2f1c4ae2c69a168e69447d3d8395ada7becaa5fb/endpoints/decorators/__init__.py#L405-L529 |
Jaymon/endpoints | endpoints/interface/uwsgi/client.py | WebsocketClient.open | def open(cls, *args, **kwargs):
"""just something to make it easier to quickly open a connection, do something
and then close it"""
c = cls(*args, **kwargs)
c.connect()
try:
yield c
finally:
c.close() | python | def open(cls, *args, **kwargs):
"""just something to make it easier to quickly open a connection, do something
and then close it"""
c = cls(*args, **kwargs)
c.connect()
try:
yield c
finally:
c.close() | [
"def",
"open",
"(",
"cls",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"c",
"=",
"cls",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"c",
".",
"connect",
"(",
")",
"try",
":",
"yield",
"c",
"finally",
":",
"c",
".",
"close",
"("... | just something to make it easier to quickly open a connection, do something
and then close it | [
"just",
"something",
"to",
"make",
"it",
"easier",
"to",
"quickly",
"open",
"a",
"connection",
"do",
"something",
"and",
"then",
"close",
"it"
] | train | https://github.com/Jaymon/endpoints/blob/2f1c4ae2c69a168e69447d3d8395ada7becaa5fb/endpoints/interface/uwsgi/client.py#L74-L83 |
Jaymon/endpoints | endpoints/interface/uwsgi/client.py | WebsocketClient.connect | def connect(self, path="", headers=None, query=None, timeout=0, **kwargs):
"""
make the actual connection to the websocket
:param headers: dict, key/val pairs of any headers to add to connection, if
you would like to override headers just pass in an empty value
:param query:... | python | def connect(self, path="", headers=None, query=None, timeout=0, **kwargs):
"""
make the actual connection to the websocket
:param headers: dict, key/val pairs of any headers to add to connection, if
you would like to override headers just pass in an empty value
:param query:... | [
"def",
"connect",
"(",
"self",
",",
"path",
"=",
"\"\"",
",",
"headers",
"=",
"None",
",",
"query",
"=",
"None",
",",
"timeout",
"=",
"0",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"None",
"ws_url",
"=",
"self",
".",
"get_fetch_url",
"(",
"p... | make the actual connection to the websocket
:param headers: dict, key/val pairs of any headers to add to connection, if
you would like to override headers just pass in an empty value
:param query: dict, any query string params you want to send up with the connection
url
... | [
"make",
"the",
"actual",
"connection",
"to",
"the",
"websocket"
] | train | https://github.com/Jaymon/endpoints/blob/2f1c4ae2c69a168e69447d3d8395ada7becaa5fb/endpoints/interface/uwsgi/client.py#L105-L151 |
Jaymon/endpoints | endpoints/interface/uwsgi/client.py | WebsocketClient.fetch | def fetch(self, method, path, query=None, body=None, timeout=0, **kwargs):
"""send a Message
:param method: string, something like "POST" or "GET"
:param path: string, the path part of a uri (eg, /foo/bar)
:param body: dict, what you want to send to "method path"
:param timeout:... | python | def fetch(self, method, path, query=None, body=None, timeout=0, **kwargs):
"""send a Message
:param method: string, something like "POST" or "GET"
:param path: string, the path part of a uri (eg, /foo/bar)
:param body: dict, what you want to send to "method path"
:param timeout:... | [
"def",
"fetch",
"(",
"self",
",",
"method",
",",
"path",
",",
"query",
"=",
"None",
",",
"body",
"=",
"None",
",",
"timeout",
"=",
"0",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"None",
"if",
"not",
"query",
":",
"query",
"=",
"{",
"}",
... | send a Message
:param method: string, something like "POST" or "GET"
:param path: string, the path part of a uri (eg, /foo/bar)
:param body: dict, what you want to send to "method path"
:param timeout: integer, how long to wait before failing trying to send | [
"send",
"a",
"Message"
] | train | https://github.com/Jaymon/endpoints/blob/2f1c4ae2c69a168e69447d3d8395ada7becaa5fb/endpoints/interface/uwsgi/client.py#L161-L226 |
Jaymon/endpoints | endpoints/interface/uwsgi/client.py | WebsocketClient.fetch_response | def fetch_response(self, req_payload, **kwargs):
"""payload has been sent, do anything else you need to do (eg, wait for response?)
:param req_payload: Payload, the payload sent to the server
:returns: Payload, the response payload
"""
if req_payload.uuid:
uuids = se... | python | def fetch_response(self, req_payload, **kwargs):
"""payload has been sent, do anything else you need to do (eg, wait for response?)
:param req_payload: Payload, the payload sent to the server
:returns: Payload, the response payload
"""
if req_payload.uuid:
uuids = se... | [
"def",
"fetch_response",
"(",
"self",
",",
"req_payload",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"req_payload",
".",
"uuid",
":",
"uuids",
"=",
"set",
"(",
"[",
"req_payload",
".",
"uuid",
",",
"\"CONNECT\"",
"]",
")",
"def",
"callback",
"(",
"res_pa... | payload has been sent, do anything else you need to do (eg, wait for response?)
:param req_payload: Payload, the payload sent to the server
:returns: Payload, the response payload | [
"payload",
"has",
"been",
"sent",
"do",
"anything",
"else",
"you",
"need",
"to",
"do",
"(",
"eg",
"wait",
"for",
"response?",
")"
] | train | https://github.com/Jaymon/endpoints/blob/2f1c4ae2c69a168e69447d3d8395ada7becaa5fb/endpoints/interface/uwsgi/client.py#L228-L250 |
Jaymon/endpoints | endpoints/interface/uwsgi/client.py | WebsocketClient.ping | def ping(self, timeout=0, **kwargs):
"""THIS DOES NOT WORK, UWSGI DOES NOT RESPOND TO PINGS"""
# http://stackoverflow.com/a/2257449/5006
def rand_id(size=8, chars=string.ascii_uppercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
payload = ra... | python | def ping(self, timeout=0, **kwargs):
"""THIS DOES NOT WORK, UWSGI DOES NOT RESPOND TO PINGS"""
# http://stackoverflow.com/a/2257449/5006
def rand_id(size=8, chars=string.ascii_uppercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
payload = ra... | [
"def",
"ping",
"(",
"self",
",",
"timeout",
"=",
"0",
",",
"*",
"*",
"kwargs",
")",
":",
"# http://stackoverflow.com/a/2257449/5006",
"def",
"rand_id",
"(",
"size",
"=",
"8",
",",
"chars",
"=",
"string",
".",
"ascii_uppercase",
"+",
"string",
".",
"digits"... | THIS DOES NOT WORK, UWSGI DOES NOT RESPOND TO PINGS | [
"THIS",
"DOES",
"NOT",
"WORK",
"UWSGI",
"DOES",
"NOT",
"RESPOND",
"TO",
"PINGS"
] | train | https://github.com/Jaymon/endpoints/blob/2f1c4ae2c69a168e69447d3d8395ada7becaa5fb/endpoints/interface/uwsgi/client.py#L252-L263 |
Jaymon/endpoints | endpoints/interface/uwsgi/client.py | WebsocketClient.recv_raw | def recv_raw(self, timeout, opcodes, **kwargs):
"""this is very internal, it will return the raw opcode and data if they
match the passed in opcodes"""
orig_timeout = self.get_timeout(timeout)
timeout = orig_timeout
while timeout > 0.0:
start = time.time()
... | python | def recv_raw(self, timeout, opcodes, **kwargs):
"""this is very internal, it will return the raw opcode and data if they
match the passed in opcodes"""
orig_timeout = self.get_timeout(timeout)
timeout = orig_timeout
while timeout > 0.0:
start = time.time()
... | [
"def",
"recv_raw",
"(",
"self",
",",
"timeout",
",",
"opcodes",
",",
"*",
"*",
"kwargs",
")",
":",
"orig_timeout",
"=",
"self",
".",
"get_timeout",
"(",
"timeout",
")",
"timeout",
"=",
"orig_timeout",
"while",
"timeout",
">",
"0.0",
":",
"start",
"=",
... | this is very internal, it will return the raw opcode and data if they
match the passed in opcodes | [
"this",
"is",
"very",
"internal",
"it",
"will",
"return",
"the",
"raw",
"opcode",
"and",
"data",
"if",
"they",
"match",
"the",
"passed",
"in",
"opcodes"
] | train | https://github.com/Jaymon/endpoints/blob/2f1c4ae2c69a168e69447d3d8395ada7becaa5fb/endpoints/interface/uwsgi/client.py#L265-L307 |
Jaymon/endpoints | endpoints/interface/uwsgi/client.py | WebsocketClient.get_fetch_response | def get_fetch_response(self, raw):
"""This just makes the payload instance more HTTPClient like"""
p = Payload(raw)
p._body = p.body
return p | python | def get_fetch_response(self, raw):
"""This just makes the payload instance more HTTPClient like"""
p = Payload(raw)
p._body = p.body
return p | [
"def",
"get_fetch_response",
"(",
"self",
",",
"raw",
")",
":",
"p",
"=",
"Payload",
"(",
"raw",
")",
"p",
".",
"_body",
"=",
"p",
".",
"body",
"return",
"p"
] | This just makes the payload instance more HTTPClient like | [
"This",
"just",
"makes",
"the",
"payload",
"instance",
"more",
"HTTPClient",
"like"
] | train | https://github.com/Jaymon/endpoints/blob/2f1c4ae2c69a168e69447d3d8395ada7becaa5fb/endpoints/interface/uwsgi/client.py#L309-L313 |
Jaymon/endpoints | endpoints/interface/uwsgi/client.py | WebsocketClient.recv | def recv(self, timeout=0, **kwargs):
"""this will receive data and convert it into a message, really this is more
of an internal method, it is used in recv_callback and recv_msg"""
opcode, data = self.recv_raw(timeout, [websocket.ABNF.OPCODE_TEXT], **kwargs)
return self.get_fetch_respons... | python | def recv(self, timeout=0, **kwargs):
"""this will receive data and convert it into a message, really this is more
of an internal method, it is used in recv_callback and recv_msg"""
opcode, data = self.recv_raw(timeout, [websocket.ABNF.OPCODE_TEXT], **kwargs)
return self.get_fetch_respons... | [
"def",
"recv",
"(",
"self",
",",
"timeout",
"=",
"0",
",",
"*",
"*",
"kwargs",
")",
":",
"opcode",
",",
"data",
"=",
"self",
".",
"recv_raw",
"(",
"timeout",
",",
"[",
"websocket",
".",
"ABNF",
".",
"OPCODE_TEXT",
"]",
",",
"*",
"*",
"kwargs",
")... | this will receive data and convert it into a message, really this is more
of an internal method, it is used in recv_callback and recv_msg | [
"this",
"will",
"receive",
"data",
"and",
"convert",
"it",
"into",
"a",
"message",
"really",
"this",
"is",
"more",
"of",
"an",
"internal",
"method",
"it",
"is",
"used",
"in",
"recv_callback",
"and",
"recv_msg"
] | train | https://github.com/Jaymon/endpoints/blob/2f1c4ae2c69a168e69447d3d8395ada7becaa5fb/endpoints/interface/uwsgi/client.py#L315-L319 |
Jaymon/endpoints | endpoints/interface/uwsgi/client.py | WebsocketClient.recv_callback | def recv_callback(self, callback, **kwargs):
"""receive messages and validate them with the callback, if the callback
returns True then the message is valid and will be returned, if False then
this will try and receive another message until timeout is 0"""
payload = None
timeout... | python | def recv_callback(self, callback, **kwargs):
"""receive messages and validate them with the callback, if the callback
returns True then the message is valid and will be returned, if False then
this will try and receive another message until timeout is 0"""
payload = None
timeout... | [
"def",
"recv_callback",
"(",
"self",
",",
"callback",
",",
"*",
"*",
"kwargs",
")",
":",
"payload",
"=",
"None",
"timeout",
"=",
"self",
".",
"get_timeout",
"(",
"*",
"*",
"kwargs",
")",
"full_timeout",
"=",
"timeout",
"while",
"timeout",
">",
"0.0",
"... | receive messages and validate them with the callback, if the callback
returns True then the message is valid and will be returned, if False then
this will try and receive another message until timeout is 0 | [
"receive",
"messages",
"and",
"validate",
"them",
"with",
"the",
"callback",
"if",
"the",
"callback",
"returns",
"True",
"then",
"the",
"message",
"is",
"valid",
"and",
"will",
"be",
"returned",
"if",
"False",
"then",
"this",
"will",
"try",
"and",
"receive",... | train | https://github.com/Jaymon/endpoints/blob/2f1c4ae2c69a168e69447d3d8395ada7becaa5fb/endpoints/interface/uwsgi/client.py#L321-L342 |
Jaymon/endpoints | endpoints/call.py | Call.create_controller | def create_controller(self):
"""Create a controller to handle the request
:returns: Controller, this Controller instance should be able to handle
the request
"""
body = None
req = self.request
res = self.response
rou = self.router
con = None
... | python | def create_controller(self):
"""Create a controller to handle the request
:returns: Controller, this Controller instance should be able to handle
the request
"""
body = None
req = self.request
res = self.response
rou = self.router
con = None
... | [
"def",
"create_controller",
"(",
"self",
")",
":",
"body",
"=",
"None",
"req",
"=",
"self",
".",
"request",
"res",
"=",
"self",
".",
"response",
"rou",
"=",
"self",
".",
"router",
"con",
"=",
"None",
"controller_info",
"=",
"{",
"}",
"try",
":",
"con... | Create a controller to handle the request
:returns: Controller, this Controller instance should be able to handle
the request | [
"Create",
"a",
"controller",
"to",
"handle",
"the",
"request"
] | train | https://github.com/Jaymon/endpoints/blob/2f1c4ae2c69a168e69447d3d8395ada7becaa5fb/endpoints/call.py#L43-L83 |
Jaymon/endpoints | endpoints/call.py | Call.handle | def handle(self):
"""Called from the interface to actually handle the request."""
body = None
req = self.request
res = self.response
rou = self.router
con = None
start = time.time()
try:
con = self.create_controller()
con.call = se... | python | def handle(self):
"""Called from the interface to actually handle the request."""
body = None
req = self.request
res = self.response
rou = self.router
con = None
start = time.time()
try:
con = self.create_controller()
con.call = se... | [
"def",
"handle",
"(",
"self",
")",
":",
"body",
"=",
"None",
"req",
"=",
"self",
".",
"request",
"res",
"=",
"self",
".",
"response",
"rou",
"=",
"self",
".",
"router",
"con",
"=",
"None",
"start",
"=",
"time",
".",
"time",
"(",
")",
"try",
":",
... | Called from the interface to actually handle the request. | [
"Called",
"from",
"the",
"interface",
"to",
"actually",
"handle",
"the",
"request",
"."
] | train | https://github.com/Jaymon/endpoints/blob/2f1c4ae2c69a168e69447d3d8395ada7becaa5fb/endpoints/call.py#L85-L130 |
Jaymon/endpoints | endpoints/call.py | Call.handle_error | def handle_error(self, e, **kwargs):
"""if an exception is raised while trying to handle the request it will
go through this method
This method will set the response body and then also call Controller.handle_error
for further customization if the Controller is available
:param ... | python | def handle_error(self, e, **kwargs):
"""if an exception is raised while trying to handle the request it will
go through this method
This method will set the response body and then also call Controller.handle_error
for further customization if the Controller is available
:param ... | [
"def",
"handle_error",
"(",
"self",
",",
"e",
",",
"*",
"*",
"kwargs",
")",
":",
"req",
"=",
"self",
".",
"request",
"res",
"=",
"self",
".",
"response",
"con",
"=",
"self",
".",
"controller",
"if",
"isinstance",
"(",
"e",
",",
"CallStop",
")",
":"... | if an exception is raised while trying to handle the request it will
go through this method
This method will set the response body and then also call Controller.handle_error
for further customization if the Controller is available
:param e: Exception, the error that was raised
... | [
"if",
"an",
"exception",
"is",
"raised",
"while",
"trying",
"to",
"handle",
"the",
"request",
"it",
"will",
"go",
"through",
"this",
"method"
] | train | https://github.com/Jaymon/endpoints/blob/2f1c4ae2c69a168e69447d3d8395ada7becaa5fb/endpoints/call.py#L132-L208 |
Jaymon/endpoints | endpoints/call.py | Router.module_names | def module_names(self):
"""get all the modules in the controller_prefix
:returns: set, a set of string module names
"""
controller_prefix = self.controller_prefix
_module_name_cache = self._module_name_cache
if controller_prefix in _module_name_cache:
return ... | python | def module_names(self):
"""get all the modules in the controller_prefix
:returns: set, a set of string module names
"""
controller_prefix = self.controller_prefix
_module_name_cache = self._module_name_cache
if controller_prefix in _module_name_cache:
return ... | [
"def",
"module_names",
"(",
"self",
")",
":",
"controller_prefix",
"=",
"self",
".",
"controller_prefix",
"_module_name_cache",
"=",
"self",
".",
"_module_name_cache",
"if",
"controller_prefix",
"in",
"_module_name_cache",
":",
"return",
"_module_name_cache",
"[",
"co... | get all the modules in the controller_prefix
:returns: set, a set of string module names | [
"get",
"all",
"the",
"modules",
"in",
"the",
"controller_prefix"
] | train | https://github.com/Jaymon/endpoints/blob/2f1c4ae2c69a168e69447d3d8395ada7becaa5fb/endpoints/call.py#L224-L247 |
Jaymon/endpoints | endpoints/call.py | Router.modules | def modules(self):
"""Returns an iterator of the actual modules, not just their names
:returns: generator, each module under self.controller_prefix
"""
for modname in self.module_names:
module = importlib.import_module(modname)
yield module | python | def modules(self):
"""Returns an iterator of the actual modules, not just their names
:returns: generator, each module under self.controller_prefix
"""
for modname in self.module_names:
module = importlib.import_module(modname)
yield module | [
"def",
"modules",
"(",
"self",
")",
":",
"for",
"modname",
"in",
"self",
".",
"module_names",
":",
"module",
"=",
"importlib",
".",
"import_module",
"(",
"modname",
")",
"yield",
"module"
] | Returns an iterator of the actual modules, not just their names
:returns: generator, each module under self.controller_prefix | [
"Returns",
"an",
"iterator",
"of",
"the",
"actual",
"modules",
"not",
"just",
"their",
"names"
] | train | https://github.com/Jaymon/endpoints/blob/2f1c4ae2c69a168e69447d3d8395ada7becaa5fb/endpoints/call.py#L250-L257 |
Jaymon/endpoints | endpoints/call.py | Router.find_modules | def find_modules(self, path, prefix):
"""recursive method that will find all the submodules of the given module
at prefix with path"""
modules = set([prefix])
# https://docs.python.org/2/library/pkgutil.html#pkgutil.iter_modules
for module_info in pkgutil.iter_modules([path]):
... | python | def find_modules(self, path, prefix):
"""recursive method that will find all the submodules of the given module
at prefix with path"""
modules = set([prefix])
# https://docs.python.org/2/library/pkgutil.html#pkgutil.iter_modules
for module_info in pkgutil.iter_modules([path]):
... | [
"def",
"find_modules",
"(",
"self",
",",
"path",
",",
"prefix",
")",
":",
"modules",
"=",
"set",
"(",
"[",
"prefix",
"]",
")",
"# https://docs.python.org/2/library/pkgutil.html#pkgutil.iter_modules",
"for",
"module_info",
"in",
"pkgutil",
".",
"iter_modules",
"(",
... | recursive method that will find all the submodules of the given module
at prefix with path | [
"recursive",
"method",
"that",
"will",
"find",
"all",
"the",
"submodules",
"of",
"the",
"given",
"module",
"at",
"prefix",
"with",
"path"
] | train | https://github.com/Jaymon/endpoints/blob/2f1c4ae2c69a168e69447d3d8395ada7becaa5fb/endpoints/call.py#L317-L336 |
Jaymon/endpoints | endpoints/call.py | Router.get_module_name | def get_module_name(self, path_args):
"""returns the module_name and remaining path args.
return -- tuple -- (module_name, path_args)"""
controller_prefix = self.controller_prefix
cset = self.module_names
module_name = controller_prefix
mod_name = module_name
whi... | python | def get_module_name(self, path_args):
"""returns the module_name and remaining path args.
return -- tuple -- (module_name, path_args)"""
controller_prefix = self.controller_prefix
cset = self.module_names
module_name = controller_prefix
mod_name = module_name
whi... | [
"def",
"get_module_name",
"(",
"self",
",",
"path_args",
")",
":",
"controller_prefix",
"=",
"self",
".",
"controller_prefix",
"cset",
"=",
"self",
".",
"module_names",
"module_name",
"=",
"controller_prefix",
"mod_name",
"=",
"module_name",
"while",
"path_args",
... | returns the module_name and remaining path args.
return -- tuple -- (module_name, path_args) | [
"returns",
"the",
"module_name",
"and",
"remaining",
"path",
"args",
"."
] | train | https://github.com/Jaymon/endpoints/blob/2f1c4ae2c69a168e69447d3d8395ada7becaa5fb/endpoints/call.py#L338-L354 |
Jaymon/endpoints | endpoints/call.py | Router.get_class | def get_class(self, module, class_name):
"""try and get the class_name from the module and make sure it is a valid
controller"""
# let's get the class
class_object = getattr(module, class_name, None)
if not class_object or not issubclass(class_object, Controller):
cla... | python | def get_class(self, module, class_name):
"""try and get the class_name from the module and make sure it is a valid
controller"""
# let's get the class
class_object = getattr(module, class_name, None)
if not class_object or not issubclass(class_object, Controller):
cla... | [
"def",
"get_class",
"(",
"self",
",",
"module",
",",
"class_name",
")",
":",
"# let's get the class",
"class_object",
"=",
"getattr",
"(",
"module",
",",
"class_name",
",",
"None",
")",
"if",
"not",
"class_object",
"or",
"not",
"issubclass",
"(",
"class_object... | try and get the class_name from the module and make sure it is a valid
controller | [
"try",
"and",
"get",
"the",
"class_name",
"from",
"the",
"module",
"and",
"make",
"sure",
"it",
"is",
"a",
"valid",
"controller"
] | train | https://github.com/Jaymon/endpoints/blob/2f1c4ae2c69a168e69447d3d8395ada7becaa5fb/endpoints/call.py#L360-L368 |
Jaymon/endpoints | endpoints/call.py | Controller.OPTIONS | def OPTIONS(self, *args, **kwargs):
"""Handles CORS requests for this controller
if self.cors is False then this will raise a 405, otherwise it sets everything
necessary to satisfy the request in self.response
"""
if not self.cors:
raise CallError(405)
req =... | python | def OPTIONS(self, *args, **kwargs):
"""Handles CORS requests for this controller
if self.cors is False then this will raise a 405, otherwise it sets everything
necessary to satisfy the request in self.response
"""
if not self.cors:
raise CallError(405)
req =... | [
"def",
"OPTIONS",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"cors",
":",
"raise",
"CallError",
"(",
"405",
")",
"req",
"=",
"self",
".",
"request",
"origin",
"=",
"req",
".",
"get_header",
"(",
"'... | Handles CORS requests for this controller
if self.cors is False then this will raise a 405, otherwise it sets everything
necessary to satisfy the request in self.response | [
"Handles",
"CORS",
"requests",
"for",
"this",
"controller"
] | train | https://github.com/Jaymon/endpoints/blob/2f1c4ae2c69a168e69447d3d8395ada7becaa5fb/endpoints/call.py#L439-L468 |
Jaymon/endpoints | endpoints/call.py | Controller.set_cors_common_headers | def set_cors_common_headers(self):
"""
This will set the headers that are needed for any cors request (OPTIONS or real)
"""
if not self.cors: return
req = self.request
origin = req.get_header('origin')
if origin:
self.response.set_header('Access-Contr... | python | def set_cors_common_headers(self):
"""
This will set the headers that are needed for any cors request (OPTIONS or real)
"""
if not self.cors: return
req = self.request
origin = req.get_header('origin')
if origin:
self.response.set_header('Access-Contr... | [
"def",
"set_cors_common_headers",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"cors",
":",
"return",
"req",
"=",
"self",
".",
"request",
"origin",
"=",
"req",
".",
"get_header",
"(",
"'origin'",
")",
"if",
"origin",
":",
"self",
".",
"response",
"... | This will set the headers that are needed for any cors request (OPTIONS or real) | [
"This",
"will",
"set",
"the",
"headers",
"that",
"are",
"needed",
"for",
"any",
"cors",
"request",
"(",
"OPTIONS",
"or",
"real",
")"
] | train | https://github.com/Jaymon/endpoints/blob/2f1c4ae2c69a168e69447d3d8395ada7becaa5fb/endpoints/call.py#L470-L479 |
Jaymon/endpoints | endpoints/call.py | Controller.handle | def handle(self, *controller_args, **controller_kwargs):
"""handles the request and returns the response
This should set any response information directly onto self.response
this method has the same signature as the request handling methods
(eg, GET, POST) so subclasses can override th... | python | def handle(self, *controller_args, **controller_kwargs):
"""handles the request and returns the response
This should set any response information directly onto self.response
this method has the same signature as the request handling methods
(eg, GET, POST) so subclasses can override th... | [
"def",
"handle",
"(",
"self",
",",
"*",
"controller_args",
",",
"*",
"*",
"controller_kwargs",
")",
":",
"req",
"=",
"self",
".",
"request",
"res",
"=",
"self",
".",
"response",
"res",
".",
"set_header",
"(",
"'Content-Type'",
",",
"\"{};charset={}\"",
"."... | handles the request and returns the response
This should set any response information directly onto self.response
this method has the same signature as the request handling methods
(eg, GET, POST) so subclasses can override this method and add decorators
:param *controller_args: tuple... | [
"handles",
"the",
"request",
"and",
"returns",
"the",
"response"
] | train | https://github.com/Jaymon/endpoints/blob/2f1c4ae2c69a168e69447d3d8395ada7becaa5fb/endpoints/call.py#L481-L543 |
Jaymon/endpoints | endpoints/call.py | Controller.find_methods | def find_methods(self):
"""Find the methods that could satisfy this request
This will go through and find any method that starts with the request.method,
so if the request was GET /foo then this would find any methods that start
with GET
https://www.w3.org/Protocols/rfc2616/rfc... | python | def find_methods(self):
"""Find the methods that could satisfy this request
This will go through and find any method that starts with the request.method,
so if the request was GET /foo then this would find any methods that start
with GET
https://www.w3.org/Protocols/rfc2616/rfc... | [
"def",
"find_methods",
"(",
"self",
")",
":",
"methods",
"=",
"[",
"]",
"req",
"=",
"self",
".",
"request",
"method_name",
"=",
"req",
".",
"method",
".",
"upper",
"(",
")",
"method_names",
"=",
"set",
"(",
")",
"members",
"=",
"inspect",
".",
"getme... | Find the methods that could satisfy this request
This will go through and find any method that starts with the request.method,
so if the request was GET /foo then this would find any methods that start
with GET
https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
:returns: l... | [
"Find",
"the",
"methods",
"that",
"could",
"satisfy",
"this",
"request"
] | train | https://github.com/Jaymon/endpoints/blob/2f1c4ae2c69a168e69447d3d8395ada7becaa5fb/endpoints/call.py#L554-L598 |
Jaymon/endpoints | endpoints/call.py | Controller.find_method_params | def find_method_params(self):
"""Return the method params
:returns: tuple (args, kwargs) that will be passed as *args, **kwargs
"""
req = self.request
args = req.controller_info["method_args"]
kwargs = req.controller_info["method_kwargs"]
return args, kwargs | python | def find_method_params(self):
"""Return the method params
:returns: tuple (args, kwargs) that will be passed as *args, **kwargs
"""
req = self.request
args = req.controller_info["method_args"]
kwargs = req.controller_info["method_kwargs"]
return args, kwargs | [
"def",
"find_method_params",
"(",
"self",
")",
":",
"req",
"=",
"self",
".",
"request",
"args",
"=",
"req",
".",
"controller_info",
"[",
"\"method_args\"",
"]",
"kwargs",
"=",
"req",
".",
"controller_info",
"[",
"\"method_kwargs\"",
"]",
"return",
"args",
",... | Return the method params
:returns: tuple (args, kwargs) that will be passed as *args, **kwargs | [
"Return",
"the",
"method",
"params"
] | train | https://github.com/Jaymon/endpoints/blob/2f1c4ae2c69a168e69447d3d8395ada7becaa5fb/endpoints/call.py#L600-L608 |
Jaymon/endpoints | endpoints/call.py | Controller.log_start | def log_start(self, start):
"""log all the headers and stuff at the start of the request"""
if not logger.isEnabledFor(logging.INFO): return
try:
req = self.request
logger.info("REQUEST {} {}?{}".format(req.method, req.path, req.query))
logger.info(datetime.... | python | def log_start(self, start):
"""log all the headers and stuff at the start of the request"""
if not logger.isEnabledFor(logging.INFO): return
try:
req = self.request
logger.info("REQUEST {} {}?{}".format(req.method, req.path, req.query))
logger.info(datetime.... | [
"def",
"log_start",
"(",
"self",
",",
"start",
")",
":",
"if",
"not",
"logger",
".",
"isEnabledFor",
"(",
"logging",
".",
"INFO",
")",
":",
"return",
"try",
":",
"req",
"=",
"self",
".",
"request",
"logger",
".",
"info",
"(",
"\"REQUEST {} {}?{}\"",
".... | log all the headers and stuff at the start of the request | [
"log",
"all",
"the",
"headers",
"and",
"stuff",
"at",
"the",
"start",
"of",
"the",
"request"
] | train | https://github.com/Jaymon/endpoints/blob/2f1c4ae2c69a168e69447d3d8395ada7becaa5fb/endpoints/call.py#L610-L643 |
Jaymon/endpoints | endpoints/call.py | Controller.log_stop | def log_stop(self, start):
"""log a summary line on how the request went"""
if not logger.isEnabledFor(logging.INFO): return
stop = time.time()
get_elapsed = lambda start, stop, multiplier, rnd: round(abs(stop - start) * float(multiplier), rnd)
elapsed = get_elapsed(start, stop,... | python | def log_stop(self, start):
"""log a summary line on how the request went"""
if not logger.isEnabledFor(logging.INFO): return
stop = time.time()
get_elapsed = lambda start, stop, multiplier, rnd: round(abs(stop - start) * float(multiplier), rnd)
elapsed = get_elapsed(start, stop,... | [
"def",
"log_stop",
"(",
"self",
",",
"start",
")",
":",
"if",
"not",
"logger",
".",
"isEnabledFor",
"(",
"logging",
".",
"INFO",
")",
":",
"return",
"stop",
"=",
"time",
".",
"time",
"(",
")",
"get_elapsed",
"=",
"lambda",
"start",
",",
"stop",
",",
... | log a summary line on how the request went | [
"log",
"a",
"summary",
"line",
"on",
"how",
"the",
"request",
"went"
] | train | https://github.com/Jaymon/endpoints/blob/2f1c4ae2c69a168e69447d3d8395ada7becaa5fb/endpoints/call.py#L645-L653 |
ksbg/sparklanes | sparklanes/_framework/lane.py | build_lane_from_yaml | def build_lane_from_yaml(path):
"""Builds a `sparklanes.Lane` object from a YAML definition file.
Parameters
----------
path: str
Path to the YAML definition file
Returns
-------
Lane
Lane, built according to definition in YAML file
"""
# Open
with open(path, 'r... | python | def build_lane_from_yaml(path):
"""Builds a `sparklanes.Lane` object from a YAML definition file.
Parameters
----------
path: str
Path to the YAML definition file
Returns
-------
Lane
Lane, built according to definition in YAML file
"""
# Open
with open(path, 'r... | [
"def",
"build_lane_from_yaml",
"(",
"path",
")",
":",
"# Open",
"with",
"open",
"(",
"path",
",",
"'rb'",
")",
"as",
"yaml_definition",
":",
"definition",
"=",
"yaml",
".",
"load",
"(",
"yaml_definition",
")",
"# Validate schema",
"try",
":",
"validate_schema"... | Builds a `sparklanes.Lane` object from a YAML definition file.
Parameters
----------
path: str
Path to the YAML definition file
Returns
-------
Lane
Lane, built according to definition in YAML file | [
"Builds",
"a",
"sparklanes",
".",
"Lane",
"object",
"from",
"a",
"YAML",
"definition",
"file",
"."
] | train | https://github.com/ksbg/sparklanes/blob/62e70892e6ae025be2f4c419f4afc34714d6884c/sparklanes/_framework/lane.py#L165-L218 |
ksbg/sparklanes | sparklanes/_framework/lane.py | Lane.__validate_task | def __validate_task(self, cls, entry_mtd_name, args, kwargs):
"""Checks if a class is a task, i.e. if it has been decorated with `sparklanes.Task`, and if
the supplied args/kwargs match the signature of the task's entry method.
Parameters
----------
cls : LaneTask
entry_... | python | def __validate_task(self, cls, entry_mtd_name, args, kwargs):
"""Checks if a class is a task, i.e. if it has been decorated with `sparklanes.Task`, and if
the supplied args/kwargs match the signature of the task's entry method.
Parameters
----------
cls : LaneTask
entry_... | [
"def",
"__validate_task",
"(",
"self",
",",
"cls",
",",
"entry_mtd_name",
",",
"args",
",",
"kwargs",
")",
":",
"if",
"not",
"isclass",
"(",
"cls",
")",
"or",
"not",
"issubclass",
"(",
"cls",
",",
"LaneTask",
")",
":",
"raise",
"TypeError",
"(",
"'Trie... | Checks if a class is a task, i.e. if it has been decorated with `sparklanes.Task`, and if
the supplied args/kwargs match the signature of the task's entry method.
Parameters
----------
cls : LaneTask
entry_mtd_name : str
Name of the method, which is called when the t... | [
"Checks",
"if",
"a",
"class",
"is",
"a",
"task",
"i",
".",
"e",
".",
"if",
"it",
"has",
"been",
"decorated",
"with",
"sparklanes",
".",
"Task",
"and",
"if",
"the",
"supplied",
"args",
"/",
"kwargs",
"match",
"the",
"signature",
"of",
"the",
"task",
"... | train | https://github.com/ksbg/sparklanes/blob/62e70892e6ae025be2f4c419f4afc34714d6884c/sparklanes/_framework/lane.py#L68-L84 |
ksbg/sparklanes | sparklanes/_framework/lane.py | Lane.add | def add(self, cls_or_branch, *args, **kwargs):
"""Adds a task or branch to the lane.
Parameters
----------
cls_or_branch : Class
*args
Variable length argument list to be passed to `cls_or_branch` during instantiation
**kwargs
Variable length keyw... | python | def add(self, cls_or_branch, *args, **kwargs):
"""Adds a task or branch to the lane.
Parameters
----------
cls_or_branch : Class
*args
Variable length argument list to be passed to `cls_or_branch` during instantiation
**kwargs
Variable length keyw... | [
"def",
"add",
"(",
"self",
",",
"cls_or_branch",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"cls_or_branch",
",",
"Branch",
")",
":",
"self",
".",
"tasks",
".",
"append",
"(",
"cls_or_branch",
")",
"# Add branch with al... | Adds a task or branch to the lane.
Parameters
----------
cls_or_branch : Class
*args
Variable length argument list to be passed to `cls_or_branch` during instantiation
**kwargs
Variable length keyword arguments to be passed to `cls_or_branch` during insta... | [
"Adds",
"a",
"task",
"or",
"branch",
"to",
"the",
"lane",
"."
] | train | https://github.com/ksbg/sparklanes/blob/62e70892e6ae025be2f4c419f4afc34714d6884c/sparklanes/_framework/lane.py#L86-L109 |
ksbg/sparklanes | sparklanes/_framework/lane.py | Lane.run | def run(self):
"""Executes the tasks in the lane in the order in which they have been added, unless
`self.run_parallel` is True, then a thread is spawned for each task and executed in
parallel (note that task threads are still spawned in the order in which they were added).
"""
l... | python | def run(self):
"""Executes the tasks in the lane in the order in which they have been added, unless
`self.run_parallel` is True, then a thread is spawned for each task and executed in
parallel (note that task threads are still spawned in the order in which they were added).
"""
l... | [
"def",
"run",
"(",
"self",
")",
":",
"logger",
"=",
"make_default_logger",
"(",
"INTERNAL_LOGGER_NAME",
")",
"logger",
".",
"info",
"(",
"'\\n%s\\nExecuting `%s`\\n%s\\n'",
",",
"'-'",
"*",
"80",
",",
"self",
".",
"name",
",",
"'-'",
"*",
"80",
")",
"logge... | Executes the tasks in the lane in the order in which they have been added, unless
`self.run_parallel` is True, then a thread is spawned for each task and executed in
parallel (note that task threads are still spawned in the order in which they were added). | [
"Executes",
"the",
"tasks",
"in",
"the",
"lane",
"in",
"the",
"order",
"in",
"which",
"they",
"have",
"been",
"added",
"unless",
"self",
".",
"run_parallel",
"is",
"True",
"then",
"a",
"thread",
"is",
"spawned",
"for",
"each",
"task",
"and",
"executed",
... | train | https://github.com/ksbg/sparklanes/blob/62e70892e6ae025be2f4c419f4afc34714d6884c/sparklanes/_framework/lane.py#L111-L146 |
cbclab/MOT | examples/german_tank_problem.py | get_historical_data | def get_historical_data(nmr_problems):
"""Get the historical tank data.
Args:
nmr_problems (int): the number of problems
Returns:
tuple: (observations, nmr_tanks_ground_truth)
"""
observations = np.tile(np.array([[10, 256, 202, 97]]), (nmr_problems, 1))
nmr_tanks_ground_truth =... | python | def get_historical_data(nmr_problems):
"""Get the historical tank data.
Args:
nmr_problems (int): the number of problems
Returns:
tuple: (observations, nmr_tanks_ground_truth)
"""
observations = np.tile(np.array([[10, 256, 202, 97]]), (nmr_problems, 1))
nmr_tanks_ground_truth =... | [
"def",
"get_historical_data",
"(",
"nmr_problems",
")",
":",
"observations",
"=",
"np",
".",
"tile",
"(",
"np",
".",
"array",
"(",
"[",
"[",
"10",
",",
"256",
",",
"202",
",",
"97",
"]",
"]",
")",
",",
"(",
"nmr_problems",
",",
"1",
")",
")",
"nm... | Get the historical tank data.
Args:
nmr_problems (int): the number of problems
Returns:
tuple: (observations, nmr_tanks_ground_truth) | [
"Get",
"the",
"historical",
"tank",
"data",
"."
] | train | https://github.com/cbclab/MOT/blob/fb3243b65025705842e82704705c00902f9a35af/examples/german_tank_problem.py#L15-L26 |
cbclab/MOT | examples/german_tank_problem.py | get_simulated_data | def get_simulated_data(nmr_problems):
"""Simulate some data.
This returns the simulated tank observations and the corresponding ground truth maximum number of tanks.
Args:
nmr_problems (int): the number of problems
Returns:
tuple: (observations, nmr_tanks_ground_truth)
"""
# T... | python | def get_simulated_data(nmr_problems):
"""Simulate some data.
This returns the simulated tank observations and the corresponding ground truth maximum number of tanks.
Args:
nmr_problems (int): the number of problems
Returns:
tuple: (observations, nmr_tanks_ground_truth)
"""
# T... | [
"def",
"get_simulated_data",
"(",
"nmr_problems",
")",
":",
"# The number of tanks we observe per problem",
"nmr_observed_tanks",
"=",
"10",
"# Generate some maximum number of tanks. Basically the ground truth of the estimation problem.",
"nmr_tanks_ground_truth",
"=",
"normal",
"(",
"... | Simulate some data.
This returns the simulated tank observations and the corresponding ground truth maximum number of tanks.
Args:
nmr_problems (int): the number of problems
Returns:
tuple: (observations, nmr_tanks_ground_truth) | [
"Simulate",
"some",
"data",
"."
] | train | https://github.com/cbclab/MOT/blob/fb3243b65025705842e82704705c00902f9a35af/examples/german_tank_problem.py#L29-L49 |
cbclab/MOT | mot/cl_routines/numerical_differentiation.py | estimate_hessian | def estimate_hessian(objective_func, parameters,
lower_bounds=None, upper_bounds=None,
step_ratio=2, nmr_steps=5,
max_step_sizes=None,
data=None, cl_runtime_info=None):
"""Estimate and return the upper triangular elements of the Hes... | python | def estimate_hessian(objective_func, parameters,
lower_bounds=None, upper_bounds=None,
step_ratio=2, nmr_steps=5,
max_step_sizes=None,
data=None, cl_runtime_info=None):
"""Estimate and return the upper triangular elements of the Hes... | [
"def",
"estimate_hessian",
"(",
"objective_func",
",",
"parameters",
",",
"lower_bounds",
"=",
"None",
",",
"upper_bounds",
"=",
"None",
",",
"step_ratio",
"=",
"2",
",",
"nmr_steps",
"=",
"5",
",",
"max_step_sizes",
"=",
"None",
",",
"data",
"=",
"None",
... | Estimate and return the upper triangular elements of the Hessian of the given function at the given parameters.
This calculates the Hessian using central difference (using a 2nd order Taylor expansion) with a Richardson
extrapolation over the proposed sequence of steps. If enough steps are given, we apply a Wy... | [
"Estimate",
"and",
"return",
"the",
"upper",
"triangular",
"elements",
"of",
"the",
"Hessian",
"of",
"the",
"given",
"function",
"at",
"the",
"given",
"parameters",
"."
] | train | https://github.com/cbclab/MOT/blob/fb3243b65025705842e82704705c00902f9a35af/mot/cl_routines/numerical_differentiation.py#L15-L135 |
cbclab/MOT | mot/cl_routines/numerical_differentiation.py | _get_numdiff_hessian_element_func | def _get_numdiff_hessian_element_func(objective_func, nmr_steps, step_ratio):
"""Return a function to compute one element of the Hessian matrix."""
return SimpleCLFunction.from_string('''
/**
* Compute the Hessian using (possibly) multiple steps with various interpolations.
*/
... | python | def _get_numdiff_hessian_element_func(objective_func, nmr_steps, step_ratio):
"""Return a function to compute one element of the Hessian matrix."""
return SimpleCLFunction.from_string('''
/**
* Compute the Hessian using (possibly) multiple steps with various interpolations.
*/
... | [
"def",
"_get_numdiff_hessian_element_func",
"(",
"objective_func",
",",
"nmr_steps",
",",
"step_ratio",
")",
":",
"return",
"SimpleCLFunction",
".",
"from_string",
"(",
"'''\n /**\n * Compute the Hessian using (possibly) multiple steps with various interpolations. \n ... | Return a function to compute one element of the Hessian matrix. | [
"Return",
"a",
"function",
"to",
"compute",
"one",
"element",
"of",
"the",
"Hessian",
"matrix",
"."
] | train | https://github.com/cbclab/MOT/blob/fb3243b65025705842e82704705c00902f9a35af/mot/cl_routines/numerical_differentiation.py#L138-L191 |
cbclab/MOT | mot/cl_routines/numerical_differentiation.py | _get_numdiff_hessian_steps_func | def _get_numdiff_hessian_steps_func(objective_func, nmr_steps, step_ratio):
"""Get a function to compute the multiple step sizes for a single element of the Hessian."""
return SimpleCLFunction.from_string('''
/**
* Compute one element of the Hessian for a number of steps.
*
*... | python | def _get_numdiff_hessian_steps_func(objective_func, nmr_steps, step_ratio):
"""Get a function to compute the multiple step sizes for a single element of the Hessian."""
return SimpleCLFunction.from_string('''
/**
* Compute one element of the Hessian for a number of steps.
*
*... | [
"def",
"_get_numdiff_hessian_steps_func",
"(",
"objective_func",
",",
"nmr_steps",
",",
"step_ratio",
")",
":",
"return",
"SimpleCLFunction",
".",
"from_string",
"(",
"'''\n /**\n * Compute one element of the Hessian for a number of steps.\n * \n * This u... | Get a function to compute the multiple step sizes for a single element of the Hessian. | [
"Get",
"a",
"function",
"to",
"compute",
"the",
"multiple",
"step",
"sizes",
"for",
"a",
"single",
"element",
"of",
"the",
"Hessian",
"."
] | train | https://github.com/cbclab/MOT/blob/fb3243b65025705842e82704705c00902f9a35af/mot/cl_routines/numerical_differentiation.py#L194-L338 |
cbclab/MOT | mot/cl_routines/numerical_differentiation.py | _get_initial_step | def _get_initial_step(parameters, lower_bounds, upper_bounds, max_step_sizes):
"""Get an initial step size to use for every parameter.
This chooses the step sizes based on the maximum step size and the lower and upper bounds.
Args:
parameters (ndarray): The parameters at which to evaluate the grad... | python | def _get_initial_step(parameters, lower_bounds, upper_bounds, max_step_sizes):
"""Get an initial step size to use for every parameter.
This chooses the step sizes based on the maximum step size and the lower and upper bounds.
Args:
parameters (ndarray): The parameters at which to evaluate the grad... | [
"def",
"_get_initial_step",
"(",
"parameters",
",",
"lower_bounds",
",",
"upper_bounds",
",",
"max_step_sizes",
")",
":",
"nmr_params",
"=",
"parameters",
".",
"shape",
"[",
"1",
"]",
"initial_step",
"=",
"np",
".",
"zeros_like",
"(",
"parameters",
")",
"if",
... | Get an initial step size to use for every parameter.
This chooses the step sizes based on the maximum step size and the lower and upper bounds.
Args:
parameters (ndarray): The parameters at which to evaluate the gradient. A (d, p) matrix with d problems,
p parameters and n samples.
... | [
"Get",
"an",
"initial",
"step",
"size",
"to",
"use",
"for",
"every",
"parameter",
"."
] | train | https://github.com/cbclab/MOT/blob/fb3243b65025705842e82704705c00902f9a35af/mot/cl_routines/numerical_differentiation.py#L597-L627 |
cbclab/MOT | mot/configuration.py | SimpleConfigAction.apply | def apply(self):
"""Apply the current action to the current runtime configuration."""
self._old_config = {k: v for k, v in _config.items()}
self._apply() | python | def apply(self):
"""Apply the current action to the current runtime configuration."""
self._old_config = {k: v for k, v in _config.items()}
self._apply() | [
"def",
"apply",
"(",
"self",
")",
":",
"self",
".",
"_old_config",
"=",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"_config",
".",
"items",
"(",
")",
"}",
"self",
".",
"_apply",
"(",
")"
] | Apply the current action to the current runtime configuration. | [
"Apply",
"the",
"current",
"action",
"to",
"the",
"current",
"runtime",
"configuration",
"."
] | train | https://github.com/cbclab/MOT/blob/fb3243b65025705842e82704705c00902f9a35af/mot/configuration.py#L156-L159 |
cbclab/MOT | mot/configuration.py | SimpleConfigAction.unapply | def unapply(self):
"""Reset the current configuration to the previous state."""
for key, value in self._old_config.items():
_config[key] = value | python | def unapply(self):
"""Reset the current configuration to the previous state."""
for key, value in self._old_config.items():
_config[key] = value | [
"def",
"unapply",
"(",
"self",
")",
":",
"for",
"key",
",",
"value",
"in",
"self",
".",
"_old_config",
".",
"items",
"(",
")",
":",
"_config",
"[",
"key",
"]",
"=",
"value"
] | Reset the current configuration to the previous state. | [
"Reset",
"the",
"current",
"configuration",
"to",
"the",
"previous",
"state",
"."
] | train | https://github.com/cbclab/MOT/blob/fb3243b65025705842e82704705c00902f9a35af/mot/configuration.py#L161-L164 |
ksbg/sparklanes | sparklanes/_framework/task.py | Task | def Task(entry): # pylint: disable=invalid-name
"""
Decorator with which classes, who act as tasks in a `Lane`, must be decorated. When a class is
being decorated, it becomes a child of `LaneTask`.
Parameters
----------
entry: The name of the task's "main" method, i.e. the method which is exec... | python | def Task(entry): # pylint: disable=invalid-name
"""
Decorator with which classes, who act as tasks in a `Lane`, must be decorated. When a class is
being decorated, it becomes a child of `LaneTask`.
Parameters
----------
entry: The name of the task's "main" method, i.e. the method which is exec... | [
"def",
"Task",
"(",
"entry",
")",
":",
"# pylint: disable=invalid-name",
"if",
"not",
"isinstance",
"(",
"entry",
",",
"string_types",
")",
":",
"# In the event that no argument is supplied to the decorator, python passes the decorated",
"# class itself as an argument. That way, we... | Decorator with which classes, who act as tasks in a `Lane`, must be decorated. When a class is
being decorated, it becomes a child of `LaneTask`.
Parameters
----------
entry: The name of the task's "main" method, i.e. the method which is executed when task is run
Returns
-------
wrapper (f... | [
"Decorator",
"with",
"which",
"classes",
"who",
"act",
"as",
"tasks",
"in",
"a",
"Lane",
"must",
"be",
"decorated",
".",
"When",
"a",
"class",
"is",
"being",
"decorated",
"it",
"becomes",
"a",
"child",
"of",
"LaneTask",
"."
] | train | https://github.com/ksbg/sparklanes/blob/62e70892e6ae025be2f4c419f4afc34714d6884c/sparklanes/_framework/task.py#L18-L89 |
ksbg/sparklanes | sparklanes/_framework/task.py | LaneTask.cache | def cache(self, name, val, overwrite=True):
"""Assigns an attribute reference to all subsequent tasks. For example, if a task caches a
DataFrame `df` using `self.cache('some_df', df)`, all tasks that follow can access the
DataFrame using `self.some_df`. Note that manually assigned attributes tha... | python | def cache(self, name, val, overwrite=True):
"""Assigns an attribute reference to all subsequent tasks. For example, if a task caches a
DataFrame `df` using `self.cache('some_df', df)`, all tasks that follow can access the
DataFrame using `self.some_df`. Note that manually assigned attributes tha... | [
"def",
"cache",
"(",
"self",
",",
"name",
",",
"val",
",",
"overwrite",
"=",
"True",
")",
":",
"if",
"name",
"in",
"TaskCache",
".",
"cached",
"and",
"not",
"overwrite",
":",
"raise",
"CacheError",
"(",
"'Object with name `%s` already in cache.'",
"%",
"name... | Assigns an attribute reference to all subsequent tasks. For example, if a task caches a
DataFrame `df` using `self.cache('some_df', df)`, all tasks that follow can access the
DataFrame using `self.some_df`. Note that manually assigned attributes that share the same
name have precedence over cach... | [
"Assigns",
"an",
"attribute",
"reference",
"to",
"all",
"subsequent",
"tasks",
".",
"For",
"example",
"if",
"a",
"task",
"caches",
"a",
"DataFrame",
"df",
"using",
"self",
".",
"cache",
"(",
"some_df",
"df",
")",
"all",
"tasks",
"that",
"follow",
"can",
... | train | https://github.com/ksbg/sparklanes/blob/62e70892e6ae025be2f4c419f4afc34714d6884c/sparklanes/_framework/task.py#L121-L140 |
ksbg/sparklanes | sparklanes/_framework/task.py | LaneTaskThread.run | def run(self):
"""Overwrites `threading.Thread.run`, to allow handling of exceptions thrown by threads
from within the main app."""
self.exc = None
try:
self.task()
except BaseException:
self.exc = sys.exc_info() | python | def run(self):
"""Overwrites `threading.Thread.run`, to allow handling of exceptions thrown by threads
from within the main app."""
self.exc = None
try:
self.task()
except BaseException:
self.exc = sys.exc_info() | [
"def",
"run",
"(",
"self",
")",
":",
"self",
".",
"exc",
"=",
"None",
"try",
":",
"self",
".",
"task",
"(",
")",
"except",
"BaseException",
":",
"self",
".",
"exc",
"=",
"sys",
".",
"exc_info",
"(",
")"
] | Overwrites `threading.Thread.run`, to allow handling of exceptions thrown by threads
from within the main app. | [
"Overwrites",
"threading",
".",
"Thread",
".",
"run",
"to",
"allow",
"handling",
"of",
"exceptions",
"thrown",
"by",
"threads",
"from",
"within",
"the",
"main",
"app",
"."
] | train | https://github.com/ksbg/sparklanes/blob/62e70892e6ae025be2f4c419f4afc34714d6884c/sparklanes/_framework/task.py#L170-L177 |
ksbg/sparklanes | sparklanes/_framework/task.py | LaneTaskThread.join | def join(self, timeout=None):
"""Overwrites `threading.Thread.join`, to allow handling of exceptions thrown by threads
from within the main app."""
Thread.join(self, timeout=timeout)
if self.exc:
msg = "Thread '%s' threw an exception `%s`: %s" \
% (self.getN... | python | def join(self, timeout=None):
"""Overwrites `threading.Thread.join`, to allow handling of exceptions thrown by threads
from within the main app."""
Thread.join(self, timeout=timeout)
if self.exc:
msg = "Thread '%s' threw an exception `%s`: %s" \
% (self.getN... | [
"def",
"join",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"Thread",
".",
"join",
"(",
"self",
",",
"timeout",
"=",
"timeout",
")",
"if",
"self",
".",
"exc",
":",
"msg",
"=",
"\"Thread '%s' threw an exception `%s`: %s\"",
"%",
"(",
"self",
".",
... | Overwrites `threading.Thread.join`, to allow handling of exceptions thrown by threads
from within the main app. | [
"Overwrites",
"threading",
".",
"Thread",
".",
"join",
"to",
"allow",
"handling",
"of",
"exceptions",
"thrown",
"by",
"threads",
"from",
"within",
"the",
"main",
"app",
"."
] | train | https://github.com/ksbg/sparklanes/blob/62e70892e6ae025be2f4c419f4afc34714d6884c/sparklanes/_framework/task.py#L179-L191 |
cbclab/MOT | docs/conf.py | mock_decorator | def mock_decorator(*args, **kwargs):
"""Mocked decorator, needed in the case we need to mock a decorator"""
def _called_decorator(dec_func):
@wraps(dec_func)
def _decorator(*args, **kwargs):
return dec_func()
return _decorator
return _called_decorator | python | def mock_decorator(*args, **kwargs):
"""Mocked decorator, needed in the case we need to mock a decorator"""
def _called_decorator(dec_func):
@wraps(dec_func)
def _decorator(*args, **kwargs):
return dec_func()
return _decorator
return _called_decorator | [
"def",
"mock_decorator",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"_called_decorator",
"(",
"dec_func",
")",
":",
"@",
"wraps",
"(",
"dec_func",
")",
"def",
"_decorator",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return... | Mocked decorator, needed in the case we need to mock a decorator | [
"Mocked",
"decorator",
"needed",
"in",
"the",
"case",
"we",
"need",
"to",
"mock",
"a",
"decorator"
] | train | https://github.com/cbclab/MOT/blob/fb3243b65025705842e82704705c00902f9a35af/docs/conf.py#L28-L35 |
cbclab/MOT | docs/conf.py | import_mock | def import_mock(name, *args, **kwargs):
"""Mock all modules starting with one of the mock_modules names."""
if any(name.startswith(s) for s in mock_modules):
return MockModule()
return orig_import(name, *args, **kwargs) | python | def import_mock(name, *args, **kwargs):
"""Mock all modules starting with one of the mock_modules names."""
if any(name.startswith(s) for s in mock_modules):
return MockModule()
return orig_import(name, *args, **kwargs) | [
"def",
"import_mock",
"(",
"name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"any",
"(",
"name",
".",
"startswith",
"(",
"s",
")",
"for",
"s",
"in",
"mock_modules",
")",
":",
"return",
"MockModule",
"(",
")",
"return",
"orig_import",... | Mock all modules starting with one of the mock_modules names. | [
"Mock",
"all",
"modules",
"starting",
"with",
"one",
"of",
"the",
"mock_modules",
"names",
"."
] | train | https://github.com/cbclab/MOT/blob/fb3243b65025705842e82704705c00902f9a35af/docs/conf.py#L59-L63 |
cbclab/MOT | mot/lib/cl_function.py | apply_cl_function | def apply_cl_function(cl_function, kernel_data, nmr_instances, use_local_reduction=False, cl_runtime_info=None):
"""Run the given function/procedure on the given set of data.
This class will wrap the given CL function in a kernel call and execute that that for every data instance using
the provided kernel ... | python | def apply_cl_function(cl_function, kernel_data, nmr_instances, use_local_reduction=False, cl_runtime_info=None):
"""Run the given function/procedure on the given set of data.
This class will wrap the given CL function in a kernel call and execute that that for every data instance using
the provided kernel ... | [
"def",
"apply_cl_function",
"(",
"cl_function",
",",
"kernel_data",
",",
"nmr_instances",
",",
"use_local_reduction",
"=",
"False",
",",
"cl_runtime_info",
"=",
"None",
")",
":",
"cl_runtime_info",
"=",
"cl_runtime_info",
"or",
"CLRuntimeInfo",
"(",
")",
"cl_environ... | Run the given function/procedure on the given set of data.
This class will wrap the given CL function in a kernel call and execute that that for every data instance using
the provided kernel data. This class will respect the read write setting of the kernel data elements such that
output can be written bac... | [
"Run",
"the",
"given",
"function",
"/",
"procedure",
"on",
"the",
"given",
"set",
"of",
"data",
"."
] | train | https://github.com/cbclab/MOT/blob/fb3243b65025705842e82704705c00902f9a35af/mot/lib/cl_function.py#L578-L633 |
cbclab/MOT | mot/lib/cl_function.py | SimpleCLFunction.from_string | def from_string(cls, cl_function, dependencies=()):
"""Parse the given CL function into a SimpleCLFunction object.
Args:
cl_function (str): the function we wish to turn into an object
dependencies (list or tuple of CLLibrary): The list of CL libraries this function depends on
... | python | def from_string(cls, cl_function, dependencies=()):
"""Parse the given CL function into a SimpleCLFunction object.
Args:
cl_function (str): the function we wish to turn into an object
dependencies (list or tuple of CLLibrary): The list of CL libraries this function depends on
... | [
"def",
"from_string",
"(",
"cls",
",",
"cl_function",
",",
"dependencies",
"=",
"(",
")",
")",
":",
"return_type",
",",
"function_name",
",",
"parameter_list",
",",
"body",
"=",
"split_cl_function",
"(",
"cl_function",
")",
"return",
"SimpleCLFunction",
"(",
"... | Parse the given CL function into a SimpleCLFunction object.
Args:
cl_function (str): the function we wish to turn into an object
dependencies (list or tuple of CLLibrary): The list of CL libraries this function depends on
Returns:
SimpleCLFunction: the CL data type ... | [
"Parse",
"the",
"given",
"CL",
"function",
"into",
"a",
"SimpleCLFunction",
"object",
"."
] | train | https://github.com/cbclab/MOT/blob/fb3243b65025705842e82704705c00902f9a35af/mot/lib/cl_function.py#L155-L166 |
cbclab/MOT | mot/lib/cl_function.py | SimpleCLFunction._get_parameter_signatures | def _get_parameter_signatures(self):
"""Get the signature of the parameters for the CL function declaration.
This should return the list of signatures of the parameters for use inside the function signature.
Returns:
list: the signatures of the parameters for the use in the CL code... | python | def _get_parameter_signatures(self):
"""Get the signature of the parameters for the CL function declaration.
This should return the list of signatures of the parameters for use inside the function signature.
Returns:
list: the signatures of the parameters for the use in the CL code... | [
"def",
"_get_parameter_signatures",
"(",
"self",
")",
":",
"declarations",
"=",
"[",
"]",
"for",
"p",
"in",
"self",
".",
"get_parameters",
"(",
")",
":",
"new_p",
"=",
"p",
".",
"get_renamed",
"(",
"p",
".",
"name",
".",
"replace",
"(",
"'.'",
",",
"... | Get the signature of the parameters for the CL function declaration.
This should return the list of signatures of the parameters for use inside the function signature.
Returns:
list: the signatures of the parameters for the use in the CL code. | [
"Get",
"the",
"signature",
"of",
"the",
"parameters",
"for",
"the",
"CL",
"function",
"declaration",
"."
] | train | https://github.com/cbclab/MOT/blob/fb3243b65025705842e82704705c00902f9a35af/mot/lib/cl_function.py#L253-L265 |
cbclab/MOT | mot/lib/cl_function.py | SimpleCLFunction._get_cl_dependency_code | def _get_cl_dependency_code(self):
"""Get the CL code for all the CL code for all the dependencies.
Returns:
str: The CL code with the actual code.
"""
code = ''
for d in self._dependencies:
code += d.get_cl_code() + "\n"
return code | python | def _get_cl_dependency_code(self):
"""Get the CL code for all the CL code for all the dependencies.
Returns:
str: The CL code with the actual code.
"""
code = ''
for d in self._dependencies:
code += d.get_cl_code() + "\n"
return code | [
"def",
"_get_cl_dependency_code",
"(",
"self",
")",
":",
"code",
"=",
"''",
"for",
"d",
"in",
"self",
".",
"_dependencies",
":",
"code",
"+=",
"d",
".",
"get_cl_code",
"(",
")",
"+",
"\"\\n\"",
"return",
"code"
] | Get the CL code for all the CL code for all the dependencies.
Returns:
str: The CL code with the actual code. | [
"Get",
"the",
"CL",
"code",
"for",
"all",
"the",
"CL",
"code",
"for",
"all",
"the",
"dependencies",
"."
] | train | https://github.com/cbclab/MOT/blob/fb3243b65025705842e82704705c00902f9a35af/mot/lib/cl_function.py#L267-L276 |
cbclab/MOT | mot/lib/cl_function.py | _ProcedureWorker._build_kernel | def _build_kernel(self, kernel_source, compile_flags=()):
"""Convenience function for building the kernel for this worker.
Args:
kernel_source (str): the kernel source to use for building the kernel
Returns:
cl.Program: a compiled CL kernel
"""
return cl... | python | def _build_kernel(self, kernel_source, compile_flags=()):
"""Convenience function for building the kernel for this worker.
Args:
kernel_source (str): the kernel source to use for building the kernel
Returns:
cl.Program: a compiled CL kernel
"""
return cl... | [
"def",
"_build_kernel",
"(",
"self",
",",
"kernel_source",
",",
"compile_flags",
"=",
"(",
")",
")",
":",
"return",
"cl",
".",
"Program",
"(",
"self",
".",
"_cl_context",
",",
"kernel_source",
")",
".",
"build",
"(",
"' '",
".",
"join",
"(",
"compile_fla... | Convenience function for building the kernel for this worker.
Args:
kernel_source (str): the kernel source to use for building the kernel
Returns:
cl.Program: a compiled CL kernel | [
"Convenience",
"function",
"for",
"building",
"the",
"kernel",
"for",
"this",
"worker",
"."
] | train | https://github.com/cbclab/MOT/blob/fb3243b65025705842e82704705c00902f9a35af/mot/lib/cl_function.py#L706-L715 |
cbclab/MOT | mot/lib/cl_function.py | _ProcedureWorker._get_kernel_arguments | def _get_kernel_arguments(self):
"""Get the list of kernel arguments for loading the kernel data elements into the kernel.
This will use the sorted keys for looping through the kernel input items.
Returns:
list of str: the list of parameter definitions
"""
declarati... | python | def _get_kernel_arguments(self):
"""Get the list of kernel arguments for loading the kernel data elements into the kernel.
This will use the sorted keys for looping through the kernel input items.
Returns:
list of str: the list of parameter definitions
"""
declarati... | [
"def",
"_get_kernel_arguments",
"(",
"self",
")",
":",
"declarations",
"=",
"[",
"]",
"for",
"name",
",",
"data",
"in",
"self",
".",
"_kernel_data",
".",
"items",
"(",
")",
":",
"declarations",
".",
"extend",
"(",
"data",
".",
"get_kernel_parameters",
"(",... | Get the list of kernel arguments for loading the kernel data elements into the kernel.
This will use the sorted keys for looping through the kernel input items.
Returns:
list of str: the list of parameter definitions | [
"Get",
"the",
"list",
"of",
"kernel",
"arguments",
"for",
"loading",
"the",
"kernel",
"data",
"elements",
"into",
"the",
"kernel",
"."
] | train | https://github.com/cbclab/MOT/blob/fb3243b65025705842e82704705c00902f9a35af/mot/lib/cl_function.py#L752-L763 |
cbclab/MOT | mot/lib/cl_function.py | _ProcedureWorker.get_scalar_arg_dtypes | def get_scalar_arg_dtypes(self):
"""Get the location and types of the input scalars.
Returns:
list: for every kernel input element either None if the data is a buffer or the numpy data type if
if is a scalar.
"""
dtypes = []
for name, data in self._ke... | python | def get_scalar_arg_dtypes(self):
"""Get the location and types of the input scalars.
Returns:
list: for every kernel input element either None if the data is a buffer or the numpy data type if
if is a scalar.
"""
dtypes = []
for name, data in self._ke... | [
"def",
"get_scalar_arg_dtypes",
"(",
"self",
")",
":",
"dtypes",
"=",
"[",
"]",
"for",
"name",
",",
"data",
"in",
"self",
".",
"_kernel_data",
".",
"items",
"(",
")",
":",
"dtypes",
".",
"extend",
"(",
"data",
".",
"get_scalar_arg_dtypes",
"(",
")",
")... | Get the location and types of the input scalars.
Returns:
list: for every kernel input element either None if the data is a buffer or the numpy data type if
if is a scalar. | [
"Get",
"the",
"location",
"and",
"types",
"of",
"the",
"input",
"scalars",
"."
] | train | https://github.com/cbclab/MOT/blob/fb3243b65025705842e82704705c00902f9a35af/mot/lib/cl_function.py#L765-L775 |
ksbg/sparklanes | sparklanes/_framework/spark.py | SparkContextAndSessionContainer.set_sc | def set_sc(cls, master=None, appName=None, sparkHome=None, pyFiles=None, environment=None,
batchSize=0, serializer=PickleSerializer(), conf=None, gateway=None, jsc=None,
profiler_cls=BasicProfiler):
"""Creates and initializes a new `SparkContext` (the old one will be stopped).
... | python | def set_sc(cls, master=None, appName=None, sparkHome=None, pyFiles=None, environment=None,
batchSize=0, serializer=PickleSerializer(), conf=None, gateway=None, jsc=None,
profiler_cls=BasicProfiler):
"""Creates and initializes a new `SparkContext` (the old one will be stopped).
... | [
"def",
"set_sc",
"(",
"cls",
",",
"master",
"=",
"None",
",",
"appName",
"=",
"None",
",",
"sparkHome",
"=",
"None",
",",
"pyFiles",
"=",
"None",
",",
"environment",
"=",
"None",
",",
"batchSize",
"=",
"0",
",",
"serializer",
"=",
"PickleSerializer",
"... | Creates and initializes a new `SparkContext` (the old one will be stopped).
Argument signature is copied from `pyspark.SparkContext
<https://spark.apache.org/docs/latest/api/python/pyspark.html#pyspark.SparkContext>`_. | [
"Creates",
"and",
"initializes",
"a",
"new",
"SparkContext",
"(",
"the",
"old",
"one",
"will",
"be",
"stopped",
")",
".",
"Argument",
"signature",
"is",
"copied",
"from",
"pyspark",
".",
"SparkContext",
"<https",
":",
"//",
"spark",
".",
"apache",
".",
"or... | train | https://github.com/ksbg/sparklanes/blob/62e70892e6ae025be2f4c419f4afc34714d6884c/sparklanes/_framework/spark.py#L24-L36 |
ksbg/sparklanes | sparklanes/_framework/spark.py | SparkContextAndSessionContainer.set_spark | def set_spark(cls, master=None, appName=None, conf=None, hive_support=False):
"""Creates and initializes a new `SparkSession`. Argument signature is copied from
`pyspark.sql.SparkSession
<https://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark.sql.SparkSession>`_.
"""
... | python | def set_spark(cls, master=None, appName=None, conf=None, hive_support=False):
"""Creates and initializes a new `SparkSession`. Argument signature is copied from
`pyspark.sql.SparkSession
<https://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark.sql.SparkSession>`_.
"""
... | [
"def",
"set_spark",
"(",
"cls",
",",
"master",
"=",
"None",
",",
"appName",
"=",
"None",
",",
"conf",
"=",
"None",
",",
"hive_support",
"=",
"False",
")",
":",
"sess",
"=",
"SparkSession",
".",
"builder",
"if",
"master",
":",
"sess",
".",
"master",
"... | Creates and initializes a new `SparkSession`. Argument signature is copied from
`pyspark.sql.SparkSession
<https://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark.sql.SparkSession>`_. | [
"Creates",
"and",
"initializes",
"a",
"new",
"SparkSession",
".",
"Argument",
"signature",
"is",
"copied",
"from",
"pyspark",
".",
"sql",
".",
"SparkSession",
"<https",
":",
"//",
"spark",
".",
"apache",
".",
"org",
"/",
"docs",
"/",
"latest",
"/",
"api",
... | train | https://github.com/ksbg/sparklanes/blob/62e70892e6ae025be2f4c419f4afc34714d6884c/sparklanes/_framework/spark.py#L39-L54 |
ksbg/sparklanes | sparklanes/_submit/submit.py | _package_and_submit | def _package_and_submit(args):
"""
Packages and submits a job, which is defined in a YAML file, to Spark.
Parameters
----------
args (List): Command-line arguments
"""
args = _parse_and_validate_args(args)
logging.debug(args)
dist = __make_tmp_dir()
try:
__package_depen... | python | def _package_and_submit(args):
"""
Packages and submits a job, which is defined in a YAML file, to Spark.
Parameters
----------
args (List): Command-line arguments
"""
args = _parse_and_validate_args(args)
logging.debug(args)
dist = __make_tmp_dir()
try:
__package_depen... | [
"def",
"_package_and_submit",
"(",
"args",
")",
":",
"args",
"=",
"_parse_and_validate_args",
"(",
"args",
")",
"logging",
".",
"debug",
"(",
"args",
")",
"dist",
"=",
"__make_tmp_dir",
"(",
")",
"try",
":",
"__package_dependencies",
"(",
"dist_dir",
"=",
"d... | Packages and submits a job, which is defined in a YAML file, to Spark.
Parameters
----------
args (List): Command-line arguments | [
"Packages",
"and",
"submits",
"a",
"job",
"which",
"is",
"defined",
"in",
"a",
"YAML",
"file",
"to",
"Spark",
"."
] | train | https://github.com/ksbg/sparklanes/blob/62e70892e6ae025be2f4c419f4afc34714d6884c/sparklanes/_submit/submit.py#L19-L47 |
ksbg/sparklanes | sparklanes/_submit/submit.py | _parse_and_validate_args | def _parse_and_validate_args(args):
"""
Parse and validate arguments. During validation, it is checked whether the given
files/directories exist, while also converting relative paths to absolute ones.
Parameters
----------
args (List): Command-line arguments
"""
class ExtendAction(argpa... | python | def _parse_and_validate_args(args):
"""
Parse and validate arguments. During validation, it is checked whether the given
files/directories exist, while also converting relative paths to absolute ones.
Parameters
----------
args (List): Command-line arguments
"""
class ExtendAction(argpa... | [
"def",
"_parse_and_validate_args",
"(",
"args",
")",
":",
"class",
"ExtendAction",
"(",
"argparse",
".",
"Action",
")",
":",
"def",
"__call__",
"(",
"self",
",",
"parser",
",",
"namespace",
",",
"values",
",",
"option_string",
"=",
"None",
")",
":",
"if",
... | Parse and validate arguments. During validation, it is checked whether the given
files/directories exist, while also converting relative paths to absolute ones.
Parameters
----------
args (List): Command-line arguments | [
"Parse",
"and",
"validate",
"arguments",
".",
"During",
"validation",
"it",
"is",
"checked",
"whether",
"the",
"given",
"files",
"/",
"directories",
"exist",
"while",
"also",
"converting",
"relative",
"paths",
"to",
"absolute",
"ones",
"."
] | train | https://github.com/ksbg/sparklanes/blob/62e70892e6ae025be2f4c419f4afc34714d6884c/sparklanes/_submit/submit.py#L50-L109 |
ksbg/sparklanes | sparklanes/_submit/submit.py | __validate_and_fix_path | def __validate_and_fix_path(path, check_file=False, check_dir=False):
"""Check if a file/directory exists and converts relative paths to absolute ones"""
# pylint: disable=superfluous-parens
if path is None:
return path
else:
if not (os.path.isfile(path) if check_file else False) \
... | python | def __validate_and_fix_path(path, check_file=False, check_dir=False):
"""Check if a file/directory exists and converts relative paths to absolute ones"""
# pylint: disable=superfluous-parens
if path is None:
return path
else:
if not (os.path.isfile(path) if check_file else False) \
... | [
"def",
"__validate_and_fix_path",
"(",
"path",
",",
"check_file",
"=",
"False",
",",
"check_dir",
"=",
"False",
")",
":",
"# pylint: disable=superfluous-parens",
"if",
"path",
"is",
"None",
":",
"return",
"path",
"else",
":",
"if",
"not",
"(",
"os",
".",
"pa... | Check if a file/directory exists and converts relative paths to absolute ones | [
"Check",
"if",
"a",
"file",
"/",
"directory",
"exists",
"and",
"converts",
"relative",
"paths",
"to",
"absolute",
"ones"
] | train | https://github.com/ksbg/sparklanes/blob/62e70892e6ae025be2f4c419f4afc34714d6884c/sparklanes/_submit/submit.py#L112-L124 |
ksbg/sparklanes | sparklanes/_submit/submit.py | __validate_and_fix_spark_args | def __validate_and_fix_spark_args(spark_args):
"""
Prepares spark arguments. In the command-line script, they are passed as for example
`-s master=local[4] deploy-mode=client verbose`, which would be passed to spark-submit as
`--master local[4] --deploy-mode client --verbose`
Parameters
-------... | python | def __validate_and_fix_spark_args(spark_args):
"""
Prepares spark arguments. In the command-line script, they are passed as for example
`-s master=local[4] deploy-mode=client verbose`, which would be passed to spark-submit as
`--master local[4] --deploy-mode client --verbose`
Parameters
-------... | [
"def",
"__validate_and_fix_spark_args",
"(",
"spark_args",
")",
":",
"pattern",
"=",
"re",
".",
"compile",
"(",
"r'[\\w\\-_]+=.+'",
")",
"fixed_args",
"=",
"[",
"]",
"for",
"arg",
"in",
"spark_args",
":",
"if",
"arg",
"not",
"in",
"SPARK_SUBMIT_FLAGS",
":",
... | Prepares spark arguments. In the command-line script, they are passed as for example
`-s master=local[4] deploy-mode=client verbose`, which would be passed to spark-submit as
`--master local[4] --deploy-mode client --verbose`
Parameters
----------
spark_args (List): List of spark arguments
Ret... | [
"Prepares",
"spark",
"arguments",
".",
"In",
"the",
"command",
"-",
"line",
"script",
"they",
"are",
"passed",
"as",
"for",
"example",
"-",
"s",
"master",
"=",
"local",
"[",
"4",
"]",
"deploy",
"-",
"mode",
"=",
"client",
"verbose",
"which",
"would",
"... | train | https://github.com/ksbg/sparklanes/blob/62e70892e6ae025be2f4c419f4afc34714d6884c/sparklanes/_submit/submit.py#L127-L155 |
ksbg/sparklanes | sparklanes/_submit/submit.py | __package_dependencies | def __package_dependencies(dist_dir, additional_reqs, silent):
"""
Installs the app's dependencies from pip and packages them (as zip), to be submitted to spark.
Parameters
----------
dist_dir (str): Path to directory where the packaged libs shall be located
additional_reqs (str): Path to a req... | python | def __package_dependencies(dist_dir, additional_reqs, silent):
"""
Installs the app's dependencies from pip and packages them (as zip), to be submitted to spark.
Parameters
----------
dist_dir (str): Path to directory where the packaged libs shall be located
additional_reqs (str): Path to a req... | [
"def",
"__package_dependencies",
"(",
"dist_dir",
",",
"additional_reqs",
",",
"silent",
")",
":",
"logging",
".",
"info",
"(",
"'Packaging dependencies'",
")",
"libs_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dist_dir",
",",
"'libs'",
")",
"if",
"not"... | Installs the app's dependencies from pip and packages them (as zip), to be submitted to spark.
Parameters
----------
dist_dir (str): Path to directory where the packaged libs shall be located
additional_reqs (str): Path to a requirements.txt, containing any of the app's additional
requirements
... | [
"Installs",
"the",
"app",
"s",
"dependencies",
"from",
"pip",
"and",
"packages",
"them",
"(",
"as",
"zip",
")",
"to",
"be",
"submitted",
"to",
"spark",
"."
] | train | https://github.com/ksbg/sparklanes/blob/62e70892e6ae025be2f4c419f4afc34714d6884c/sparklanes/_submit/submit.py#L172-L210 |
ksbg/sparklanes | sparklanes/_submit/submit.py | __package_app | def __package_app(tasks_pkg, dist_dir, custom_main=None, extra_data=None):
"""
Packages the `tasks_pkg` (as zip) to `dist_dir`. Also copies the 'main' python file to
`dist_dir`, to be submitted to spark. Same for `extra_data`.
Parameters
----------
tasks_pkg (str): Path to the python package co... | python | def __package_app(tasks_pkg, dist_dir, custom_main=None, extra_data=None):
"""
Packages the `tasks_pkg` (as zip) to `dist_dir`. Also copies the 'main' python file to
`dist_dir`, to be submitted to spark. Same for `extra_data`.
Parameters
----------
tasks_pkg (str): Path to the python package co... | [
"def",
"__package_app",
"(",
"tasks_pkg",
",",
"dist_dir",
",",
"custom_main",
"=",
"None",
",",
"extra_data",
"=",
"None",
")",
":",
"logging",
".",
"info",
"(",
"'Packaging application'",
")",
"# Package tasks",
"tasks_dir_splits",
"=",
"os",
".",
"path",
".... | Packages the `tasks_pkg` (as zip) to `dist_dir`. Also copies the 'main' python file to
`dist_dir`, to be submitted to spark. Same for `extra_data`.
Parameters
----------
tasks_pkg (str): Path to the python package containing tasks
dist_dir (str): Path to the directory where the packaged code should... | [
"Packages",
"the",
"tasks_pkg",
"(",
"as",
"zip",
")",
"to",
"dist_dir",
".",
"Also",
"copies",
"the",
"main",
"python",
"file",
"to",
"dist_dir",
"to",
"be",
"submitted",
"to",
"spark",
".",
"Same",
"for",
"extra_data",
"."
] | train | https://github.com/ksbg/sparklanes/blob/62e70892e6ae025be2f4c419f4afc34714d6884c/sparklanes/_submit/submit.py#L213-L263 |
ksbg/sparklanes | sparklanes/_submit/submit.py | __run_spark_submit | def __run_spark_submit(lane_yaml, dist_dir, spark_home, spark_args, silent):
"""
Submits the packaged application to spark using a `spark-submit` subprocess
Parameters
----------
lane_yaml (str): Path to the YAML lane definition file
dist_dir (str): Path to the directory where the packaged code... | python | def __run_spark_submit(lane_yaml, dist_dir, spark_home, spark_args, silent):
"""
Submits the packaged application to spark using a `spark-submit` subprocess
Parameters
----------
lane_yaml (str): Path to the YAML lane definition file
dist_dir (str): Path to the directory where the packaged code... | [
"def",
"__run_spark_submit",
"(",
"lane_yaml",
",",
"dist_dir",
",",
"spark_home",
",",
"spark_args",
",",
"silent",
")",
":",
"# spark-submit binary",
"cmd",
"=",
"[",
"'spark-submit'",
"if",
"spark_home",
"is",
"None",
"else",
"os",
".",
"path",
".",
"join",... | Submits the packaged application to spark using a `spark-submit` subprocess
Parameters
----------
lane_yaml (str): Path to the YAML lane definition file
dist_dir (str): Path to the directory where the packaged code is located
spark_args (str): String of any additional spark config args to be passed... | [
"Submits",
"the",
"packaged",
"application",
"to",
"spark",
"using",
"a",
"spark",
"-",
"submit",
"subprocess"
] | train | https://github.com/ksbg/sparklanes/blob/62e70892e6ae025be2f4c419f4afc34714d6884c/sparklanes/_submit/submit.py#L266-L295 |
cbclab/MOT | mot/lib/utils.py | add_include_guards | def add_include_guards(cl_str, guard_name=None):
"""Add include guards to the given string.
If you are including the same body of CL code multiple times in a Kernel, it is important to add include
guards (https://en.wikipedia.org/wiki/Include_guard) around them to prevent the kernel from registering the fu... | python | def add_include_guards(cl_str, guard_name=None):
"""Add include guards to the given string.
If you are including the same body of CL code multiple times in a Kernel, it is important to add include
guards (https://en.wikipedia.org/wiki/Include_guard) around them to prevent the kernel from registering the fu... | [
"def",
"add_include_guards",
"(",
"cl_str",
",",
"guard_name",
"=",
"None",
")",
":",
"if",
"not",
"guard_name",
":",
"guard_name",
"=",
"'GUARD_'",
"+",
"hashlib",
".",
"md5",
"(",
"cl_str",
".",
"encode",
"(",
"'utf-8'",
")",
")",
".",
"hexdigest",
"("... | Add include guards to the given string.
If you are including the same body of CL code multiple times in a Kernel, it is important to add include
guards (https://en.wikipedia.org/wiki/Include_guard) around them to prevent the kernel from registering the function
twice.
Args:
cl_str (str): the p... | [
"Add",
"include",
"guards",
"to",
"the",
"given",
"string",
"."
] | train | https://github.com/cbclab/MOT/blob/fb3243b65025705842e82704705c00902f9a35af/mot/lib/utils.py#L21-L44 |
cbclab/MOT | mot/lib/utils.py | ctype_to_dtype | def ctype_to_dtype(cl_type, mot_float_type='float'):
"""Get the numpy dtype of the given cl_type string.
Args:
cl_type (str): the CL data type to match, for example 'float' or 'float4'.
mot_float_type (str): the C name of the ``mot_float_type``. The dtype will be looked up recursively.
Ret... | python | def ctype_to_dtype(cl_type, mot_float_type='float'):
"""Get the numpy dtype of the given cl_type string.
Args:
cl_type (str): the CL data type to match, for example 'float' or 'float4'.
mot_float_type (str): the C name of the ``mot_float_type``. The dtype will be looked up recursively.
Ret... | [
"def",
"ctype_to_dtype",
"(",
"cl_type",
",",
"mot_float_type",
"=",
"'float'",
")",
":",
"if",
"is_vector_ctype",
"(",
"cl_type",
")",
":",
"raw_type",
",",
"vector_length",
"=",
"split_vector_ctype",
"(",
"cl_type",
")",
"if",
"raw_type",
"==",
"'mot_float_typ... | Get the numpy dtype of the given cl_type string.
Args:
cl_type (str): the CL data type to match, for example 'float' or 'float4'.
mot_float_type (str): the C name of the ``mot_float_type``. The dtype will be looked up recursively.
Returns:
dtype: the numpy datatype | [
"Get",
"the",
"numpy",
"dtype",
"of",
"the",
"given",
"cl_type",
"string",
"."
] | train | https://github.com/cbclab/MOT/blob/fb3243b65025705842e82704705c00902f9a35af/mot/lib/utils.py#L60-L99 |
cbclab/MOT | mot/lib/utils.py | convert_data_to_dtype | def convert_data_to_dtype(data, data_type, mot_float_type='float'):
"""Convert the given input data to the correct numpy type.
Args:
data (ndarray): The value to convert to the correct numpy type
data_type (str): the data type we need to convert the data to
mot_float_type (str): the dat... | python | def convert_data_to_dtype(data, data_type, mot_float_type='float'):
"""Convert the given input data to the correct numpy type.
Args:
data (ndarray): The value to convert to the correct numpy type
data_type (str): the data type we need to convert the data to
mot_float_type (str): the dat... | [
"def",
"convert_data_to_dtype",
"(",
"data",
",",
"data_type",
",",
"mot_float_type",
"=",
"'float'",
")",
":",
"scalar_dtype",
"=",
"ctype_to_dtype",
"(",
"data_type",
",",
"mot_float_type",
")",
"if",
"isinstance",
"(",
"data",
",",
"numbers",
".",
"Number",
... | Convert the given input data to the correct numpy type.
Args:
data (ndarray): The value to convert to the correct numpy type
data_type (str): the data type we need to convert the data to
mot_float_type (str): the data type of the current ``mot_float_type``
Returns:
ndarray: the... | [
"Convert",
"the",
"given",
"input",
"data",
"to",
"the",
"correct",
"numpy",
"type",
"."
] | train | https://github.com/cbclab/MOT/blob/fb3243b65025705842e82704705c00902f9a35af/mot/lib/utils.py#L102-L137 |
cbclab/MOT | mot/lib/utils.py | split_vector_ctype | def split_vector_ctype(ctype):
"""Split a vector ctype into a raw ctype and the vector length.
If the given ctype is not a vector type, we raise an error. I
Args:
ctype (str): the ctype to possibly split into a raw ctype and the vector length
Returns:
tuple: the raw ctype and the vec... | python | def split_vector_ctype(ctype):
"""Split a vector ctype into a raw ctype and the vector length.
If the given ctype is not a vector type, we raise an error. I
Args:
ctype (str): the ctype to possibly split into a raw ctype and the vector length
Returns:
tuple: the raw ctype and the vec... | [
"def",
"split_vector_ctype",
"(",
"ctype",
")",
":",
"if",
"not",
"is_vector_ctype",
"(",
"ctype",
")",
":",
"raise",
"ValueError",
"(",
"'The given ctype is not a vector type.'",
")",
"for",
"vector_length",
"in",
"[",
"2",
",",
"3",
",",
"4",
",",
"8",
","... | Split a vector ctype into a raw ctype and the vector length.
If the given ctype is not a vector type, we raise an error. I
Args:
ctype (str): the ctype to possibly split into a raw ctype and the vector length
Returns:
tuple: the raw ctype and the vector length | [
"Split",
"a",
"vector",
"ctype",
"into",
"a",
"raw",
"ctype",
"and",
"the",
"vector",
"length",
"."
] | train | https://github.com/cbclab/MOT/blob/fb3243b65025705842e82704705c00902f9a35af/mot/lib/utils.py#L140-L156 |
cbclab/MOT | mot/lib/utils.py | device_type_from_string | def device_type_from_string(cl_device_type_str):
"""Converts values like ``gpu`` to a pyopencl device type string.
Supported values are: ``accelerator``, ``cpu``, ``custom``, ``gpu``. If ``all`` is given, None is returned.
Args:
cl_device_type_str (str): The string we want to convert to a device t... | python | def device_type_from_string(cl_device_type_str):
"""Converts values like ``gpu`` to a pyopencl device type string.
Supported values are: ``accelerator``, ``cpu``, ``custom``, ``gpu``. If ``all`` is given, None is returned.
Args:
cl_device_type_str (str): The string we want to convert to a device t... | [
"def",
"device_type_from_string",
"(",
"cl_device_type_str",
")",
":",
"cl_device_type_str",
"=",
"cl_device_type_str",
".",
"upper",
"(",
")",
"if",
"hasattr",
"(",
"cl",
".",
"device_type",
",",
"cl_device_type_str",
")",
":",
"return",
"getattr",
"(",
"cl",
"... | Converts values like ``gpu`` to a pyopencl device type string.
Supported values are: ``accelerator``, ``cpu``, ``custom``, ``gpu``. If ``all`` is given, None is returned.
Args:
cl_device_type_str (str): The string we want to convert to a device type.
Returns:
cl.device_type: the pyopencl ... | [
"Converts",
"values",
"like",
"gpu",
"to",
"a",
"pyopencl",
"device",
"type",
"string",
"."
] | train | https://github.com/cbclab/MOT/blob/fb3243b65025705842e82704705c00902f9a35af/mot/lib/utils.py#L171-L185 |
cbclab/MOT | mot/lib/utils.py | get_float_type_def | def get_float_type_def(double_precision, include_complex=True):
"""Get the model floating point type definition.
Args:
double_precision (boolean): if True we will use the double type for the mot_float_type type.
Else, we will use the single precision float type for the mot_float_type type.
... | python | def get_float_type_def(double_precision, include_complex=True):
"""Get the model floating point type definition.
Args:
double_precision (boolean): if True we will use the double type for the mot_float_type type.
Else, we will use the single precision float type for the mot_float_type type.
... | [
"def",
"get_float_type_def",
"(",
"double_precision",
",",
"include_complex",
"=",
"True",
")",
":",
"if",
"include_complex",
":",
"with",
"open",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"resource_filename",
"(",
"'mot'",
",",
"'data/opencl/complex.h'",
")"... | Get the model floating point type definition.
Args:
double_precision (boolean): if True we will use the double type for the mot_float_type type.
Else, we will use the single precision float type for the mot_float_type type.
include_complex (boolean): if we include support for complex nu... | [
"Get",
"the",
"model",
"floating",
"point",
"type",
"definition",
"."
] | train | https://github.com/cbclab/MOT/blob/fb3243b65025705842e82704705c00902f9a35af/mot/lib/utils.py#L201-L258 |
cbclab/MOT | mot/lib/utils.py | topological_sort | def topological_sort(data):
"""Topological sort the given dictionary structure.
Args:
data (dict); dictionary structure where the value is a list of dependencies for that given key.
For example: ``{'a': (), 'b': ('a',)}``, where ``a`` depends on nothing and ``b`` depends on ``a``.
Retu... | python | def topological_sort(data):
"""Topological sort the given dictionary structure.
Args:
data (dict); dictionary structure where the value is a list of dependencies for that given key.
For example: ``{'a': (), 'b': ('a',)}``, where ``a`` depends on nothing and ``b`` depends on ``a``.
Retu... | [
"def",
"topological_sort",
"(",
"data",
")",
":",
"def",
"check_self_dependencies",
"(",
"input_data",
")",
":",
"\"\"\"Check if there are self dependencies within a node.\n\n Self dependencies are for example: ``{'a': ('a',)}``.\n\n Args:\n input_data (dict): the in... | Topological sort the given dictionary structure.
Args:
data (dict); dictionary structure where the value is a list of dependencies for that given key.
For example: ``{'a': (), 'b': ('a',)}``, where ``a`` depends on nothing and ``b`` depends on ``a``.
Returns:
tuple: the dependencie... | [
"Topological",
"sort",
"the",
"given",
"dictionary",
"structure",
"."
] | train | https://github.com/cbclab/MOT/blob/fb3243b65025705842e82704705c00902f9a35af/mot/lib/utils.py#L261-L345 |
cbclab/MOT | mot/lib/utils.py | is_scalar | def is_scalar(value):
"""Test if the given value is a scalar.
This function also works with memory mapped array values, in contrast to the numpy is_scalar method.
Args:
value: the value to test for being a scalar value
Returns:
boolean: if the given value is a scalar or not
"""
... | python | def is_scalar(value):
"""Test if the given value is a scalar.
This function also works with memory mapped array values, in contrast to the numpy is_scalar method.
Args:
value: the value to test for being a scalar value
Returns:
boolean: if the given value is a scalar or not
"""
... | [
"def",
"is_scalar",
"(",
"value",
")",
":",
"return",
"np",
".",
"isscalar",
"(",
"value",
")",
"or",
"(",
"isinstance",
"(",
"value",
",",
"np",
".",
"ndarray",
")",
"and",
"(",
"len",
"(",
"np",
".",
"squeeze",
"(",
"value",
")",
".",
"shape",
... | Test if the given value is a scalar.
This function also works with memory mapped array values, in contrast to the numpy is_scalar method.
Args:
value: the value to test for being a scalar value
Returns:
boolean: if the given value is a scalar or not | [
"Test",
"if",
"the",
"given",
"value",
"is",
"a",
"scalar",
"."
] | train | https://github.com/cbclab/MOT/blob/fb3243b65025705842e82704705c00902f9a35af/mot/lib/utils.py#L348-L359 |
cbclab/MOT | mot/lib/utils.py | all_elements_equal | def all_elements_equal(value):
"""Checks if all elements in the given value are equal to each other.
If the input is a single value the result is trivial. If not, we compare all the values to see
if they are exactly the same.
Args:
value (ndarray or number): a numpy array or a single number.
... | python | def all_elements_equal(value):
"""Checks if all elements in the given value are equal to each other.
If the input is a single value the result is trivial. If not, we compare all the values to see
if they are exactly the same.
Args:
value (ndarray or number): a numpy array or a single number.
... | [
"def",
"all_elements_equal",
"(",
"value",
")",
":",
"if",
"is_scalar",
"(",
"value",
")",
":",
"return",
"True",
"return",
"np",
".",
"array",
"(",
"value",
"==",
"value",
".",
"flatten",
"(",
")",
"[",
"0",
"]",
")",
".",
"all",
"(",
")"
] | Checks if all elements in the given value are equal to each other.
If the input is a single value the result is trivial. If not, we compare all the values to see
if they are exactly the same.
Args:
value (ndarray or number): a numpy array or a single number.
Returns:
bool: true if all... | [
"Checks",
"if",
"all",
"elements",
"in",
"the",
"given",
"value",
"are",
"equal",
"to",
"each",
"other",
"."
] | train | https://github.com/cbclab/MOT/blob/fb3243b65025705842e82704705c00902f9a35af/mot/lib/utils.py#L362-L376 |
cbclab/MOT | mot/lib/utils.py | get_single_value | def get_single_value(value):
"""Get a single value out of the given value.
This is meant to be used after a call to :func:`all_elements_equal` that returned True. With this
function we return a single number from the input value.
Args:
value (ndarray or number): a numpy array or a single numbe... | python | def get_single_value(value):
"""Get a single value out of the given value.
This is meant to be used after a call to :func:`all_elements_equal` that returned True. With this
function we return a single number from the input value.
Args:
value (ndarray or number): a numpy array or a single numbe... | [
"def",
"get_single_value",
"(",
"value",
")",
":",
"if",
"not",
"all_elements_equal",
"(",
"value",
")",
":",
"raise",
"ValueError",
"(",
"'Not all values are equal to each other.'",
")",
"if",
"is_scalar",
"(",
"value",
")",
":",
"return",
"value",
"return",
"v... | Get a single value out of the given value.
This is meant to be used after a call to :func:`all_elements_equal` that returned True. With this
function we return a single number from the input value.
Args:
value (ndarray or number): a numpy array or a single number.
Returns:
number: a s... | [
"Get",
"a",
"single",
"value",
"out",
"of",
"the",
"given",
"value",
"."
] | train | https://github.com/cbclab/MOT/blob/fb3243b65025705842e82704705c00902f9a35af/mot/lib/utils.py#L379-L399 |
cbclab/MOT | mot/lib/utils.py | all_logging_disabled | def all_logging_disabled(highest_level=logging.CRITICAL):
"""Disable all logging temporarily.
A context manager that will prevent any logging messages triggered during the body from being processed.
Args:
highest_level: the maximum logging level that is being blocked
"""
previous_level = l... | python | def all_logging_disabled(highest_level=logging.CRITICAL):
"""Disable all logging temporarily.
A context manager that will prevent any logging messages triggered during the body from being processed.
Args:
highest_level: the maximum logging level that is being blocked
"""
previous_level = l... | [
"def",
"all_logging_disabled",
"(",
"highest_level",
"=",
"logging",
".",
"CRITICAL",
")",
":",
"previous_level",
"=",
"logging",
".",
"root",
".",
"manager",
".",
"disable",
"logging",
".",
"disable",
"(",
"highest_level",
")",
"try",
":",
"yield",
"finally",... | Disable all logging temporarily.
A context manager that will prevent any logging messages triggered during the body from being processed.
Args:
highest_level: the maximum logging level that is being blocked | [
"Disable",
"all",
"logging",
"temporarily",
"."
] | train | https://github.com/cbclab/MOT/blob/fb3243b65025705842e82704705c00902f9a35af/mot/lib/utils.py#L403-L416 |
cbclab/MOT | mot/lib/utils.py | split_in_batches | def split_in_batches(nmr_elements, max_batch_size):
"""Split the total number of elements into batches of the specified maximum size.
Examples::
split_in_batches(30, 8) -> [(0, 8), (8, 15), (16, 23), (24, 29)]
for batch_start, batch_end in split_in_batches(2000, 100):
array[batch_s... | python | def split_in_batches(nmr_elements, max_batch_size):
"""Split the total number of elements into batches of the specified maximum size.
Examples::
split_in_batches(30, 8) -> [(0, 8), (8, 15), (16, 23), (24, 29)]
for batch_start, batch_end in split_in_batches(2000, 100):
array[batch_s... | [
"def",
"split_in_batches",
"(",
"nmr_elements",
",",
"max_batch_size",
")",
":",
"offset",
"=",
"0",
"elements_left",
"=",
"nmr_elements",
"while",
"elements_left",
">",
"0",
":",
"next_batch",
"=",
"(",
"offset",
",",
"offset",
"+",
"min",
"(",
"elements_left... | Split the total number of elements into batches of the specified maximum size.
Examples::
split_in_batches(30, 8) -> [(0, 8), (8, 15), (16, 23), (24, 29)]
for batch_start, batch_end in split_in_batches(2000, 100):
array[batch_start:batch_end]
Yields:
tuple: the start and e... | [
"Split",
"the",
"total",
"number",
"of",
"elements",
"into",
"batches",
"of",
"the",
"specified",
"maximum",
"size",
"."
] | train | https://github.com/cbclab/MOT/blob/fb3243b65025705842e82704705c00902f9a35af/mot/lib/utils.py#L460-L480 |
cbclab/MOT | mot/lib/utils.py | covariance_to_correlations | def covariance_to_correlations(covariance):
"""Transform a covariance matrix into a correlations matrix.
This can be seen as dividing a covariance matrix by the outer product of the diagonal.
As post processing we replace the infinities and the NaNs with zeros and clip the result to [-1, 1].
Args:
... | python | def covariance_to_correlations(covariance):
"""Transform a covariance matrix into a correlations matrix.
This can be seen as dividing a covariance matrix by the outer product of the diagonal.
As post processing we replace the infinities and the NaNs with zeros and clip the result to [-1, 1].
Args:
... | [
"def",
"covariance_to_correlations",
"(",
"covariance",
")",
":",
"diagonal_ind",
"=",
"np",
".",
"arange",
"(",
"covariance",
".",
"shape",
"[",
"1",
"]",
")",
"diagonal_els",
"=",
"covariance",
"[",
":",
",",
"diagonal_ind",
",",
"diagonal_ind",
"]",
"resu... | Transform a covariance matrix into a correlations matrix.
This can be seen as dividing a covariance matrix by the outer product of the diagonal.
As post processing we replace the infinities and the NaNs with zeros and clip the result to [-1, 1].
Args:
covariance (ndarray): a matrix of shape (n, p... | [
"Transform",
"a",
"covariance",
"matrix",
"into",
"a",
"correlations",
"matrix",
"."
] | train | https://github.com/cbclab/MOT/blob/fb3243b65025705842e82704705c00902f9a35af/mot/lib/utils.py#L483-L500 |
cbclab/MOT | mot/lib/utils.py | multiprocess_mapping | def multiprocess_mapping(func, iterable):
"""Multiprocess mapping the given function on the given iterable.
This only works in Linux and Mac systems since Windows has no forking capability. On Windows we fall back on
single processing. Also, if we reach memory limits we fall back on single cpu processing.
... | python | def multiprocess_mapping(func, iterable):
"""Multiprocess mapping the given function on the given iterable.
This only works in Linux and Mac systems since Windows has no forking capability. On Windows we fall back on
single processing. Also, if we reach memory limits we fall back on single cpu processing.
... | [
"def",
"multiprocess_mapping",
"(",
"func",
",",
"iterable",
")",
":",
"if",
"os",
".",
"name",
"==",
"'nt'",
":",
"# In Windows there is no fork.",
"return",
"list",
"(",
"map",
"(",
"func",
",",
"iterable",
")",
")",
"try",
":",
"p",
"=",
"multiprocessin... | Multiprocess mapping the given function on the given iterable.
This only works in Linux and Mac systems since Windows has no forking capability. On Windows we fall back on
single processing. Also, if we reach memory limits we fall back on single cpu processing.
Args:
func (func): the function to a... | [
"Multiprocess",
"mapping",
"the",
"given",
"function",
"on",
"the",
"given",
"iterable",
"."
] | train | https://github.com/cbclab/MOT/blob/fb3243b65025705842e82704705c00902f9a35af/mot/lib/utils.py#L503-L522 |
cbclab/MOT | mot/lib/utils.py | parse_cl_function | def parse_cl_function(cl_code, dependencies=()):
"""Parse the given OpenCL string to a single SimpleCLFunction.
If the string contains more than one function, we will return only the last, with all the other added as a
dependency.
Args:
cl_code (str): the input string containing one or more fu... | python | def parse_cl_function(cl_code, dependencies=()):
"""Parse the given OpenCL string to a single SimpleCLFunction.
If the string contains more than one function, we will return only the last, with all the other added as a
dependency.
Args:
cl_code (str): the input string containing one or more fu... | [
"def",
"parse_cl_function",
"(",
"cl_code",
",",
"dependencies",
"=",
"(",
")",
")",
":",
"from",
"mot",
".",
"lib",
".",
"cl_function",
"import",
"SimpleCLFunction",
"def",
"separate_cl_functions",
"(",
"input_str",
")",
":",
"\"\"\"Separate all the OpenCL function... | Parse the given OpenCL string to a single SimpleCLFunction.
If the string contains more than one function, we will return only the last, with all the other added as a
dependency.
Args:
cl_code (str): the input string containing one or more functions.
dependencies (Iterable[CLCodeObject]): ... | [
"Parse",
"the",
"given",
"OpenCL",
"string",
"to",
"a",
"single",
"SimpleCLFunction",
"."
] | train | https://github.com/cbclab/MOT/blob/fb3243b65025705842e82704705c00902f9a35af/mot/lib/utils.py#L546-L600 |
cbclab/MOT | mot/lib/utils.py | split_cl_function | def split_cl_function(cl_str):
"""Split an CL function into a return type, function name, parameters list and the body.
Args:
cl_str (str): the CL code to parse and plit into components
Returns:
tuple: string elements for the return type, function name, parameter list and the body
"""
... | python | def split_cl_function(cl_str):
"""Split an CL function into a return type, function name, parameters list and the body.
Args:
cl_str (str): the CL code to parse and plit into components
Returns:
tuple: string elements for the return type, function name, parameter list and the body
"""
... | [
"def",
"split_cl_function",
"(",
"cl_str",
")",
":",
"class",
"Semantics",
":",
"def",
"__init__",
"(",
"self",
")",
":",
"self",
".",
"_return_type",
"=",
"''",
"self",
".",
"_function_name",
"=",
"''",
"self",
".",
"_parameter_list",
"=",
"[",
"]",
"se... | Split an CL function into a return type, function name, parameters list and the body.
Args:
cl_str (str): the CL code to parse and plit into components
Returns:
tuple: string elements for the return type, function name, parameter list and the body | [
"Split",
"an",
"CL",
"function",
"into",
"a",
"return",
"type",
"function",
"name",
"parameters",
"list",
"and",
"the",
"body",
"."
] | train | https://github.com/cbclab/MOT/blob/fb3243b65025705842e82704705c00902f9a35af/mot/lib/utils.py#L603-L653 |
ksbg/sparklanes | sparklanes/_framework/log.py | make_default_logger | def make_default_logger(name=INTERNAL_LOGGER_NAME, level=logging.INFO,
fmt='%(asctime)s - %(name)s - %(levelname)s - %(message)s'):
"""Create a logger with the default configuration"""
logger = logging.getLogger(name)
logger.setLevel(level)
if not logger.handlers:
handler... | python | def make_default_logger(name=INTERNAL_LOGGER_NAME, level=logging.INFO,
fmt='%(asctime)s - %(name)s - %(levelname)s - %(message)s'):
"""Create a logger with the default configuration"""
logger = logging.getLogger(name)
logger.setLevel(level)
if not logger.handlers:
handler... | [
"def",
"make_default_logger",
"(",
"name",
"=",
"INTERNAL_LOGGER_NAME",
",",
"level",
"=",
"logging",
".",
"INFO",
",",
"fmt",
"=",
"'%(asctime)s - %(name)s - %(levelname)s - %(message)s'",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"name",
")",
"l... | Create a logger with the default configuration | [
"Create",
"a",
"logger",
"with",
"the",
"default",
"configuration"
] | train | https://github.com/ksbg/sparklanes/blob/62e70892e6ae025be2f4c419f4afc34714d6884c/sparklanes/_framework/log.py#L8-L20 |
cbclab/MOT | mot/lib/cl_environments.py | CLEnvironment.is_gpu | def is_gpu(self):
"""Check if the device associated with this environment is a GPU.
Returns:
boolean: True if the device is an GPU, false otherwise.
"""
return self._device.get_info(cl.device_info.TYPE) == cl.device_type.GPU | python | def is_gpu(self):
"""Check if the device associated with this environment is a GPU.
Returns:
boolean: True if the device is an GPU, false otherwise.
"""
return self._device.get_info(cl.device_info.TYPE) == cl.device_type.GPU | [
"def",
"is_gpu",
"(",
"self",
")",
":",
"return",
"self",
".",
"_device",
".",
"get_info",
"(",
"cl",
".",
"device_info",
".",
"TYPE",
")",
"==",
"cl",
".",
"device_type",
".",
"GPU"
] | Check if the device associated with this environment is a GPU.
Returns:
boolean: True if the device is an GPU, false otherwise. | [
"Check",
"if",
"the",
"device",
"associated",
"with",
"this",
"environment",
"is",
"a",
"GPU",
"."
] | train | https://github.com/cbclab/MOT/blob/fb3243b65025705842e82704705c00902f9a35af/mot/lib/cl_environments.py#L79-L85 |
cbclab/MOT | mot/lib/cl_environments.py | CLEnvironment.is_cpu | def is_cpu(self):
"""Check if the device associated with this environment is a CPU.
Returns:
boolean: True if the device is an CPU, false otherwise.
"""
return self._device.get_info(cl.device_info.TYPE) == cl.device_type.CPU | python | def is_cpu(self):
"""Check if the device associated with this environment is a CPU.
Returns:
boolean: True if the device is an CPU, false otherwise.
"""
return self._device.get_info(cl.device_info.TYPE) == cl.device_type.CPU | [
"def",
"is_cpu",
"(",
"self",
")",
":",
"return",
"self",
".",
"_device",
".",
"get_info",
"(",
"cl",
".",
"device_info",
".",
"TYPE",
")",
"==",
"cl",
".",
"device_type",
".",
"CPU"
] | Check if the device associated with this environment is a CPU.
Returns:
boolean: True if the device is an CPU, false otherwise. | [
"Check",
"if",
"the",
"device",
"associated",
"with",
"this",
"environment",
"is",
"a",
"CPU",
"."
] | train | https://github.com/cbclab/MOT/blob/fb3243b65025705842e82704705c00902f9a35af/mot/lib/cl_environments.py#L88-L94 |
cbclab/MOT | mot/lib/cl_environments.py | CLEnvironmentFactory.single_device | def single_device(cl_device_type='GPU', platform=None, fallback_to_any_device_type=False):
"""Get a list containing a single device environment, for a device of the given type on the given platform.
This will only fetch devices that support double (possibly only double with a pragma
defined, bu... | python | def single_device(cl_device_type='GPU', platform=None, fallback_to_any_device_type=False):
"""Get a list containing a single device environment, for a device of the given type on the given platform.
This will only fetch devices that support double (possibly only double with a pragma
defined, bu... | [
"def",
"single_device",
"(",
"cl_device_type",
"=",
"'GPU'",
",",
"platform",
"=",
"None",
",",
"fallback_to_any_device_type",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"cl_device_type",
",",
"str",
")",
":",
"cl_device_type",
"=",
"device_type_from_string"... | Get a list containing a single device environment, for a device of the given type on the given platform.
This will only fetch devices that support double (possibly only double with a pragma
defined, but still, it should support double).
Args:
cl_device_type (cl.device_type.* or str... | [
"Get",
"a",
"list",
"containing",
"a",
"single",
"device",
"environment",
"for",
"a",
"device",
"of",
"the",
"given",
"type",
"on",
"the",
"given",
"platform",
"."
] | train | https://github.com/cbclab/MOT/blob/fb3243b65025705842e82704705c00902f9a35af/mot/lib/cl_environments.py#L164-L207 |
cbclab/MOT | mot/lib/cl_environments.py | CLEnvironmentFactory.all_devices | def all_devices(cl_device_type=None, platform=None):
"""Get multiple device environments, optionally only of the indicated type.
This will only fetch devices that support double point precision.
Args:
cl_device_type (cl.device_type.* or string): The type of the device we want,
... | python | def all_devices(cl_device_type=None, platform=None):
"""Get multiple device environments, optionally only of the indicated type.
This will only fetch devices that support double point precision.
Args:
cl_device_type (cl.device_type.* or string): The type of the device we want,
... | [
"def",
"all_devices",
"(",
"cl_device_type",
"=",
"None",
",",
"platform",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"cl_device_type",
",",
"str",
")",
":",
"cl_device_type",
"=",
"device_type_from_string",
"(",
"cl_device_type",
")",
"runtime_list",
"=",
... | Get multiple device environments, optionally only of the indicated type.
This will only fetch devices that support double point precision.
Args:
cl_device_type (cl.device_type.* or string): The type of the device we want,
can be a opencl device type or a string matching 'GP... | [
"Get",
"multiple",
"device",
"environments",
"optionally",
"only",
"of",
"the",
"indicated",
"type",
"."
] | train | https://github.com/cbclab/MOT/blob/fb3243b65025705842e82704705c00902f9a35af/mot/lib/cl_environments.py#L210-L244 |
cbclab/MOT | mot/lib/cl_environments.py | CLEnvironmentFactory.smart_device_selection | def smart_device_selection(preferred_device_type=None):
"""Get a list of device environments that is suitable for use in MOT.
Basically this gets the total list of devices using all_devices() and applies a filter on it.
This filter does the following:
1) if the 'AMD Accelerated Par... | python | def smart_device_selection(preferred_device_type=None):
"""Get a list of device environments that is suitable for use in MOT.
Basically this gets the total list of devices using all_devices() and applies a filter on it.
This filter does the following:
1) if the 'AMD Accelerated Par... | [
"def",
"smart_device_selection",
"(",
"preferred_device_type",
"=",
"None",
")",
":",
"cl_environments",
"=",
"CLEnvironmentFactory",
".",
"all_devices",
"(",
"cl_device_type",
"=",
"preferred_device_type",
")",
"platform_names",
"=",
"[",
"env",
".",
"platform",
".",... | Get a list of device environments that is suitable for use in MOT.
Basically this gets the total list of devices using all_devices() and applies a filter on it.
This filter does the following:
1) if the 'AMD Accelerated Parallel Processing' is available remove all environments using the 'C... | [
"Get",
"a",
"list",
"of",
"device",
"environments",
"that",
"is",
"suitable",
"for",
"use",
"in",
"MOT",
"."
] | train | https://github.com/cbclab/MOT/blob/fb3243b65025705842e82704705c00902f9a35af/mot/lib/cl_environments.py#L247-L275 |
cbclab/MOT | mot/mcmc_diagnostics.py | multivariate_ess | def multivariate_ess(samples, batch_size_generator=None):
r"""Estimate the multivariate Effective Sample Size for the samples of every problem.
This essentially applies :func:`estimate_multivariate_ess` to every problem.
Args:
samples (ndarray, dict or generator): either a matrix of shape (d, p, n... | python | def multivariate_ess(samples, batch_size_generator=None):
r"""Estimate the multivariate Effective Sample Size for the samples of every problem.
This essentially applies :func:`estimate_multivariate_ess` to every problem.
Args:
samples (ndarray, dict or generator): either a matrix of shape (d, p, n... | [
"def",
"multivariate_ess",
"(",
"samples",
",",
"batch_size_generator",
"=",
"None",
")",
":",
"samples_generator",
"=",
"_get_sample_generator",
"(",
"samples",
")",
"return",
"np",
".",
"array",
"(",
"multiprocess_mapping",
"(",
"_MultivariateESSMultiProcessing",
"(... | r"""Estimate the multivariate Effective Sample Size for the samples of every problem.
This essentially applies :func:`estimate_multivariate_ess` to every problem.
Args:
samples (ndarray, dict or generator): either a matrix of shape (d, p, n) with d problems, p parameters and
n samples, or ... | [
"r",
"Estimate",
"the",
"multivariate",
"Effective",
"Sample",
"Size",
"for",
"the",
"samples",
"of",
"every",
"problem",
"."
] | train | https://github.com/cbclab/MOT/blob/fb3243b65025705842e82704705c00902f9a35af/mot/mcmc_diagnostics.py#L21-L37 |
cbclab/MOT | mot/mcmc_diagnostics.py | univariate_ess | def univariate_ess(samples, method='standard_error', **kwargs):
r"""Estimate the univariate Effective Sample Size for the samples of every problem.
This computes the ESS using:
.. math::
ESS(X) = n * \frac{\lambda^{2}}{\sigma^{2}}
Where :math:`\lambda` is the standard deviation o... | python | def univariate_ess(samples, method='standard_error', **kwargs):
r"""Estimate the univariate Effective Sample Size for the samples of every problem.
This computes the ESS using:
.. math::
ESS(X) = n * \frac{\lambda^{2}}{\sigma^{2}}
Where :math:`\lambda` is the standard deviation o... | [
"def",
"univariate_ess",
"(",
"samples",
",",
"method",
"=",
"'standard_error'",
",",
"*",
"*",
"kwargs",
")",
":",
"samples_generator",
"=",
"_get_sample_generator",
"(",
"samples",
")",
"return",
"np",
".",
"array",
"(",
"multiprocess_mapping",
"(",
"_Univaria... | r"""Estimate the univariate Effective Sample Size for the samples of every problem.
This computes the ESS using:
.. math::
ESS(X) = n * \frac{\lambda^{2}}{\sigma^{2}}
Where :math:`\lambda` is the standard deviation of the chain and :math:`\sigma` is estimated using the
monte ... | [
"r",
"Estimate",
"the",
"univariate",
"Effective",
"Sample",
"Size",
"for",
"the",
"samples",
"of",
"every",
"problem",
"."
] | train | https://github.com/cbclab/MOT/blob/fb3243b65025705842e82704705c00902f9a35af/mot/mcmc_diagnostics.py#L50-L82 |
cbclab/MOT | mot/mcmc_diagnostics.py | _get_sample_generator | def _get_sample_generator(samples):
"""Get a sample generator from the given polymorphic input.
Args:
samples (ndarray, dict or generator): either an matrix of shape (d, p, n) with d problems, p parameters and
n samples, or a dictionary with for every parameter a matrix with shape (d, n) or... | python | def _get_sample_generator(samples):
"""Get a sample generator from the given polymorphic input.
Args:
samples (ndarray, dict or generator): either an matrix of shape (d, p, n) with d problems, p parameters and
n samples, or a dictionary with for every parameter a matrix with shape (d, n) or... | [
"def",
"_get_sample_generator",
"(",
"samples",
")",
":",
"if",
"isinstance",
"(",
"samples",
",",
"Mapping",
")",
":",
"def",
"samples_generator",
"(",
")",
":",
"for",
"ind",
"in",
"range",
"(",
"samples",
"[",
"list",
"(",
"samples",
".",
"keys",
"(",... | Get a sample generator from the given polymorphic input.
Args:
samples (ndarray, dict or generator): either an matrix of shape (d, p, n) with d problems, p parameters and
n samples, or a dictionary with for every parameter a matrix with shape (d, n) or, finally,
a generator function... | [
"Get",
"a",
"sample",
"generator",
"from",
"the",
"given",
"polymorphic",
"input",
"."
] | train | https://github.com/cbclab/MOT/blob/fb3243b65025705842e82704705c00902f9a35af/mot/mcmc_diagnostics.py#L105-L126 |
cbclab/MOT | mot/mcmc_diagnostics.py | get_auto_correlation | def get_auto_correlation(chain, lag):
r"""Estimates the auto correlation for the given chain (1d vector) with the given lag.
Given a lag :math:`k`, the auto correlation coefficient :math:`\rho_{k}` is estimated as:
.. math::
\hat{\rho}_{k} = \frac{E[(X_{t} - \mu)(X_{t + k} - \mu)]}{\sigma^{2}}
... | python | def get_auto_correlation(chain, lag):
r"""Estimates the auto correlation for the given chain (1d vector) with the given lag.
Given a lag :math:`k`, the auto correlation coefficient :math:`\rho_{k}` is estimated as:
.. math::
\hat{\rho}_{k} = \frac{E[(X_{t} - \mu)(X_{t + k} - \mu)]}{\sigma^{2}}
... | [
"def",
"get_auto_correlation",
"(",
"chain",
",",
"lag",
")",
":",
"normalized_chain",
"=",
"chain",
"-",
"np",
".",
"mean",
"(",
"chain",
",",
"dtype",
"=",
"np",
".",
"float64",
")",
"lagged_mean",
"=",
"np",
".",
"mean",
"(",
"normalized_chain",
"[",
... | r"""Estimates the auto correlation for the given chain (1d vector) with the given lag.
Given a lag :math:`k`, the auto correlation coefficient :math:`\rho_{k}` is estimated as:
.. math::
\hat{\rho}_{k} = \frac{E[(X_{t} - \mu)(X_{t + k} - \mu)]}{\sigma^{2}}
Please note that this equation only wor... | [
"r",
"Estimates",
"the",
"auto",
"correlation",
"for",
"the",
"given",
"chain",
"(",
"1d",
"vector",
")",
"with",
"the",
"given",
"lag",
"."
] | train | https://github.com/cbclab/MOT/blob/fb3243b65025705842e82704705c00902f9a35af/mot/mcmc_diagnostics.py#L129-L150 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.