repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1
value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 3
values | summary stringlengths 4 350 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
carta/ldap_tools | src/ldap_tools/user.py | API.__ldap_attr | def __ldap_attr(self, fname, lname, type, group,
group_api): # pragma: no cover
"""User LDAP attributes."""
return {
'uid':
str(self.username).encode(),
'cn':
' '.join([fname, lname]).encode(),
'sn':
str(lname).... | python | def __ldap_attr(self, fname, lname, type, group,
group_api): # pragma: no cover
"""User LDAP attributes."""
return {
'uid':
str(self.username).encode(),
'cn':
' '.join([fname, lname]).encode(),
'sn':
str(lname).... | [
"def",
"__ldap_attr",
"(",
"self",
",",
"fname",
",",
"lname",
",",
"type",
",",
"group",
",",
"group_api",
")",
":",
"# pragma: no cover",
"return",
"{",
"'uid'",
":",
"str",
"(",
"self",
".",
"username",
")",
".",
"encode",
"(",
")",
",",
"'cn'",
"... | User LDAP attributes. | [
"User",
"LDAP",
"attributes",
"."
] | 7c039304a5abaf836c7afc35cf068b4471306264 | https://github.com/carta/ldap_tools/blob/7c039304a5abaf836c7afc35cf068b4471306264/src/ldap_tools/user.py#L93-L117 | train | User LDAP attributes. |
carta/ldap_tools | src/ldap_tools/user.py | API.__create_password | def __create_password(): # pragma: no cover
"""Create a password for the user."""
salt = b64encode(API.__generate_string(32))
password = b64encode(API.__generate_string(64))
return b64encode(sha1(password + salt).digest()) | python | def __create_password(): # pragma: no cover
"""Create a password for the user."""
salt = b64encode(API.__generate_string(32))
password = b64encode(API.__generate_string(64))
return b64encode(sha1(password + salt).digest()) | [
"def",
"__create_password",
"(",
")",
":",
"# pragma: no cover",
"salt",
"=",
"b64encode",
"(",
"API",
".",
"__generate_string",
"(",
"32",
")",
")",
"password",
"=",
"b64encode",
"(",
"API",
".",
"__generate_string",
"(",
"64",
")",
")",
"return",
"b64encod... | Create a password for the user. | [
"Create",
"a",
"password",
"for",
"the",
"user",
"."
] | 7c039304a5abaf836c7afc35cf068b4471306264 | https://github.com/carta/ldap_tools/blob/7c039304a5abaf836c7afc35cf068b4471306264/src/ldap_tools/user.py#L135-L139 | train | Create a password for the user. |
carta/ldap_tools | src/ldap_tools/user.py | API.__generate_string | def __generate_string(length): # pragma: no cover
"""Generate a string for password creation."""
return ''.join(
SystemRandom().choice(string.ascii_letters + string.digits)
for x in range(length)).encode() | python | def __generate_string(length): # pragma: no cover
"""Generate a string for password creation."""
return ''.join(
SystemRandom().choice(string.ascii_letters + string.digits)
for x in range(length)).encode() | [
"def",
"__generate_string",
"(",
"length",
")",
":",
"# pragma: no cover",
"return",
"''",
".",
"join",
"(",
"SystemRandom",
"(",
")",
".",
"choice",
"(",
"string",
".",
"ascii_letters",
"+",
"string",
".",
"digits",
")",
"for",
"x",
"in",
"range",
"(",
... | Generate a string for password creation. | [
"Generate",
"a",
"string",
"for",
"password",
"creation",
"."
] | 7c039304a5abaf836c7afc35cf068b4471306264 | https://github.com/carta/ldap_tools/blob/7c039304a5abaf836c7afc35cf068b4471306264/src/ldap_tools/user.py#L141-L145 | train | Generate a string for password creation. |
carta/ldap_tools | src/ldap_tools/user.py | CLI.create | def create(config, name, group, type):
"""Create an LDAP user."""
if type not in ('user', 'service'):
raise click.BadOptionUsage("--type must be 'user' or 'service'")
client = Client()
client.prepare_connection()
user_api = API(client)
group_api = GroupApi(cli... | python | def create(config, name, group, type):
"""Create an LDAP user."""
if type not in ('user', 'service'):
raise click.BadOptionUsage("--type must be 'user' or 'service'")
client = Client()
client.prepare_connection()
user_api = API(client)
group_api = GroupApi(cli... | [
"def",
"create",
"(",
"config",
",",
"name",
",",
"group",
",",
"type",
")",
":",
"if",
"type",
"not",
"in",
"(",
"'user'",
",",
"'service'",
")",
":",
"raise",
"click",
".",
"BadOptionUsage",
"(",
"\"--type must be 'user' or 'service'\"",
")",
"client",
"... | Create an LDAP user. | [
"Create",
"an",
"LDAP",
"user",
"."
] | 7c039304a5abaf836c7afc35cf068b4471306264 | https://github.com/carta/ldap_tools/blob/7c039304a5abaf836c7afc35cf068b4471306264/src/ldap_tools/user.py#L184-L192 | train | Create an LDAP user. |
carta/ldap_tools | src/ldap_tools/user.py | CLI.delete | def delete(config, username, type):
"""Delete an LDAP user."""
client = Client()
client.prepare_connection()
user_api = API(client)
user_api.delete(username, type) | python | def delete(config, username, type):
"""Delete an LDAP user."""
client = Client()
client.prepare_connection()
user_api = API(client)
user_api.delete(username, type) | [
"def",
"delete",
"(",
"config",
",",
"username",
",",
"type",
")",
":",
"client",
"=",
"Client",
"(",
")",
"client",
".",
"prepare_connection",
"(",
")",
"user_api",
"=",
"API",
"(",
"client",
")",
"user_api",
".",
"delete",
"(",
"username",
",",
"type... | Delete an LDAP user. | [
"Delete",
"an",
"LDAP",
"user",
"."
] | 7c039304a5abaf836c7afc35cf068b4471306264 | https://github.com/carta/ldap_tools/blob/7c039304a5abaf836c7afc35cf068b4471306264/src/ldap_tools/user.py#L204-L209 | train | Delete an LDAP user. |
carta/ldap_tools | src/ldap_tools/user.py | CLI.index | def index(config):
"""Display user info in LDIF format."""
client = Client()
client.prepare_connection()
user_api = API(client)
CLI.show_user(user_api.index()) | python | def index(config):
"""Display user info in LDIF format."""
client = Client()
client.prepare_connection()
user_api = API(client)
CLI.show_user(user_api.index()) | [
"def",
"index",
"(",
"config",
")",
":",
"client",
"=",
"Client",
"(",
")",
"client",
".",
"prepare_connection",
"(",
")",
"user_api",
"=",
"API",
"(",
"client",
")",
"CLI",
".",
"show_user",
"(",
"user_api",
".",
"index",
"(",
")",
")"
] | Display user info in LDIF format. | [
"Display",
"user",
"info",
"in",
"LDIF",
"format",
"."
] | 7c039304a5abaf836c7afc35cf068b4471306264 | https://github.com/carta/ldap_tools/blob/7c039304a5abaf836c7afc35cf068b4471306264/src/ldap_tools/user.py#L213-L218 | train | Display user info in LDIF format. |
carta/ldap_tools | src/ldap_tools/user.py | CLI.show | def show(config, username):
"""Display a specific user."""
client = Client()
client.prepare_connection()
user_api = API(client)
CLI.show_user(user_api.show(username)) | python | def show(config, username):
"""Display a specific user."""
client = Client()
client.prepare_connection()
user_api = API(client)
CLI.show_user(user_api.show(username)) | [
"def",
"show",
"(",
"config",
",",
"username",
")",
":",
"client",
"=",
"Client",
"(",
")",
"client",
".",
"prepare_connection",
"(",
")",
"user_api",
"=",
"API",
"(",
"client",
")",
"CLI",
".",
"show_user",
"(",
"user_api",
".",
"show",
"(",
"username... | Display a specific user. | [
"Display",
"a",
"specific",
"user",
"."
] | 7c039304a5abaf836c7afc35cf068b4471306264 | https://github.com/carta/ldap_tools/blob/7c039304a5abaf836c7afc35cf068b4471306264/src/ldap_tools/user.py#L224-L229 | train | Display a specific user. |
ludeeus/GHLocalApi | ghlocalapi/bluetooth.py | Bluetooth.set_discovery_enabled | async def set_discovery_enabled(self):
"""Enable bluetooth discoverablility."""
endpoint = '/setup/bluetooth/discovery'
data = {"enable_discovery": True}
url = API.format(ip=self._ipaddress, endpoint=endpoint)
try:
async with async_timeout.timeout(5, loop=self._loop):... | python | async def set_discovery_enabled(self):
"""Enable bluetooth discoverablility."""
endpoint = '/setup/bluetooth/discovery'
data = {"enable_discovery": True}
url = API.format(ip=self._ipaddress, endpoint=endpoint)
try:
async with async_timeout.timeout(5, loop=self._loop):... | [
"async",
"def",
"set_discovery_enabled",
"(",
"self",
")",
":",
"endpoint",
"=",
"'/setup/bluetooth/discovery'",
"data",
"=",
"{",
"\"enable_discovery\"",
":",
"True",
"}",
"url",
"=",
"API",
".",
"format",
"(",
"ip",
"=",
"self",
".",
"_ipaddress",
",",
"en... | Enable bluetooth discoverablility. | [
"Enable",
"bluetooth",
"discoverablility",
"."
] | 93abdee299c4a4b65aa9dd03c77ec34e174e3c56 | https://github.com/ludeeus/GHLocalApi/blob/93abdee299c4a4b65aa9dd03c77ec34e174e3c56/ghlocalapi/bluetooth.py#L43-L56 | train | Enable bluetooth discoverablility. |
ludeeus/GHLocalApi | ghlocalapi/bluetooth.py | Bluetooth.get_scan_result | async def get_scan_result(self):
"""Scan for bluetooth devices."""
endpoint = '/setup/bluetooth/scan_results'
url = API.format(ip=self._ipaddress, endpoint=endpoint)
try:
async with async_timeout.timeout(5, loop=self._loop):
response = await self._session.get(... | python | async def get_scan_result(self):
"""Scan for bluetooth devices."""
endpoint = '/setup/bluetooth/scan_results'
url = API.format(ip=self._ipaddress, endpoint=endpoint)
try:
async with async_timeout.timeout(5, loop=self._loop):
response = await self._session.get(... | [
"async",
"def",
"get_scan_result",
"(",
"self",
")",
":",
"endpoint",
"=",
"'/setup/bluetooth/scan_results'",
"url",
"=",
"API",
".",
"format",
"(",
"ip",
"=",
"self",
".",
"_ipaddress",
",",
"endpoint",
"=",
"endpoint",
")",
"try",
":",
"async",
"with",
"... | Scan for bluetooth devices. | [
"Scan",
"for",
"bluetooth",
"devices",
"."
] | 93abdee299c4a4b65aa9dd03c77ec34e174e3c56 | https://github.com/ludeeus/GHLocalApi/blob/93abdee299c4a4b65aa9dd03c77ec34e174e3c56/ghlocalapi/bluetooth.py#L90-L101 | train | Get bluetooth devices. |
ludeeus/GHLocalApi | ghlocalapi/bluetooth.py | Bluetooth.scan_for_devices_multi_run | async def scan_for_devices_multi_run(self, runs=2):
"""Scan for devices multiple times."""
run = 1
master = {}
while run < runs + 1:
await self.scan_for_devices()
await self.get_scan_result()
if master is None:
for device in self._devic... | python | async def scan_for_devices_multi_run(self, runs=2):
"""Scan for devices multiple times."""
run = 1
master = {}
while run < runs + 1:
await self.scan_for_devices()
await self.get_scan_result()
if master is None:
for device in self._devic... | [
"async",
"def",
"scan_for_devices_multi_run",
"(",
"self",
",",
"runs",
"=",
"2",
")",
":",
"run",
"=",
"1",
"master",
"=",
"{",
"}",
"while",
"run",
"<",
"runs",
"+",
"1",
":",
"await",
"self",
".",
"scan_for_devices",
"(",
")",
"await",
"self",
"."... | Scan for devices multiple times. | [
"Scan",
"for",
"devices",
"multiple",
"times",
"."
] | 93abdee299c4a4b65aa9dd03c77ec34e174e3c56 | https://github.com/ludeeus/GHLocalApi/blob/93abdee299c4a4b65aa9dd03c77ec34e174e3c56/ghlocalapi/bluetooth.py#L103-L137 | train | Scan for devices multiple times. |
coopernurse/barrister | barrister/runtime.py | contract_from_file | def contract_from_file(fname):
"""
Loads a Barrister IDL JSON from the given file and returns a Contract class
:Parameters:
fname
Filename containing Barrister IDL JSON to load
"""
f = open(fname)
j = f.read()
f.close()
return Contract(json.loads(j)) | python | def contract_from_file(fname):
"""
Loads a Barrister IDL JSON from the given file and returns a Contract class
:Parameters:
fname
Filename containing Barrister IDL JSON to load
"""
f = open(fname)
j = f.read()
f.close()
return Contract(json.loads(j)) | [
"def",
"contract_from_file",
"(",
"fname",
")",
":",
"f",
"=",
"open",
"(",
"fname",
")",
"j",
"=",
"f",
".",
"read",
"(",
")",
"f",
".",
"close",
"(",
")",
"return",
"Contract",
"(",
"json",
".",
"loads",
"(",
"j",
")",
")"
] | Loads a Barrister IDL JSON from the given file and returns a Contract class
:Parameters:
fname
Filename containing Barrister IDL JSON to load | [
"Loads",
"a",
"Barrister",
"IDL",
"JSON",
"from",
"the",
"given",
"file",
"and",
"returns",
"a",
"Contract",
"class"
] | 0471b1d98d3327ba381684db496ec94c79c20848 | https://github.com/coopernurse/barrister/blob/0471b1d98d3327ba381684db496ec94c79c20848/barrister/runtime.py#L27-L38 | train | Loads a Barrister IDL JSON file and returns a Contract class |
coopernurse/barrister | barrister/runtime.py | unpack_method | def unpack_method(method):
"""
Given a JSON-RPC method in: [interface].[function] notation, returns a tuple of the interface
name and function.
For example, unpack_method("MyService.LoadUser") would return: ("MyService", "LoadUser")
:Parameters:
method
String method name
"""
... | python | def unpack_method(method):
"""
Given a JSON-RPC method in: [interface].[function] notation, returns a tuple of the interface
name and function.
For example, unpack_method("MyService.LoadUser") would return: ("MyService", "LoadUser")
:Parameters:
method
String method name
"""
... | [
"def",
"unpack_method",
"(",
"method",
")",
":",
"pos",
"=",
"method",
".",
"find",
"(",
"\".\"",
")",
"if",
"pos",
"==",
"-",
"1",
":",
"raise",
"RpcException",
"(",
"ERR_METHOD_NOT_FOUND",
",",
"\"Method not found: %s\"",
"%",
"method",
")",
"iface_name",
... | Given a JSON-RPC method in: [interface].[function] notation, returns a tuple of the interface
name and function.
For example, unpack_method("MyService.LoadUser") would return: ("MyService", "LoadUser")
:Parameters:
method
String method name | [
"Given",
"a",
"JSON",
"-",
"RPC",
"method",
"in",
":",
"[",
"interface",
"]",
".",
"[",
"function",
"]",
"notation",
"returns",
"a",
"tuple",
"of",
"the",
"interface",
"name",
"and",
"function",
"."
] | 0471b1d98d3327ba381684db496ec94c79c20848 | https://github.com/coopernurse/barrister/blob/0471b1d98d3327ba381684db496ec94c79c20848/barrister/runtime.py#L40-L57 | train | Given a JSON - RPC method in the interface. [ function notation returns a tuple of the interface name and function name. |
coopernurse/barrister | barrister/runtime.py | err_response | def err_response(reqid, code, msg, data=None):
"""
Formats a JSON-RPC error as a dict with keys: 'jsonrpc', 'id', 'error'
"""
err = { "code": code, "message": msg }
if data:
err["data"] = data
return { "jsonrpc": "2.0", "id": reqid, "error": err } | python | def err_response(reqid, code, msg, data=None):
"""
Formats a JSON-RPC error as a dict with keys: 'jsonrpc', 'id', 'error'
"""
err = { "code": code, "message": msg }
if data:
err["data"] = data
return { "jsonrpc": "2.0", "id": reqid, "error": err } | [
"def",
"err_response",
"(",
"reqid",
",",
"code",
",",
"msg",
",",
"data",
"=",
"None",
")",
":",
"err",
"=",
"{",
"\"code\"",
":",
"code",
",",
"\"message\"",
":",
"msg",
"}",
"if",
"data",
":",
"err",
"[",
"\"data\"",
"]",
"=",
"data",
"return",
... | Formats a JSON-RPC error as a dict with keys: 'jsonrpc', 'id', 'error' | [
"Formats",
"a",
"JSON",
"-",
"RPC",
"error",
"as",
"a",
"dict",
"with",
"keys",
":",
"jsonrpc",
"id",
"error"
] | 0471b1d98d3327ba381684db496ec94c79c20848 | https://github.com/coopernurse/barrister/blob/0471b1d98d3327ba381684db496ec94c79c20848/barrister/runtime.py#L72-L79 | train | Formats a JSON - RPC error as a dict with keys : jsonrpc id error message data |
coopernurse/barrister | barrister/runtime.py | safe_get | def safe_get(d, key, def_val=None):
"""
Helper function to fetch value from a dictionary
* `d` - Dictionary to fetch value from
* `key` - Key to lookup in dictionary
* `def_val` - Default value to return if dict does not have a member with key
"""
if d.has_key(key):
return d[key... | python | def safe_get(d, key, def_val=None):
"""
Helper function to fetch value from a dictionary
* `d` - Dictionary to fetch value from
* `key` - Key to lookup in dictionary
* `def_val` - Default value to return if dict does not have a member with key
"""
if d.has_key(key):
return d[key... | [
"def",
"safe_get",
"(",
"d",
",",
"key",
",",
"def_val",
"=",
"None",
")",
":",
"if",
"d",
".",
"has_key",
"(",
"key",
")",
":",
"return",
"d",
"[",
"key",
"]",
"else",
":",
"return",
"def_val"
] | Helper function to fetch value from a dictionary
* `d` - Dictionary to fetch value from
* `key` - Key to lookup in dictionary
* `def_val` - Default value to return if dict does not have a member with key | [
"Helper",
"function",
"to",
"fetch",
"value",
"from",
"a",
"dictionary",
"*",
"d",
"-",
"Dictionary",
"to",
"fetch",
"value",
"from",
"*",
"key",
"-",
"Key",
"to",
"lookup",
"in",
"dictionary",
"*",
"def_val",
"-",
"Default",
"value",
"to",
"return",
"if... | 0471b1d98d3327ba381684db496ec94c79c20848 | https://github.com/coopernurse/barrister/blob/0471b1d98d3327ba381684db496ec94c79c20848/barrister/runtime.py#L81-L92 | train | Helper function to fetch a value from a dictionary |
coopernurse/barrister | barrister/runtime.py | RequestContext.get_prop | def get_prop(self, key, default_val=None):
"""
Returns a property set on the context.
:Parameters:
key
String key to lookup in the context props dict
default_val
Value to return if key is not set on the context props
"""
if self.props.... | python | def get_prop(self, key, default_val=None):
"""
Returns a property set on the context.
:Parameters:
key
String key to lookup in the context props dict
default_val
Value to return if key is not set on the context props
"""
if self.props.... | [
"def",
"get_prop",
"(",
"self",
",",
"key",
",",
"default_val",
"=",
"None",
")",
":",
"if",
"self",
".",
"props",
".",
"has_key",
"(",
"key",
")",
":",
"return",
"self",
".",
"props",
"[",
"key",
"]",
"else",
":",
"return",
"default_val"
] | Returns a property set on the context.
:Parameters:
key
String key to lookup in the context props dict
default_val
Value to return if key is not set on the context props | [
"Returns",
"a",
"property",
"set",
"on",
"the",
"context",
"."
] | 0471b1d98d3327ba381684db496ec94c79c20848 | https://github.com/coopernurse/barrister/blob/0471b1d98d3327ba381684db496ec94c79c20848/barrister/runtime.py#L146-L159 | train | Returns a property set on the context. |
coopernurse/barrister | barrister/runtime.py | RequestContext.set_error | def set_error(self, code, msg, data=None):
"""
Set an error on this request, which will prevent request execution.
Should only be called from "pre" hook methods. If called from a post hook, this
operation will be ignored.
:Parameters:
code
Integer error co... | python | def set_error(self, code, msg, data=None):
"""
Set an error on this request, which will prevent request execution.
Should only be called from "pre" hook methods. If called from a post hook, this
operation will be ignored.
:Parameters:
code
Integer error co... | [
"def",
"set_error",
"(",
"self",
",",
"code",
",",
"msg",
",",
"data",
"=",
"None",
")",
":",
"self",
".",
"error",
"=",
"err_response",
"(",
"self",
".",
"request",
"[",
"\"id\"",
"]",
",",
"code",
",",
"msg",
",",
"data",
")"
] | Set an error on this request, which will prevent request execution.
Should only be called from "pre" hook methods. If called from a post hook, this
operation will be ignored.
:Parameters:
code
Integer error code
msg
String description of the error
... | [
"Set",
"an",
"error",
"on",
"this",
"request",
"which",
"will",
"prevent",
"request",
"execution",
".",
"Should",
"only",
"be",
"called",
"from",
"pre",
"hook",
"methods",
".",
"If",
"called",
"from",
"a",
"post",
"hook",
"this",
"operation",
"will",
"be",... | 0471b1d98d3327ba381684db496ec94c79c20848 | https://github.com/coopernurse/barrister/blob/0471b1d98d3327ba381684db496ec94c79c20848/barrister/runtime.py#L161-L176 | train | Set an error on this request. |
coopernurse/barrister | barrister/runtime.py | Server.add_handler | def add_handler(self, iface_name, handler):
"""
Associates the given handler with the interface name. If the interface does not exist in
the Contract, an RpcException is raised.
:Parameters:
iface_name
Name of interface that this handler implements
handl... | python | def add_handler(self, iface_name, handler):
"""
Associates the given handler with the interface name. If the interface does not exist in
the Contract, an RpcException is raised.
:Parameters:
iface_name
Name of interface that this handler implements
handl... | [
"def",
"add_handler",
"(",
"self",
",",
"iface_name",
",",
"handler",
")",
":",
"if",
"self",
".",
"contract",
".",
"has_interface",
"(",
"iface_name",
")",
":",
"self",
".",
"handlers",
"[",
"iface_name",
"]",
"=",
"handler",
"else",
":",
"raise",
"RpcE... | Associates the given handler with the interface name. If the interface does not exist in
the Contract, an RpcException is raised.
:Parameters:
iface_name
Name of interface that this handler implements
handler
Instance of a class that implements all functions... | [
"Associates",
"the",
"given",
"handler",
"with",
"the",
"interface",
"name",
".",
"If",
"the",
"interface",
"does",
"not",
"exist",
"in",
"the",
"Contract",
"an",
"RpcException",
"is",
"raised",
"."
] | 0471b1d98d3327ba381684db496ec94c79c20848 | https://github.com/coopernurse/barrister/blob/0471b1d98d3327ba381684db496ec94c79c20848/barrister/runtime.py#L235-L249 | train | Adds the given handler to the set of handlers for the given interface. |
coopernurse/barrister | barrister/runtime.py | Server.set_filters | def set_filters(self, filters):
"""
Sets the filters for the server.
:Parameters:
filters
List of filters to set on this server, or None to remove all filters.
Elements in list should subclass Filter
"""
if filters == None or isinstance(filters,... | python | def set_filters(self, filters):
"""
Sets the filters for the server.
:Parameters:
filters
List of filters to set on this server, or None to remove all filters.
Elements in list should subclass Filter
"""
if filters == None or isinstance(filters,... | [
"def",
"set_filters",
"(",
"self",
",",
"filters",
")",
":",
"if",
"filters",
"==",
"None",
"or",
"isinstance",
"(",
"filters",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"self",
".",
"filters",
"=",
"filters",
"else",
":",
"self",
".",
"filters"... | Sets the filters for the server.
:Parameters:
filters
List of filters to set on this server, or None to remove all filters.
Elements in list should subclass Filter | [
"Sets",
"the",
"filters",
"for",
"the",
"server",
"."
] | 0471b1d98d3327ba381684db496ec94c79c20848 | https://github.com/coopernurse/barrister/blob/0471b1d98d3327ba381684db496ec94c79c20848/barrister/runtime.py#L251-L263 | train | Sets the filters for the server. |
coopernurse/barrister | barrister/runtime.py | Server.call_json | def call_json(self, req_json, props=None):
"""
Deserializes req_json as JSON, invokes self.call(), and serializes result to JSON.
Returns JSON encoded string.
:Parameters:
req_json
JSON-RPC request serialized as JSON string
props
Application d... | python | def call_json(self, req_json, props=None):
"""
Deserializes req_json as JSON, invokes self.call(), and serializes result to JSON.
Returns JSON encoded string.
:Parameters:
req_json
JSON-RPC request serialized as JSON string
props
Application d... | [
"def",
"call_json",
"(",
"self",
",",
"req_json",
",",
"props",
"=",
"None",
")",
":",
"try",
":",
"req",
"=",
"json",
".",
"loads",
"(",
"req_json",
")",
"except",
":",
"msg",
"=",
"\"Unable to parse JSON: %s\"",
"%",
"req_json",
"return",
"json",
".",
... | Deserializes req_json as JSON, invokes self.call(), and serializes result to JSON.
Returns JSON encoded string.
:Parameters:
req_json
JSON-RPC request serialized as JSON string
props
Application defined properties to set on RequestContext for use with filters... | [
"Deserializes",
"req_json",
"as",
"JSON",
"invokes",
"self",
".",
"call",
"()",
"and",
"serializes",
"result",
"to",
"JSON",
".",
"Returns",
"JSON",
"encoded",
"string",
"."
] | 0471b1d98d3327ba381684db496ec94c79c20848 | https://github.com/coopernurse/barrister/blob/0471b1d98d3327ba381684db496ec94c79c20848/barrister/runtime.py#L265-L282 | train | Deserializes req_json as JSON and invokes self. call and serializes result to JSON. |
coopernurse/barrister | barrister/runtime.py | Server.call | def call(self, req, props=None):
"""
Executes a Barrister request and returns a response. If the request is a list, then the
response will also be a list. If the request is an empty list, a RpcException is raised.
:Parameters:
req
The request. Either a list of di... | python | def call(self, req, props=None):
"""
Executes a Barrister request and returns a response. If the request is a list, then the
response will also be a list. If the request is an empty list, a RpcException is raised.
:Parameters:
req
The request. Either a list of di... | [
"def",
"call",
"(",
"self",
",",
"req",
",",
"props",
"=",
"None",
")",
":",
"resp",
"=",
"None",
"if",
"self",
".",
"log",
".",
"isEnabledFor",
"(",
"logging",
".",
"DEBUG",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"\"Request: %s\"",
"%",
... | Executes a Barrister request and returns a response. If the request is a list, then the
response will also be a list. If the request is an empty list, a RpcException is raised.
:Parameters:
req
The request. Either a list of dicts, or a single dict.
props
Ap... | [
"Executes",
"a",
"Barrister",
"request",
"and",
"returns",
"a",
"response",
".",
"If",
"the",
"request",
"is",
"a",
"list",
"then",
"the",
"response",
"will",
"also",
"be",
"a",
"list",
".",
"If",
"the",
"request",
"is",
"an",
"empty",
"list",
"a",
"Rp... | 0471b1d98d3327ba381684db496ec94c79c20848 | https://github.com/coopernurse/barrister/blob/0471b1d98d3327ba381684db496ec94c79c20848/barrister/runtime.py#L284-L313 | train | Executes a Barrister request and returns a response. |
coopernurse/barrister | barrister/runtime.py | Server._call_and_format | def _call_and_format(self, req, props=None):
"""
Invokes a single request against a handler using _call() and traps any errors,
formatting them using _err(). If the request is successful it is wrapped in a
JSON-RPC 2.0 compliant dict with keys: 'jsonrpc', 'id', 'result'.
:Para... | python | def _call_and_format(self, req, props=None):
"""
Invokes a single request against a handler using _call() and traps any errors,
formatting them using _err(). If the request is successful it is wrapped in a
JSON-RPC 2.0 compliant dict with keys: 'jsonrpc', 'id', 'result'.
:Para... | [
"def",
"_call_and_format",
"(",
"self",
",",
"req",
",",
"props",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"req",
",",
"dict",
")",
":",
"return",
"err_response",
"(",
"None",
",",
"ERR_INVALID_REQ",
",",
"\"Invalid Request. %s is not an object.\... | Invokes a single request against a handler using _call() and traps any errors,
formatting them using _err(). If the request is successful it is wrapped in a
JSON-RPC 2.0 compliant dict with keys: 'jsonrpc', 'id', 'result'.
:Parameters:
req
A single dict representing a si... | [
"Invokes",
"a",
"single",
"request",
"against",
"a",
"handler",
"using",
"_call",
"()",
"and",
"traps",
"any",
"errors",
"formatting",
"them",
"using",
"_err",
"()",
".",
"If",
"the",
"request",
"is",
"successful",
"it",
"is",
"wrapped",
"in",
"a",
"JSON",... | 0471b1d98d3327ba381684db496ec94c79c20848 | https://github.com/coopernurse/barrister/blob/0471b1d98d3327ba381684db496ec94c79c20848/barrister/runtime.py#L315-L362 | train | Calls the _call method and formats the response. |
coopernurse/barrister | barrister/runtime.py | Server._call | def _call(self, context):
"""
Executes a single request against a handler. If the req.method == 'barrister-idl', the
Contract IDL JSON structure is returned. Otherwise the method is resolved to a handler
based on the interface name, and the appropriate function is called on the handler... | python | def _call(self, context):
"""
Executes a single request against a handler. If the req.method == 'barrister-idl', the
Contract IDL JSON structure is returned. Otherwise the method is resolved to a handler
based on the interface name, and the appropriate function is called on the handler... | [
"def",
"_call",
"(",
"self",
",",
"context",
")",
":",
"req",
"=",
"context",
".",
"request",
"if",
"not",
"req",
".",
"has_key",
"(",
"\"method\"",
")",
":",
"raise",
"RpcException",
"(",
"ERR_INVALID_REQ",
",",
"\"Invalid Request. No 'method'.\"",
")",
"me... | Executes a single request against a handler. If the req.method == 'barrister-idl', the
Contract IDL JSON structure is returned. Otherwise the method is resolved to a handler
based on the interface name, and the appropriate function is called on the handler.
:Parameter:
req
... | [
"Executes",
"a",
"single",
"request",
"against",
"a",
"handler",
".",
"If",
"the",
"req",
".",
"method",
"==",
"barrister",
"-",
"idl",
"the",
"Contract",
"IDL",
"JSON",
"structure",
"is",
"returned",
".",
"Otherwise",
"the",
"method",
"is",
"resolved",
"t... | 0471b1d98d3327ba381684db496ec94c79c20848 | https://github.com/coopernurse/barrister/blob/0471b1d98d3327ba381684db496ec94c79c20848/barrister/runtime.py#L364-L414 | train | Executes a single request against a specific handler. |
coopernurse/barrister | barrister/runtime.py | HttpTransport.request | def request(self, req):
"""
Makes a request against the server and returns the deserialized result.
:Parameters:
req
List or dict representing a JSON-RPC formatted request
"""
data = json.dumps(req)
req = urllib2.Request(self.url, data, self.headers... | python | def request(self, req):
"""
Makes a request against the server and returns the deserialized result.
:Parameters:
req
List or dict representing a JSON-RPC formatted request
"""
data = json.dumps(req)
req = urllib2.Request(self.url, data, self.headers... | [
"def",
"request",
"(",
"self",
",",
"req",
")",
":",
"data",
"=",
"json",
".",
"dumps",
"(",
"req",
")",
"req",
"=",
"urllib2",
".",
"Request",
"(",
"self",
".",
"url",
",",
"data",
",",
"self",
".",
"headers",
")",
"f",
"=",
"self",
".",
"open... | Makes a request against the server and returns the deserialized result.
:Parameters:
req
List or dict representing a JSON-RPC formatted request | [
"Makes",
"a",
"request",
"against",
"the",
"server",
"and",
"returns",
"the",
"deserialized",
"result",
"."
] | 0471b1d98d3327ba381684db496ec94c79c20848 | https://github.com/coopernurse/barrister/blob/0471b1d98d3327ba381684db496ec94c79c20848/barrister/runtime.py#L444-L457 | train | Makes a request against the server and returns the deserialized result. |
coopernurse/barrister | barrister/runtime.py | Client.call | def call(self, iface_name, func_name, params):
"""
Makes a single RPC request and returns the result.
:Parameters:
iface_name
Interface name to call
func_name
Function to call on the interface
params
List of parameters to pass to... | python | def call(self, iface_name, func_name, params):
"""
Makes a single RPC request and returns the result.
:Parameters:
iface_name
Interface name to call
func_name
Function to call on the interface
params
List of parameters to pass to... | [
"def",
"call",
"(",
"self",
",",
"iface_name",
",",
"func_name",
",",
"params",
")",
":",
"req",
"=",
"self",
".",
"to_request",
"(",
"iface_name",
",",
"func_name",
",",
"params",
")",
"if",
"self",
".",
"log",
".",
"isEnabledFor",
"(",
"logging",
"."... | Makes a single RPC request and returns the result.
:Parameters:
iface_name
Interface name to call
func_name
Function to call on the interface
params
List of parameters to pass to the function | [
"Makes",
"a",
"single",
"RPC",
"request",
"and",
"returns",
"the",
"result",
"."
] | 0471b1d98d3327ba381684db496ec94c79c20848 | https://github.com/coopernurse/barrister/blob/0471b1d98d3327ba381684db496ec94c79c20848/barrister/runtime.py#L543-L561 | train | Makes a single RPC request and returns the result. |
coopernurse/barrister | barrister/runtime.py | Client.to_request | def to_request(self, iface_name, func_name, params):
"""
Converts the arguments to a JSON-RPC request dict. The 'id' field is populated
using the id_gen function passed to the Client constructor.
If validate_request==True on the Client constructor, the params are validated
agai... | python | def to_request(self, iface_name, func_name, params):
"""
Converts the arguments to a JSON-RPC request dict. The 'id' field is populated
using the id_gen function passed to the Client constructor.
If validate_request==True on the Client constructor, the params are validated
agai... | [
"def",
"to_request",
"(",
"self",
",",
"iface_name",
",",
"func_name",
",",
"params",
")",
":",
"if",
"self",
".",
"validate_req",
":",
"self",
".",
"contract",
".",
"validate_request",
"(",
"iface_name",
",",
"func_name",
",",
"params",
")",
"method",
"="... | Converts the arguments to a JSON-RPC request dict. The 'id' field is populated
using the id_gen function passed to the Client constructor.
If validate_request==True on the Client constructor, the params are validated
against the expected types for the function and a RpcException raised if they... | [
"Converts",
"the",
"arguments",
"to",
"a",
"JSON",
"-",
"RPC",
"request",
"dict",
".",
"The",
"id",
"field",
"is",
"populated",
"using",
"the",
"id_gen",
"function",
"passed",
"to",
"the",
"Client",
"constructor",
"."
] | 0471b1d98d3327ba381684db496ec94c79c20848 | https://github.com/coopernurse/barrister/blob/0471b1d98d3327ba381684db496ec94c79c20848/barrister/runtime.py#L563-L585 | train | Converts the arguments to a JSON - RPC request dict. |
coopernurse/barrister | barrister/runtime.py | Client.to_result | def to_result(self, iface_name, func_name, resp):
"""
Takes a JSON-RPC response and checks for an "error" slot. If it exists,
a RpcException is raised. If no "error" slot exists, the "result" slot is
returned.
If validate_response==True on the Client constructor, the result is... | python | def to_result(self, iface_name, func_name, resp):
"""
Takes a JSON-RPC response and checks for an "error" slot. If it exists,
a RpcException is raised. If no "error" slot exists, the "result" slot is
returned.
If validate_response==True on the Client constructor, the result is... | [
"def",
"to_result",
"(",
"self",
",",
"iface_name",
",",
"func_name",
",",
"resp",
")",
":",
"if",
"resp",
".",
"has_key",
"(",
"\"error\"",
")",
":",
"e",
"=",
"resp",
"[",
"\"error\"",
"]",
"data",
"=",
"None",
"if",
"e",
".",
"has_key",
"(",
"\"... | Takes a JSON-RPC response and checks for an "error" slot. If it exists,
a RpcException is raised. If no "error" slot exists, the "result" slot is
returned.
If validate_response==True on the Client constructor, the result is validated
against the expected return type for the function a... | [
"Takes",
"a",
"JSON",
"-",
"RPC",
"response",
"and",
"checks",
"for",
"an",
"error",
"slot",
".",
"If",
"it",
"exists",
"a",
"RpcException",
"is",
"raised",
".",
"If",
"no",
"error",
"slot",
"exists",
"the",
"result",
"slot",
"is",
"returned",
"."
] | 0471b1d98d3327ba381684db496ec94c79c20848 | https://github.com/coopernurse/barrister/blob/0471b1d98d3327ba381684db496ec94c79c20848/barrister/runtime.py#L587-L616 | train | Takes a JSON - RPC response and returns a result. |
coopernurse/barrister | barrister/runtime.py | InterfaceClientProxy._caller | def _caller(self, iface_name, func_name):
"""
Returns a function for the given interface and function name. When invoked it
calls client.call() with the correct arguments.
:Parameters:
iface_name
Name of interface to call when invoked
func_name
... | python | def _caller(self, iface_name, func_name):
"""
Returns a function for the given interface and function name. When invoked it
calls client.call() with the correct arguments.
:Parameters:
iface_name
Name of interface to call when invoked
func_name
... | [
"def",
"_caller",
"(",
"self",
",",
"iface_name",
",",
"func_name",
")",
":",
"def",
"caller",
"(",
"*",
"params",
")",
":",
"return",
"self",
".",
"client",
".",
"call",
"(",
"iface_name",
",",
"func_name",
",",
"params",
")",
"return",
"caller"
] | Returns a function for the given interface and function name. When invoked it
calls client.call() with the correct arguments.
:Parameters:
iface_name
Name of interface to call when invoked
func_name
Name of function to call when invoked
par... | [
"Returns",
"a",
"function",
"for",
"the",
"given",
"interface",
"and",
"function",
"name",
".",
"When",
"invoked",
"it",
"calls",
"client",
".",
"call",
"()",
"with",
"the",
"correct",
"arguments",
".",
":",
"Parameters",
":",
"iface_name",
"Name",
"of",
"... | 0471b1d98d3327ba381684db496ec94c79c20848 | https://github.com/coopernurse/barrister/blob/0471b1d98d3327ba381684db496ec94c79c20848/barrister/runtime.py#L647-L662 | train | Returns a function that calls client. call with the correct arguments. |
coopernurse/barrister | barrister/runtime.py | Batch.call | def call(self, iface_name, func_name, params):
"""
Implements the call() function with same signature as Client.call(). Raises
a RpcException if send() has already been called on this batch. Otherwise
appends the request to an internal list.
This method is not commonly called ... | python | def call(self, iface_name, func_name, params):
"""
Implements the call() function with same signature as Client.call(). Raises
a RpcException if send() has already been called on this batch. Otherwise
appends the request to an internal list.
This method is not commonly called ... | [
"def",
"call",
"(",
"self",
",",
"iface_name",
",",
"func_name",
",",
"params",
")",
":",
"if",
"self",
".",
"sent",
":",
"raise",
"Exception",
"(",
"\"Batch already sent. Cannot add more calls.\"",
")",
"else",
":",
"req",
"=",
"self",
".",
"client",
".",
... | Implements the call() function with same signature as Client.call(). Raises
a RpcException if send() has already been called on this batch. Otherwise
appends the request to an internal list.
This method is not commonly called directly. | [
"Implements",
"the",
"call",
"()",
"function",
"with",
"same",
"signature",
"as",
"Client",
".",
"call",
"()",
".",
"Raises",
"a",
"RpcException",
"if",
"send",
"()",
"has",
"already",
"been",
"called",
"on",
"this",
"batch",
".",
"Otherwise",
"appends",
"... | 0471b1d98d3327ba381684db496ec94c79c20848 | https://github.com/coopernurse/barrister/blob/0471b1d98d3327ba381684db496ec94c79c20848/barrister/runtime.py#L687-L699 | train | Implements the call method with same signature as Client. call. |
coopernurse/barrister | barrister/runtime.py | Batch.send | def send(self):
"""
Sends the batch request to the server and returns a list of RpcResponse
objects. The list will be in the order that the requests were made to
the batch. Note that the RpcResponse objects may contain an error or a
successful result. When you iterate through... | python | def send(self):
"""
Sends the batch request to the server and returns a list of RpcResponse
objects. The list will be in the order that the requests were made to
the batch. Note that the RpcResponse objects may contain an error or a
successful result. When you iterate through... | [
"def",
"send",
"(",
"self",
")",
":",
"if",
"self",
".",
"sent",
":",
"raise",
"Exception",
"(",
"\"Batch already sent. Cannot send() again.\"",
")",
"else",
":",
"self",
".",
"sent",
"=",
"True",
"results",
"=",
"self",
".",
"client",
".",
"transport",
".... | Sends the batch request to the server and returns a list of RpcResponse
objects. The list will be in the order that the requests were made to
the batch. Note that the RpcResponse objects may contain an error or a
successful result. When you iterate through the list, you must test for
... | [
"Sends",
"the",
"batch",
"request",
"to",
"the",
"server",
"and",
"returns",
"a",
"list",
"of",
"RpcResponse",
"objects",
".",
"The",
"list",
"will",
"be",
"in",
"the",
"order",
"that",
"the",
"requests",
"were",
"made",
"to",
"the",
"batch",
".",
"Note"... | 0471b1d98d3327ba381684db496ec94c79c20848 | https://github.com/coopernurse/barrister/blob/0471b1d98d3327ba381684db496ec94c79c20848/barrister/runtime.py#L701-L739 | train | Sends the request to the server and returns a list of RpcResponse objects. |
coopernurse/barrister | barrister/runtime.py | Contract.validate_request | def validate_request(self, iface_name, func_name, params):
"""
Validates that the given params match the expected length and types for this
interface and function.
Returns two element tuple: (bool, string)
- `bool` - True if valid, False if not
- `string` - Descripti... | python | def validate_request(self, iface_name, func_name, params):
"""
Validates that the given params match the expected length and types for this
interface and function.
Returns two element tuple: (bool, string)
- `bool` - True if valid, False if not
- `string` - Descripti... | [
"def",
"validate_request",
"(",
"self",
",",
"iface_name",
",",
"func_name",
",",
"params",
")",
":",
"self",
".",
"interface",
"(",
"iface_name",
")",
".",
"function",
"(",
"func_name",
")",
".",
"validate_params",
"(",
"params",
")"
] | Validates that the given params match the expected length and types for this
interface and function.
Returns two element tuple: (bool, string)
- `bool` - True if valid, False if not
- `string` - Description of validation error, or None if valid
:Parameters:
iface_... | [
"Validates",
"that",
"the",
"given",
"params",
"match",
"the",
"expected",
"length",
"and",
"types",
"for",
"this",
"interface",
"and",
"function",
"."
] | 0471b1d98d3327ba381684db496ec94c79c20848 | https://github.com/coopernurse/barrister/blob/0471b1d98d3327ba381684db496ec94c79c20848/barrister/runtime.py#L786-L804 | train | Validates that the given params match the expected length and types for this
interface and function.
Returns a 2 element tuple that is True if valid False if not valid None if not valid |
coopernurse/barrister | barrister/runtime.py | Contract.validate_response | def validate_response(self, iface_name, func_name, resp):
"""
Validates that the response matches the return type for the function
Returns two element tuple: (bool, string)
- `bool` - True if valid, False if not
- `string` - Description of validation error, or None if valid
... | python | def validate_response(self, iface_name, func_name, resp):
"""
Validates that the response matches the return type for the function
Returns two element tuple: (bool, string)
- `bool` - True if valid, False if not
- `string` - Description of validation error, or None if valid
... | [
"def",
"validate_response",
"(",
"self",
",",
"iface_name",
",",
"func_name",
",",
"resp",
")",
":",
"self",
".",
"interface",
"(",
"iface_name",
")",
".",
"function",
"(",
"func_name",
")",
".",
"validate_response",
"(",
"resp",
")"
] | Validates that the response matches the return type for the function
Returns two element tuple: (bool, string)
- `bool` - True if valid, False if not
- `string` - Description of validation error, or None if valid
:Parameters:
iface_name
Name of interface
... | [
"Validates",
"that",
"the",
"response",
"matches",
"the",
"return",
"type",
"for",
"the",
"function"
] | 0471b1d98d3327ba381684db496ec94c79c20848 | https://github.com/coopernurse/barrister/blob/0471b1d98d3327ba381684db496ec94c79c20848/barrister/runtime.py#L806-L823 | train | Validates that the response for the function
is valid for the interfaceunused. |
coopernurse/barrister | barrister/runtime.py | Contract.get | def get(self, name):
"""
Returns the struct, enum, or interface with the given name, or raises RpcException if
no elements match that name.
:Parameters:
name
Name of struct/enum/interface to return
"""
if self.structs.has_key(name):
retu... | python | def get(self, name):
"""
Returns the struct, enum, or interface with the given name, or raises RpcException if
no elements match that name.
:Parameters:
name
Name of struct/enum/interface to return
"""
if self.structs.has_key(name):
retu... | [
"def",
"get",
"(",
"self",
",",
"name",
")",
":",
"if",
"self",
".",
"structs",
".",
"has_key",
"(",
"name",
")",
":",
"return",
"self",
".",
"structs",
"[",
"name",
"]",
"elif",
"self",
".",
"enums",
".",
"has_key",
"(",
"name",
")",
":",
"retur... | Returns the struct, enum, or interface with the given name, or raises RpcException if
no elements match that name.
:Parameters:
name
Name of struct/enum/interface to return | [
"Returns",
"the",
"struct",
"enum",
"or",
"interface",
"with",
"the",
"given",
"name",
"or",
"raises",
"RpcException",
"if",
"no",
"elements",
"match",
"that",
"name",
"."
] | 0471b1d98d3327ba381684db496ec94c79c20848 | https://github.com/coopernurse/barrister/blob/0471b1d98d3327ba381684db496ec94c79c20848/barrister/runtime.py#L825-L841 | train | Returns the struct enum or interface with the given name or raises RpcException if no such element is found. |
coopernurse/barrister | barrister/runtime.py | Contract.struct | def struct(self, struct_name):
"""
Returns the struct with the given name, or raises RpcException if no struct matches
"""
if self.structs.has_key(struct_name):
return self.structs[struct_name]
else:
raise RpcException(ERR_INVALID_PARAMS, "Unknown struct: ... | python | def struct(self, struct_name):
"""
Returns the struct with the given name, or raises RpcException if no struct matches
"""
if self.structs.has_key(struct_name):
return self.structs[struct_name]
else:
raise RpcException(ERR_INVALID_PARAMS, "Unknown struct: ... | [
"def",
"struct",
"(",
"self",
",",
"struct_name",
")",
":",
"if",
"self",
".",
"structs",
".",
"has_key",
"(",
"struct_name",
")",
":",
"return",
"self",
".",
"structs",
"[",
"struct_name",
"]",
"else",
":",
"raise",
"RpcException",
"(",
"ERR_INVALID_PARAM... | Returns the struct with the given name, or raises RpcException if no struct matches | [
"Returns",
"the",
"struct",
"with",
"the",
"given",
"name",
"or",
"raises",
"RpcException",
"if",
"no",
"struct",
"matches"
] | 0471b1d98d3327ba381684db496ec94c79c20848 | https://github.com/coopernurse/barrister/blob/0471b1d98d3327ba381684db496ec94c79c20848/barrister/runtime.py#L843-L850 | train | Returns the struct with the given name or raises RpcException if no struct matches the given name. |
coopernurse/barrister | barrister/runtime.py | Contract.interface | def interface(self, iface_name):
"""
Returns the interface with the given name, or raises RpcException if no interface matches
"""
if self.has_interface(iface_name):
return self.interfaces[iface_name]
else:
raise RpcException(ERR_INVALID_PARAMS, "Unknown i... | python | def interface(self, iface_name):
"""
Returns the interface with the given name, or raises RpcException if no interface matches
"""
if self.has_interface(iface_name):
return self.interfaces[iface_name]
else:
raise RpcException(ERR_INVALID_PARAMS, "Unknown i... | [
"def",
"interface",
"(",
"self",
",",
"iface_name",
")",
":",
"if",
"self",
".",
"has_interface",
"(",
"iface_name",
")",
":",
"return",
"self",
".",
"interfaces",
"[",
"iface_name",
"]",
"else",
":",
"raise",
"RpcException",
"(",
"ERR_INVALID_PARAMS",
",",
... | Returns the interface with the given name, or raises RpcException if no interface matches | [
"Returns",
"the",
"interface",
"with",
"the",
"given",
"name",
"or",
"raises",
"RpcException",
"if",
"no",
"interface",
"matches"
] | 0471b1d98d3327ba381684db496ec94c79c20848 | https://github.com/coopernurse/barrister/blob/0471b1d98d3327ba381684db496ec94c79c20848/barrister/runtime.py#L858-L865 | train | Returns the interface with the given name or raises RpcException if no interface with the given name exists. |
coopernurse/barrister | barrister/runtime.py | Contract.validate | def validate(self, expected_type, is_array, val):
"""
Validates that the expected type matches the value
Returns two element tuple: (bool, string)
- `bool` - True if valid, False if not
- `string` - Description of validation error, or None if valid
:Parameters:
... | python | def validate(self, expected_type, is_array, val):
"""
Validates that the expected type matches the value
Returns two element tuple: (bool, string)
- `bool` - True if valid, False if not
- `string` - Description of validation error, or None if valid
:Parameters:
... | [
"def",
"validate",
"(",
"self",
",",
"expected_type",
",",
"is_array",
",",
"val",
")",
":",
"if",
"val",
"==",
"None",
":",
"if",
"expected_type",
".",
"optional",
":",
"return",
"True",
",",
"None",
"else",
":",
"return",
"False",
",",
"\"Value cannot ... | Validates that the expected type matches the value
Returns two element tuple: (bool, string)
- `bool` - True if valid, False if not
- `string` - Description of validation error, or None if valid
:Parameters:
expected_type
string name of the type expected. This ma... | [
"Validates",
"that",
"the",
"expected",
"type",
"matches",
"the",
"value"
] | 0471b1d98d3327ba381684db496ec94c79c20848 | https://github.com/coopernurse/barrister/blob/0471b1d98d3327ba381684db496ec94c79c20848/barrister/runtime.py#L867-L911 | train | Validates that the value is of the expected type. |
coopernurse/barrister | barrister/runtime.py | Interface.function | def function(self, func_name):
"""
Returns the Function instance associated with the given func_name, or raises a
RpcException if no function matches.
"""
if self.functions.has_key(func_name):
return self.functions[func_name]
else:
raise RpcExcepti... | python | def function(self, func_name):
"""
Returns the Function instance associated with the given func_name, or raises a
RpcException if no function matches.
"""
if self.functions.has_key(func_name):
return self.functions[func_name]
else:
raise RpcExcepti... | [
"def",
"function",
"(",
"self",
",",
"func_name",
")",
":",
"if",
"self",
".",
"functions",
".",
"has_key",
"(",
"func_name",
")",
":",
"return",
"self",
".",
"functions",
"[",
"func_name",
"]",
"else",
":",
"raise",
"RpcException",
"(",
"ERR_METHOD_NOT_FO... | Returns the Function instance associated with the given func_name, or raises a
RpcException if no function matches. | [
"Returns",
"the",
"Function",
"instance",
"associated",
"with",
"the",
"given",
"func_name",
"or",
"raises",
"a",
"RpcException",
"if",
"no",
"function",
"matches",
"."
] | 0471b1d98d3327ba381684db496ec94c79c20848 | https://github.com/coopernurse/barrister/blob/0471b1d98d3327ba381684db496ec94c79c20848/barrister/runtime.py#L937-L946 | train | Returns the Function instance associated with the given func_name. |
coopernurse/barrister | barrister/runtime.py | Enum.validate | def validate(self, val):
"""
Validates that the val is in the list of values for this Enum.
Returns two element tuple: (bool, string)
- `bool` - True if valid, False if not
- `string` - Description of validation error, or None if valid
:Parameters:
val
... | python | def validate(self, val):
"""
Validates that the val is in the list of values for this Enum.
Returns two element tuple: (bool, string)
- `bool` - True if valid, False if not
- `string` - Description of validation error, or None if valid
:Parameters:
val
... | [
"def",
"validate",
"(",
"self",
",",
"val",
")",
":",
"if",
"val",
"in",
"self",
".",
"values",
":",
"return",
"True",
",",
"None",
"else",
":",
"return",
"False",
",",
"\"'%s' is not in enum: %s\"",
"%",
"(",
"val",
",",
"str",
"(",
"self",
".",
"va... | Validates that the val is in the list of values for this Enum.
Returns two element tuple: (bool, string)
- `bool` - True if valid, False if not
- `string` - Description of validation error, or None if valid
:Parameters:
val
Value to validate. Should be a string. | [
"Validates",
"that",
"the",
"val",
"is",
"in",
"the",
"list",
"of",
"values",
"for",
"this",
"Enum",
"."
] | 0471b1d98d3327ba381684db496ec94c79c20848 | https://github.com/coopernurse/barrister/blob/0471b1d98d3327ba381684db496ec94c79c20848/barrister/runtime.py#L966-L982 | train | Validates that the val is in the list of values for this Enum. |
coopernurse/barrister | barrister/runtime.py | Struct.field | def field(self, name):
"""
Returns the field on this struct with the given name. Will try to find this
name on all ancestors if this struct extends another.
If found, returns a dict with keys: 'name', 'comment', 'type', 'is_array'
If not found, returns None
:Parameters... | python | def field(self, name):
"""
Returns the field on this struct with the given name. Will try to find this
name on all ancestors if this struct extends another.
If found, returns a dict with keys: 'name', 'comment', 'type', 'is_array'
If not found, returns None
:Parameters... | [
"def",
"field",
"(",
"self",
",",
"name",
")",
":",
"if",
"self",
".",
"fields",
".",
"has_key",
"(",
"name",
")",
":",
"return",
"self",
".",
"fields",
"[",
"name",
"]",
"elif",
"self",
".",
"extends",
":",
"if",
"not",
"self",
".",
"parent",
":... | Returns the field on this struct with the given name. Will try to find this
name on all ancestors if this struct extends another.
If found, returns a dict with keys: 'name', 'comment', 'type', 'is_array'
If not found, returns None
:Parameters:
name
string name of... | [
"Returns",
"the",
"field",
"on",
"this",
"struct",
"with",
"the",
"given",
"name",
".",
"Will",
"try",
"to",
"find",
"this",
"name",
"on",
"all",
"ancestors",
"if",
"this",
"struct",
"extends",
"another",
"."
] | 0471b1d98d3327ba381684db496ec94c79c20848 | https://github.com/coopernurse/barrister/blob/0471b1d98d3327ba381684db496ec94c79c20848/barrister/runtime.py#L1007-L1026 | train | Returns the field on this struct with the given name. Will try to find this
name on all ancestors and return None if no such field exists. |
coopernurse/barrister | barrister/runtime.py | Struct.validate | def validate(self, val):
"""
Validates that the val matches the expected fields for this struct.
val must be a dict, and must contain only fields represented by this struct and its
ancestors.
Returns two element tuple: (bool, string)
- `bool` - True if valid, False if n... | python | def validate(self, val):
"""
Validates that the val matches the expected fields for this struct.
val must be a dict, and must contain only fields represented by this struct and its
ancestors.
Returns two element tuple: (bool, string)
- `bool` - True if valid, False if n... | [
"def",
"validate",
"(",
"self",
",",
"val",
")",
":",
"if",
"type",
"(",
"val",
")",
"is",
"not",
"dict",
":",
"return",
"False",
",",
"\"%s is not a dict\"",
"%",
"(",
"str",
"(",
"val",
")",
")",
"for",
"k",
",",
"v",
"in",
"val",
".",
"items",... | Validates that the val matches the expected fields for this struct.
val must be a dict, and must contain only fields represented by this struct and its
ancestors.
Returns two element tuple: (bool, string)
- `bool` - True if valid, False if not
- `string` - Description of valida... | [
"Validates",
"that",
"the",
"val",
"matches",
"the",
"expected",
"fields",
"for",
"this",
"struct",
".",
"val",
"must",
"be",
"a",
"dict",
"and",
"must",
"contain",
"only",
"fields",
"represented",
"by",
"this",
"struct",
"and",
"its",
"ancestors",
"."
] | 0471b1d98d3327ba381684db496ec94c79c20848 | https://github.com/coopernurse/barrister/blob/0471b1d98d3327ba381684db496ec94c79c20848/barrister/runtime.py#L1028-L1060 | train | Validates that the val matches the expected fields for this struct. |
coopernurse/barrister | barrister/runtime.py | Struct.get_all_fields | def get_all_fields(self, arr):
"""
Returns a list containing this struct's fields and all the fields of
its ancestors. Used during validation.
"""
for k, v in self.fields.items():
arr.append(v)
if self.extends:
parent = self.contract.... | python | def get_all_fields(self, arr):
"""
Returns a list containing this struct's fields and all the fields of
its ancestors. Used during validation.
"""
for k, v in self.fields.items():
arr.append(v)
if self.extends:
parent = self.contract.... | [
"def",
"get_all_fields",
"(",
"self",
",",
"arr",
")",
":",
"for",
"k",
",",
"v",
"in",
"self",
".",
"fields",
".",
"items",
"(",
")",
":",
"arr",
".",
"append",
"(",
"v",
")",
"if",
"self",
".",
"extends",
":",
"parent",
"=",
"self",
".",
"con... | Returns a list containing this struct's fields and all the fields of
its ancestors. Used during validation. | [
"Returns",
"a",
"list",
"containing",
"this",
"struct",
"s",
"fields",
"and",
"all",
"the",
"fields",
"of",
"its",
"ancestors",
".",
"Used",
"during",
"validation",
"."
] | 0471b1d98d3327ba381684db496ec94c79c20848 | https://github.com/coopernurse/barrister/blob/0471b1d98d3327ba381684db496ec94c79c20848/barrister/runtime.py#L1062-L1075 | train | Returns a list containing this struct s fields and all the fields of
s ancestors. Used during validation. |
coopernurse/barrister | barrister/runtime.py | Function.validate_params | def validate_params(self, params):
"""
Validates params against expected types for this function.
Raises RpcException if the params are invalid.
"""
plen = 0
if params != None:
plen = len(params)
if len(self.params) != plen:
vals = (self... | python | def validate_params(self, params):
"""
Validates params against expected types for this function.
Raises RpcException if the params are invalid.
"""
plen = 0
if params != None:
plen = len(params)
if len(self.params) != plen:
vals = (self... | [
"def",
"validate_params",
"(",
"self",
",",
"params",
")",
":",
"plen",
"=",
"0",
"if",
"params",
"!=",
"None",
":",
"plen",
"=",
"len",
"(",
"params",
")",
"if",
"len",
"(",
"self",
".",
"params",
")",
"!=",
"plen",
":",
"vals",
"=",
"(",
"self"... | Validates params against expected types for this function.
Raises RpcException if the params are invalid. | [
"Validates",
"params",
"against",
"expected",
"types",
"for",
"this",
"function",
".",
"Raises",
"RpcException",
"if",
"the",
"params",
"are",
"invalid",
"."
] | 0471b1d98d3327ba381684db496ec94c79c20848 | https://github.com/coopernurse/barrister/blob/0471b1d98d3327ba381684db496ec94c79c20848/barrister/runtime.py#L1102-L1120 | train | Validates the params against expected types for this function. Raises RpcException if the params are invalid. |
coopernurse/barrister | barrister/runtime.py | Function.validate_response | def validate_response(self, resp):
"""
Validates resp against expected return type for this function.
Raises RpcException if the response is invalid.
"""
ok, msg = self.contract.validate(self.returns,
self.returns.is_array, resp)
... | python | def validate_response(self, resp):
"""
Validates resp against expected return type for this function.
Raises RpcException if the response is invalid.
"""
ok, msg = self.contract.validate(self.returns,
self.returns.is_array, resp)
... | [
"def",
"validate_response",
"(",
"self",
",",
"resp",
")",
":",
"ok",
",",
"msg",
"=",
"self",
".",
"contract",
".",
"validate",
"(",
"self",
".",
"returns",
",",
"self",
".",
"returns",
".",
"is_array",
",",
"resp",
")",
"if",
"not",
"ok",
":",
"v... | Validates resp against expected return type for this function.
Raises RpcException if the response is invalid. | [
"Validates",
"resp",
"against",
"expected",
"return",
"type",
"for",
"this",
"function",
".",
"Raises",
"RpcException",
"if",
"the",
"response",
"is",
"invalid",
"."
] | 0471b1d98d3327ba381684db496ec94c79c20848 | https://github.com/coopernurse/barrister/blob/0471b1d98d3327ba381684db496ec94c79c20848/barrister/runtime.py#L1122-L1132 | train | Validates the response against expected return type for this function. Raises RpcException if the response is invalid. |
coopernurse/barrister | barrister/runtime.py | Function._validate_param | def _validate_param(self, expected, param):
"""
Validates a single param against its expected type.
Raises RpcException if the param is invalid
:Parameters:
expected
Type instance
param
Parameter value to validate
"""
o... | python | def _validate_param(self, expected, param):
"""
Validates a single param against its expected type.
Raises RpcException if the param is invalid
:Parameters:
expected
Type instance
param
Parameter value to validate
"""
o... | [
"def",
"_validate_param",
"(",
"self",
",",
"expected",
",",
"param",
")",
":",
"ok",
",",
"msg",
"=",
"self",
".",
"contract",
".",
"validate",
"(",
"expected",
",",
"expected",
".",
"is_array",
",",
"param",
")",
"if",
"not",
"ok",
":",
"vals",
"="... | Validates a single param against its expected type.
Raises RpcException if the param is invalid
:Parameters:
expected
Type instance
param
Parameter value to validate | [
"Validates",
"a",
"single",
"param",
"against",
"its",
"expected",
"type",
".",
"Raises",
"RpcException",
"if",
"the",
"param",
"is",
"invalid",
":",
"Parameters",
":",
"expected",
"Type",
"instance",
"param",
"Parameter",
"value",
"to",
"validate"
] | 0471b1d98d3327ba381684db496ec94c79c20848 | https://github.com/coopernurse/barrister/blob/0471b1d98d3327ba381684db496ec94c79c20848/barrister/runtime.py#L1134-L1149 | train | Validates a single parameter against its expected type. |
mkoura/dump2polarion | dump2polarion/submit.py | submit | def submit(xml_root, submit_config, session, dry_run=None, **kwargs):
"""Submits data to the Polarion Importer."""
properties.xunit_fill_testrun_id(xml_root, kwargs.get("testrun_id"))
if dry_run is not None:
properties.set_dry_run(xml_root, dry_run)
xml_input = utils.etree_to_string(xml_root)
... | python | def submit(xml_root, submit_config, session, dry_run=None, **kwargs):
"""Submits data to the Polarion Importer."""
properties.xunit_fill_testrun_id(xml_root, kwargs.get("testrun_id"))
if dry_run is not None:
properties.set_dry_run(xml_root, dry_run)
xml_input = utils.etree_to_string(xml_root)
... | [
"def",
"submit",
"(",
"xml_root",
",",
"submit_config",
",",
"session",
",",
"dry_run",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"properties",
".",
"xunit_fill_testrun_id",
"(",
"xml_root",
",",
"kwargs",
".",
"get",
"(",
"\"testrun_id\"",
")",
")",... | Submits data to the Polarion Importer. | [
"Submits",
"data",
"to",
"the",
"Polarion",
"Importer",
"."
] | f4bd24e9d5070e282aad15f1e8bb514c0525cd37 | https://github.com/mkoura/dump2polarion/blob/f4bd24e9d5070e282aad15f1e8bb514c0525cd37/dump2polarion/submit.py#L153-L169 | train | Submits data to Polarion Importer. |
mkoura/dump2polarion | dump2polarion/submit.py | submit_and_verify | def submit_and_verify(
xml_str=None, xml_file=None, xml_root=None, config=None, session=None, dry_run=None, **kwargs
):
"""Submits data to the Polarion Importer and checks that it was imported."""
try:
config = config or configuration.get_config()
xml_root = _get_xml_root(xml_root, xml_str, ... | python | def submit_and_verify(
xml_str=None, xml_file=None, xml_root=None, config=None, session=None, dry_run=None, **kwargs
):
"""Submits data to the Polarion Importer and checks that it was imported."""
try:
config = config or configuration.get_config()
xml_root = _get_xml_root(xml_root, xml_str, ... | [
"def",
"submit_and_verify",
"(",
"xml_str",
"=",
"None",
",",
"xml_file",
"=",
"None",
",",
"xml_root",
"=",
"None",
",",
"config",
"=",
"None",
",",
"session",
"=",
"None",
",",
"dry_run",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
... | Submits data to the Polarion Importer and checks that it was imported. | [
"Submits",
"data",
"to",
"the",
"Polarion",
"Importer",
"and",
"checks",
"that",
"it",
"was",
"imported",
"."
] | f4bd24e9d5070e282aad15f1e8bb514c0525cd37 | https://github.com/mkoura/dump2polarion/blob/f4bd24e9d5070e282aad15f1e8bb514c0525cd37/dump2polarion/submit.py#L173-L200 | train | Submits data to the Polarion Importer and checks that it was imported. |
mkoura/dump2polarion | dump2polarion/submit.py | SubmitResponse.get_job_ids | def get_job_ids(self):
"""Returns job IDs of the import."""
if not self.parsed_response:
return None
try:
job_ids = self.parsed_response["files"]["results.xml"]["job-ids"]
except KeyError:
return None
if not job_ids or job_ids == [0]:
... | python | def get_job_ids(self):
"""Returns job IDs of the import."""
if not self.parsed_response:
return None
try:
job_ids = self.parsed_response["files"]["results.xml"]["job-ids"]
except KeyError:
return None
if not job_ids or job_ids == [0]:
... | [
"def",
"get_job_ids",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"parsed_response",
":",
"return",
"None",
"try",
":",
"job_ids",
"=",
"self",
".",
"parsed_response",
"[",
"\"files\"",
"]",
"[",
"\"results.xml\"",
"]",
"[",
"\"job-ids\"",
"]",
"excep... | Returns job IDs of the import. | [
"Returns",
"job",
"IDs",
"of",
"the",
"import",
"."
] | f4bd24e9d5070e282aad15f1e8bb514c0525cd37 | https://github.com/mkoura/dump2polarion/blob/f4bd24e9d5070e282aad15f1e8bb514c0525cd37/dump2polarion/submit.py#L35-L45 | train | Returns the job IDs of the import. |
mkoura/dump2polarion | dump2polarion/submit.py | SubmitResponse.validate_response | def validate_response(self):
"""Checks that the response is valid and import succeeded."""
if self.response is None:
logger.error("Failed to submit")
return False
if not self.response:
logger.error(
"HTTP status %d: failed to submit to %s",
... | python | def validate_response(self):
"""Checks that the response is valid and import succeeded."""
if self.response is None:
logger.error("Failed to submit")
return False
if not self.response:
logger.error(
"HTTP status %d: failed to submit to %s",
... | [
"def",
"validate_response",
"(",
"self",
")",
":",
"if",
"self",
".",
"response",
"is",
"None",
":",
"logger",
".",
"error",
"(",
"\"Failed to submit\"",
")",
"return",
"False",
"if",
"not",
"self",
".",
"response",
":",
"logger",
".",
"error",
"(",
"\"H... | Checks that the response is valid and import succeeded. | [
"Checks",
"that",
"the",
"response",
"is",
"valid",
"and",
"import",
"succeeded",
"."
] | f4bd24e9d5070e282aad15f1e8bb514c0525cd37 | https://github.com/mkoura/dump2polarion/blob/f4bd24e9d5070e282aad15f1e8bb514c0525cd37/dump2polarion/submit.py#L53-L84 | train | Checks that the response is valid and import succeeded. |
mkoura/dump2polarion | dump2polarion/submit.py | SubmitConfig.get_targets | def get_targets(self):
"""Sets targets."""
if self.xml_root.tag == "testcases":
self.submit_target = self.config.get("testcase_taget")
self.queue_url = self.config.get("testcase_queue")
self.log_url = self.config.get("testcase_log")
elif self.xml_root.tag == "... | python | def get_targets(self):
"""Sets targets."""
if self.xml_root.tag == "testcases":
self.submit_target = self.config.get("testcase_taget")
self.queue_url = self.config.get("testcase_queue")
self.log_url = self.config.get("testcase_log")
elif self.xml_root.tag == "... | [
"def",
"get_targets",
"(",
"self",
")",
":",
"if",
"self",
".",
"xml_root",
".",
"tag",
"==",
"\"testcases\"",
":",
"self",
".",
"submit_target",
"=",
"self",
".",
"config",
".",
"get",
"(",
"\"testcase_taget\"",
")",
"self",
".",
"queue_url",
"=",
"self... | Sets targets. | [
"Sets",
"targets",
"."
] | f4bd24e9d5070e282aad15f1e8bb514c0525cd37 | https://github.com/mkoura/dump2polarion/blob/f4bd24e9d5070e282aad15f1e8bb514c0525cd37/dump2polarion/submit.py#L109-L124 | train | Sets targets. |
mkoura/dump2polarion | dump2polarion/submit.py | SubmitConfig.get_credentials | def get_credentials(self, **kwargs):
"""Sets credentails."""
login = (
kwargs.get("user") or os.environ.get("POLARION_USERNAME") or self.config.get("username")
)
pwd = (
kwargs.get("password")
or os.environ.get("POLARION_PASSWORD")
or self.... | python | def get_credentials(self, **kwargs):
"""Sets credentails."""
login = (
kwargs.get("user") or os.environ.get("POLARION_USERNAME") or self.config.get("username")
)
pwd = (
kwargs.get("password")
or os.environ.get("POLARION_PASSWORD")
or self.... | [
"def",
"get_credentials",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"login",
"=",
"(",
"kwargs",
".",
"get",
"(",
"\"user\"",
")",
"or",
"os",
".",
"environ",
".",
"get",
"(",
"\"POLARION_USERNAME\"",
")",
"or",
"self",
".",
"config",
".",
"get... | Sets credentails. | [
"Sets",
"credentails",
"."
] | f4bd24e9d5070e282aad15f1e8bb514c0525cd37 | https://github.com/mkoura/dump2polarion/blob/f4bd24e9d5070e282aad15f1e8bb514c0525cd37/dump2polarion/submit.py#L126-L140 | train | Sets credentials. |
praekeltfoundation/seed-message-sender | message_sender/formatters.py | e_164 | def e_164(msisdn: str) -> str:
"""
Returns the msisdn in E.164 international format.
"""
# Phonenumbers library requires the + to identify the country, so we add it if it
# does not already exist
number = phonenumbers.parse("+{}".format(msisdn.lstrip("+")), None)
return phonenumbers.format_n... | python | def e_164(msisdn: str) -> str:
"""
Returns the msisdn in E.164 international format.
"""
# Phonenumbers library requires the + to identify the country, so we add it if it
# does not already exist
number = phonenumbers.parse("+{}".format(msisdn.lstrip("+")), None)
return phonenumbers.format_n... | [
"def",
"e_164",
"(",
"msisdn",
":",
"str",
")",
"->",
"str",
":",
"# Phonenumbers library requires the + to identify the country, so we add it if it",
"# does not already exist",
"number",
"=",
"phonenumbers",
".",
"parse",
"(",
"\"+{}\"",
".",
"format",
"(",
"msisdn",
... | Returns the msisdn in E.164 international format. | [
"Returns",
"the",
"msisdn",
"in",
"E",
".",
"164",
"international",
"format",
"."
] | 257b01635171b9dbe1f5f13baa810c971bb2620e | https://github.com/praekeltfoundation/seed-message-sender/blob/257b01635171b9dbe1f5f13baa810c971bb2620e/message_sender/formatters.py#L31-L38 | train | Returns the msisdn in E. 164 international format. |
mgoral/subconvert | src/subconvert/utils/VideoPlayer.py | VideoPlayer.loadFile | def loadFile(self, filePath):
"""Loads a file"""
self._filePath = filePath
if self._proc.state() != QProcess.Running:
self._kill()
self._run(self._filePath)
else:
self._execute("pausing_keep_force pt_step 1")
self._execute("get_property pa... | python | def loadFile(self, filePath):
"""Loads a file"""
self._filePath = filePath
if self._proc.state() != QProcess.Running:
self._kill()
self._run(self._filePath)
else:
self._execute("pausing_keep_force pt_step 1")
self._execute("get_property pa... | [
"def",
"loadFile",
"(",
"self",
",",
"filePath",
")",
":",
"self",
".",
"_filePath",
"=",
"filePath",
"if",
"self",
".",
"_proc",
".",
"state",
"(",
")",
"!=",
"QProcess",
".",
"Running",
":",
"self",
".",
"_kill",
"(",
")",
"self",
".",
"_run",
"(... | Loads a file | [
"Loads",
"a",
"file"
] | 59701e5e69ef1ca26ce7d1d766c936664aa2cb32 | https://github.com/mgoral/subconvert/blob/59701e5e69ef1ca26ce7d1d766c936664aa2cb32/src/subconvert/utils/VideoPlayer.py#L107-L121 | train | Loads a file into the internal data structures. |
mgoral/subconvert | src/subconvert/utils/VideoPlayer.py | VideoPlayer.play | def play(self):
"""Starts a playback"""
if self._proc.state() == QProcess.Running:
if self.isPlaying is False:
self._execute("pause")
self._changePlayingState(True)
elif self._filePath is not None:
self._kill()
self._run(self._f... | python | def play(self):
"""Starts a playback"""
if self._proc.state() == QProcess.Running:
if self.isPlaying is False:
self._execute("pause")
self._changePlayingState(True)
elif self._filePath is not None:
self._kill()
self._run(self._f... | [
"def",
"play",
"(",
"self",
")",
":",
"if",
"self",
".",
"_proc",
".",
"state",
"(",
")",
"==",
"QProcess",
".",
"Running",
":",
"if",
"self",
".",
"isPlaying",
"is",
"False",
":",
"self",
".",
"_execute",
"(",
"\"pause\"",
")",
"self",
".",
"_chan... | Starts a playback | [
"Starts",
"a",
"playback"
] | 59701e5e69ef1ca26ce7d1d766c936664aa2cb32 | https://github.com/mgoral/subconvert/blob/59701e5e69ef1ca26ce7d1d766c936664aa2cb32/src/subconvert/utils/VideoPlayer.py#L123-L132 | train | Starts a playback |
mgoral/subconvert | src/subconvert/utils/VideoPlayer.py | VideoPlayer.pause | def pause(self):
"""Pauses playback"""
if self.isPlaying is True:
self._execute("pause")
self._changePlayingState(False) | python | def pause(self):
"""Pauses playback"""
if self.isPlaying is True:
self._execute("pause")
self._changePlayingState(False) | [
"def",
"pause",
"(",
"self",
")",
":",
"if",
"self",
".",
"isPlaying",
"is",
"True",
":",
"self",
".",
"_execute",
"(",
"\"pause\"",
")",
"self",
".",
"_changePlayingState",
"(",
"False",
")"
] | Pauses playback | [
"Pauses",
"playback"
] | 59701e5e69ef1ca26ce7d1d766c936664aa2cb32 | https://github.com/mgoral/subconvert/blob/59701e5e69ef1ca26ce7d1d766c936664aa2cb32/src/subconvert/utils/VideoPlayer.py#L138-L142 | train | Pauses playback. |
mgoral/subconvert | src/subconvert/utils/VideoPlayer.py | VideoPlayer.stop | def stop(self):
"""Stops playback"""
if self.isPlaying is True:
self._execute("stop")
self._changePlayingState(False) | python | def stop(self):
"""Stops playback"""
if self.isPlaying is True:
self._execute("stop")
self._changePlayingState(False) | [
"def",
"stop",
"(",
"self",
")",
":",
"if",
"self",
".",
"isPlaying",
"is",
"True",
":",
"self",
".",
"_execute",
"(",
"\"stop\"",
")",
"self",
".",
"_changePlayingState",
"(",
"False",
")"
] | Stops playback | [
"Stops",
"playback"
] | 59701e5e69ef1ca26ce7d1d766c936664aa2cb32 | https://github.com/mgoral/subconvert/blob/59701e5e69ef1ca26ce7d1d766c936664aa2cb32/src/subconvert/utils/VideoPlayer.py#L144-L148 | train | Stops playback. |
mgoral/subconvert | src/subconvert/utils/VideoPlayer.py | VideoPlayer.setVolume | def setVolume(self, volume):
"""Changes volume"""
val = float(val)
cmd = "volume %s" % val
self._execute(cmd) | python | def setVolume(self, volume):
"""Changes volume"""
val = float(val)
cmd = "volume %s" % val
self._execute(cmd) | [
"def",
"setVolume",
"(",
"self",
",",
"volume",
")",
":",
"val",
"=",
"float",
"(",
"val",
")",
"cmd",
"=",
"\"volume %s\"",
"%",
"val",
"self",
".",
"_execute",
"(",
"cmd",
")"
] | Changes volume | [
"Changes",
"volume"
] | 59701e5e69ef1ca26ce7d1d766c936664aa2cb32 | https://github.com/mgoral/subconvert/blob/59701e5e69ef1ca26ce7d1d766c936664aa2cb32/src/subconvert/utils/VideoPlayer.py#L161-L165 | train | Changes the volume of the current locale |
davidfokkema/artist | demo/demo_fourier_with_legend.py | square | def square(x):
"""Square wave of period 2*L"""
def H(x):
"""Heaveside step function"""
if x < 0.:
return 0.
if x == 0.:
return 0.5
if x > 0.:
return 1.
return 2 * (H(x / L) - H(x / L - 1)) - 1 | python | def square(x):
"""Square wave of period 2*L"""
def H(x):
"""Heaveside step function"""
if x < 0.:
return 0.
if x == 0.:
return 0.5
if x > 0.:
return 1.
return 2 * (H(x / L) - H(x / L - 1)) - 1 | [
"def",
"square",
"(",
"x",
")",
":",
"def",
"H",
"(",
"x",
")",
":",
"\"\"\"Heaveside step function\"\"\"",
"if",
"x",
"<",
"0.",
":",
"return",
"0.",
"if",
"x",
"==",
"0.",
":",
"return",
"0.5",
"if",
"x",
">",
"0.",
":",
"return",
"1.",
"return",... | Square wave of period 2*L | [
"Square",
"wave",
"of",
"period",
"2",
"*",
"L"
] | 26ae7987522622710f2910980770c50012fda47d | https://github.com/davidfokkema/artist/blob/26ae7987522622710f2910980770c50012fda47d/demo/demo_fourier_with_legend.py#L11-L23 | train | Square wave of period 2L |
davidfokkema/artist | demo/demo_fourier_with_legend.py | fourier | def fourier(x, N):
"""Fourier approximation with N terms"""
term = 0.
for n in range(1, N, 2):
term += (1. / n) * math.sin(n * math.pi * x / L)
return (4. / (math.pi)) * term | python | def fourier(x, N):
"""Fourier approximation with N terms"""
term = 0.
for n in range(1, N, 2):
term += (1. / n) * math.sin(n * math.pi * x / L)
return (4. / (math.pi)) * term | [
"def",
"fourier",
"(",
"x",
",",
"N",
")",
":",
"term",
"=",
"0.",
"for",
"n",
"in",
"range",
"(",
"1",
",",
"N",
",",
"2",
")",
":",
"term",
"+=",
"(",
"1.",
"/",
"n",
")",
"*",
"math",
".",
"sin",
"(",
"n",
"*",
"math",
".",
"pi",
"*"... | Fourier approximation with N terms | [
"Fourier",
"approximation",
"with",
"N",
"terms"
] | 26ae7987522622710f2910980770c50012fda47d | https://github.com/davidfokkema/artist/blob/26ae7987522622710f2910980770c50012fda47d/demo/demo_fourier_with_legend.py#L26-L32 | train | Fourier approximation with N terms |
davidfokkema/artist | demo/demo_fourier_with_legend.py | add_custom_pin | def add_custom_pin(plot, x, y, label, distance='3ex'):
"""Add a pin at the maximum value of a data series (sort of)"""
# only use the second quarter, for cosmetic reasons
q = int(0.25 * len(y))
y = y[q:2*q]
max_index = q + np.argmax(y)
max_x = x[max_index]
plot.add_pin(label, x=max_x, locat... | python | def add_custom_pin(plot, x, y, label, distance='3ex'):
"""Add a pin at the maximum value of a data series (sort of)"""
# only use the second quarter, for cosmetic reasons
q = int(0.25 * len(y))
y = y[q:2*q]
max_index = q + np.argmax(y)
max_x = x[max_index]
plot.add_pin(label, x=max_x, locat... | [
"def",
"add_custom_pin",
"(",
"plot",
",",
"x",
",",
"y",
",",
"label",
",",
"distance",
"=",
"'3ex'",
")",
":",
"# only use the second quarter, for cosmetic reasons",
"q",
"=",
"int",
"(",
"0.25",
"*",
"len",
"(",
"y",
")",
")",
"y",
"=",
"y",
"[",
"q... | Add a pin at the maximum value of a data series (sort of) | [
"Add",
"a",
"pin",
"at",
"the",
"maximum",
"value",
"of",
"a",
"data",
"series",
"(",
"sort",
"of",
")"
] | 26ae7987522622710f2910980770c50012fda47d | https://github.com/davidfokkema/artist/blob/26ae7987522622710f2910980770c50012fda47d/demo/demo_fourier_with_legend.py#L35-L44 | train | Add a custom pin at the maximum value of a data series. |
coopernurse/barrister | barrister/docco.py | format_type | def format_type(t, includeOptional=True):
"""
Returns the type as a string. If the type is an array, then it is prepended with []
:Parameters:
t
The type as a dict. Keys: 'type', 'is_array'
"""
s = ""
if t.has_key('is_array') and t['is_array']:
s = "[]%s" % t['type']
... | python | def format_type(t, includeOptional=True):
"""
Returns the type as a string. If the type is an array, then it is prepended with []
:Parameters:
t
The type as a dict. Keys: 'type', 'is_array'
"""
s = ""
if t.has_key('is_array') and t['is_array']:
s = "[]%s" % t['type']
... | [
"def",
"format_type",
"(",
"t",
",",
"includeOptional",
"=",
"True",
")",
":",
"s",
"=",
"\"\"",
"if",
"t",
".",
"has_key",
"(",
"'is_array'",
")",
"and",
"t",
"[",
"'is_array'",
"]",
":",
"s",
"=",
"\"[]%s\"",
"%",
"t",
"[",
"'type'",
"]",
"else",... | Returns the type as a string. If the type is an array, then it is prepended with []
:Parameters:
t
The type as a dict. Keys: 'type', 'is_array' | [
"Returns",
"the",
"type",
"as",
"a",
"string",
".",
"If",
"the",
"type",
"is",
"an",
"array",
"then",
"it",
"is",
"prepended",
"with",
"[]",
":",
"Parameters",
":",
"t",
"The",
"type",
"as",
"a",
"dict",
".",
"Keys",
":",
"type",
"is_array"
] | 0471b1d98d3327ba381684db496ec94c79c20848 | https://github.com/coopernurse/barrister/blob/0471b1d98d3327ba381684db496ec94c79c20848/barrister/docco.py#L214-L229 | train | Formats the type as a string. |
coopernurse/barrister | barrister/docco.py | docco_html | def docco_html(title, idl_parsed, diagram_fname=None):
"""
Translates a parsed Barrister IDL into HTML. Returns a string containing the HTML.
:Parameters:
title
Title of the document. Will be included in <title> and <h1> tags
idl_parsed
Parsed representation of IDL to convert t... | python | def docco_html(title, idl_parsed, diagram_fname=None):
"""
Translates a parsed Barrister IDL into HTML. Returns a string containing the HTML.
:Parameters:
title
Title of the document. Will be included in <title> and <h1> tags
idl_parsed
Parsed representation of IDL to convert t... | [
"def",
"docco_html",
"(",
"title",
",",
"idl_parsed",
",",
"diagram_fname",
"=",
"None",
")",
":",
"sections",
"=",
"to_sections",
"(",
"idl_parsed",
")",
"s",
"=",
"\"\"\"<!DOCTYPE html>\n<html>\n<head>\n <title>%s</title>\n <meta http-equiv=\"content-type\" content=\"text... | Translates a parsed Barrister IDL into HTML. Returns a string containing the HTML.
:Parameters:
title
Title of the document. Will be included in <title> and <h1> tags
idl_parsed
Parsed representation of IDL to convert to HTML | [
"Translates",
"a",
"parsed",
"Barrister",
"IDL",
"into",
"HTML",
".",
"Returns",
"a",
"string",
"containing",
"the",
"HTML",
"."
] | 0471b1d98d3327ba381684db496ec94c79c20848 | https://github.com/coopernurse/barrister/blob/0471b1d98d3327ba381684db496ec94c79c20848/barrister/docco.py#L231-L291 | train | Returns a string containing the HTML representation of the IDL. |
coopernurse/barrister | barrister/docco.py | parse_enum | def parse_enum(enum):
"""
Returns a docco section for the given enum.
:Parameters:
enum
Parsed IDL enum dict. Keys: 'comment', 'name', 'values'
"""
docs = enum['comment']
code = '<span class="k">enum</span> <span class="gs">%s</span> {\n' % enum['name']
for v in enum["values"]... | python | def parse_enum(enum):
"""
Returns a docco section for the given enum.
:Parameters:
enum
Parsed IDL enum dict. Keys: 'comment', 'name', 'values'
"""
docs = enum['comment']
code = '<span class="k">enum</span> <span class="gs">%s</span> {\n' % enum['name']
for v in enum["values"]... | [
"def",
"parse_enum",
"(",
"enum",
")",
":",
"docs",
"=",
"enum",
"[",
"'comment'",
"]",
"code",
"=",
"'<span class=\"k\">enum</span> <span class=\"gs\">%s</span> {\\n'",
"%",
"enum",
"[",
"'name'",
"]",
"for",
"v",
"in",
"enum",
"[",
"\"values\"",
"]",
":",
"i... | Returns a docco section for the given enum.
:Parameters:
enum
Parsed IDL enum dict. Keys: 'comment', 'name', 'values' | [
"Returns",
"a",
"docco",
"section",
"for",
"the",
"given",
"enum",
"."
] | 0471b1d98d3327ba381684db496ec94c79c20848 | https://github.com/coopernurse/barrister/blob/0471b1d98d3327ba381684db496ec94c79c20848/barrister/docco.py#L293-L310 | train | Parses an IDL enum dict and returns a docco section for the given enum. |
coopernurse/barrister | barrister/docco.py | parse_struct | def parse_struct(s):
"""
Returns a docco section for the given struct.
:Parameters:
s
Parsed IDL struct dict. Keys: 'comment', 'name', 'extends', 'fields'
"""
docs = s['comment']
code = '<span class="k">struct</span> <span class="gs">%s</span>' % s['name']
if s['extends']:
... | python | def parse_struct(s):
"""
Returns a docco section for the given struct.
:Parameters:
s
Parsed IDL struct dict. Keys: 'comment', 'name', 'extends', 'fields'
"""
docs = s['comment']
code = '<span class="k">struct</span> <span class="gs">%s</span>' % s['name']
if s['extends']:
... | [
"def",
"parse_struct",
"(",
"s",
")",
":",
"docs",
"=",
"s",
"[",
"'comment'",
"]",
"code",
"=",
"'<span class=\"k\">struct</span> <span class=\"gs\">%s</span>'",
"%",
"s",
"[",
"'name'",
"]",
"if",
"s",
"[",
"'extends'",
"]",
":",
"code",
"+=",
"' extends <sp... | Returns a docco section for the given struct.
:Parameters:
s
Parsed IDL struct dict. Keys: 'comment', 'name', 'extends', 'fields' | [
"Returns",
"a",
"docco",
"section",
"for",
"the",
"given",
"struct",
"."
] | 0471b1d98d3327ba381684db496ec94c79c20848 | https://github.com/coopernurse/barrister/blob/0471b1d98d3327ba381684db496ec94c79c20848/barrister/docco.py#L312-L352 | train | Parses the IDL struct and returns a docco section for the given struct. |
coopernurse/barrister | barrister/docco.py | parse_interface | def parse_interface(iface):
"""
Returns a docco section for the given interface.
:Parameters:
iface
Parsed IDL interface dict. Keys: 'comment', 'name', 'returns', 'params'
"""
sections = [ ]
docs = iface['comment']
code = '<span class="k">interface</span> <span class="gs">%s</... | python | def parse_interface(iface):
"""
Returns a docco section for the given interface.
:Parameters:
iface
Parsed IDL interface dict. Keys: 'comment', 'name', 'returns', 'params'
"""
sections = [ ]
docs = iface['comment']
code = '<span class="k">interface</span> <span class="gs">%s</... | [
"def",
"parse_interface",
"(",
"iface",
")",
":",
"sections",
"=",
"[",
"]",
"docs",
"=",
"iface",
"[",
"'comment'",
"]",
"code",
"=",
"'<span class=\"k\">interface</span> <span class=\"gs\">%s</span> {\\n'",
"%",
"iface",
"[",
"'name'",
"]",
"for",
"v",
"in",
"... | Returns a docco section for the given interface.
:Parameters:
iface
Parsed IDL interface dict. Keys: 'comment', 'name', 'returns', 'params' | [
"Returns",
"a",
"docco",
"section",
"for",
"the",
"given",
"interface",
"."
] | 0471b1d98d3327ba381684db496ec94c79c20848 | https://github.com/coopernurse/barrister/blob/0471b1d98d3327ba381684db496ec94c79c20848/barrister/docco.py#L354-L383 | train | Parses the IDL interface dict and returns a list of docco sections for the given interface. |
coopernurse/barrister | barrister/docco.py | to_sections | def to_sections(idl_parsed):
"""
Iterates through elements in idl_parsed list and returns a list of section dicts.
Currently elements of type "comment", "enum", "struct", and "interface" are processed.
:Parameters:
idl_parsed
Barrister parsed IDL
"""
sections = []
for entity i... | python | def to_sections(idl_parsed):
"""
Iterates through elements in idl_parsed list and returns a list of section dicts.
Currently elements of type "comment", "enum", "struct", and "interface" are processed.
:Parameters:
idl_parsed
Barrister parsed IDL
"""
sections = []
for entity i... | [
"def",
"to_sections",
"(",
"idl_parsed",
")",
":",
"sections",
"=",
"[",
"]",
"for",
"entity",
"in",
"idl_parsed",
":",
"if",
"entity",
"[",
"\"type\"",
"]",
"==",
"\"comment\"",
":",
"sections",
".",
"append",
"(",
"to_section",
"(",
"entity",
"[",
"\"v... | Iterates through elements in idl_parsed list and returns a list of section dicts.
Currently elements of type "comment", "enum", "struct", and "interface" are processed.
:Parameters:
idl_parsed
Barrister parsed IDL | [
"Iterates",
"through",
"elements",
"in",
"idl_parsed",
"list",
"and",
"returns",
"a",
"list",
"of",
"section",
"dicts",
".",
"Currently",
"elements",
"of",
"type",
"comment",
"enum",
"struct",
"and",
"interface",
"are",
"processed",
"."
] | 0471b1d98d3327ba381684db496ec94c79c20848 | https://github.com/coopernurse/barrister/blob/0471b1d98d3327ba381684db496ec94c79c20848/barrister/docco.py#L411-L430 | train | Iterate through elements in idl_parsed list and returns a list of section dicts. |
PythonOptimizers/cygenja | cygenja/treemap/location_descriptor.py | LocationDescriptor.sub_location | def sub_location(self, nbr):
"""
Return a given sub location, 0-based.
Args:
nbr:
Returns:
"""
assert nbr > -1, "Sub location number must be greater or equal to 0!"
assert nbr < self.nbr_of_sub_locations() - 1, "Sub location number must be lower than... | python | def sub_location(self, nbr):
"""
Return a given sub location, 0-based.
Args:
nbr:
Returns:
"""
assert nbr > -1, "Sub location number must be greater or equal to 0!"
assert nbr < self.nbr_of_sub_locations() - 1, "Sub location number must be lower than... | [
"def",
"sub_location",
"(",
"self",
",",
"nbr",
")",
":",
"assert",
"nbr",
">",
"-",
"1",
",",
"\"Sub location number must be greater or equal to 0!\"",
"assert",
"nbr",
"<",
"self",
".",
"nbr_of_sub_locations",
"(",
")",
"-",
"1",
",",
"\"Sub location number must... | Return a given sub location, 0-based.
Args:
nbr:
Returns: | [
"Return",
"a",
"given",
"sub",
"location",
"0",
"-",
"based",
"."
] | a9ef91cdfa8452beeeec4f050f928b830379f91c | https://github.com/PythonOptimizers/cygenja/blob/a9ef91cdfa8452beeeec4f050f928b830379f91c/cygenja/treemap/location_descriptor.py#L119-L130 | train | Returns a given sub location 0 - based. |
PythonOptimizers/cygenja | cygenja/treemap/location_descriptor.py | LocationDescriptor.get_locations_list | def get_locations_list(self, lower_bound=0, upper_bound=None):
"""
Return the internal location list.
Args:
lower_bound:
upper_bound:
Returns:
"""
real_upper_bound = upper_bound
if upper_bound is None:
real_upper_bound = self.... | python | def get_locations_list(self, lower_bound=0, upper_bound=None):
"""
Return the internal location list.
Args:
lower_bound:
upper_bound:
Returns:
"""
real_upper_bound = upper_bound
if upper_bound is None:
real_upper_bound = self.... | [
"def",
"get_locations_list",
"(",
"self",
",",
"lower_bound",
"=",
"0",
",",
"upper_bound",
"=",
"None",
")",
":",
"real_upper_bound",
"=",
"upper_bound",
"if",
"upper_bound",
"is",
"None",
":",
"real_upper_bound",
"=",
"self",
".",
"nbr_of_sub_locations",
"(",
... | Return the internal location list.
Args:
lower_bound:
upper_bound:
Returns: | [
"Return",
"the",
"internal",
"location",
"list",
"."
] | a9ef91cdfa8452beeeec4f050f928b830379f91c | https://github.com/PythonOptimizers/cygenja/blob/a9ef91cdfa8452beeeec4f050f928b830379f91c/cygenja/treemap/location_descriptor.py#L132-L149 | train | Return the internal location list. |
PythonOptimizers/cygenja | cygenja/treemap/location_descriptor.py | LocationDescriptor.to_string | def to_string(self, other_separation_char=None):
"""
String representation of :class:`LocationDescriptor` object.
Args:
other_separation_char: If needed, another separator character can be used.
Returns:
"""
separation_char = self._separation_char
if... | python | def to_string(self, other_separation_char=None):
"""
String representation of :class:`LocationDescriptor` object.
Args:
other_separation_char: If needed, another separator character can be used.
Returns:
"""
separation_char = self._separation_char
if... | [
"def",
"to_string",
"(",
"self",
",",
"other_separation_char",
"=",
"None",
")",
":",
"separation_char",
"=",
"self",
".",
"_separation_char",
"if",
"other_separation_char",
"is",
"not",
"None",
":",
"separation_char",
"=",
"other_separation_char",
"return",
"separa... | String representation of :class:`LocationDescriptor` object.
Args:
other_separation_char: If needed, another separator character can be used.
Returns: | [
"String",
"representation",
"of",
":",
"class",
":",
"LocationDescriptor",
"object",
"."
] | a9ef91cdfa8452beeeec4f050f928b830379f91c | https://github.com/PythonOptimizers/cygenja/blob/a9ef91cdfa8452beeeec4f050f928b830379f91c/cygenja/treemap/location_descriptor.py#L241-L253 | train | Returns a string representation of the object. |
tweekmonster/moult | moult/ast_scanner.py | ast_value | def ast_value(val, scope, return_name=False):
'''Recursively parse out an AST value. This makes no attempt to load
modules or reconstruct functions on purpose. We do not want to
inadvertently call destructive code.
'''
# :TODO: refactor the hell out of this
try:
if isinstance(val, (ast... | python | def ast_value(val, scope, return_name=False):
'''Recursively parse out an AST value. This makes no attempt to load
modules or reconstruct functions on purpose. We do not want to
inadvertently call destructive code.
'''
# :TODO: refactor the hell out of this
try:
if isinstance(val, (ast... | [
"def",
"ast_value",
"(",
"val",
",",
"scope",
",",
"return_name",
"=",
"False",
")",
":",
"# :TODO: refactor the hell out of this",
"try",
":",
"if",
"isinstance",
"(",
"val",
",",
"(",
"ast",
".",
"Assign",
",",
"ast",
".",
"Delete",
")",
")",
":",
"if"... | Recursively parse out an AST value. This makes no attempt to load
modules or reconstruct functions on purpose. We do not want to
inadvertently call destructive code. | [
"Recursively",
"parse",
"out",
"an",
"AST",
"value",
".",
"This",
"makes",
"no",
"attempt",
"to",
"load",
"modules",
"or",
"reconstruct",
"functions",
"on",
"purpose",
".",
"We",
"do",
"not",
"want",
"to",
"inadvertently",
"call",
"destructive",
"code",
"."
... | 38d3a3b9002336219897ebe263ca1d8dcadbecf5 | https://github.com/tweekmonster/moult/blob/38d3a3b9002336219897ebe263ca1d8dcadbecf5/moult/ast_scanner.py#L22-L106 | train | Recursively parse out an AST value. |
tweekmonster/moult | moult/ast_scanner.py | get_args | def get_args(args, kwargs, arg_names):
'''Get arguments as a dict.
'''
n_args = len(arg_names)
if len(args) + len(kwargs) > n_args:
raise MoultScannerError('Too many arguments supplied. Expected: {}'.format(n_args))
out_args = {}
for i, a in enumerate(args):
out_args[arg_names[i... | python | def get_args(args, kwargs, arg_names):
'''Get arguments as a dict.
'''
n_args = len(arg_names)
if len(args) + len(kwargs) > n_args:
raise MoultScannerError('Too many arguments supplied. Expected: {}'.format(n_args))
out_args = {}
for i, a in enumerate(args):
out_args[arg_names[i... | [
"def",
"get_args",
"(",
"args",
",",
"kwargs",
",",
"arg_names",
")",
":",
"n_args",
"=",
"len",
"(",
"arg_names",
")",
"if",
"len",
"(",
"args",
")",
"+",
"len",
"(",
"kwargs",
")",
">",
"n_args",
":",
"raise",
"MoultScannerError",
"(",
"'Too many arg... | Get arguments as a dict. | [
"Get",
"arguments",
"as",
"a",
"dict",
"."
] | 38d3a3b9002336219897ebe263ca1d8dcadbecf5 | https://github.com/tweekmonster/moult/blob/38d3a3b9002336219897ebe263ca1d8dcadbecf5/moult/ast_scanner.py#L123-L139 | train | Get arguments as a dict.
|
tweekmonster/moult | moult/ast_scanner.py | ast_scan_file | def ast_scan_file(filename, re_fallback=True):
'''Scans a file for imports using AST.
In addition to normal imports, try to get imports via `__import__`
or `import_module` calls. The AST parser should be able to resolve
simple variable assignments in cases where these functions are called
with vari... | python | def ast_scan_file(filename, re_fallback=True):
'''Scans a file for imports using AST.
In addition to normal imports, try to get imports via `__import__`
or `import_module` calls. The AST parser should be able to resolve
simple variable assignments in cases where these functions are called
with vari... | [
"def",
"ast_scan_file",
"(",
"filename",
",",
"re_fallback",
"=",
"True",
")",
":",
"try",
":",
"with",
"io",
".",
"open",
"(",
"filename",
",",
"'rb'",
")",
"as",
"fp",
":",
"try",
":",
"root",
"=",
"ast",
".",
"parse",
"(",
"fp",
".",
"read",
"... | Scans a file for imports using AST.
In addition to normal imports, try to get imports via `__import__`
or `import_module` calls. The AST parser should be able to resolve
simple variable assignments in cases where these functions are called
with variables instead of strings. | [
"Scans",
"a",
"file",
"for",
"imports",
"using",
"AST",
"."
] | 38d3a3b9002336219897ebe263ca1d8dcadbecf5 | https://github.com/tweekmonster/moult/blob/38d3a3b9002336219897ebe263ca1d8dcadbecf5/moult/ast_scanner.py#L291-L319 | train | Scans a file for imports using AST. |
djaodjin/djaodjin-deployutils | deployutils/apps/django/backends/encrypted_cookies.py | SessionStore.prepare | def prepare(session_data={}, #pylint: disable=dangerous-default-value
passphrase=None):
"""
Returns *session_dict* as a base64 encrypted json string.
The full encrypted text is special crafted to be compatible
with openssl. It can be decrypted with:
$ echo _fu... | python | def prepare(session_data={}, #pylint: disable=dangerous-default-value
passphrase=None):
"""
Returns *session_dict* as a base64 encrypted json string.
The full encrypted text is special crafted to be compatible
with openssl. It can be decrypted with:
$ echo _fu... | [
"def",
"prepare",
"(",
"session_data",
"=",
"{",
"}",
",",
"#pylint: disable=dangerous-default-value",
"passphrase",
"=",
"None",
")",
":",
"if",
"passphrase",
"is",
"None",
":",
"passphrase",
"=",
"settings",
".",
"DJAODJIN_SECRET_KEY",
"encrypted",
"=",
"crypt",... | Returns *session_dict* as a base64 encrypted json string.
The full encrypted text is special crafted to be compatible
with openssl. It can be decrypted with:
$ echo _full_encypted_ | openssl aes-256-cbc -d -a -k _passphrase_ -p
salt=...
key=...
iv=...
... | [
"Returns",
"*",
"session_dict",
"*",
"as",
"a",
"base64",
"encrypted",
"json",
"string",
"."
] | a0fe3cf3030dbbf09025c69ce75a69b326565dd8 | https://github.com/djaodjin/djaodjin-deployutils/blob/a0fe3cf3030dbbf09025c69ce75a69b326565dd8/deployutils/apps/django/backends/encrypted_cookies.py#L60-L88 | train | Prepares the session_data to be used in the cookie. |
djaodjin/djaodjin-deployutils | deployutils/apps/django/backends/encrypted_cookies.py | SessionStore.load | def load(self):
"""
We load the data from the key itself instead of fetching from
some external data store. Opposite of _get_session_key(),
raises BadSignature if signature fails.
$ echo '_json_formatted_' | openssl aes-256-cbc -a -k _passphrase_ -p
salt=...
... | python | def load(self):
"""
We load the data from the key itself instead of fetching from
some external data store. Opposite of _get_session_key(),
raises BadSignature if signature fails.
$ echo '_json_formatted_' | openssl aes-256-cbc -a -k _passphrase_ -p
salt=...
... | [
"def",
"load",
"(",
"self",
")",
":",
"session_data",
"=",
"{",
"}",
"try",
":",
"session_text",
"=",
"crypt",
".",
"decrypt",
"(",
"self",
".",
"session_key",
",",
"passphrase",
"=",
"settings",
".",
"DJAODJIN_SECRET_KEY",
",",
"debug_stmt",
"=",
"\"encry... | We load the data from the key itself instead of fetching from
some external data store. Opposite of _get_session_key(),
raises BadSignature if signature fails.
$ echo '_json_formatted_' | openssl aes-256-cbc -a -k _passphrase_ -p
salt=...
key=...
iv=...
... | [
"We",
"load",
"the",
"data",
"from",
"the",
"key",
"itself",
"instead",
"of",
"fetching",
"from",
"some",
"external",
"data",
"store",
".",
"Opposite",
"of",
"_get_session_key",
"()",
"raises",
"BadSignature",
"if",
"signature",
"fails",
"."
] | a0fe3cf3030dbbf09025c69ce75a69b326565dd8 | https://github.com/djaodjin/djaodjin-deployutils/blob/a0fe3cf3030dbbf09025c69ce75a69b326565dd8/deployutils/apps/django/backends/encrypted_cookies.py#L90-L130 | train | Load the session data from the key itself if it is not already there. |
djaodjin/djaodjin-deployutils | deployutils/apps/flask/sessions.py | DjaoDjinSessionInterface.open_session | def open_session(self, app, request):
"""
We load the data from the key itself instead of fetching from
some external data store. Opposite of _get_session_key(),
raises BadSignature if signature fails.
$ echo '_json_formatted_' | openssl aes-256-cbc -a -k _passphrase_ -p
... | python | def open_session(self, app, request):
"""
We load the data from the key itself instead of fetching from
some external data store. Opposite of _get_session_key(),
raises BadSignature if signature fails.
$ echo '_json_formatted_' | openssl aes-256-cbc -a -k _passphrase_ -p
... | [
"def",
"open_session",
"(",
"self",
",",
"app",
",",
"request",
")",
":",
"session_key",
"=",
"request",
".",
"cookies",
".",
"get",
"(",
"app",
".",
"session_cookie_name",
")",
"if",
"not",
"session_key",
":",
"found",
"=",
"False",
"for",
"path",
"in",... | We load the data from the key itself instead of fetching from
some external data store. Opposite of _get_session_key(),
raises BadSignature if signature fails.
$ echo '_json_formatted_' | openssl aes-256-cbc -a -k _passphrase_ -p
salt=...
key=...
iv=...
... | [
"We",
"load",
"the",
"data",
"from",
"the",
"key",
"itself",
"instead",
"of",
"fetching",
"from",
"some",
"external",
"data",
"store",
".",
"Opposite",
"of",
"_get_session_key",
"()",
"raises",
"BadSignature",
"if",
"signature",
"fails",
"."
] | a0fe3cf3030dbbf09025c69ce75a69b326565dd8 | https://github.com/djaodjin/djaodjin-deployutils/blob/a0fe3cf3030dbbf09025c69ce75a69b326565dd8/deployutils/apps/flask/sessions.py#L73-L105 | train | Open the session from the key itself. |
DavidMStraub/pylha | pylha/export.py | dump | def dump(d, fmt='json', stream=None):
"""Serialize structured data into a stream in JSON, YAML, or LHA format.
If stream is None, return the produced string instead.
Parameters:
- fmt: should be 'json' (default), 'yaml', or 'lha'
- stream: if None, return string
"""
if fmt == 'json':
... | python | def dump(d, fmt='json', stream=None):
"""Serialize structured data into a stream in JSON, YAML, or LHA format.
If stream is None, return the produced string instead.
Parameters:
- fmt: should be 'json' (default), 'yaml', or 'lha'
- stream: if None, return string
"""
if fmt == 'json':
... | [
"def",
"dump",
"(",
"d",
",",
"fmt",
"=",
"'json'",
",",
"stream",
"=",
"None",
")",
":",
"if",
"fmt",
"==",
"'json'",
":",
"return",
"_dump_json",
"(",
"d",
",",
"stream",
"=",
"stream",
")",
"elif",
"fmt",
"==",
"'yaml'",
":",
"return",
"yaml",
... | Serialize structured data into a stream in JSON, YAML, or LHA format.
If stream is None, return the produced string instead.
Parameters:
- fmt: should be 'json' (default), 'yaml', or 'lha'
- stream: if None, return string | [
"Serialize",
"structured",
"data",
"into",
"a",
"stream",
"in",
"JSON",
"YAML",
"or",
"LHA",
"format",
".",
"If",
"stream",
"is",
"None",
"return",
"the",
"produced",
"string",
"instead",
"."
] | 8d65074609321e5eaf97fe962c56f6d79a3ad2b6 | https://github.com/DavidMStraub/pylha/blob/8d65074609321e5eaf97fe962c56f6d79a3ad2b6/pylha/export.py#L13-L30 | train | Serialize structured data into a stream in JSON YAML or LHA format. |
mintchaos/django_inlines | django_inlines/inlines.py | parse_inline | def parse_inline(text):
"""
Takes a string of text from a text inline and returns a 3 tuple of
(name, value, **kwargs).
"""
m = INLINE_SPLITTER.match(text)
if not m:
raise InlineUnparsableError
args = m.group('args')
name = m.group('name')
value = ""
kwtxt = ""
kwarg... | python | def parse_inline(text):
"""
Takes a string of text from a text inline and returns a 3 tuple of
(name, value, **kwargs).
"""
m = INLINE_SPLITTER.match(text)
if not m:
raise InlineUnparsableError
args = m.group('args')
name = m.group('name')
value = ""
kwtxt = ""
kwarg... | [
"def",
"parse_inline",
"(",
"text",
")",
":",
"m",
"=",
"INLINE_SPLITTER",
".",
"match",
"(",
"text",
")",
"if",
"not",
"m",
":",
"raise",
"InlineUnparsableError",
"args",
"=",
"m",
".",
"group",
"(",
"'args'",
")",
"name",
"=",
"m",
".",
"group",
"(... | Takes a string of text from a text inline and returns a 3 tuple of
(name, value, **kwargs). | [
"Takes",
"a",
"string",
"of",
"text",
"from",
"a",
"text",
"inline",
"and",
"returns",
"a",
"3",
"tuple",
"of",
"(",
"name",
"value",
"**",
"kwargs",
")",
"."
] | 1912e508d04884713a6c44a068c21fbd217d478a | https://github.com/mintchaos/django_inlines/blob/1912e508d04884713a6c44a068c21fbd217d478a/django_inlines/inlines.py#L41-L65 | train | Takes a string of text from a text inline and returns a 3 tuple of name value kwargs. |
mintchaos/django_inlines | django_inlines/inlines.py | inline_for_model | def inline_for_model(model, variants=[], inline_args={}):
"""
A shortcut function to produce ModelInlines for django models
"""
if not isinstance(model, ModelBase):
raise ValueError("inline_for_model requires it's argument to be a Django Model")
d = dict(model=model)
if variants:
... | python | def inline_for_model(model, variants=[], inline_args={}):
"""
A shortcut function to produce ModelInlines for django models
"""
if not isinstance(model, ModelBase):
raise ValueError("inline_for_model requires it's argument to be a Django Model")
d = dict(model=model)
if variants:
... | [
"def",
"inline_for_model",
"(",
"model",
",",
"variants",
"=",
"[",
"]",
",",
"inline_args",
"=",
"{",
"}",
")",
":",
"if",
"not",
"isinstance",
"(",
"model",
",",
"ModelBase",
")",
":",
"raise",
"ValueError",
"(",
"\"inline_for_model requires it's argument to... | A shortcut function to produce ModelInlines for django models | [
"A",
"shortcut",
"function",
"to",
"produce",
"ModelInlines",
"for",
"django",
"models"
] | 1912e508d04884713a6c44a068c21fbd217d478a | https://github.com/mintchaos/django_inlines/blob/1912e508d04884713a6c44a068c21fbd217d478a/django_inlines/inlines.py#L68-L81 | train | A shortcut function to produce ModelInlines for django models |
romanorac/discomll | discomll/regression/locally_weighted_linear_regression.py | fit_predict | def fit_predict(training_data, fitting_data, tau=1, samples_per_job=0, save_results=True, show=False):
from disco.worker.pipeline.worker import Worker, Stage
from disco.core import Job, result_iterator
from disco.core import Disco
"""
training_data - training samples
fitting_data - dataset to b... | python | def fit_predict(training_data, fitting_data, tau=1, samples_per_job=0, save_results=True, show=False):
from disco.worker.pipeline.worker import Worker, Stage
from disco.core import Job, result_iterator
from disco.core import Disco
"""
training_data - training samples
fitting_data - dataset to b... | [
"def",
"fit_predict",
"(",
"training_data",
",",
"fitting_data",
",",
"tau",
"=",
"1",
",",
"samples_per_job",
"=",
"0",
",",
"save_results",
"=",
"True",
",",
"show",
"=",
"False",
")",
":",
"from",
"disco",
".",
"worker",
".",
"pipeline",
".",
"worker"... | training_data - training samples
fitting_data - dataset to be fitted to training data.
tau - controls how quickly the weight of a training sample falls off with distance of its x(i) from the query point x.
samples_per_job - define a number of samples that will be processed in single mapreduce job. If 0, alg... | [
"training_data",
"-",
"training",
"samples",
"fitting_data",
"-",
"dataset",
"to",
"be",
"fitted",
"to",
"training",
"data",
".",
"tau",
"-",
"controls",
"how",
"quickly",
"the",
"weight",
"of",
"a",
"training",
"sample",
"falls",
"off",
"with",
"distance",
... | a4703daffb2ba3c9f614bc3dbe45ae55884aea00 | https://github.com/romanorac/discomll/blob/a4703daffb2ba3c9f614bc3dbe45ae55884aea00/discomll/regression/locally_weighted_linear_regression.py#L83-L139 | train | Fit a predict on the training data and return the result. |
openearth/mmi-python | mmi/runner.py | Runner.initialize_mpi | def initialize_mpi(mpi=False):
"""initialize mpi settings"""
if mpi:
import mpi4py.MPI
comm = mpi4py.MPI.COMM_WORLD
rank = comm.Get_rank()
size = comm.Get_size()
else:
comm = None
rank = 0
size = 1
return... | python | def initialize_mpi(mpi=False):
"""initialize mpi settings"""
if mpi:
import mpi4py.MPI
comm = mpi4py.MPI.COMM_WORLD
rank = comm.Get_rank()
size = comm.Get_size()
else:
comm = None
rank = 0
size = 1
return... | [
"def",
"initialize_mpi",
"(",
"mpi",
"=",
"False",
")",
":",
"if",
"mpi",
":",
"import",
"mpi4py",
".",
"MPI",
"comm",
"=",
"mpi4py",
".",
"MPI",
".",
"COMM_WORLD",
"rank",
"=",
"comm",
".",
"Get_rank",
"(",
")",
"size",
"=",
"comm",
".",
"Get_size",... | initialize mpi settings | [
"initialize",
"mpi",
"settings"
] | a2f4ac96b1e7f2fa903f668b3e05c4e86ad42e8d | https://github.com/openearth/mmi-python/blob/a2f4ac96b1e7f2fa903f668b3e05c4e86ad42e8d/mmi/runner.py#L73-L89 | train | initialize mpi settings |
openearth/mmi-python | mmi/runner.py | Runner.create_ports | def create_ports(port, mpi, rank):
"""create a list of ports for the current rank"""
if port == "random" or port is None:
# ports will be filled in using random binding
ports = {}
else:
port = int(port)
ports = {
"REQ": port + 0,
... | python | def create_ports(port, mpi, rank):
"""create a list of ports for the current rank"""
if port == "random" or port is None:
# ports will be filled in using random binding
ports = {}
else:
port = int(port)
ports = {
"REQ": port + 0,
... | [
"def",
"create_ports",
"(",
"port",
",",
"mpi",
",",
"rank",
")",
":",
"if",
"port",
"==",
"\"random\"",
"or",
"port",
"is",
"None",
":",
"# ports will be filled in using random binding",
"ports",
"=",
"{",
"}",
"else",
":",
"port",
"=",
"int",
"(",
"port"... | create a list of ports for the current rank | [
"create",
"a",
"list",
"of",
"ports",
"for",
"the",
"current",
"rank"
] | a2f4ac96b1e7f2fa903f668b3e05c4e86ad42e8d | https://github.com/openearth/mmi-python/blob/a2f4ac96b1e7f2fa903f668b3e05c4e86ad42e8d/mmi/runner.py#L92-L110 | train | create a list of ports for the current rank |
openearth/mmi-python | mmi/runner.py | Runner.import_from_string | def import_from_string(full_class_name):
"""return a class based on it's full class name"""
s = full_class_name.split('.')
class_name = s[-1]
module_name = full_class_name[:-len(class_name)-1]
module = importlib.import_module(module_name)
# the class, it's common to spell... | python | def import_from_string(full_class_name):
"""return a class based on it's full class name"""
s = full_class_name.split('.')
class_name = s[-1]
module_name = full_class_name[:-len(class_name)-1]
module = importlib.import_module(module_name)
# the class, it's common to spell... | [
"def",
"import_from_string",
"(",
"full_class_name",
")",
":",
"s",
"=",
"full_class_name",
".",
"split",
"(",
"'.'",
")",
"class_name",
"=",
"s",
"[",
"-",
"1",
"]",
"module_name",
"=",
"full_class_name",
"[",
":",
"-",
"len",
"(",
"class_name",
")",
"-... | return a class based on it's full class name | [
"return",
"a",
"class",
"based",
"on",
"it",
"s",
"full",
"class",
"name"
] | a2f4ac96b1e7f2fa903f668b3e05c4e86ad42e8d | https://github.com/openearth/mmi-python/blob/a2f4ac96b1e7f2fa903f668b3e05c4e86ad42e8d/mmi/runner.py#L113-L121 | train | import a class based on it s full class name |
openearth/mmi-python | mmi/runner.py | Runner.create_bmi_model | def create_bmi_model(self, engine, bmi_class=None, wrapper_kwargs=None):
"""initialize a bmi mode using an optional class"""
if wrapper_kwargs is None:
wrapper_kwargs = {}
if bmi_class is None:
wrapper_class = bmi.wrapper.BMIWrapper
else:
wrapper_class... | python | def create_bmi_model(self, engine, bmi_class=None, wrapper_kwargs=None):
"""initialize a bmi mode using an optional class"""
if wrapper_kwargs is None:
wrapper_kwargs = {}
if bmi_class is None:
wrapper_class = bmi.wrapper.BMIWrapper
else:
wrapper_class... | [
"def",
"create_bmi_model",
"(",
"self",
",",
"engine",
",",
"bmi_class",
"=",
"None",
",",
"wrapper_kwargs",
"=",
"None",
")",
":",
"if",
"wrapper_kwargs",
"is",
"None",
":",
"wrapper_kwargs",
"=",
"{",
"}",
"if",
"bmi_class",
"is",
"None",
":",
"wrapper_c... | initialize a bmi mode using an optional class | [
"initialize",
"a",
"bmi",
"mode",
"using",
"an",
"optional",
"class"
] | a2f4ac96b1e7f2fa903f668b3e05c4e86ad42e8d | https://github.com/openearth/mmi-python/blob/a2f4ac96b1e7f2fa903f668b3e05c4e86ad42e8d/mmi/runner.py#L123-L146 | train | create a bmi model using an optional class |
openearth/mmi-python | mmi/runner.py | Runner.register | def register(self):
"""register model at tracking server"""
# connect to tracker
result = requests.post(urljoin(self.tracker, 'models'), data=json.dumps(self.metadata))
logger.debug("registered at server %s: %s", self.tracker, result)
self.metadata["tracker"] = result.json() | python | def register(self):
"""register model at tracking server"""
# connect to tracker
result = requests.post(urljoin(self.tracker, 'models'), data=json.dumps(self.metadata))
logger.debug("registered at server %s: %s", self.tracker, result)
self.metadata["tracker"] = result.json() | [
"def",
"register",
"(",
"self",
")",
":",
"# connect to tracker",
"result",
"=",
"requests",
".",
"post",
"(",
"urljoin",
"(",
"self",
".",
"tracker",
",",
"'models'",
")",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"self",
".",
"metadata",
")",
")",... | register model at tracking server | [
"register",
"model",
"at",
"tracking",
"server"
] | a2f4ac96b1e7f2fa903f668b3e05c4e86ad42e8d | https://github.com/openearth/mmi-python/blob/a2f4ac96b1e7f2fa903f668b3e05c4e86ad42e8d/mmi/runner.py#L148-L153 | train | register model at tracking server |
openearth/mmi-python | mmi/runner.py | Runner.unregister | def unregister(self):
"""unregister model at tracking server"""
uuid = self.metadata["tracker"]["uuid"]
# connect to server
result = requests.delete(urljoin(self.tracker, 'models' + "/" + uuid))
logger.debug("unregistered at server %s with %s: %s", self.tracker, uuid, result) | python | def unregister(self):
"""unregister model at tracking server"""
uuid = self.metadata["tracker"]["uuid"]
# connect to server
result = requests.delete(urljoin(self.tracker, 'models' + "/" + uuid))
logger.debug("unregistered at server %s with %s: %s", self.tracker, uuid, result) | [
"def",
"unregister",
"(",
"self",
")",
":",
"uuid",
"=",
"self",
".",
"metadata",
"[",
"\"tracker\"",
"]",
"[",
"\"uuid\"",
"]",
"# connect to server",
"result",
"=",
"requests",
".",
"delete",
"(",
"urljoin",
"(",
"self",
".",
"tracker",
",",
"'models'",
... | unregister model at tracking server | [
"unregister",
"model",
"at",
"tracking",
"server"
] | a2f4ac96b1e7f2fa903f668b3e05c4e86ad42e8d | https://github.com/openearth/mmi-python/blob/a2f4ac96b1e7f2fa903f668b3e05c4e86ad42e8d/mmi/runner.py#L155-L160 | train | unregister model at tracking server |
openearth/mmi-python | mmi/runner.py | Runner.process_incoming | def process_incoming(self):
"""
process incoming messages
data is a dict with several arrays
"""
model = self.model
sockets = self.sockets
# Check for new messages
if not sockets:
return
# unpack sockets
poller = sockets['pol... | python | def process_incoming(self):
"""
process incoming messages
data is a dict with several arrays
"""
model = self.model
sockets = self.sockets
# Check for new messages
if not sockets:
return
# unpack sockets
poller = sockets['pol... | [
"def",
"process_incoming",
"(",
"self",
")",
":",
"model",
"=",
"self",
".",
"model",
"sockets",
"=",
"self",
".",
"sockets",
"# Check for new messages",
"if",
"not",
"sockets",
":",
"return",
"# unpack sockets",
"poller",
"=",
"sockets",
"[",
"'poller'",
"]",... | process incoming messages
data is a dict with several arrays | [
"process",
"incoming",
"messages"
] | a2f4ac96b1e7f2fa903f668b3e05c4e86ad42e8d | https://github.com/openearth/mmi-python/blob/a2f4ac96b1e7f2fa903f668b3e05c4e86ad42e8d/mmi/runner.py#L186-L327 | train | process incoming messages and return a dict with the data. |
openearth/mmi-python | mmi/runner.py | Runner.create_sockets | def create_sockets(self):
"""create zmq sockets"""
ports = self.ports
context = zmq.Context()
poller = zmq.Poller()
# Socket to handle init data
rep = context.socket(zmq.REP)
# this was inconsequent: here REQ is for the client, we reply with REP.
# PULL... | python | def create_sockets(self):
"""create zmq sockets"""
ports = self.ports
context = zmq.Context()
poller = zmq.Poller()
# Socket to handle init data
rep = context.socket(zmq.REP)
# this was inconsequent: here REQ is for the client, we reply with REP.
# PULL... | [
"def",
"create_sockets",
"(",
"self",
")",
":",
"ports",
"=",
"self",
".",
"ports",
"context",
"=",
"zmq",
".",
"Context",
"(",
")",
"poller",
"=",
"zmq",
".",
"Poller",
"(",
")",
"# Socket to handle init data",
"rep",
"=",
"context",
".",
"socket",
"(",... | create zmq sockets | [
"create",
"zmq",
"sockets"
] | a2f4ac96b1e7f2fa903f668b3e05c4e86ad42e8d | https://github.com/openearth/mmi-python/blob/a2f4ac96b1e7f2fa903f668b3e05c4e86ad42e8d/mmi/runner.py#L329-L381 | train | create zmq sockets |
openearth/mmi-python | mmi/runner.py | Runner.run | def run(self):
"""run the model"""
model = self.model
configfile = self.configfile
interval = self.interval
sockets = self.sockets
model.initialize(configfile)
if model.state == 'pause':
logger.info(
"model initialized and started in ... | python | def run(self):
"""run the model"""
model = self.model
configfile = self.configfile
interval = self.interval
sockets = self.sockets
model.initialize(configfile)
if model.state == 'pause':
logger.info(
"model initialized and started in ... | [
"def",
"run",
"(",
"self",
")",
":",
"model",
"=",
"self",
".",
"model",
"configfile",
"=",
"self",
".",
"configfile",
"interval",
"=",
"self",
".",
"interval",
"sockets",
"=",
"self",
".",
"sockets",
"model",
".",
"initialize",
"(",
"configfile",
")",
... | run the model | [
"run",
"the",
"model"
] | a2f4ac96b1e7f2fa903f668b3e05c4e86ad42e8d | https://github.com/openearth/mmi-python/blob/a2f4ac96b1e7f2fa903f668b3e05c4e86ad42e8d/mmi/runner.py#L383-L436 | train | run the model |
acutesoftware/virtual-AI-simulator | vais/z_prototypes/calc_building_design.py | calc_basics | def calc_basics(width=-1, length=-1, height=2.4, prevailing_wind=2.8):
"""
calculate various aspects of the structure
"""
if width == -1:
width = int(input('enter building width : '))
if length == -1:
length = int(input('enter building length : '))
res = {}
res['area... | python | def calc_basics(width=-1, length=-1, height=2.4, prevailing_wind=2.8):
"""
calculate various aspects of the structure
"""
if width == -1:
width = int(input('enter building width : '))
if length == -1:
length = int(input('enter building length : '))
res = {}
res['area... | [
"def",
"calc_basics",
"(",
"width",
"=",
"-",
"1",
",",
"length",
"=",
"-",
"1",
",",
"height",
"=",
"2.4",
",",
"prevailing_wind",
"=",
"2.8",
")",
":",
"if",
"width",
"==",
"-",
"1",
":",
"width",
"=",
"int",
"(",
"input",
"(",
"'enter building w... | calculate various aspects of the structure | [
"calculate",
"various",
"aspects",
"of",
"the",
"structure"
] | 57de679a5b1a58c38fefe6aea58af1f3a7e79c58 | https://github.com/acutesoftware/virtual-AI-simulator/blob/57de679a5b1a58c38fefe6aea58af1f3a7e79c58/vais/z_prototypes/calc_building_design.py#L29-L44 | train | Calculate various aspects of the structure
|
acutesoftware/virtual-AI-simulator | vais/z_prototypes/calc_building_design.py | bld_rafter_deflection | def bld_rafter_deflection(length=-9, force=-9, E_mod_elasticity=-9, I_moment_of_intertia=-9):
"""
calculate rafter deflections - see test_calc_building_design.py for
Sample values for equations below from Structures II course
"""
if length == -9:
length = float(input('enter rafter... | python | def bld_rafter_deflection(length=-9, force=-9, E_mod_elasticity=-9, I_moment_of_intertia=-9):
"""
calculate rafter deflections - see test_calc_building_design.py for
Sample values for equations below from Structures II course
"""
if length == -9:
length = float(input('enter rafter... | [
"def",
"bld_rafter_deflection",
"(",
"length",
"=",
"-",
"9",
",",
"force",
"=",
"-",
"9",
",",
"E_mod_elasticity",
"=",
"-",
"9",
",",
"I_moment_of_intertia",
"=",
"-",
"9",
")",
":",
"if",
"length",
"==",
"-",
"9",
":",
"length",
"=",
"float",
"(",... | calculate rafter deflections - see test_calc_building_design.py for
Sample values for equations below from Structures II course | [
"calculate",
"rafter",
"deflections",
"-",
"see",
"test_calc_building_design",
".",
"py",
"for",
"Sample",
"values",
"for",
"equations",
"below",
"from",
"Structures",
"II",
"course"
] | 57de679a5b1a58c38fefe6aea58af1f3a7e79c58 | https://github.com/acutesoftware/virtual-AI-simulator/blob/57de679a5b1a58c38fefe6aea58af1f3a7e79c58/vais/z_prototypes/calc_building_design.py#L47-L72 | train | calculate rafter deflections |
The-Politico/politico-civic-election-night | electionnight/serializers/body.py | BodySerializer.get_division | def get_division(self, obj):
"""Division."""
if self.context.get("division"):
return DivisionSerializer(self.context.get("division")).data
else:
if obj.slug == "senate":
return DivisionSerializer(obj.jurisdiction.division).data
else:
... | python | def get_division(self, obj):
"""Division."""
if self.context.get("division"):
return DivisionSerializer(self.context.get("division")).data
else:
if obj.slug == "senate":
return DivisionSerializer(obj.jurisdiction.division).data
else:
... | [
"def",
"get_division",
"(",
"self",
",",
"obj",
")",
":",
"if",
"self",
".",
"context",
".",
"get",
"(",
"\"division\"",
")",
":",
"return",
"DivisionSerializer",
"(",
"self",
".",
"context",
".",
"get",
"(",
"\"division\"",
")",
")",
".",
"data",
"els... | Division. | [
"Division",
"."
] | a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6 | https://github.com/The-Politico/politico-civic-election-night/blob/a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6/electionnight/serializers/body.py#L35-L53 | train | Returns a list of all the states in the division. |
The-Politico/politico-civic-election-night | electionnight/serializers/body.py | BodySerializer.get_parties | def get_parties(self, obj):
"""All parties."""
return PartySerializer(Party.objects.all(), many=True).data | python | def get_parties(self, obj):
"""All parties."""
return PartySerializer(Party.objects.all(), many=True).data | [
"def",
"get_parties",
"(",
"self",
",",
"obj",
")",
":",
"return",
"PartySerializer",
"(",
"Party",
".",
"objects",
".",
"all",
"(",
")",
",",
"many",
"=",
"True",
")",
".",
"data"
] | All parties. | [
"All",
"parties",
"."
] | a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6 | https://github.com/The-Politico/politico-civic-election-night/blob/a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6/electionnight/serializers/body.py#L55-L57 | train | Get all parties for the given object. |
The-Politico/politico-civic-election-night | electionnight/serializers/body.py | BodySerializer.get_elections | def get_elections(self, obj):
"""All elections held on an election day."""
election_day = ElectionDay.objects.get(
date=self.context["election_date"]
)
kwargs = {"race__office__body": obj, "election_day": election_day}
if self.context.get("division") and obj.slug == ... | python | def get_elections(self, obj):
"""All elections held on an election day."""
election_day = ElectionDay.objects.get(
date=self.context["election_date"]
)
kwargs = {"race__office__body": obj, "election_day": election_day}
if self.context.get("division") and obj.slug == ... | [
"def",
"get_elections",
"(",
"self",
",",
"obj",
")",
":",
"election_day",
"=",
"ElectionDay",
".",
"objects",
".",
"get",
"(",
"date",
"=",
"self",
".",
"context",
"[",
"\"election_date\"",
"]",
")",
"kwargs",
"=",
"{",
"\"race__office__body\"",
":",
"obj... | All elections held on an election day. | [
"All",
"elections",
"held",
"on",
"an",
"election",
"day",
"."
] | a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6 | https://github.com/The-Politico/politico-civic-election-night/blob/a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6/electionnight/serializers/body.py#L59-L75 | train | All elections held on an election day. |
VIVelev/PyDojoML | dojo/metrics/classification.py | accuracy_score | def accuracy_score(y, y_pred):
"""Calculates the fraction of the correctly
classified samples over all.
Parameters:
-----------
y : vector, shape (n_samples,)
The target labels.
y_pred : vector, shape (n_samples,)
The predicted labels.
Returns:
--------
accuracy : ... | python | def accuracy_score(y, y_pred):
"""Calculates the fraction of the correctly
classified samples over all.
Parameters:
-----------
y : vector, shape (n_samples,)
The target labels.
y_pred : vector, shape (n_samples,)
The predicted labels.
Returns:
--------
accuracy : ... | [
"def",
"accuracy_score",
"(",
"y",
",",
"y_pred",
")",
":",
"y",
",",
"y_pred",
"=",
"convert_assert",
"(",
"y",
",",
"y_pred",
")",
"return",
"np",
".",
"count_nonzero",
"(",
"y",
"==",
"y_pred",
")",
"/",
"y",
".",
"size"
] | Calculates the fraction of the correctly
classified samples over all.
Parameters:
-----------
y : vector, shape (n_samples,)
The target labels.
y_pred : vector, shape (n_samples,)
The predicted labels.
Returns:
--------
accuracy : float number, the fraction
of the ... | [
"Calculates",
"the",
"fraction",
"of",
"the",
"correctly",
"classified",
"samples",
"over",
"all",
".",
"Parameters",
":",
"-----------",
"y",
":",
"vector",
"shape",
"(",
"n_samples",
")",
"The",
"target",
"labels",
"."
] | 773fdce6866aa6decd306a5a85f94129fed816eb | https://github.com/VIVelev/PyDojoML/blob/773fdce6866aa6decd306a5a85f94129fed816eb/dojo/metrics/classification.py#L21-L41 | train | Calculates the fraction of the correctly classified samples over all. |
VIVelev/PyDojoML | dojo/metrics/classification.py | true_positives | def true_positives(y, y_pred):
"""True-positives
Parameters:
-----------
y : vector, shape (n_samples,)
The target labels.
y_pred : vector, shape (n_samples,)
The predicted labels.
Returns:
--------
tp : integer, the number of true-positives
"""
y, y_pred... | python | def true_positives(y, y_pred):
"""True-positives
Parameters:
-----------
y : vector, shape (n_samples,)
The target labels.
y_pred : vector, shape (n_samples,)
The predicted labels.
Returns:
--------
tp : integer, the number of true-positives
"""
y, y_pred... | [
"def",
"true_positives",
"(",
"y",
",",
"y_pred",
")",
":",
"y",
",",
"y_pred",
"=",
"convert_assert",
"(",
"y",
",",
"y_pred",
")",
"assert_binary_problem",
"(",
"y",
")",
"return",
"np",
".",
"count_nonzero",
"(",
"y_pred",
"[",
"y",
"==",
"1",
"]",
... | True-positives
Parameters:
-----------
y : vector, shape (n_samples,)
The target labels.
y_pred : vector, shape (n_samples,)
The predicted labels.
Returns:
--------
tp : integer, the number of true-positives | [
"True",
"-",
"positives",
"Parameters",
":",
"-----------",
"y",
":",
"vector",
"shape",
"(",
"n_samples",
")",
"The",
"target",
"labels",
"."
] | 773fdce6866aa6decd306a5a85f94129fed816eb | https://github.com/VIVelev/PyDojoML/blob/773fdce6866aa6decd306a5a85f94129fed816eb/dojo/metrics/classification.py#L49-L69 | train | Returns the number of true positives in the base node. |
VIVelev/PyDojoML | dojo/metrics/classification.py | false_positives | def false_positives(y, y_pred):
"""False-positives
Parameters:
-----------
y : vector, shape (n_samples,)
The target labels.
y_pred : vector, shape (n_samples,)
The predicted labels.
Returns:
--------
fp : integer, the number of false-positives
"""
y, y_p... | python | def false_positives(y, y_pred):
"""False-positives
Parameters:
-----------
y : vector, shape (n_samples,)
The target labels.
y_pred : vector, shape (n_samples,)
The predicted labels.
Returns:
--------
fp : integer, the number of false-positives
"""
y, y_p... | [
"def",
"false_positives",
"(",
"y",
",",
"y_pred",
")",
":",
"y",
",",
"y_pred",
"=",
"convert_assert",
"(",
"y",
",",
"y_pred",
")",
"assert_binary_problem",
"(",
"y",
")",
"return",
"np",
".",
"count_nonzero",
"(",
"y_pred",
"[",
"y",
"==",
"0",
"]",... | False-positives
Parameters:
-----------
y : vector, shape (n_samples,)
The target labels.
y_pred : vector, shape (n_samples,)
The predicted labels.
Returns:
--------
fp : integer, the number of false-positives | [
"False",
"-",
"positives",
"Parameters",
":",
"-----------",
"y",
":",
"vector",
"shape",
"(",
"n_samples",
")",
"The",
"target",
"labels",
"."
] | 773fdce6866aa6decd306a5a85f94129fed816eb | https://github.com/VIVelev/PyDojoML/blob/773fdce6866aa6decd306a5a85f94129fed816eb/dojo/metrics/classification.py#L73-L93 | train | Returns the number of false positives in the base node. |
VIVelev/PyDojoML | dojo/metrics/classification.py | true_negatives | def true_negatives(y, y_pred):
"""True-negatives
Parameters:
-----------
y : vector, shape (n_samples,)
The target labels.
y_pred : vector, shape (n_samples,)
The predicted labels.
Returns:
--------
tn : integer, the number of true-negatives
"""
y, y_pred... | python | def true_negatives(y, y_pred):
"""True-negatives
Parameters:
-----------
y : vector, shape (n_samples,)
The target labels.
y_pred : vector, shape (n_samples,)
The predicted labels.
Returns:
--------
tn : integer, the number of true-negatives
"""
y, y_pred... | [
"def",
"true_negatives",
"(",
"y",
",",
"y_pred",
")",
":",
"y",
",",
"y_pred",
"=",
"convert_assert",
"(",
"y",
",",
"y_pred",
")",
"assert_binary_problem",
"(",
"y",
")",
"return",
"np",
".",
"count_nonzero",
"(",
"y_pred",
"[",
"y",
"==",
"0",
"]",
... | True-negatives
Parameters:
-----------
y : vector, shape (n_samples,)
The target labels.
y_pred : vector, shape (n_samples,)
The predicted labels.
Returns:
--------
tn : integer, the number of true-negatives | [
"True",
"-",
"negatives",
"Parameters",
":",
"-----------",
"y",
":",
"vector",
"shape",
"(",
"n_samples",
")",
"The",
"target",
"labels",
"."
] | 773fdce6866aa6decd306a5a85f94129fed816eb | https://github.com/VIVelev/PyDojoML/blob/773fdce6866aa6decd306a5a85f94129fed816eb/dojo/metrics/classification.py#L97-L117 | train | Returns the number of true negatives in the base node. |
VIVelev/PyDojoML | dojo/metrics/classification.py | false_negatives | def false_negatives(y, y_pred):
"""False-negatives
Parameters:
-----------
y : vector, shape (n_samples,)
The target labels.
y_pred : vector, shape (n_samples,)
The predicted labels.
Returns:
--------
fn : integer, the number of false-negatives
"""
y, y_p... | python | def false_negatives(y, y_pred):
"""False-negatives
Parameters:
-----------
y : vector, shape (n_samples,)
The target labels.
y_pred : vector, shape (n_samples,)
The predicted labels.
Returns:
--------
fn : integer, the number of false-negatives
"""
y, y_p... | [
"def",
"false_negatives",
"(",
"y",
",",
"y_pred",
")",
":",
"y",
",",
"y_pred",
"=",
"convert_assert",
"(",
"y",
",",
"y_pred",
")",
"assert_binary_problem",
"(",
"y",
")",
"return",
"np",
".",
"count_nonzero",
"(",
"y_pred",
"[",
"y",
"==",
"1",
"]",... | False-negatives
Parameters:
-----------
y : vector, shape (n_samples,)
The target labels.
y_pred : vector, shape (n_samples,)
The predicted labels.
Returns:
--------
fn : integer, the number of false-negatives | [
"False",
"-",
"negatives",
"Parameters",
":",
"-----------",
"y",
":",
"vector",
"shape",
"(",
"n_samples",
")",
"The",
"target",
"labels",
"."
] | 773fdce6866aa6decd306a5a85f94129fed816eb | https://github.com/VIVelev/PyDojoML/blob/773fdce6866aa6decd306a5a85f94129fed816eb/dojo/metrics/classification.py#L121-L141 | train | Returns the number of false negatives in the base node. |
VIVelev/PyDojoML | dojo/metrics/classification.py | precision | def precision(y, y_pred):
"""Precision score
precision = true_positives / (true_positives + false_positives)
Parameters:
-----------
y : vector, shape (n_samples,)
The target labels.
y_pred : vector, shape (n_samples,)
The predicted labels.
Returns:
--------
preci... | python | def precision(y, y_pred):
"""Precision score
precision = true_positives / (true_positives + false_positives)
Parameters:
-----------
y : vector, shape (n_samples,)
The target labels.
y_pred : vector, shape (n_samples,)
The predicted labels.
Returns:
--------
preci... | [
"def",
"precision",
"(",
"y",
",",
"y_pred",
")",
":",
"tp",
"=",
"true_positives",
"(",
"y",
",",
"y_pred",
")",
"fp",
"=",
"false_positives",
"(",
"y",
",",
"y_pred",
")",
"return",
"tp",
"/",
"(",
"tp",
"+",
"fp",
")"
] | Precision score
precision = true_positives / (true_positives + false_positives)
Parameters:
-----------
y : vector, shape (n_samples,)
The target labels.
y_pred : vector, shape (n_samples,)
The predicted labels.
Returns:
--------
precision : float | [
"Precision",
"score"
] | 773fdce6866aa6decd306a5a85f94129fed816eb | https://github.com/VIVelev/PyDojoML/blob/773fdce6866aa6decd306a5a85f94129fed816eb/dojo/metrics/classification.py#L145-L166 | train | Precision score of the target labels y and y_pred. |
VIVelev/PyDojoML | dojo/metrics/classification.py | recall | def recall(y, y_pred):
"""Recall score
recall = true_positives / (true_positives + false_negatives)
Parameters:
-----------
y : vector, shape (n_samples,)
The target labels.
y_pred : vector, shape (n_samples,)
The predicted labels.
Returns:
--------
recall : float... | python | def recall(y, y_pred):
"""Recall score
recall = true_positives / (true_positives + false_negatives)
Parameters:
-----------
y : vector, shape (n_samples,)
The target labels.
y_pred : vector, shape (n_samples,)
The predicted labels.
Returns:
--------
recall : float... | [
"def",
"recall",
"(",
"y",
",",
"y_pred",
")",
":",
"tp",
"=",
"true_positives",
"(",
"y",
",",
"y_pred",
")",
"fn",
"=",
"false_negatives",
"(",
"y",
",",
"y_pred",
")",
"return",
"tp",
"/",
"(",
"tp",
"+",
"fn",
")"
] | Recall score
recall = true_positives / (true_positives + false_negatives)
Parameters:
-----------
y : vector, shape (n_samples,)
The target labels.
y_pred : vector, shape (n_samples,)
The predicted labels.
Returns:
--------
recall : float | [
"Recall",
"score"
] | 773fdce6866aa6decd306a5a85f94129fed816eb | https://github.com/VIVelev/PyDojoML/blob/773fdce6866aa6decd306a5a85f94129fed816eb/dojo/metrics/classification.py#L170-L191 | train | Recall score of a target and predicted labels. |
VIVelev/PyDojoML | dojo/metrics/classification.py | f1_score | def f1_score(y, y_pred):
"""F1 score
f1_score = 2 * precision*recall / (precision + recall)
Parameters:
-----------
y : vector, shape (n_samples,)
The target labels.
y_pred : vector, shape (n_samples,)
The predicted labels.
Returns:
--------
f1_score : float
... | python | def f1_score(y, y_pred):
"""F1 score
f1_score = 2 * precision*recall / (precision + recall)
Parameters:
-----------
y : vector, shape (n_samples,)
The target labels.
y_pred : vector, shape (n_samples,)
The predicted labels.
Returns:
--------
f1_score : float
... | [
"def",
"f1_score",
"(",
"y",
",",
"y_pred",
")",
":",
"p",
"=",
"precision",
"(",
"y",
",",
"y_pred",
")",
"r",
"=",
"recall",
"(",
"y",
",",
"y_pred",
")",
"return",
"2",
"*",
"p",
"*",
"r",
"/",
"(",
"p",
"+",
"r",
")"
] | F1 score
f1_score = 2 * precision*recall / (precision + recall)
Parameters:
-----------
y : vector, shape (n_samples,)
The target labels.
y_pred : vector, shape (n_samples,)
The predicted labels.
Returns:
--------
f1_score : float | [
"F1",
"score"
] | 773fdce6866aa6decd306a5a85f94129fed816eb | https://github.com/VIVelev/PyDojoML/blob/773fdce6866aa6decd306a5a85f94129fed816eb/dojo/metrics/classification.py#L195-L217 | train | F1 score of a single node. |
tjcsl/cslbot | cslbot/commands/babble.py | cmd | def cmd(send, msg, args):
"""Babbles like a user
Syntax: {command} [nick] [--length <1|2>] [--start <word>]
"""
parser = arguments.ArgParser(args['config'])
parser.add_argument('speaker', nargs='?', default=args['config']['core']['channel'])
parser.add_argument('--length', type=int, choices=[1, ... | python | def cmd(send, msg, args):
"""Babbles like a user
Syntax: {command} [nick] [--length <1|2>] [--start <word>]
"""
parser = arguments.ArgParser(args['config'])
parser.add_argument('speaker', nargs='?', default=args['config']['core']['channel'])
parser.add_argument('--length', type=int, choices=[1, ... | [
"def",
"cmd",
"(",
"send",
",",
"msg",
",",
"args",
")",
":",
"parser",
"=",
"arguments",
".",
"ArgParser",
"(",
"args",
"[",
"'config'",
"]",
")",
"parser",
".",
"add_argument",
"(",
"'speaker'",
",",
"nargs",
"=",
"'?'",
",",
"default",
"=",
"args"... | Babbles like a user
Syntax: {command} [nick] [--length <1|2>] [--start <word>] | [
"Babbles",
"like",
"a",
"user",
"Syntax",
":",
"{",
"command",
"}",
"[",
"nick",
"]",
"[",
"--",
"length",
"<1|2",
">",
"]",
"[",
"--",
"start",
"<word",
">",
"]"
] | aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/babble.py#L85-L101 | train | Babbles like a user
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.