repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
tchellomello/python-arlo | pyarlo/base_station.py | ArloBaseStation._decode_sensor_data | def _decode_sensor_data(properties):
"""Decode, decompress, and parse the data from the history API"""
b64_input = ""
for s in properties.get('payload'):
# pylint: disable=consider-using-join
b64_input += s
decoded = base64.b64decode(b64_input)
data = zli... | python | def _decode_sensor_data(properties):
"""Decode, decompress, and parse the data from the history API"""
b64_input = ""
for s in properties.get('payload'):
# pylint: disable=consider-using-join
b64_input += s
decoded = base64.b64decode(b64_input)
data = zli... | [
"def",
"_decode_sensor_data",
"(",
"properties",
")",
":",
"b64_input",
"=",
"\"\"",
"for",
"s",
"in",
"properties",
".",
"get",
"(",
"'payload'",
")",
":",
"# pylint: disable=consider-using-join",
"b64_input",
"+=",
"s",
"decoded",
"=",
"base64",
".",
"b64decod... | Decode, decompress, and parse the data from the history API | [
"Decode",
"decompress",
"and",
"parse",
"the",
"data",
"from",
"the",
"history",
"API"
] | db70aeb81705309c56ad32bbab1094f6cd146524 | https://github.com/tchellomello/python-arlo/blob/db70aeb81705309c56ad32bbab1094f6cd146524/pyarlo/base_station.py#L559-L584 | train |
tchellomello/python-arlo | pyarlo/base_station.py | ArloBaseStation._parse_statistic | def _parse_statistic(data, scale):
"""Parse binary statistics returned from the history API"""
i = 0
for byte in bytearray(data):
i = (i << 8) + byte
if i == 32768:
return None
if scale == 0:
return i
return float(i) / (scale * 10) | python | def _parse_statistic(data, scale):
"""Parse binary statistics returned from the history API"""
i = 0
for byte in bytearray(data):
i = (i << 8) + byte
if i == 32768:
return None
if scale == 0:
return i
return float(i) / (scale * 10) | [
"def",
"_parse_statistic",
"(",
"data",
",",
"scale",
")",
":",
"i",
"=",
"0",
"for",
"byte",
"in",
"bytearray",
"(",
"data",
")",
":",
"i",
"=",
"(",
"i",
"<<",
"8",
")",
"+",
"byte",
"if",
"i",
"==",
"32768",
":",
"return",
"None",
"if",
"sca... | Parse binary statistics returned from the history API | [
"Parse",
"binary",
"statistics",
"returned",
"from",
"the",
"history",
"API"
] | db70aeb81705309c56ad32bbab1094f6cd146524 | https://github.com/tchellomello/python-arlo/blob/db70aeb81705309c56ad32bbab1094f6cd146524/pyarlo/base_station.py#L587-L599 | train |
tchellomello/python-arlo | pyarlo/base_station.py | ArloBaseStation.play_track | def play_track(self, track_id=DEFAULT_TRACK_ID, position=0):
"""Plays a track at the given position."""
self.publish(
action='playTrack',
resource='audioPlayback/player',
publish_response=False,
properties={'trackId': track_id, 'position': position}
... | python | def play_track(self, track_id=DEFAULT_TRACK_ID, position=0):
"""Plays a track at the given position."""
self.publish(
action='playTrack',
resource='audioPlayback/player',
publish_response=False,
properties={'trackId': track_id, 'position': position}
... | [
"def",
"play_track",
"(",
"self",
",",
"track_id",
"=",
"DEFAULT_TRACK_ID",
",",
"position",
"=",
"0",
")",
":",
"self",
".",
"publish",
"(",
"action",
"=",
"'playTrack'",
",",
"resource",
"=",
"'audioPlayback/player'",
",",
"publish_response",
"=",
"False",
... | Plays a track at the given position. | [
"Plays",
"a",
"track",
"at",
"the",
"given",
"position",
"."
] | db70aeb81705309c56ad32bbab1094f6cd146524 | https://github.com/tchellomello/python-arlo/blob/db70aeb81705309c56ad32bbab1094f6cd146524/pyarlo/base_station.py#L618-L625 | train |
tchellomello/python-arlo | pyarlo/base_station.py | ArloBaseStation.set_shuffle_on | def set_shuffle_on(self):
"""Sets playback to shuffle."""
self.publish(
action='set',
resource='audioPlayback/config',
publish_response=False,
properties={'config': {'shuffleActive': True}}
) | python | def set_shuffle_on(self):
"""Sets playback to shuffle."""
self.publish(
action='set',
resource='audioPlayback/config',
publish_response=False,
properties={'config': {'shuffleActive': True}}
) | [
"def",
"set_shuffle_on",
"(",
"self",
")",
":",
"self",
".",
"publish",
"(",
"action",
"=",
"'set'",
",",
"resource",
"=",
"'audioPlayback/config'",
",",
"publish_response",
"=",
"False",
",",
"properties",
"=",
"{",
"'config'",
":",
"{",
"'shuffleActive'",
... | Sets playback to shuffle. | [
"Sets",
"playback",
"to",
"shuffle",
"."
] | db70aeb81705309c56ad32bbab1094f6cd146524 | https://github.com/tchellomello/python-arlo/blob/db70aeb81705309c56ad32bbab1094f6cd146524/pyarlo/base_station.py#L661-L668 | train |
tchellomello/python-arlo | pyarlo/base_station.py | ArloBaseStation.set_shuffle_off | def set_shuffle_off(self):
"""Sets playback to sequential."""
self.publish(
action='set',
resource='audioPlayback/config',
publish_response=False,
properties={'config': {'shuffleActive': False}}
) | python | def set_shuffle_off(self):
"""Sets playback to sequential."""
self.publish(
action='set',
resource='audioPlayback/config',
publish_response=False,
properties={'config': {'shuffleActive': False}}
) | [
"def",
"set_shuffle_off",
"(",
"self",
")",
":",
"self",
".",
"publish",
"(",
"action",
"=",
"'set'",
",",
"resource",
"=",
"'audioPlayback/config'",
",",
"publish_response",
"=",
"False",
",",
"properties",
"=",
"{",
"'config'",
":",
"{",
"'shuffleActive'",
... | Sets playback to sequential. | [
"Sets",
"playback",
"to",
"sequential",
"."
] | db70aeb81705309c56ad32bbab1094f6cd146524 | https://github.com/tchellomello/python-arlo/blob/db70aeb81705309c56ad32bbab1094f6cd146524/pyarlo/base_station.py#L670-L677 | train |
tchellomello/python-arlo | pyarlo/base_station.py | ArloBaseStation.set_night_light_on | def set_night_light_on(self):
"""Turns on the night light."""
self.publish(
action='set',
resource='cameras/{}'.format(self.device_id),
publish_response=False,
properties={'nightLight': {'enabled': True}}
) | python | def set_night_light_on(self):
"""Turns on the night light."""
self.publish(
action='set',
resource='cameras/{}'.format(self.device_id),
publish_response=False,
properties={'nightLight': {'enabled': True}}
) | [
"def",
"set_night_light_on",
"(",
"self",
")",
":",
"self",
".",
"publish",
"(",
"action",
"=",
"'set'",
",",
"resource",
"=",
"'cameras/{}'",
".",
"format",
"(",
"self",
".",
"device_id",
")",
",",
"publish_response",
"=",
"False",
",",
"properties",
"=",... | Turns on the night light. | [
"Turns",
"on",
"the",
"night",
"light",
"."
] | db70aeb81705309c56ad32bbab1094f6cd146524 | https://github.com/tchellomello/python-arlo/blob/db70aeb81705309c56ad32bbab1094f6cd146524/pyarlo/base_station.py#L688-L695 | train |
tchellomello/python-arlo | pyarlo/base_station.py | ArloBaseStation.set_night_light_off | def set_night_light_off(self):
"""Turns off the night light."""
self.publish(
action='set',
resource='cameras/{}'.format(self.device_id),
publish_response=False,
properties={'nightLight': {'enabled': False}}
) | python | def set_night_light_off(self):
"""Turns off the night light."""
self.publish(
action='set',
resource='cameras/{}'.format(self.device_id),
publish_response=False,
properties={'nightLight': {'enabled': False}}
) | [
"def",
"set_night_light_off",
"(",
"self",
")",
":",
"self",
".",
"publish",
"(",
"action",
"=",
"'set'",
",",
"resource",
"=",
"'cameras/{}'",
".",
"format",
"(",
"self",
".",
"device_id",
")",
",",
"publish_response",
"=",
"False",
",",
"properties",
"="... | Turns off the night light. | [
"Turns",
"off",
"the",
"night",
"light",
"."
] | db70aeb81705309c56ad32bbab1094f6cd146524 | https://github.com/tchellomello/python-arlo/blob/db70aeb81705309c56ad32bbab1094f6cd146524/pyarlo/base_station.py#L697-L704 | train |
tchellomello/python-arlo | pyarlo/base_station.py | ArloBaseStation.mode | def mode(self, mode):
"""Set Arlo camera mode.
:param mode: arm, disarm
"""
modes = self.available_modes
if (not modes) or (mode not in modes):
return
self.publish(
action='set',
resource='modes' if mode != 'schedule' else 'schedule',
... | python | def mode(self, mode):
"""Set Arlo camera mode.
:param mode: arm, disarm
"""
modes = self.available_modes
if (not modes) or (mode not in modes):
return
self.publish(
action='set',
resource='modes' if mode != 'schedule' else 'schedule',
... | [
"def",
"mode",
"(",
"self",
",",
"mode",
")",
":",
"modes",
"=",
"self",
".",
"available_modes",
"if",
"(",
"not",
"modes",
")",
"or",
"(",
"mode",
"not",
"in",
"modes",
")",
":",
"return",
"self",
".",
"publish",
"(",
"action",
"=",
"'set'",
",",
... | Set Arlo camera mode.
:param mode: arm, disarm | [
"Set",
"Arlo",
"camera",
"mode",
"."
] | db70aeb81705309c56ad32bbab1094f6cd146524 | https://github.com/tchellomello/python-arlo/blob/db70aeb81705309c56ad32bbab1094f6cd146524/pyarlo/base_station.py#L728-L741 | train |
zestyping/q | q.py | Q.unindent | def unindent(self, lines):
"""Removes any indentation that is common to all of the given lines."""
indent = min(
len(self.re.match(r'^ *', line).group()) for line in lines)
return [line[indent:].rstrip() for line in lines] | python | def unindent(self, lines):
"""Removes any indentation that is common to all of the given lines."""
indent = min(
len(self.re.match(r'^ *', line).group()) for line in lines)
return [line[indent:].rstrip() for line in lines] | [
"def",
"unindent",
"(",
"self",
",",
"lines",
")",
":",
"indent",
"=",
"min",
"(",
"len",
"(",
"self",
".",
"re",
".",
"match",
"(",
"r'^ *'",
",",
"line",
")",
".",
"group",
"(",
")",
")",
"for",
"line",
"in",
"lines",
")",
"return",
"[",
"lin... | Removes any indentation that is common to all of the given lines. | [
"Removes",
"any",
"indentation",
"that",
"is",
"common",
"to",
"all",
"of",
"the",
"given",
"lines",
"."
] | 1c178bf3595eb579f29957f674c08f4a1cd00ffe | https://github.com/zestyping/q/blob/1c178bf3595eb579f29957f674c08f4a1cd00ffe/q.py#L194-L198 | train |
zestyping/q | q.py | Q.get_call_exprs | def get_call_exprs(self, line):
"""Gets the argument expressions from the source of a function call."""
line = line.lstrip()
try:
tree = self.ast.parse(line)
except SyntaxError:
return None
for node in self.ast.walk(tree):
if isinstance(node, s... | python | def get_call_exprs(self, line):
"""Gets the argument expressions from the source of a function call."""
line = line.lstrip()
try:
tree = self.ast.parse(line)
except SyntaxError:
return None
for node in self.ast.walk(tree):
if isinstance(node, s... | [
"def",
"get_call_exprs",
"(",
"self",
",",
"line",
")",
":",
"line",
"=",
"line",
".",
"lstrip",
"(",
")",
"try",
":",
"tree",
"=",
"self",
".",
"ast",
".",
"parse",
"(",
"line",
")",
"except",
"SyntaxError",
":",
"return",
"None",
"for",
"node",
"... | Gets the argument expressions from the source of a function call. | [
"Gets",
"the",
"argument",
"expressions",
"from",
"the",
"source",
"of",
"a",
"function",
"call",
"."
] | 1c178bf3595eb579f29957f674c08f4a1cd00ffe | https://github.com/zestyping/q/blob/1c178bf3595eb579f29957f674c08f4a1cd00ffe/q.py#L214-L241 | train |
zestyping/q | q.py | Q.show | def show(self, func_name, values, labels=None):
"""Prints out nice representations of the given values."""
s = self.Stanza(self.indent)
if func_name == '<module>' and self.in_console:
func_name = '<console>'
s.add([func_name + ': '])
reprs = map(self.safe_repr, values... | python | def show(self, func_name, values, labels=None):
"""Prints out nice representations of the given values."""
s = self.Stanza(self.indent)
if func_name == '<module>' and self.in_console:
func_name = '<console>'
s.add([func_name + ': '])
reprs = map(self.safe_repr, values... | [
"def",
"show",
"(",
"self",
",",
"func_name",
",",
"values",
",",
"labels",
"=",
"None",
")",
":",
"s",
"=",
"self",
".",
"Stanza",
"(",
"self",
".",
"indent",
")",
"if",
"func_name",
"==",
"'<module>'",
"and",
"self",
".",
"in_console",
":",
"func_n... | Prints out nice representations of the given values. | [
"Prints",
"out",
"nice",
"representations",
"of",
"the",
"given",
"values",
"."
] | 1c178bf3595eb579f29957f674c08f4a1cd00ffe | https://github.com/zestyping/q/blob/1c178bf3595eb579f29957f674c08f4a1cd00ffe/q.py#L243-L260 | train |
zestyping/q | q.py | Q.trace | def trace(self, func):
"""Decorator to print out a function's arguments and return value."""
def wrapper(*args, **kwargs):
# Print out the call to the function with its arguments.
s = self.Stanza(self.indent)
s.add([self.GREEN, func.__name__, self.NORMAL, '('])
... | python | def trace(self, func):
"""Decorator to print out a function's arguments and return value."""
def wrapper(*args, **kwargs):
# Print out the call to the function with its arguments.
s = self.Stanza(self.indent)
s.add([self.GREEN, func.__name__, self.NORMAL, '('])
... | [
"def",
"trace",
"(",
"self",
",",
"func",
")",
":",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Print out the call to the function with its arguments.",
"s",
"=",
"self",
".",
"Stanza",
"(",
"self",
".",
"indent",
")",
"s",
... | Decorator to print out a function's arguments and return value. | [
"Decorator",
"to",
"print",
"out",
"a",
"function",
"s",
"arguments",
"and",
"return",
"value",
"."
] | 1c178bf3595eb579f29957f674c08f4a1cd00ffe | https://github.com/zestyping/q/blob/1c178bf3595eb579f29957f674c08f4a1cd00ffe/q.py#L262-L312 | train |
zestyping/q | q.py | Q.d | def d(self, depth=1):
"""Launches an interactive console at the point where it's called."""
info = self.inspect.getframeinfo(self.sys._getframe(1))
s = self.Stanza(self.indent)
s.add([info.function + ': '])
s.add([self.MAGENTA, 'Interactive console opened', self.NORMAL])
... | python | def d(self, depth=1):
"""Launches an interactive console at the point where it's called."""
info = self.inspect.getframeinfo(self.sys._getframe(1))
s = self.Stanza(self.indent)
s.add([info.function + ': '])
s.add([self.MAGENTA, 'Interactive console opened', self.NORMAL])
... | [
"def",
"d",
"(",
"self",
",",
"depth",
"=",
"1",
")",
":",
"info",
"=",
"self",
".",
"inspect",
".",
"getframeinfo",
"(",
"self",
".",
"sys",
".",
"_getframe",
"(",
"1",
")",
")",
"s",
"=",
"self",
".",
"Stanza",
"(",
"self",
".",
"indent",
")"... | Launches an interactive console at the point where it's called. | [
"Launches",
"an",
"interactive",
"console",
"at",
"the",
"point",
"where",
"it",
"s",
"called",
"."
] | 1c178bf3595eb579f29957f674c08f4a1cd00ffe | https://github.com/zestyping/q/blob/1c178bf3595eb579f29957f674c08f4a1cd00ffe/q.py#L353-L374 | train |
pyopenapi/pyswagger | pyswagger/scanner/v1_2/upgrade.py | Upgrade.swagger | def swagger(self):
""" some preparation before returning Swagger object
"""
# prepare Swagger.host & Swagger.basePath
if not self.__swagger:
return None
common_path = os.path.commonprefix(list(self.__swagger.paths))
# remove tailing slash,
# because a... | python | def swagger(self):
""" some preparation before returning Swagger object
"""
# prepare Swagger.host & Swagger.basePath
if not self.__swagger:
return None
common_path = os.path.commonprefix(list(self.__swagger.paths))
# remove tailing slash,
# because a... | [
"def",
"swagger",
"(",
"self",
")",
":",
"# prepare Swagger.host & Swagger.basePath",
"if",
"not",
"self",
".",
"__swagger",
":",
"return",
"None",
"common_path",
"=",
"os",
".",
"path",
".",
"commonprefix",
"(",
"list",
"(",
"self",
".",
"__swagger",
".",
"... | some preparation before returning Swagger object | [
"some",
"preparation",
"before",
"returning",
"Swagger",
"object"
] | 333c4ca08e758cd2194943d9904a3eda3fe43977 | https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/scanner/v1_2/upgrade.py#L288-L311 | train |
pyopenapi/pyswagger | pyswagger/utils.py | scope_compose | def scope_compose(scope, name, sep=private.SCOPE_SEPARATOR):
""" compose a new scope
:param str scope: current scope
:param str name: name of next level in scope
:return the composed scope
"""
if name == None:
new_scope = scope
else:
new_scope = scope if scope else name
... | python | def scope_compose(scope, name, sep=private.SCOPE_SEPARATOR):
""" compose a new scope
:param str scope: current scope
:param str name: name of next level in scope
:return the composed scope
"""
if name == None:
new_scope = scope
else:
new_scope = scope if scope else name
... | [
"def",
"scope_compose",
"(",
"scope",
",",
"name",
",",
"sep",
"=",
"private",
".",
"SCOPE_SEPARATOR",
")",
":",
"if",
"name",
"==",
"None",
":",
"new_scope",
"=",
"scope",
"else",
":",
"new_scope",
"=",
"scope",
"if",
"scope",
"else",
"name",
"if",
"s... | compose a new scope
:param str scope: current scope
:param str name: name of next level in scope
:return the composed scope | [
"compose",
"a",
"new",
"scope"
] | 333c4ca08e758cd2194943d9904a3eda3fe43977 | https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/utils.py#L15-L31 | train |
pyopenapi/pyswagger | pyswagger/utils.py | nv_tuple_list_replace | def nv_tuple_list_replace(l, v):
""" replace a tuple in a tuple list
"""
_found = False
for i, x in enumerate(l):
if x[0] == v[0]:
l[i] = v
_found = True
if not _found:
l.append(v) | python | def nv_tuple_list_replace(l, v):
""" replace a tuple in a tuple list
"""
_found = False
for i, x in enumerate(l):
if x[0] == v[0]:
l[i] = v
_found = True
if not _found:
l.append(v) | [
"def",
"nv_tuple_list_replace",
"(",
"l",
",",
"v",
")",
":",
"_found",
"=",
"False",
"for",
"i",
",",
"x",
"in",
"enumerate",
"(",
"l",
")",
":",
"if",
"x",
"[",
"0",
"]",
"==",
"v",
"[",
"0",
"]",
":",
"l",
"[",
"i",
"]",
"=",
"v",
"_foun... | replace a tuple in a tuple list | [
"replace",
"a",
"tuple",
"in",
"a",
"tuple",
"list"
] | 333c4ca08e758cd2194943d9904a3eda3fe43977 | https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/utils.py#L286-L296 | train |
pyopenapi/pyswagger | pyswagger/utils.py | url_dirname | def url_dirname(url):
""" Return the folder containing the '.json' file
"""
p = six.moves.urllib.parse.urlparse(url)
for e in [private.FILE_EXT_JSON, private.FILE_EXT_YAML]:
if p.path.endswith(e):
return six.moves.urllib.parse.urlunparse(
p[:2]+
(os.pa... | python | def url_dirname(url):
""" Return the folder containing the '.json' file
"""
p = six.moves.urllib.parse.urlparse(url)
for e in [private.FILE_EXT_JSON, private.FILE_EXT_YAML]:
if p.path.endswith(e):
return six.moves.urllib.parse.urlunparse(
p[:2]+
(os.pa... | [
"def",
"url_dirname",
"(",
"url",
")",
":",
"p",
"=",
"six",
".",
"moves",
".",
"urllib",
".",
"parse",
".",
"urlparse",
"(",
"url",
")",
"for",
"e",
"in",
"[",
"private",
".",
"FILE_EXT_JSON",
",",
"private",
".",
"FILE_EXT_YAML",
"]",
":",
"if",
... | Return the folder containing the '.json' file | [
"Return",
"the",
"folder",
"containing",
"the",
".",
"json",
"file"
] | 333c4ca08e758cd2194943d9904a3eda3fe43977 | https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/utils.py#L332-L343 | train |
pyopenapi/pyswagger | pyswagger/utils.py | url_join | def url_join(url, path):
""" url version of os.path.join
"""
p = six.moves.urllib.parse.urlparse(url)
t = None
if p.path and p.path[-1] == '/':
if path and path[0] == '/':
path = path[1:]
t = ''.join([p.path, path])
else:
t = ('' if path and path[0] == '/' el... | python | def url_join(url, path):
""" url version of os.path.join
"""
p = six.moves.urllib.parse.urlparse(url)
t = None
if p.path and p.path[-1] == '/':
if path and path[0] == '/':
path = path[1:]
t = ''.join([p.path, path])
else:
t = ('' if path and path[0] == '/' el... | [
"def",
"url_join",
"(",
"url",
",",
"path",
")",
":",
"p",
"=",
"six",
".",
"moves",
".",
"urllib",
".",
"parse",
".",
"urlparse",
"(",
"url",
")",
"t",
"=",
"None",
"if",
"p",
".",
"path",
"and",
"p",
".",
"path",
"[",
"-",
"1",
"]",
"==",
... | url version of os.path.join | [
"url",
"version",
"of",
"os",
".",
"path",
".",
"join"
] | 333c4ca08e758cd2194943d9904a3eda3fe43977 | https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/utils.py#L345-L362 | train |
pyopenapi/pyswagger | pyswagger/utils.py | derelativise_url | def derelativise_url(url):
'''
Normalizes URLs, gets rid of .. and .
'''
parsed = six.moves.urllib.parse.urlparse(url)
newpath=[]
for chunk in parsed.path[1:].split('/'):
if chunk == '.':
continue
elif chunk == '..':
# parent dir.
newpath=newpa... | python | def derelativise_url(url):
'''
Normalizes URLs, gets rid of .. and .
'''
parsed = six.moves.urllib.parse.urlparse(url)
newpath=[]
for chunk in parsed.path[1:].split('/'):
if chunk == '.':
continue
elif chunk == '..':
# parent dir.
newpath=newpa... | [
"def",
"derelativise_url",
"(",
"url",
")",
":",
"parsed",
"=",
"six",
".",
"moves",
".",
"urllib",
".",
"parse",
".",
"urlparse",
"(",
"url",
")",
"newpath",
"=",
"[",
"]",
"for",
"chunk",
"in",
"parsed",
".",
"path",
"[",
"1",
":",
"]",
".",
"s... | Normalizes URLs, gets rid of .. and . | [
"Normalizes",
"URLs",
"gets",
"rid",
"of",
"..",
"and",
"."
] | 333c4ca08e758cd2194943d9904a3eda3fe43977 | https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/utils.py#L405-L424 | train |
pyopenapi/pyswagger | pyswagger/utils.py | get_swagger_version | def get_swagger_version(obj):
""" get swagger version from loaded json """
if isinstance(obj, dict):
if 'swaggerVersion' in obj:
return obj['swaggerVersion']
elif 'swagger' in obj:
return obj['swagger']
return None
else:
# should be an instance of Bas... | python | def get_swagger_version(obj):
""" get swagger version from loaded json """
if isinstance(obj, dict):
if 'swaggerVersion' in obj:
return obj['swaggerVersion']
elif 'swagger' in obj:
return obj['swagger']
return None
else:
# should be an instance of Bas... | [
"def",
"get_swagger_version",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"dict",
")",
":",
"if",
"'swaggerVersion'",
"in",
"obj",
":",
"return",
"obj",
"[",
"'swaggerVersion'",
"]",
"elif",
"'swagger'",
"in",
"obj",
":",
"return",
"obj",
... | get swagger version from loaded json | [
"get",
"swagger",
"version",
"from",
"loaded",
"json"
] | 333c4ca08e758cd2194943d9904a3eda3fe43977 | https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/utils.py#L426-L437 | train |
pyopenapi/pyswagger | pyswagger/utils.py | walk | def walk(start, ofn, cyc=None):
""" Non recursive DFS to detect cycles
:param start: start vertex in graph
:param ofn: function to get the list of outgoing edges of a vertex
:param cyc: list of existing cycles, cycles are represented in a list started with minimum vertex.
:return: cycles
:rtype... | python | def walk(start, ofn, cyc=None):
""" Non recursive DFS to detect cycles
:param start: start vertex in graph
:param ofn: function to get the list of outgoing edges of a vertex
:param cyc: list of existing cycles, cycles are represented in a list started with minimum vertex.
:return: cycles
:rtype... | [
"def",
"walk",
"(",
"start",
",",
"ofn",
",",
"cyc",
"=",
"None",
")",
":",
"ctx",
",",
"stk",
"=",
"{",
"}",
",",
"[",
"start",
"]",
"cyc",
"=",
"[",
"]",
"if",
"cyc",
"==",
"None",
"else",
"cyc",
"while",
"len",
"(",
"stk",
")",
":",
"top... | Non recursive DFS to detect cycles
:param start: start vertex in graph
:param ofn: function to get the list of outgoing edges of a vertex
:param cyc: list of existing cycles, cycles are represented in a list started with minimum vertex.
:return: cycles
:rtype: list of lists | [
"Non",
"recursive",
"DFS",
"to",
"detect",
"cycles"
] | 333c4ca08e758cd2194943d9904a3eda3fe43977 | https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/utils.py#L439-L480 | train |
pyopenapi/pyswagger | pyswagger/scanner/v1_2/validate.py | Validate._validate_param | def _validate_param(self, path, obj, _):
""" validate option combination of Parameter object """
errs = []
if obj.allowMultiple:
if not obj.paramType in ('path', 'query', 'header'):
errs.append('allowMultiple should be applied on path, header, or query parameters')
... | python | def _validate_param(self, path, obj, _):
""" validate option combination of Parameter object """
errs = []
if obj.allowMultiple:
if not obj.paramType in ('path', 'query', 'header'):
errs.append('allowMultiple should be applied on path, header, or query parameters')
... | [
"def",
"_validate_param",
"(",
"self",
",",
"path",
",",
"obj",
",",
"_",
")",
":",
"errs",
"=",
"[",
"]",
"if",
"obj",
".",
"allowMultiple",
":",
"if",
"not",
"obj",
".",
"paramType",
"in",
"(",
"'path'",
",",
"'query'",
",",
"'header'",
")",
":",... | validate option combination of Parameter object | [
"validate",
"option",
"combination",
"of",
"Parameter",
"object"
] | 333c4ca08e758cd2194943d9904a3eda3fe43977 | https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/scanner/v1_2/validate.py#L53-L75 | train |
pyopenapi/pyswagger | pyswagger/scanner/v1_2/validate.py | Validate._validate_items | def _validate_items(self, path, obj, _):
""" validate option combination of Property object """
errs = []
if obj.type == 'void':
errs.append('void is only allowed in Operation object.')
return path, obj.__class__.__name__, errs | python | def _validate_items(self, path, obj, _):
""" validate option combination of Property object """
errs = []
if obj.type == 'void':
errs.append('void is only allowed in Operation object.')
return path, obj.__class__.__name__, errs | [
"def",
"_validate_items",
"(",
"self",
",",
"path",
",",
"obj",
",",
"_",
")",
":",
"errs",
"=",
"[",
"]",
"if",
"obj",
".",
"type",
"==",
"'void'",
":",
"errs",
".",
"append",
"(",
"'void is only allowed in Operation object.'",
")",
"return",
"path",
",... | validate option combination of Property object | [
"validate",
"option",
"combination",
"of",
"Property",
"object"
] | 333c4ca08e758cd2194943d9904a3eda3fe43977 | https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/scanner/v1_2/validate.py#L88-L95 | train |
pyopenapi/pyswagger | pyswagger/scanner/v1_2/validate.py | Validate._validate_auth | def _validate_auth(self, path, obj, _):
""" validate that apiKey and oauth2 requirements """
errs = []
if obj.type == 'apiKey':
if not obj.passAs:
errs.append('need "passAs" for apiKey')
if not obj.keyname:
errs.append('need "keyname" for ... | python | def _validate_auth(self, path, obj, _):
""" validate that apiKey and oauth2 requirements """
errs = []
if obj.type == 'apiKey':
if not obj.passAs:
errs.append('need "passAs" for apiKey')
if not obj.keyname:
errs.append('need "keyname" for ... | [
"def",
"_validate_auth",
"(",
"self",
",",
"path",
",",
"obj",
",",
"_",
")",
":",
"errs",
"=",
"[",
"]",
"if",
"obj",
".",
"type",
"==",
"'apiKey'",
":",
"if",
"not",
"obj",
".",
"passAs",
":",
"errs",
".",
"append",
"(",
"'need \"passAs\" for apiKe... | validate that apiKey and oauth2 requirements | [
"validate",
"that",
"apiKey",
"and",
"oauth2",
"requirements"
] | 333c4ca08e758cd2194943d9904a3eda3fe43977 | https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/scanner/v1_2/validate.py#L98-L112 | train |
pyopenapi/pyswagger | pyswagger/scanner/v1_2/validate.py | Validate._validate_granttype | def _validate_granttype(self, path, obj, _):
""" make sure either implicit or authorization_code is defined """
errs = []
if not obj.implicit and not obj.authorization_code:
errs.append('Either implicit or authorization_code should be defined.')
return path, obj.__class__._... | python | def _validate_granttype(self, path, obj, _):
""" make sure either implicit or authorization_code is defined """
errs = []
if not obj.implicit and not obj.authorization_code:
errs.append('Either implicit or authorization_code should be defined.')
return path, obj.__class__._... | [
"def",
"_validate_granttype",
"(",
"self",
",",
"path",
",",
"obj",
",",
"_",
")",
":",
"errs",
"=",
"[",
"]",
"if",
"not",
"obj",
".",
"implicit",
"and",
"not",
"obj",
".",
"authorization_code",
":",
"errs",
".",
"append",
"(",
"'Either implicit or auth... | make sure either implicit or authorization_code is defined | [
"make",
"sure",
"either",
"implicit",
"or",
"authorization_code",
"is",
"defined"
] | 333c4ca08e758cd2194943d9904a3eda3fe43977 | https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/scanner/v1_2/validate.py#L115-L122 | train |
pyopenapi/pyswagger | pyswagger/scanner/v1_2/validate.py | Validate._validate_auths | def _validate_auths(self, path, obj, app):
""" make sure that apiKey and basicAuth are empty list
in Operation object.
"""
errs = []
for k, v in six.iteritems(obj.authorizations or {}):
if k not in app.raw.authorizations:
errs.append('auth {0} not fou... | python | def _validate_auths(self, path, obj, app):
""" make sure that apiKey and basicAuth are empty list
in Operation object.
"""
errs = []
for k, v in six.iteritems(obj.authorizations or {}):
if k not in app.raw.authorizations:
errs.append('auth {0} not fou... | [
"def",
"_validate_auths",
"(",
"self",
",",
"path",
",",
"obj",
",",
"app",
")",
":",
"errs",
"=",
"[",
"]",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"obj",
".",
"authorizations",
"or",
"{",
"}",
")",
":",
"if",
"k",
"not",
"in... | make sure that apiKey and basicAuth are empty list
in Operation object. | [
"make",
"sure",
"that",
"apiKey",
"and",
"basicAuth",
"are",
"empty",
"list",
"in",
"Operation",
"object",
"."
] | 333c4ca08e758cd2194943d9904a3eda3fe43977 | https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/scanner/v1_2/validate.py#L125-L138 | train |
pyopenapi/pyswagger | pyswagger/scan.py | default_tree_traversal | def default_tree_traversal(root, leaves):
""" default tree traversal """
objs = [('#', root)]
while len(objs) > 0:
path, obj = objs.pop()
# name of child are json-pointer encoded, we don't have
# to encode it again.
if obj.__class__ not in leaves:
objs.extend(map... | python | def default_tree_traversal(root, leaves):
""" default tree traversal """
objs = [('#', root)]
while len(objs) > 0:
path, obj = objs.pop()
# name of child are json-pointer encoded, we don't have
# to encode it again.
if obj.__class__ not in leaves:
objs.extend(map... | [
"def",
"default_tree_traversal",
"(",
"root",
",",
"leaves",
")",
":",
"objs",
"=",
"[",
"(",
"'#'",
",",
"root",
")",
"]",
"while",
"len",
"(",
"objs",
")",
">",
"0",
":",
"path",
",",
"obj",
"=",
"objs",
".",
"pop",
"(",
")",
"# name of child are... | default tree traversal | [
"default",
"tree",
"traversal"
] | 333c4ca08e758cd2194943d9904a3eda3fe43977 | https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/scan.py#L6-L19 | train |
pyopenapi/pyswagger | pyswagger/primitives/render.py | Renderer.render_all | def render_all(self, op, exclude=[], opt=None):
""" render a set of parameter for an Operation
:param op Operation: the swagger spec object
:param opt dict: render option
:return: a set of parameters that can be passed to Operation.__call__
:rtype: dict
"""
opt =... | python | def render_all(self, op, exclude=[], opt=None):
""" render a set of parameter for an Operation
:param op Operation: the swagger spec object
:param opt dict: render option
:return: a set of parameters that can be passed to Operation.__call__
:rtype: dict
"""
opt =... | [
"def",
"render_all",
"(",
"self",
",",
"op",
",",
"exclude",
"=",
"[",
"]",
",",
"opt",
"=",
"None",
")",
":",
"opt",
"=",
"self",
".",
"default",
"(",
")",
"if",
"opt",
"==",
"None",
"else",
"opt",
"if",
"not",
"isinstance",
"(",
"op",
",",
"O... | render a set of parameter for an Operation
:param op Operation: the swagger spec object
:param opt dict: render option
:return: a set of parameters that can be passed to Operation.__call__
:rtype: dict | [
"render",
"a",
"set",
"of",
"parameter",
"for",
"an",
"Operation"
] | 333c4ca08e758cd2194943d9904a3eda3fe43977 | https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/primitives/render.py#L287-L314 | train |
pyopenapi/pyswagger | pyswagger/io.py | Request._prepare_forms | def _prepare_forms(self):
""" private function to prepare content for paramType=form
"""
content_type = 'application/x-www-form-urlencoded'
if self.__op.consumes and content_type not in self.__op.consumes:
raise errs.SchemaError('content type {0} does not present in {1}'.form... | python | def _prepare_forms(self):
""" private function to prepare content for paramType=form
"""
content_type = 'application/x-www-form-urlencoded'
if self.__op.consumes and content_type not in self.__op.consumes:
raise errs.SchemaError('content type {0} does not present in {1}'.form... | [
"def",
"_prepare_forms",
"(",
"self",
")",
":",
"content_type",
"=",
"'application/x-www-form-urlencoded'",
"if",
"self",
".",
"__op",
".",
"consumes",
"and",
"content_type",
"not",
"in",
"self",
".",
"__op",
".",
"consumes",
":",
"raise",
"errs",
".",
"Schema... | private function to prepare content for paramType=form | [
"private",
"function",
"to",
"prepare",
"content",
"for",
"paramType",
"=",
"form"
] | 333c4ca08e758cd2194943d9904a3eda3fe43977 | https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/io.py#L56-L63 | train |
pyopenapi/pyswagger | pyswagger/io.py | Request._prepare_body | def _prepare_body(self):
""" private function to prepare content for paramType=body
"""
content_type = self.__consume
if not content_type:
content_type = self.__op.consumes[0] if self.__op.consumes else 'application/json'
if self.__op.consumes and content_type not in ... | python | def _prepare_body(self):
""" private function to prepare content for paramType=body
"""
content_type = self.__consume
if not content_type:
content_type = self.__op.consumes[0] if self.__op.consumes else 'application/json'
if self.__op.consumes and content_type not in ... | [
"def",
"_prepare_body",
"(",
"self",
")",
":",
"content_type",
"=",
"self",
".",
"__consume",
"if",
"not",
"content_type",
":",
"content_type",
"=",
"self",
".",
"__op",
".",
"consumes",
"[",
"0",
"]",
"if",
"self",
".",
"__op",
".",
"consumes",
"else",
... | private function to prepare content for paramType=body | [
"private",
"function",
"to",
"prepare",
"content",
"for",
"paramType",
"=",
"body"
] | 333c4ca08e758cd2194943d9904a3eda3fe43977 | https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/io.py#L65-L85 | train |
pyopenapi/pyswagger | pyswagger/io.py | Request._prepare_files | def _prepare_files(self, encoding):
""" private function to prepare content for paramType=form with File
"""
content_type = 'multipart/form-data'
if self.__op.consumes and content_type not in self.__op.consumes:
raise errs.SchemaError('content type {0} does not present in {1}... | python | def _prepare_files(self, encoding):
""" private function to prepare content for paramType=form with File
"""
content_type = 'multipart/form-data'
if self.__op.consumes and content_type not in self.__op.consumes:
raise errs.SchemaError('content type {0} does not present in {1}... | [
"def",
"_prepare_files",
"(",
"self",
",",
"encoding",
")",
":",
"content_type",
"=",
"'multipart/form-data'",
"if",
"self",
".",
"__op",
".",
"consumes",
"and",
"content_type",
"not",
"in",
"self",
".",
"__op",
".",
"consumes",
":",
"raise",
"errs",
".",
... | private function to prepare content for paramType=form with File | [
"private",
"function",
"to",
"prepare",
"content",
"for",
"paramType",
"=",
"form",
"with",
"File"
] | 333c4ca08e758cd2194943d9904a3eda3fe43977 | https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/io.py#L87-L151 | train |
pyopenapi/pyswagger | pyswagger/io.py | Request.prepare | def prepare(self, scheme='http', handle_files=True, encoding='utf-8'):
""" make this request ready for Clients
:param str scheme: scheme used in this request
:param bool handle_files: False to skip multipart/form-data encoding
:param str encoding: encoding for body content.
:rty... | python | def prepare(self, scheme='http', handle_files=True, encoding='utf-8'):
""" make this request ready for Clients
:param str scheme: scheme used in this request
:param bool handle_files: False to skip multipart/form-data encoding
:param str encoding: encoding for body content.
:rty... | [
"def",
"prepare",
"(",
"self",
",",
"scheme",
"=",
"'http'",
",",
"handle_files",
"=",
"True",
",",
"encoding",
"=",
"'utf-8'",
")",
":",
"if",
"isinstance",
"(",
"scheme",
",",
"list",
")",
":",
"if",
"self",
".",
"__scheme",
"is",
"None",
":",
"sch... | make this request ready for Clients
:param str scheme: scheme used in this request
:param bool handle_files: False to skip multipart/form-data encoding
:param str encoding: encoding for body content.
:rtype: Request | [
"make",
"this",
"request",
"ready",
"for",
"Clients"
] | 333c4ca08e758cd2194943d9904a3eda3fe43977 | https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/io.py#L174-L239 | train |
pyopenapi/pyswagger | pyswagger/io.py | Response.apply_with | def apply_with(self, status=None, raw=None, header=None):
""" update header, status code, raw datum, ...etc
:param int status: status code
:param str raw: body content
:param dict header: header section
:return: return self for chaining
:rtype: Response
"""
... | python | def apply_with(self, status=None, raw=None, header=None):
""" update header, status code, raw datum, ...etc
:param int status: status code
:param str raw: body content
:param dict header: header section
:return: return self for chaining
:rtype: Response
"""
... | [
"def",
"apply_with",
"(",
"self",
",",
"status",
"=",
"None",
",",
"raw",
"=",
"None",
",",
"header",
"=",
"None",
")",
":",
"if",
"status",
"!=",
"None",
":",
"self",
".",
"__status",
"=",
"status",
"r",
"=",
"(",
"final",
"(",
"self",
".",
"__o... | update header, status code, raw datum, ...etc
:param int status: status code
:param str raw: body content
:param dict header: header section
:return: return self for chaining
:rtype: Response | [
"update",
"header",
"status",
"code",
"raw",
"datum",
"...",
"etc"
] | 333c4ca08e758cd2194943d9904a3eda3fe43977 | https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/io.py#L374-L419 | train |
pyopenapi/pyswagger | pyswagger/spec/base.py | Context.parse | def parse(self, obj=None):
""" major part do parsing.
:param dict obj: json object to be parsed.
:raises ValueError: if obj is not a dict type.
"""
if obj == None:
return
if not isinstance(obj, dict):
raise ValueError('invalid obj passed: ' + str... | python | def parse(self, obj=None):
""" major part do parsing.
:param dict obj: json object to be parsed.
:raises ValueError: if obj is not a dict type.
"""
if obj == None:
return
if not isinstance(obj, dict):
raise ValueError('invalid obj passed: ' + str... | [
"def",
"parse",
"(",
"self",
",",
"obj",
"=",
"None",
")",
":",
"if",
"obj",
"==",
"None",
":",
"return",
"if",
"not",
"isinstance",
"(",
"obj",
",",
"dict",
")",
":",
"raise",
"ValueError",
"(",
"'invalid obj passed: '",
"+",
"str",
"(",
"type",
"("... | major part do parsing.
:param dict obj: json object to be parsed.
:raises ValueError: if obj is not a dict type. | [
"major",
"part",
"do",
"parsing",
"."
] | 333c4ca08e758cd2194943d9904a3eda3fe43977 | https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/spec/base.py#L118-L171 | train |
pyopenapi/pyswagger | pyswagger/spec/base.py | BaseObj._assign_parent | def _assign_parent(self, ctx):
""" parent assignment, internal usage only
"""
def _assign(cls, _, obj):
if obj == None:
return
if cls.is_produced(obj):
if isinstance(obj, BaseObj):
obj._parent__ = self
else:... | python | def _assign_parent(self, ctx):
""" parent assignment, internal usage only
"""
def _assign(cls, _, obj):
if obj == None:
return
if cls.is_produced(obj):
if isinstance(obj, BaseObj):
obj._parent__ = self
else:... | [
"def",
"_assign_parent",
"(",
"self",
",",
"ctx",
")",
":",
"def",
"_assign",
"(",
"cls",
",",
"_",
",",
"obj",
")",
":",
"if",
"obj",
"==",
"None",
":",
"return",
"if",
"cls",
".",
"is_produced",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"o... | parent assignment, internal usage only | [
"parent",
"assignment",
"internal",
"usage",
"only"
] | 333c4ca08e758cd2194943d9904a3eda3fe43977 | https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/spec/base.py#L217-L236 | train |
pyopenapi/pyswagger | pyswagger/spec/base.py | BaseObj.get_private_name | def get_private_name(self, f):
""" get private protected name of an attribute
:param str f: name of the private attribute to be accessed.
"""
f = self.__swagger_rename__[f] if f in self.__swagger_rename__.keys() else f
return '_' + self.__class__.__name__ + '__' + f | python | def get_private_name(self, f):
""" get private protected name of an attribute
:param str f: name of the private attribute to be accessed.
"""
f = self.__swagger_rename__[f] if f in self.__swagger_rename__.keys() else f
return '_' + self.__class__.__name__ + '__' + f | [
"def",
"get_private_name",
"(",
"self",
",",
"f",
")",
":",
"f",
"=",
"self",
".",
"__swagger_rename__",
"[",
"f",
"]",
"if",
"f",
"in",
"self",
".",
"__swagger_rename__",
".",
"keys",
"(",
")",
"else",
"f",
"return",
"'_'",
"+",
"self",
".",
"__clas... | get private protected name of an attribute
:param str f: name of the private attribute to be accessed. | [
"get",
"private",
"protected",
"name",
"of",
"an",
"attribute"
] | 333c4ca08e758cd2194943d9904a3eda3fe43977 | https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/spec/base.py#L238-L244 | train |
pyopenapi/pyswagger | pyswagger/spec/base.py | BaseObj.update_field | def update_field(self, f, obj):
""" update a field
:param str f: name of field to be updated.
:param obj: value of field to be updated.
"""
n = self.get_private_name(f)
if not hasattr(self, n):
raise AttributeError('{0} is not in {1}'.format(n, self.__class__... | python | def update_field(self, f, obj):
""" update a field
:param str f: name of field to be updated.
:param obj: value of field to be updated.
"""
n = self.get_private_name(f)
if not hasattr(self, n):
raise AttributeError('{0} is not in {1}'.format(n, self.__class__... | [
"def",
"update_field",
"(",
"self",
",",
"f",
",",
"obj",
")",
":",
"n",
"=",
"self",
".",
"get_private_name",
"(",
"f",
")",
"if",
"not",
"hasattr",
"(",
"self",
",",
"n",
")",
":",
"raise",
"AttributeError",
"(",
"'{0} is not in {1}'",
".",
"format",... | update a field
:param str f: name of field to be updated.
:param obj: value of field to be updated. | [
"update",
"a",
"field"
] | 333c4ca08e758cd2194943d9904a3eda3fe43977 | https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/spec/base.py#L246-L257 | train |
pyopenapi/pyswagger | pyswagger/spec/base.py | BaseObj.resolve | def resolve(self, ts):
""" resolve a list of tokens to an child object
:param list ts: list of tokens
"""
if isinstance(ts, six.string_types):
ts = [ts]
obj = self
while len(ts) > 0:
t = ts.pop(0)
if issubclass(obj.__class__, BaseObj... | python | def resolve(self, ts):
""" resolve a list of tokens to an child object
:param list ts: list of tokens
"""
if isinstance(ts, six.string_types):
ts = [ts]
obj = self
while len(ts) > 0:
t = ts.pop(0)
if issubclass(obj.__class__, BaseObj... | [
"def",
"resolve",
"(",
"self",
",",
"ts",
")",
":",
"if",
"isinstance",
"(",
"ts",
",",
"six",
".",
"string_types",
")",
":",
"ts",
"=",
"[",
"ts",
"]",
"obj",
"=",
"self",
"while",
"len",
"(",
"ts",
")",
">",
"0",
":",
"t",
"=",
"ts",
".",
... | resolve a list of tokens to an child object
:param list ts: list of tokens | [
"resolve",
"a",
"list",
"of",
"tokens",
"to",
"an",
"child",
"object"
] | 333c4ca08e758cd2194943d9904a3eda3fe43977 | https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/spec/base.py#L259-L278 | train |
pyopenapi/pyswagger | pyswagger/spec/base.py | BaseObj.compare | def compare(self, other, base=None):
""" comparison, will return the first difference """
if self.__class__ != other.__class__:
return False, ''
names = self._field_names_
def cmp_func(name, s, o):
# special case for string types
if isinstance(s, six... | python | def compare(self, other, base=None):
""" comparison, will return the first difference """
if self.__class__ != other.__class__:
return False, ''
names = self._field_names_
def cmp_func(name, s, o):
# special case for string types
if isinstance(s, six... | [
"def",
"compare",
"(",
"self",
",",
"other",
",",
"base",
"=",
"None",
")",
":",
"if",
"self",
".",
"__class__",
"!=",
"other",
".",
"__class__",
":",
"return",
"False",
",",
"''",
"names",
"=",
"self",
".",
"_field_names_",
"def",
"cmp_func",
"(",
"... | comparison, will return the first difference | [
"comparison",
"will",
"return",
"the",
"first",
"difference"
] | 333c4ca08e758cd2194943d9904a3eda3fe43977 | https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/spec/base.py#L345-L391 | train |
pyopenapi/pyswagger | pyswagger/spec/base.py | BaseObj._field_names_ | def _field_names_(self):
""" get list of field names defined in Swagger spec
:return: a list of field names
:rtype: a list of str
"""
ret = []
for n in six.iterkeys(self.__swagger_fields__):
new_n = self.__swagger_rename__.get(n, None)
ret.append(... | python | def _field_names_(self):
""" get list of field names defined in Swagger spec
:return: a list of field names
:rtype: a list of str
"""
ret = []
for n in six.iterkeys(self.__swagger_fields__):
new_n = self.__swagger_rename__.get(n, None)
ret.append(... | [
"def",
"_field_names_",
"(",
"self",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"n",
"in",
"six",
".",
"iterkeys",
"(",
"self",
".",
"__swagger_fields__",
")",
":",
"new_n",
"=",
"self",
".",
"__swagger_rename__",
".",
"get",
"(",
"n",
",",
"None",
")",
... | get list of field names defined in Swagger spec
:return: a list of field names
:rtype: a list of str | [
"get",
"list",
"of",
"field",
"names",
"defined",
"in",
"Swagger",
"spec"
] | 333c4ca08e758cd2194943d9904a3eda3fe43977 | https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/spec/base.py#L438-L449 | train |
pyopenapi/pyswagger | pyswagger/spec/base.py | BaseObj._children_ | def _children_(self):
""" get children objects
:rtype: a dict of children {child_name: child_object}
"""
ret = {}
names = self._field_names_
def down(name, obj):
if isinstance(obj, BaseObj):
if not isinstance(obj, weakref.ProxyTypes):
... | python | def _children_(self):
""" get children objects
:rtype: a dict of children {child_name: child_object}
"""
ret = {}
names = self._field_names_
def down(name, obj):
if isinstance(obj, BaseObj):
if not isinstance(obj, weakref.ProxyTypes):
... | [
"def",
"_children_",
"(",
"self",
")",
":",
"ret",
"=",
"{",
"}",
"names",
"=",
"self",
".",
"_field_names_",
"def",
"down",
"(",
"name",
",",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"BaseObj",
")",
":",
"if",
"not",
"isinstance",
"("... | get children objects
:rtype: a dict of children {child_name: child_object} | [
"get",
"children",
"objects"
] | 333c4ca08e758cd2194943d9904a3eda3fe43977 | https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/spec/base.py#L452-L474 | train |
pyopenapi/pyswagger | pyswagger/core.py | App.load | def load(kls, url, getter=None, parser=None, url_load_hook=None, sep=consts.private.SCOPE_SEPARATOR, prim=None, mime_codec=None, resolver=None):
""" load json as a raw App
:param str url: url of path of Swagger API definition
:param getter: customized Getter
:type getter: sub class/inst... | python | def load(kls, url, getter=None, parser=None, url_load_hook=None, sep=consts.private.SCOPE_SEPARATOR, prim=None, mime_codec=None, resolver=None):
""" load json as a raw App
:param str url: url of path of Swagger API definition
:param getter: customized Getter
:type getter: sub class/inst... | [
"def",
"load",
"(",
"kls",
",",
"url",
",",
"getter",
"=",
"None",
",",
"parser",
"=",
"None",
",",
"url_load_hook",
"=",
"None",
",",
"sep",
"=",
"consts",
".",
"private",
".",
"SCOPE_SEPARATOR",
",",
"prim",
"=",
"None",
",",
"mime_codec",
"=",
"No... | load json as a raw App
:param str url: url of path of Swagger API definition
:param getter: customized Getter
:type getter: sub class/instance of Getter
:param parser: the parser to parse the loaded json.
:type parser: pyswagger.base.Context
:param dict app_cache: the ca... | [
"load",
"json",
"as",
"a",
"raw",
"App"
] | 333c4ca08e758cd2194943d9904a3eda3fe43977 | https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/core.py#L261-L294 | train |
pyopenapi/pyswagger | pyswagger/core.py | App.prepare | def prepare(self, strict=True):
""" preparation for loaded json
:param bool strict: when in strict mode, exception would be raised if not valid.
"""
self.__root = self.prepare_obj(self.raw, self.__url)
self.validate(strict=strict)
if hasattr(self.__root, 'schemes') and... | python | def prepare(self, strict=True):
""" preparation for loaded json
:param bool strict: when in strict mode, exception would be raised if not valid.
"""
self.__root = self.prepare_obj(self.raw, self.__url)
self.validate(strict=strict)
if hasattr(self.__root, 'schemes') and... | [
"def",
"prepare",
"(",
"self",
",",
"strict",
"=",
"True",
")",
":",
"self",
".",
"__root",
"=",
"self",
".",
"prepare_obj",
"(",
"self",
".",
"raw",
",",
"self",
".",
"__url",
")",
"self",
".",
"validate",
"(",
"strict",
"=",
"strict",
")",
"if",
... | preparation for loaded json
:param bool strict: when in strict mode, exception would be raised if not valid. | [
"preparation",
"for",
"loaded",
"json"
] | 333c4ca08e758cd2194943d9904a3eda3fe43977 | https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/core.py#L312-L351 | train |
pyopenapi/pyswagger | pyswagger/core.py | App.create | def create(kls, url, strict=True):
""" factory of App
:param str url: url of path of Swagger API definition
:param bool strict: when in strict mode, exception would be raised if not valid.
:return: the created App object
:rtype: App
:raises ValueError: if url is wrong
... | python | def create(kls, url, strict=True):
""" factory of App
:param str url: url of path of Swagger API definition
:param bool strict: when in strict mode, exception would be raised if not valid.
:return: the created App object
:rtype: App
:raises ValueError: if url is wrong
... | [
"def",
"create",
"(",
"kls",
",",
"url",
",",
"strict",
"=",
"True",
")",
":",
"app",
"=",
"kls",
".",
"load",
"(",
"url",
")",
"app",
".",
"prepare",
"(",
"strict",
"=",
"strict",
")",
"return",
"app"
] | factory of App
:param str url: url of path of Swagger API definition
:param bool strict: when in strict mode, exception would be raised if not valid.
:return: the created App object
:rtype: App
:raises ValueError: if url is wrong
:raises NotImplementedError: the swagger ... | [
"factory",
"of",
"App"
] | 333c4ca08e758cd2194943d9904a3eda3fe43977 | https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/core.py#L354-L367 | train |
pyopenapi/pyswagger | pyswagger/core.py | App.resolve | def resolve(self, jref, parser=None):
""" JSON reference resolver
:param str jref: a JSON Reference, refer to http://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03 for details.
:param parser: the parser corresponding to target object.
:type parser: pyswagger.base.Context
:retu... | python | def resolve(self, jref, parser=None):
""" JSON reference resolver
:param str jref: a JSON Reference, refer to http://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03 for details.
:param parser: the parser corresponding to target object.
:type parser: pyswagger.base.Context
:retu... | [
"def",
"resolve",
"(",
"self",
",",
"jref",
",",
"parser",
"=",
"None",
")",
":",
"logger",
".",
"info",
"(",
"'resolving: [{0}]'",
".",
"format",
"(",
"jref",
")",
")",
"if",
"jref",
"==",
"None",
"or",
"len",
"(",
"jref",
")",
"==",
"0",
":",
"... | JSON reference resolver
:param str jref: a JSON Reference, refer to http://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03 for details.
:param parser: the parser corresponding to target object.
:type parser: pyswagger.base.Context
:return: the referenced object, wrapped by weakref.Prox... | [
"JSON",
"reference",
"resolver"
] | 333c4ca08e758cd2194943d9904a3eda3fe43977 | https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/core.py#L374-L426 | train |
pyopenapi/pyswagger | pyswagger/core.py | BaseClient.prepare_schemes | def prepare_schemes(self, req):
""" make sure this client support schemes required by current request
:param pyswagger.io.Request req: current request object
"""
# fix test bug when in python3 scheme, more details in commint msg
ret = sorted(self.__schemes__ & set(req.schemes),... | python | def prepare_schemes(self, req):
""" make sure this client support schemes required by current request
:param pyswagger.io.Request req: current request object
"""
# fix test bug when in python3 scheme, more details in commint msg
ret = sorted(self.__schemes__ & set(req.schemes),... | [
"def",
"prepare_schemes",
"(",
"self",
",",
"req",
")",
":",
"# fix test bug when in python3 scheme, more details in commint msg",
"ret",
"=",
"sorted",
"(",
"self",
".",
"__schemes__",
"&",
"set",
"(",
"req",
".",
"schemes",
")",
",",
"reverse",
"=",
"True",
")... | make sure this client support schemes required by current request
:param pyswagger.io.Request req: current request object | [
"make",
"sure",
"this",
"client",
"support",
"schemes",
"required",
"by",
"current",
"request"
] | 333c4ca08e758cd2194943d9904a3eda3fe43977 | https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/core.py#L558-L569 | train |
pyopenapi/pyswagger | pyswagger/core.py | BaseClient.compose_headers | def compose_headers(self, req, headers=None, opt=None, as_dict=False):
""" a utility to compose headers from pyswagger.io.Request and customized headers
:return: list of tuple (key, value) when as_dict is False, else dict
"""
if headers is None:
return list(req.header.items(... | python | def compose_headers(self, req, headers=None, opt=None, as_dict=False):
""" a utility to compose headers from pyswagger.io.Request and customized headers
:return: list of tuple (key, value) when as_dict is False, else dict
"""
if headers is None:
return list(req.header.items(... | [
"def",
"compose_headers",
"(",
"self",
",",
"req",
",",
"headers",
"=",
"None",
",",
"opt",
"=",
"None",
",",
"as_dict",
"=",
"False",
")",
":",
"if",
"headers",
"is",
"None",
":",
"return",
"list",
"(",
"req",
".",
"header",
".",
"items",
"(",
")"... | a utility to compose headers from pyswagger.io.Request and customized headers
:return: list of tuple (key, value) when as_dict is False, else dict | [
"a",
"utility",
"to",
"compose",
"headers",
"from",
"pyswagger",
".",
"io",
".",
"Request",
"and",
"customized",
"headers"
] | 333c4ca08e758cd2194943d9904a3eda3fe43977 | https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/core.py#L571-L608 | train |
pyopenapi/pyswagger | pyswagger/core.py | BaseClient.request | def request(self, req_and_resp, opt=None, headers=None):
""" preprocess before performing a request, usually some patching.
authorization also applied here.
:param req_and_resp: tuple of Request and Response
:type req_and_resp: (Request, Response)
:param opt: customized options
... | python | def request(self, req_and_resp, opt=None, headers=None):
""" preprocess before performing a request, usually some patching.
authorization also applied here.
:param req_and_resp: tuple of Request and Response
:type req_and_resp: (Request, Response)
:param opt: customized options
... | [
"def",
"request",
"(",
"self",
",",
"req_and_resp",
",",
"opt",
"=",
"None",
",",
"headers",
"=",
"None",
")",
":",
"req",
",",
"resp",
"=",
"req_and_resp",
"# dump info for debugging",
"logger",
".",
"info",
"(",
"'request.url: {0}'",
".",
"format",
"(",
... | preprocess before performing a request, usually some patching.
authorization also applied here.
:param req_and_resp: tuple of Request and Response
:type req_and_resp: (Request, Response)
:param opt: customized options
:type opt: dict
:param headers: customized headers
... | [
"preprocess",
"before",
"performing",
"a",
"request",
"usually",
"some",
"patching",
".",
"authorization",
"also",
"applied",
"here",
"."
] | 333c4ca08e758cd2194943d9904a3eda3fe43977 | https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/core.py#L610-L636 | train |
pyopenapi/pyswagger | pyswagger/primitives/_array.py | Array.to_url | def to_url(self):
""" special function for handling 'multi',
refer to Swagger 2.0, Parameter Object, collectionFormat
"""
if self.__collection_format == 'multi':
return [str(s) for s in self]
else:
return [str(self)] | python | def to_url(self):
""" special function for handling 'multi',
refer to Swagger 2.0, Parameter Object, collectionFormat
"""
if self.__collection_format == 'multi':
return [str(s) for s in self]
else:
return [str(self)] | [
"def",
"to_url",
"(",
"self",
")",
":",
"if",
"self",
".",
"__collection_format",
"==",
"'multi'",
":",
"return",
"[",
"str",
"(",
"s",
")",
"for",
"s",
"in",
"self",
"]",
"else",
":",
"return",
"[",
"str",
"(",
"self",
")",
"]"
] | special function for handling 'multi',
refer to Swagger 2.0, Parameter Object, collectionFormat | [
"special",
"function",
"for",
"handling",
"multi",
"refer",
"to",
"Swagger",
"2",
".",
"0",
"Parameter",
"Object",
"collectionFormat"
] | 333c4ca08e758cd2194943d9904a3eda3fe43977 | https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/primitives/_array.py#L83-L90 | train |
pyopenapi/pyswagger | pyswagger/primitives/_model.py | Model.apply_with | def apply_with(self, obj, val, ctx):
""" recursively apply Schema object
:param obj.Model obj: model object to instruct how to create this model
:param dict val: things used to construct this model
"""
for k, v in six.iteritems(val):
if k in obj.properties:
... | python | def apply_with(self, obj, val, ctx):
""" recursively apply Schema object
:param obj.Model obj: model object to instruct how to create this model
:param dict val: things used to construct this model
"""
for k, v in six.iteritems(val):
if k in obj.properties:
... | [
"def",
"apply_with",
"(",
"self",
",",
"obj",
",",
"val",
",",
"ctx",
")",
":",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"val",
")",
":",
"if",
"k",
"in",
"obj",
".",
"properties",
":",
"pobj",
"=",
"obj",
".",
"properties",
".... | recursively apply Schema object
:param obj.Model obj: model object to instruct how to create this model
:param dict val: things used to construct this model | [
"recursively",
"apply",
"Schema",
"object"
] | 333c4ca08e758cd2194943d9904a3eda3fe43977 | https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/primitives/_model.py#L17-L60 | train |
pyopenapi/pyswagger | pyswagger/scanner/v2_0/yaml.py | YamlFixer._op | def _op(self, _, obj, app):
""" convert status code in Responses from int to string
"""
if obj.responses == None: return
tmp = {}
for k, v in six.iteritems(obj.responses):
if isinstance(k, six.integer_types):
tmp[str(k)] = v
else:
... | python | def _op(self, _, obj, app):
""" convert status code in Responses from int to string
"""
if obj.responses == None: return
tmp = {}
for k, v in six.iteritems(obj.responses):
if isinstance(k, six.integer_types):
tmp[str(k)] = v
else:
... | [
"def",
"_op",
"(",
"self",
",",
"_",
",",
"obj",
",",
"app",
")",
":",
"if",
"obj",
".",
"responses",
"==",
"None",
":",
"return",
"tmp",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"obj",
".",
"responses",
")",
"... | convert status code in Responses from int to string | [
"convert",
"status",
"code",
"in",
"Responses",
"from",
"int",
"to",
"string"
] | 333c4ca08e758cd2194943d9904a3eda3fe43977 | https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/scanner/v2_0/yaml.py#L15-L26 | train |
pyopenapi/pyswagger | pyswagger/primitives/__init__.py | Primitive.produce | def produce(self, obj, val, ctx=None):
""" factory function to create primitives
:param pyswagger.spec.v2_0.objects.Schema obj: spec to construct primitives
:param val: value to construct primitives
:return: the created primitive
"""
val = obj.default if val == None els... | python | def produce(self, obj, val, ctx=None):
""" factory function to create primitives
:param pyswagger.spec.v2_0.objects.Schema obj: spec to construct primitives
:param val: value to construct primitives
:return: the created primitive
"""
val = obj.default if val == None els... | [
"def",
"produce",
"(",
"self",
",",
"obj",
",",
"val",
",",
"ctx",
"=",
"None",
")",
":",
"val",
"=",
"obj",
".",
"default",
"if",
"val",
"==",
"None",
"else",
"val",
"if",
"val",
"==",
"None",
":",
"return",
"None",
"obj",
"=",
"deref",
"(",
"... | factory function to create primitives
:param pyswagger.spec.v2_0.objects.Schema obj: spec to construct primitives
:param val: value to construct primitives
:return: the created primitive | [
"factory",
"function",
"to",
"create",
"primitives"
] | 333c4ca08e758cd2194943d9904a3eda3fe43977 | https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/primitives/__init__.py#L151-L243 | train |
arogozhnikov/einops | einops/einops.py | _check_elementary_axis_name | def _check_elementary_axis_name(name: str) -> bool:
"""
Valid elementary axes contain only lower latin letters and digits and start with a letter.
"""
if len(name) == 0:
return False
if not 'a' <= name[0] <= 'z':
return False
for letter in name:
if (not letter.isdigit()) ... | python | def _check_elementary_axis_name(name: str) -> bool:
"""
Valid elementary axes contain only lower latin letters and digits and start with a letter.
"""
if len(name) == 0:
return False
if not 'a' <= name[0] <= 'z':
return False
for letter in name:
if (not letter.isdigit()) ... | [
"def",
"_check_elementary_axis_name",
"(",
"name",
":",
"str",
")",
"->",
"bool",
":",
"if",
"len",
"(",
"name",
")",
"==",
"0",
":",
"return",
"False",
"if",
"not",
"'a'",
"<=",
"name",
"[",
"0",
"]",
"<=",
"'z'",
":",
"return",
"False",
"for",
"l... | Valid elementary axes contain only lower latin letters and digits and start with a letter. | [
"Valid",
"elementary",
"axes",
"contain",
"only",
"lower",
"latin",
"letters",
"and",
"digits",
"and",
"start",
"with",
"a",
"letter",
"."
] | 9698f0f5efa6c5a79daa75253137ba5d79a95615 | https://github.com/arogozhnikov/einops/blob/9698f0f5efa6c5a79daa75253137ba5d79a95615/einops/einops.py#L268-L279 | train |
Kautenja/nes-py | nes_py/_image_viewer.py | ImageViewer.open | def open(self):
"""Open the window."""
self._window = Window(
caption=self.caption,
height=self.height,
width=self.width,
vsync=False,
resizable=True,
) | python | def open(self):
"""Open the window."""
self._window = Window(
caption=self.caption,
height=self.height,
width=self.width,
vsync=False,
resizable=True,
) | [
"def",
"open",
"(",
"self",
")",
":",
"self",
".",
"_window",
"=",
"Window",
"(",
"caption",
"=",
"self",
".",
"caption",
",",
"height",
"=",
"self",
".",
"height",
",",
"width",
"=",
"self",
".",
"width",
",",
"vsync",
"=",
"False",
",",
"resizabl... | Open the window. | [
"Open",
"the",
"window",
"."
] | a113885198d418f38fcf24b8f79ac508975788c2 | https://github.com/Kautenja/nes-py/blob/a113885198d418f38fcf24b8f79ac508975788c2/nes_py/_image_viewer.py#L40-L48 | train |
Kautenja/nes-py | nes_py/_image_viewer.py | ImageViewer.show | def show(self, frame):
"""
Show an array of pixels on the window.
Args:
frame (numpy.ndarray): the frame to show on the window
Returns:
None
"""
# check that the frame has the correct dimensions
if len(frame.shape) != 3:
raise... | python | def show(self, frame):
"""
Show an array of pixels on the window.
Args:
frame (numpy.ndarray): the frame to show on the window
Returns:
None
"""
# check that the frame has the correct dimensions
if len(frame.shape) != 3:
raise... | [
"def",
"show",
"(",
"self",
",",
"frame",
")",
":",
"# check that the frame has the correct dimensions",
"if",
"len",
"(",
"frame",
".",
"shape",
")",
"!=",
"3",
":",
"raise",
"ValueError",
"(",
"'frame should have shape with only 3 dimensions'",
")",
"# open the wind... | Show an array of pixels on the window.
Args:
frame (numpy.ndarray): the frame to show on the window
Returns:
None | [
"Show",
"an",
"array",
"of",
"pixels",
"on",
"the",
"window",
"."
] | a113885198d418f38fcf24b8f79ac508975788c2 | https://github.com/Kautenja/nes-py/blob/a113885198d418f38fcf24b8f79ac508975788c2/nes_py/_image_viewer.py#L50-L80 | train |
Kautenja/nes-py | nes_py/app/play_human.py | display_arr | def display_arr(screen, arr, video_size, transpose):
"""
Display an image to the pygame screen.
Args:
screen (pygame.Surface): the pygame surface to write frames to
arr (np.ndarray): numpy array representing a single frame of gameplay
video_size (tuple): the size to render the frame... | python | def display_arr(screen, arr, video_size, transpose):
"""
Display an image to the pygame screen.
Args:
screen (pygame.Surface): the pygame surface to write frames to
arr (np.ndarray): numpy array representing a single frame of gameplay
video_size (tuple): the size to render the frame... | [
"def",
"display_arr",
"(",
"screen",
",",
"arr",
",",
"video_size",
",",
"transpose",
")",
":",
"# take the transpose if necessary",
"if",
"transpose",
":",
"pyg_img",
"=",
"pygame",
".",
"surfarray",
".",
"make_surface",
"(",
"arr",
".",
"swapaxes",
"(",
"0",... | Display an image to the pygame screen.
Args:
screen (pygame.Surface): the pygame surface to write frames to
arr (np.ndarray): numpy array representing a single frame of gameplay
video_size (tuple): the size to render the frame as
transpose (bool): whether to transpose the frame befo... | [
"Display",
"an",
"image",
"to",
"the",
"pygame",
"screen",
"."
] | a113885198d418f38fcf24b8f79ac508975788c2 | https://github.com/Kautenja/nes-py/blob/a113885198d418f38fcf24b8f79ac508975788c2/nes_py/app/play_human.py#L6-L28 | train |
Kautenja/nes-py | nes_py/app/play_human.py | play | def play(env, transpose=True, fps=30, nop_=0):
"""Play the game using the keyboard as a human.
Args:
env (gym.Env): the environment to use for playing
transpose (bool): whether to transpose frame before viewing them
fps (int): number of steps of the environment to execute every second
... | python | def play(env, transpose=True, fps=30, nop_=0):
"""Play the game using the keyboard as a human.
Args:
env (gym.Env): the environment to use for playing
transpose (bool): whether to transpose frame before viewing them
fps (int): number of steps of the environment to execute every second
... | [
"def",
"play",
"(",
"env",
",",
"transpose",
"=",
"True",
",",
"fps",
"=",
"30",
",",
"nop_",
"=",
"0",
")",
":",
"# ensure the observation space is a box of pixels",
"assert",
"isinstance",
"(",
"env",
".",
"observation_space",
",",
"gym",
".",
"spaces",
".... | Play the game using the keyboard as a human.
Args:
env (gym.Env): the environment to use for playing
transpose (bool): whether to transpose frame before viewing them
fps (int): number of steps of the environment to execute every second
nop_ (any): the object to use as a null op acti... | [
"Play",
"the",
"game",
"using",
"the",
"keyboard",
"as",
"a",
"human",
"."
] | a113885198d418f38fcf24b8f79ac508975788c2 | https://github.com/Kautenja/nes-py/blob/a113885198d418f38fcf24b8f79ac508975788c2/nes_py/app/play_human.py#L31-L135 | train |
Kautenja/nes-py | nes_py/app/play_human.py | play_human | def play_human(env):
"""
Play the environment using keyboard as a human.
Args:
env (gym.Env): the initialized gym environment to play
Returns:
None
"""
# play the game and catch a potential keyboard interrupt
try:
play(env, fps=env.metadata['video.frames_per_second... | python | def play_human(env):
"""
Play the environment using keyboard as a human.
Args:
env (gym.Env): the initialized gym environment to play
Returns:
None
"""
# play the game and catch a potential keyboard interrupt
try:
play(env, fps=env.metadata['video.frames_per_second... | [
"def",
"play_human",
"(",
"env",
")",
":",
"# play the game and catch a potential keyboard interrupt",
"try",
":",
"play",
"(",
"env",
",",
"fps",
"=",
"env",
".",
"metadata",
"[",
"'video.frames_per_second'",
"]",
")",
"except",
"KeyboardInterrupt",
":",
"pass",
... | Play the environment using keyboard as a human.
Args:
env (gym.Env): the initialized gym environment to play
Returns:
None | [
"Play",
"the",
"environment",
"using",
"keyboard",
"as",
"a",
"human",
"."
] | a113885198d418f38fcf24b8f79ac508975788c2 | https://github.com/Kautenja/nes-py/blob/a113885198d418f38fcf24b8f79ac508975788c2/nes_py/app/play_human.py#L138-L155 | train |
Kautenja/nes-py | nes_py/wrappers/binary_to_discrete_space_env.py | BinarySpaceToDiscreteSpaceEnv.get_action_meanings | def get_action_meanings(self):
"""Return a list of actions meanings."""
actions = sorted(self._action_meanings.keys())
return [self._action_meanings[action] for action in actions] | python | def get_action_meanings(self):
"""Return a list of actions meanings."""
actions = sorted(self._action_meanings.keys())
return [self._action_meanings[action] for action in actions] | [
"def",
"get_action_meanings",
"(",
"self",
")",
":",
"actions",
"=",
"sorted",
"(",
"self",
".",
"_action_meanings",
".",
"keys",
"(",
")",
")",
"return",
"[",
"self",
".",
"_action_meanings",
"[",
"action",
"]",
"for",
"action",
"in",
"actions",
"]"
] | Return a list of actions meanings. | [
"Return",
"a",
"list",
"of",
"actions",
"meanings",
"."
] | a113885198d418f38fcf24b8f79ac508975788c2 | https://github.com/Kautenja/nes-py/blob/a113885198d418f38fcf24b8f79ac508975788c2/nes_py/wrappers/binary_to_discrete_space_env.py#L90-L93 | train |
Kautenja/nes-py | nes_py/_rom.py | ROM.prg_rom | def prg_rom(self):
"""Return the PRG ROM of the ROM file."""
try:
return self.raw_data[self.prg_rom_start:self.prg_rom_stop]
except IndexError:
raise ValueError('failed to read PRG-ROM on ROM.') | python | def prg_rom(self):
"""Return the PRG ROM of the ROM file."""
try:
return self.raw_data[self.prg_rom_start:self.prg_rom_stop]
except IndexError:
raise ValueError('failed to read PRG-ROM on ROM.') | [
"def",
"prg_rom",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"raw_data",
"[",
"self",
".",
"prg_rom_start",
":",
"self",
".",
"prg_rom_stop",
"]",
"except",
"IndexError",
":",
"raise",
"ValueError",
"(",
"'failed to read PRG-ROM on ROM.'",
")"
] | Return the PRG ROM of the ROM file. | [
"Return",
"the",
"PRG",
"ROM",
"of",
"the",
"ROM",
"file",
"."
] | a113885198d418f38fcf24b8f79ac508975788c2 | https://github.com/Kautenja/nes-py/blob/a113885198d418f38fcf24b8f79ac508975788c2/nes_py/_rom.py#L201-L206 | train |
Kautenja/nes-py | nes_py/_rom.py | ROM.chr_rom | def chr_rom(self):
"""Return the CHR ROM of the ROM file."""
try:
return self.raw_data[self.chr_rom_start:self.chr_rom_stop]
except IndexError:
raise ValueError('failed to read CHR-ROM on ROM.') | python | def chr_rom(self):
"""Return the CHR ROM of the ROM file."""
try:
return self.raw_data[self.chr_rom_start:self.chr_rom_stop]
except IndexError:
raise ValueError('failed to read CHR-ROM on ROM.') | [
"def",
"chr_rom",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"raw_data",
"[",
"self",
".",
"chr_rom_start",
":",
"self",
".",
"chr_rom_stop",
"]",
"except",
"IndexError",
":",
"raise",
"ValueError",
"(",
"'failed to read CHR-ROM on ROM.'",
")"
] | Return the CHR ROM of the ROM file. | [
"Return",
"the",
"CHR",
"ROM",
"of",
"the",
"ROM",
"file",
"."
] | a113885198d418f38fcf24b8f79ac508975788c2 | https://github.com/Kautenja/nes-py/blob/a113885198d418f38fcf24b8f79ac508975788c2/nes_py/_rom.py#L219-L224 | train |
Kautenja/nes-py | nes_py/nes_env.py | NESEnv._screen_buffer | def _screen_buffer(self):
"""Setup the screen buffer from the C++ code."""
# get the address of the screen
address = _LIB.Screen(self._env)
# create a buffer from the contents of the address location
buffer_ = ctypes.cast(address, ctypes.POINTER(SCREEN_TENSOR)).contents
#... | python | def _screen_buffer(self):
"""Setup the screen buffer from the C++ code."""
# get the address of the screen
address = _LIB.Screen(self._env)
# create a buffer from the contents of the address location
buffer_ = ctypes.cast(address, ctypes.POINTER(SCREEN_TENSOR)).contents
#... | [
"def",
"_screen_buffer",
"(",
"self",
")",
":",
"# get the address of the screen",
"address",
"=",
"_LIB",
".",
"Screen",
"(",
"self",
".",
"_env",
")",
"# create a buffer from the contents of the address location",
"buffer_",
"=",
"ctypes",
".",
"cast",
"(",
"address... | Setup the screen buffer from the C++ code. | [
"Setup",
"the",
"screen",
"buffer",
"from",
"the",
"C",
"++",
"code",
"."
] | a113885198d418f38fcf24b8f79ac508975788c2 | https://github.com/Kautenja/nes-py/blob/a113885198d418f38fcf24b8f79ac508975788c2/nes_py/nes_env.py#L152-L167 | train |
Kautenja/nes-py | nes_py/nes_env.py | NESEnv._ram_buffer | def _ram_buffer(self):
"""Setup the RAM buffer from the C++ code."""
# get the address of the RAM
address = _LIB.Memory(self._env)
# create a buffer from the contents of the address location
buffer_ = ctypes.cast(address, ctypes.POINTER(RAM_VECTOR)).contents
# create a Nu... | python | def _ram_buffer(self):
"""Setup the RAM buffer from the C++ code."""
# get the address of the RAM
address = _LIB.Memory(self._env)
# create a buffer from the contents of the address location
buffer_ = ctypes.cast(address, ctypes.POINTER(RAM_VECTOR)).contents
# create a Nu... | [
"def",
"_ram_buffer",
"(",
"self",
")",
":",
"# get the address of the RAM",
"address",
"=",
"_LIB",
".",
"Memory",
"(",
"self",
".",
"_env",
")",
"# create a buffer from the contents of the address location",
"buffer_",
"=",
"ctypes",
".",
"cast",
"(",
"address",
"... | Setup the RAM buffer from the C++ code. | [
"Setup",
"the",
"RAM",
"buffer",
"from",
"the",
"C",
"++",
"code",
"."
] | a113885198d418f38fcf24b8f79ac508975788c2 | https://github.com/Kautenja/nes-py/blob/a113885198d418f38fcf24b8f79ac508975788c2/nes_py/nes_env.py#L169-L176 | train |
Kautenja/nes-py | nes_py/nes_env.py | NESEnv._controller_buffer | def _controller_buffer(self, port):
"""
Find the pointer to a controller and setup a NumPy buffer.
Args:
port: the port of the controller to setup
Returns:
a NumPy buffer with the controller's binary data
"""
# get the address of the controller
... | python | def _controller_buffer(self, port):
"""
Find the pointer to a controller and setup a NumPy buffer.
Args:
port: the port of the controller to setup
Returns:
a NumPy buffer with the controller's binary data
"""
# get the address of the controller
... | [
"def",
"_controller_buffer",
"(",
"self",
",",
"port",
")",
":",
"# get the address of the controller",
"address",
"=",
"_LIB",
".",
"Controller",
"(",
"self",
".",
"_env",
",",
"port",
")",
"# create a memory buffer using the ctypes pointer for this vector",
"buffer_",
... | Find the pointer to a controller and setup a NumPy buffer.
Args:
port: the port of the controller to setup
Returns:
a NumPy buffer with the controller's binary data | [
"Find",
"the",
"pointer",
"to",
"a",
"controller",
"and",
"setup",
"a",
"NumPy",
"buffer",
"."
] | a113885198d418f38fcf24b8f79ac508975788c2 | https://github.com/Kautenja/nes-py/blob/a113885198d418f38fcf24b8f79ac508975788c2/nes_py/nes_env.py#L178-L194 | train |
Kautenja/nes-py | nes_py/nes_env.py | NESEnv._frame_advance | def _frame_advance(self, action):
"""
Advance a frame in the emulator with an action.
Args:
action (byte): the action to press on the joy-pad
Returns:
None
"""
# set the action on the controller
self.controllers[0][:] = action
# ... | python | def _frame_advance(self, action):
"""
Advance a frame in the emulator with an action.
Args:
action (byte): the action to press on the joy-pad
Returns:
None
"""
# set the action on the controller
self.controllers[0][:] = action
# ... | [
"def",
"_frame_advance",
"(",
"self",
",",
"action",
")",
":",
"# set the action on the controller",
"self",
".",
"controllers",
"[",
"0",
"]",
"[",
":",
"]",
"=",
"action",
"# perform a step on the emulator",
"_LIB",
".",
"Step",
"(",
"self",
".",
"_env",
")"... | Advance a frame in the emulator with an action.
Args:
action (byte): the action to press on the joy-pad
Returns:
None | [
"Advance",
"a",
"frame",
"in",
"the",
"emulator",
"with",
"an",
"action",
"."
] | a113885198d418f38fcf24b8f79ac508975788c2 | https://github.com/Kautenja/nes-py/blob/a113885198d418f38fcf24b8f79ac508975788c2/nes_py/nes_env.py#L196-L210 | train |
Kautenja/nes-py | nes_py/nes_env.py | NESEnv.reset | def reset(self):
"""
Reset the state of the environment and returns an initial observation.
Returns:
state (np.ndarray): next frame as a result of the given action
"""
# call the before reset callback
self._will_reset()
# reset the emulator
i... | python | def reset(self):
"""
Reset the state of the environment and returns an initial observation.
Returns:
state (np.ndarray): next frame as a result of the given action
"""
# call the before reset callback
self._will_reset()
# reset the emulator
i... | [
"def",
"reset",
"(",
"self",
")",
":",
"# call the before reset callback",
"self",
".",
"_will_reset",
"(",
")",
"# reset the emulator",
"if",
"self",
".",
"_has_backup",
":",
"self",
".",
"_restore",
"(",
")",
"else",
":",
"_LIB",
".",
"Reset",
"(",
"self",... | Reset the state of the environment and returns an initial observation.
Returns:
state (np.ndarray): next frame as a result of the given action | [
"Reset",
"the",
"state",
"of",
"the",
"environment",
"and",
"returns",
"an",
"initial",
"observation",
"."
] | a113885198d418f38fcf24b8f79ac508975788c2 | https://github.com/Kautenja/nes-py/blob/a113885198d418f38fcf24b8f79ac508975788c2/nes_py/nes_env.py#L245-L265 | train |
Kautenja/nes-py | nes_py/nes_env.py | NESEnv.step | def step(self, action):
"""
Run one frame of the NES and return the relevant observation data.
Args:
action (byte): the bitmap determining which buttons to press
Returns:
a tuple of:
- state (np.ndarray): next frame as a result of the given action
... | python | def step(self, action):
"""
Run one frame of the NES and return the relevant observation data.
Args:
action (byte): the bitmap determining which buttons to press
Returns:
a tuple of:
- state (np.ndarray): next frame as a result of the given action
... | [
"def",
"step",
"(",
"self",
",",
"action",
")",
":",
"# if the environment is done, raise an error",
"if",
"self",
".",
"done",
":",
"raise",
"ValueError",
"(",
"'cannot step in a done environment! call `reset`'",
")",
"# set the action on the controller",
"self",
".",
"c... | Run one frame of the NES and return the relevant observation data.
Args:
action (byte): the bitmap determining which buttons to press
Returns:
a tuple of:
- state (np.ndarray): next frame as a result of the given action
- reward (float) : amount of rewar... | [
"Run",
"one",
"frame",
"of",
"the",
"NES",
"and",
"return",
"the",
"relevant",
"observation",
"data",
"."
] | a113885198d418f38fcf24b8f79ac508975788c2 | https://github.com/Kautenja/nes-py/blob/a113885198d418f38fcf24b8f79ac508975788c2/nes_py/nes_env.py#L271-L307 | train |
Kautenja/nes-py | nes_py/nes_env.py | NESEnv.close | def close(self):
"""Close the environment."""
# make sure the environment hasn't already been closed
if self._env is None:
raise ValueError('env has already been closed.')
# purge the environment from C++ memory
_LIB.Close(self._env)
# deallocate the object lo... | python | def close(self):
"""Close the environment."""
# make sure the environment hasn't already been closed
if self._env is None:
raise ValueError('env has already been closed.')
# purge the environment from C++ memory
_LIB.Close(self._env)
# deallocate the object lo... | [
"def",
"close",
"(",
"self",
")",
":",
"# make sure the environment hasn't already been closed",
"if",
"self",
".",
"_env",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'env has already been closed.'",
")",
"# purge the environment from C++ memory",
"_LIB",
".",
"Close... | Close the environment. | [
"Close",
"the",
"environment",
"."
] | a113885198d418f38fcf24b8f79ac508975788c2 | https://github.com/Kautenja/nes-py/blob/a113885198d418f38fcf24b8f79ac508975788c2/nes_py/nes_env.py#L334-L345 | train |
Kautenja/nes-py | nes_py/nes_env.py | NESEnv.render | def render(self, mode='human'):
"""
Render the environment.
Args:
mode (str): the mode to render with:
- human: render to the current display
- rgb_array: Return an numpy.ndarray with shape (x, y, 3),
representing RGB values for an x-by-y pixel ... | python | def render(self, mode='human'):
"""
Render the environment.
Args:
mode (str): the mode to render with:
- human: render to the current display
- rgb_array: Return an numpy.ndarray with shape (x, y, 3),
representing RGB values for an x-by-y pixel ... | [
"def",
"render",
"(",
"self",
",",
"mode",
"=",
"'human'",
")",
":",
"if",
"mode",
"==",
"'human'",
":",
"# if the viewer isn't setup, import it and create one",
"if",
"self",
".",
"viewer",
"is",
"None",
":",
"from",
".",
"_image_viewer",
"import",
"ImageViewer... | Render the environment.
Args:
mode (str): the mode to render with:
- human: render to the current display
- rgb_array: Return an numpy.ndarray with shape (x, y, 3),
representing RGB values for an x-by-y pixel image
Returns:
a numpy array if... | [
"Render",
"the",
"environment",
"."
] | a113885198d418f38fcf24b8f79ac508975788c2 | https://github.com/Kautenja/nes-py/blob/a113885198d418f38fcf24b8f79ac508975788c2/nes_py/nes_env.py#L347-L386 | train |
Kautenja/nes-py | nes_py/app/cli.py | _get_args | def _get_args():
"""Parse arguments from the command line and return them."""
parser = argparse.ArgumentParser(description=__doc__)
# add the argument for the Super Mario Bros environment to run
parser.add_argument('--rom', '-r',
type=str,
help='The path to the ROM to play.',
req... | python | def _get_args():
"""Parse arguments from the command line and return them."""
parser = argparse.ArgumentParser(description=__doc__)
# add the argument for the Super Mario Bros environment to run
parser.add_argument('--rom', '-r',
type=str,
help='The path to the ROM to play.',
req... | [
"def",
"_get_args",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"__doc__",
")",
"# add the argument for the Super Mario Bros environment to run",
"parser",
".",
"add_argument",
"(",
"'--rom'",
",",
"'-r'",
",",
"type",
"... | Parse arguments from the command line and return them. | [
"Parse",
"arguments",
"from",
"the",
"command",
"line",
"and",
"return",
"them",
"."
] | a113885198d418f38fcf24b8f79ac508975788c2 | https://github.com/Kautenja/nes-py/blob/a113885198d418f38fcf24b8f79ac508975788c2/nes_py/app/cli.py#L8-L30 | train |
Kautenja/nes-py | nes_py/app/cli.py | main | def main():
"""The main entry point for the command line interface."""
# get arguments from the command line
args = _get_args()
# create the environment
env = NESEnv(args.rom)
# play the environment with the given mode
if args.mode == 'human':
play_human(env)
else:
play_r... | python | def main():
"""The main entry point for the command line interface."""
# get arguments from the command line
args = _get_args()
# create the environment
env = NESEnv(args.rom)
# play the environment with the given mode
if args.mode == 'human':
play_human(env)
else:
play_r... | [
"def",
"main",
"(",
")",
":",
"# get arguments from the command line",
"args",
"=",
"_get_args",
"(",
")",
"# create the environment",
"env",
"=",
"NESEnv",
"(",
"args",
".",
"rom",
")",
"# play the environment with the given mode",
"if",
"args",
".",
"mode",
"==",
... | The main entry point for the command line interface. | [
"The",
"main",
"entry",
"point",
"for",
"the",
"command",
"line",
"interface",
"."
] | a113885198d418f38fcf24b8f79ac508975788c2 | https://github.com/Kautenja/nes-py/blob/a113885198d418f38fcf24b8f79ac508975788c2/nes_py/app/cli.py#L33-L43 | train |
Kautenja/nes-py | nes_py/app/play_random.py | play_random | def play_random(env, steps):
"""
Play the environment making uniformly random decisions.
Args:
env (gym.Env): the initialized gym environment to play
steps (int): the number of random steps to take
Returns:
None
"""
try:
done = True
progress = tqdm(rang... | python | def play_random(env, steps):
"""
Play the environment making uniformly random decisions.
Args:
env (gym.Env): the initialized gym environment to play
steps (int): the number of random steps to take
Returns:
None
"""
try:
done = True
progress = tqdm(rang... | [
"def",
"play_random",
"(",
"env",
",",
"steps",
")",
":",
"try",
":",
"done",
"=",
"True",
"progress",
"=",
"tqdm",
"(",
"range",
"(",
"steps",
")",
")",
"for",
"_",
"in",
"progress",
":",
"if",
"done",
":",
"_",
"=",
"env",
".",
"reset",
"(",
... | Play the environment making uniformly random decisions.
Args:
env (gym.Env): the initialized gym environment to play
steps (int): the number of random steps to take
Returns:
None | [
"Play",
"the",
"environment",
"making",
"uniformly",
"random",
"decisions",
"."
] | a113885198d418f38fcf24b8f79ac508975788c2 | https://github.com/Kautenja/nes-py/blob/a113885198d418f38fcf24b8f79ac508975788c2/nes_py/app/play_random.py#L5-L30 | train |
czielinski/portfolioopt | portfolioopt/portfolioopt.py | markowitz_portfolio | def markowitz_portfolio(cov_mat, exp_rets, target_ret,
allow_short=False, market_neutral=False):
"""
Computes a Markowitz portfolio.
Parameters
----------
cov_mat: pandas.DataFrame
Covariance matrix of asset returns.
exp_rets: pandas.Series
Expected asset... | python | def markowitz_portfolio(cov_mat, exp_rets, target_ret,
allow_short=False, market_neutral=False):
"""
Computes a Markowitz portfolio.
Parameters
----------
cov_mat: pandas.DataFrame
Covariance matrix of asset returns.
exp_rets: pandas.Series
Expected asset... | [
"def",
"markowitz_portfolio",
"(",
"cov_mat",
",",
"exp_rets",
",",
"target_ret",
",",
"allow_short",
"=",
"False",
",",
"market_neutral",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"cov_mat",
",",
"pd",
".",
"DataFrame",
")",
":",
"raise",
"V... | Computes a Markowitz portfolio.
Parameters
----------
cov_mat: pandas.DataFrame
Covariance matrix of asset returns.
exp_rets: pandas.Series
Expected asset returns (often historical returns).
target_ret: float
Target return of portfolio.
allow_short: bool, optional
... | [
"Computes",
"a",
"Markowitz",
"portfolio",
"."
] | 96ac25daab0c0dbc8933330a92ff31fb898112f2 | https://github.com/czielinski/portfolioopt/blob/96ac25daab0c0dbc8933330a92ff31fb898112f2/portfolioopt/portfolioopt.py#L45-L122 | train |
czielinski/portfolioopt | portfolioopt/portfolioopt.py | min_var_portfolio | def min_var_portfolio(cov_mat, allow_short=False):
"""
Computes the minimum variance portfolio.
Note: As the variance is not invariant with respect
to leverage, it is not possible to construct non-trivial
market neutral minimum variance portfolios. This is because
the variance approaches zero w... | python | def min_var_portfolio(cov_mat, allow_short=False):
"""
Computes the minimum variance portfolio.
Note: As the variance is not invariant with respect
to leverage, it is not possible to construct non-trivial
market neutral minimum variance portfolios. This is because
the variance approaches zero w... | [
"def",
"min_var_portfolio",
"(",
"cov_mat",
",",
"allow_short",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"cov_mat",
",",
"pd",
".",
"DataFrame",
")",
":",
"raise",
"ValueError",
"(",
"\"Covariance matrix is not a DataFrame\"",
")",
"n",
"=",
"le... | Computes the minimum variance portfolio.
Note: As the variance is not invariant with respect
to leverage, it is not possible to construct non-trivial
market neutral minimum variance portfolios. This is because
the variance approaches zero with decreasing leverage,
i.e. the market neutral portfolio ... | [
"Computes",
"the",
"minimum",
"variance",
"portfolio",
"."
] | 96ac25daab0c0dbc8933330a92ff31fb898112f2 | https://github.com/czielinski/portfolioopt/blob/96ac25daab0c0dbc8933330a92ff31fb898112f2/portfolioopt/portfolioopt.py#L125-L180 | train |
czielinski/portfolioopt | example.py | print_portfolio_info | def print_portfolio_info(returns, avg_rets, weights):
"""
Print information on expected portfolio performance.
"""
ret = (weights * avg_rets).sum()
std = (weights * returns).sum(1).std()
sharpe = ret / std
print("Optimal weights:\n{}\n".format(weights))
print("Expected return: {}".form... | python | def print_portfolio_info(returns, avg_rets, weights):
"""
Print information on expected portfolio performance.
"""
ret = (weights * avg_rets).sum()
std = (weights * returns).sum(1).std()
sharpe = ret / std
print("Optimal weights:\n{}\n".format(weights))
print("Expected return: {}".form... | [
"def",
"print_portfolio_info",
"(",
"returns",
",",
"avg_rets",
",",
"weights",
")",
":",
"ret",
"=",
"(",
"weights",
"*",
"avg_rets",
")",
".",
"sum",
"(",
")",
"std",
"=",
"(",
"weights",
"*",
"returns",
")",
".",
"sum",
"(",
"1",
")",
".",
"std"... | Print information on expected portfolio performance. | [
"Print",
"information",
"on",
"expected",
"portfolio",
"performance",
"."
] | 96ac25daab0c0dbc8933330a92ff31fb898112f2 | https://github.com/czielinski/portfolioopt/blob/96ac25daab0c0dbc8933330a92ff31fb898112f2/example.py#L36-L46 | train |
CityOfZion/neo-boa | boa/code/module.py | Module.main | def main(self):
"""
Return the default method in this module.
:return: the default method in this module
:rtype: ``boa.code.method.Method``
"""
for m in self.methods:
if m.name in ['Main', 'main']:
return m
if len(self.methods):
... | python | def main(self):
"""
Return the default method in this module.
:return: the default method in this module
:rtype: ``boa.code.method.Method``
"""
for m in self.methods:
if m.name in ['Main', 'main']:
return m
if len(self.methods):
... | [
"def",
"main",
"(",
"self",
")",
":",
"for",
"m",
"in",
"self",
".",
"methods",
":",
"if",
"m",
".",
"name",
"in",
"[",
"'Main'",
",",
"'main'",
"]",
":",
"return",
"m",
"if",
"len",
"(",
"self",
".",
"methods",
")",
":",
"return",
"self",
".",... | Return the default method in this module.
:return: the default method in this module
:rtype: ``boa.code.method.Method`` | [
"Return",
"the",
"default",
"method",
"in",
"this",
"module",
"."
] | 5ec0f0acb2e2e3e4bbd3530252e6eae61b23d59b | https://github.com/CityOfZion/neo-boa/blob/5ec0f0acb2e2e3e4bbd3530252e6eae61b23d59b/boa/code/module.py#L74-L90 | train |
CityOfZion/neo-boa | boa/code/module.py | Module.orderered_methods | def orderered_methods(self):
"""
An ordered list of methods
:return: A list of ordered methods is this module
:rtype: list
"""
oms = []
self.methods.reverse()
if self.main:
oms = [self.main]
for m in self.methods:
if m... | python | def orderered_methods(self):
"""
An ordered list of methods
:return: A list of ordered methods is this module
:rtype: list
"""
oms = []
self.methods.reverse()
if self.main:
oms = [self.main]
for m in self.methods:
if m... | [
"def",
"orderered_methods",
"(",
"self",
")",
":",
"oms",
"=",
"[",
"]",
"self",
".",
"methods",
".",
"reverse",
"(",
")",
"if",
"self",
".",
"main",
":",
"oms",
"=",
"[",
"self",
".",
"main",
"]",
"for",
"m",
"in",
"self",
".",
"methods",
":",
... | An ordered list of methods
:return: A list of ordered methods is this module
:rtype: list | [
"An",
"ordered",
"list",
"of",
"methods"
] | 5ec0f0acb2e2e3e4bbd3530252e6eae61b23d59b | https://github.com/CityOfZion/neo-boa/blob/5ec0f0acb2e2e3e4bbd3530252e6eae61b23d59b/boa/code/module.py#L93-L114 | train |
CityOfZion/neo-boa | boa/code/module.py | Module.write_methods | def write_methods(self):
"""
Write all methods in the current module to a byte string.
:return: A bytestring of all current methods in this module
:rtype: bytes
"""
b_array = bytearray()
for key, vm_token in self.all_vm_tokens.items():
b_array.appen... | python | def write_methods(self):
"""
Write all methods in the current module to a byte string.
:return: A bytestring of all current methods in this module
:rtype: bytes
"""
b_array = bytearray()
for key, vm_token in self.all_vm_tokens.items():
b_array.appen... | [
"def",
"write_methods",
"(",
"self",
")",
":",
"b_array",
"=",
"bytearray",
"(",
")",
"for",
"key",
",",
"vm_token",
"in",
"self",
".",
"all_vm_tokens",
".",
"items",
"(",
")",
":",
"b_array",
".",
"append",
"(",
"vm_token",
".",
"out_op",
")",
"if",
... | Write all methods in the current module to a byte string.
:return: A bytestring of all current methods in this module
:rtype: bytes | [
"Write",
"all",
"methods",
"in",
"the",
"current",
"module",
"to",
"a",
"byte",
"string",
"."
] | 5ec0f0acb2e2e3e4bbd3530252e6eae61b23d59b | https://github.com/CityOfZion/neo-boa/blob/5ec0f0acb2e2e3e4bbd3530252e6eae61b23d59b/boa/code/module.py#L215-L232 | train |
CityOfZion/neo-boa | boa/code/module.py | Module.link_methods | def link_methods(self):
"""
Perform linkage of addresses between methods.
"""
from ..compiler import Compiler
for method in self.methods:
method.prepare()
self.all_vm_tokens = OrderedDict()
address = 0
for method in self.orderered_methods:... | python | def link_methods(self):
"""
Perform linkage of addresses between methods.
"""
from ..compiler import Compiler
for method in self.methods:
method.prepare()
self.all_vm_tokens = OrderedDict()
address = 0
for method in self.orderered_methods:... | [
"def",
"link_methods",
"(",
"self",
")",
":",
"from",
".",
".",
"compiler",
"import",
"Compiler",
"for",
"method",
"in",
"self",
".",
"methods",
":",
"method",
".",
"prepare",
"(",
")",
"self",
".",
"all_vm_tokens",
"=",
"OrderedDict",
"(",
")",
"address... | Perform linkage of addresses between methods. | [
"Perform",
"linkage",
"of",
"addresses",
"between",
"methods",
"."
] | 5ec0f0acb2e2e3e4bbd3530252e6eae61b23d59b | https://github.com/CityOfZion/neo-boa/blob/5ec0f0acb2e2e3e4bbd3530252e6eae61b23d59b/boa/code/module.py#L234-L280 | train |
CityOfZion/neo-boa | boa/code/module.py | Module.export_debug | def export_debug(self, output_path):
"""
this method is used to generate a debug map for NEO debugger
"""
file_hash = hashlib.md5(open(output_path, 'rb').read()).hexdigest()
avm_name = os.path.splitext(os.path.basename(output_path))[0]
json_data = self.generate_debug_js... | python | def export_debug(self, output_path):
"""
this method is used to generate a debug map for NEO debugger
"""
file_hash = hashlib.md5(open(output_path, 'rb').read()).hexdigest()
avm_name = os.path.splitext(os.path.basename(output_path))[0]
json_data = self.generate_debug_js... | [
"def",
"export_debug",
"(",
"self",
",",
"output_path",
")",
":",
"file_hash",
"=",
"hashlib",
".",
"md5",
"(",
"open",
"(",
"output_path",
",",
"'rb'",
")",
".",
"read",
"(",
")",
")",
".",
"hexdigest",
"(",
")",
"avm_name",
"=",
"os",
".",
"path",
... | this method is used to generate a debug map for NEO debugger | [
"this",
"method",
"is",
"used",
"to",
"generate",
"a",
"debug",
"map",
"for",
"NEO",
"debugger"
] | 5ec0f0acb2e2e3e4bbd3530252e6eae61b23d59b | https://github.com/CityOfZion/neo-boa/blob/5ec0f0acb2e2e3e4bbd3530252e6eae61b23d59b/boa/code/module.py#L363-L375 | train |
CityOfZion/neo-boa | boa/compiler.py | Compiler.load_and_save | def load_and_save(path, output_path=None, use_nep8=True):
"""
Call `load_and_save` to load a Python file to be compiled to the .avm format and save the result.
By default, the resultant .avm file is saved along side the source file.
:param path: The path of the Python file to compile
... | python | def load_and_save(path, output_path=None, use_nep8=True):
"""
Call `load_and_save` to load a Python file to be compiled to the .avm format and save the result.
By default, the resultant .avm file is saved along side the source file.
:param path: The path of the Python file to compile
... | [
"def",
"load_and_save",
"(",
"path",
",",
"output_path",
"=",
"None",
",",
"use_nep8",
"=",
"True",
")",
":",
"compiler",
"=",
"Compiler",
".",
"load",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"path",
")",
",",
"use_nep8",
"=",
"use_nep8",
")",
"... | Call `load_and_save` to load a Python file to be compiled to the .avm format and save the result.
By default, the resultant .avm file is saved along side the source file.
:param path: The path of the Python file to compile
:param output_path: Optional path to save the compiled `.avm` file
... | [
"Call",
"load_and_save",
"to",
"load",
"a",
"Python",
"file",
"to",
"be",
"compiled",
"to",
"the",
".",
"avm",
"format",
"and",
"save",
"the",
"result",
".",
"By",
"default",
"the",
"resultant",
".",
"avm",
"file",
"is",
"saved",
"along",
"side",
"the",
... | 5ec0f0acb2e2e3e4bbd3530252e6eae61b23d59b | https://github.com/CityOfZion/neo-boa/blob/5ec0f0acb2e2e3e4bbd3530252e6eae61b23d59b/boa/compiler.py#L79-L108 | train |
CityOfZion/neo-boa | boa/compiler.py | Compiler.load | def load(path, use_nep8=True):
"""
Call `load` to load a Python file to be compiled but not to write to .avm
:param path: the path of the Python file to compile
:return: The instance of the compiler
The following returns the compiler object for inspection.
.. code-bloc... | python | def load(path, use_nep8=True):
"""
Call `load` to load a Python file to be compiled but not to write to .avm
:param path: the path of the Python file to compile
:return: The instance of the compiler
The following returns the compiler object for inspection.
.. code-bloc... | [
"def",
"load",
"(",
"path",
",",
"use_nep8",
"=",
"True",
")",
":",
"Compiler",
".",
"__instance",
"=",
"None",
"compiler",
"=",
"Compiler",
".",
"instance",
"(",
")",
"compiler",
".",
"nep8",
"=",
"use_nep8",
"compiler",
".",
"entry_module",
"=",
"Modul... | Call `load` to load a Python file to be compiled but not to write to .avm
:param path: the path of the Python file to compile
:return: The instance of the compiler
The following returns the compiler object for inspection.
.. code-block:: python
from boa.compiler import Co... | [
"Call",
"load",
"to",
"load",
"a",
"Python",
"file",
"to",
"be",
"compiled",
"but",
"not",
"to",
"write",
"to",
".",
"avm"
] | 5ec0f0acb2e2e3e4bbd3530252e6eae61b23d59b | https://github.com/CityOfZion/neo-boa/blob/5ec0f0acb2e2e3e4bbd3530252e6eae61b23d59b/boa/compiler.py#L111-L133 | train |
swimlane/swimlane-python | swimlane/core/adapters/helper.py | HelperAdapter.add_record_references | def add_record_references(self, app_id, record_id, field_id, target_record_ids):
"""Bulk operation to directly add record references without making any additional requests
Warnings:
Does not perform any app, record, or target app/record validation
Args:
app_id (str): Fu... | python | def add_record_references(self, app_id, record_id, field_id, target_record_ids):
"""Bulk operation to directly add record references without making any additional requests
Warnings:
Does not perform any app, record, or target app/record validation
Args:
app_id (str): Fu... | [
"def",
"add_record_references",
"(",
"self",
",",
"app_id",
",",
"record_id",
",",
"field_id",
",",
"target_record_ids",
")",
":",
"self",
".",
"_swimlane",
".",
"request",
"(",
"'post'",
",",
"'app/{0}/record/{1}/add-references'",
".",
"format",
"(",
"app_id",
... | Bulk operation to directly add record references without making any additional requests
Warnings:
Does not perform any app, record, or target app/record validation
Args:
app_id (str): Full App ID string
record_id (str): Full parent Record ID string
field... | [
"Bulk",
"operation",
"to",
"directly",
"add",
"record",
"references",
"without",
"making",
"any",
"additional",
"requests"
] | 588fc503a76799bcdb5aecdf2f64a6ee05e3922d | https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/adapters/helper.py#L11-L31 | train |
swimlane/swimlane-python | swimlane/core/adapters/helper.py | HelperAdapter.add_comment | def add_comment(self, app_id, record_id, field_id, message):
"""Directly add a comment to a record without retrieving the app or record first
Warnings:
Does not perform any app, record, or field ID validation
Args:
app_id (str): Full App ID string
record_id ... | python | def add_comment(self, app_id, record_id, field_id, message):
"""Directly add a comment to a record without retrieving the app or record first
Warnings:
Does not perform any app, record, or field ID validation
Args:
app_id (str): Full App ID string
record_id ... | [
"def",
"add_comment",
"(",
"self",
",",
"app_id",
",",
"record_id",
",",
"field_id",
",",
"message",
")",
":",
"self",
".",
"_swimlane",
".",
"request",
"(",
"'post'",
",",
"'app/{0}/record/{1}/{2}/comment'",
".",
"format",
"(",
"app_id",
",",
"record_id",
"... | Directly add a comment to a record without retrieving the app or record first
Warnings:
Does not perform any app, record, or field ID validation
Args:
app_id (str): Full App ID string
record_id (str): Full parent Record ID string
field_id (str): Full fie... | [
"Directly",
"add",
"a",
"comment",
"to",
"a",
"record",
"without",
"retrieving",
"the",
"app",
"or",
"record",
"first"
] | 588fc503a76799bcdb5aecdf2f64a6ee05e3922d | https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/adapters/helper.py#L33-L57 | train |
swimlane/swimlane-python | swimlane/core/fields/reference.py | ReferenceCursor._evaluate | def _evaluate(self):
"""Scan for orphaned records and retrieve any records that have not already been grabbed"""
retrieved_records = SortedDict()
for record_id, record in six.iteritems(self._elements):
if record is self._field._unset:
# Record has not yet been retri... | python | def _evaluate(self):
"""Scan for orphaned records and retrieve any records that have not already been grabbed"""
retrieved_records = SortedDict()
for record_id, record in six.iteritems(self._elements):
if record is self._field._unset:
# Record has not yet been retri... | [
"def",
"_evaluate",
"(",
"self",
")",
":",
"retrieved_records",
"=",
"SortedDict",
"(",
")",
"for",
"record_id",
",",
"record",
"in",
"six",
".",
"iteritems",
"(",
"self",
".",
"_elements",
")",
":",
"if",
"record",
"is",
"self",
".",
"_field",
".",
"_... | Scan for orphaned records and retrieve any records that have not already been grabbed | [
"Scan",
"for",
"orphaned",
"records",
"and",
"retrieve",
"any",
"records",
"that",
"have",
"not",
"already",
"been",
"grabbed"
] | 588fc503a76799bcdb5aecdf2f64a6ee05e3922d | https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/fields/reference.py#L26-L45 | train |
swimlane/swimlane-python | swimlane/core/fields/reference.py | ReferenceCursor.add | def add(self, record):
"""Add a reference to the provided record"""
self._field.validate_value(record)
self._elements[record.id] = record
self._sync_field() | python | def add(self, record):
"""Add a reference to the provided record"""
self._field.validate_value(record)
self._elements[record.id] = record
self._sync_field() | [
"def",
"add",
"(",
"self",
",",
"record",
")",
":",
"self",
".",
"_field",
".",
"validate_value",
"(",
"record",
")",
"self",
".",
"_elements",
"[",
"record",
".",
"id",
"]",
"=",
"record",
"self",
".",
"_sync_field",
"(",
")"
] | Add a reference to the provided record | [
"Add",
"a",
"reference",
"to",
"the",
"provided",
"record"
] | 588fc503a76799bcdb5aecdf2f64a6ee05e3922d | https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/fields/reference.py#L47-L51 | train |
swimlane/swimlane-python | swimlane/core/fields/reference.py | ReferenceCursor.remove | def remove(self, record):
"""Remove a reference to the provided record"""
self._field.validate_value(record)
del self._elements[record.id]
self._sync_field() | python | def remove(self, record):
"""Remove a reference to the provided record"""
self._field.validate_value(record)
del self._elements[record.id]
self._sync_field() | [
"def",
"remove",
"(",
"self",
",",
"record",
")",
":",
"self",
".",
"_field",
".",
"validate_value",
"(",
"record",
")",
"del",
"self",
".",
"_elements",
"[",
"record",
".",
"id",
"]",
"self",
".",
"_sync_field",
"(",
")"
] | Remove a reference to the provided record | [
"Remove",
"a",
"reference",
"to",
"the",
"provided",
"record"
] | 588fc503a76799bcdb5aecdf2f64a6ee05e3922d | https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/fields/reference.py#L53-L57 | train |
swimlane/swimlane-python | swimlane/core/fields/reference.py | ReferenceField.target_app | def target_app(self):
"""Defer target app retrieval until requested"""
if self.__target_app is None:
self.__target_app = self._swimlane.apps.get(id=self.__target_app_id)
return self.__target_app | python | def target_app(self):
"""Defer target app retrieval until requested"""
if self.__target_app is None:
self.__target_app = self._swimlane.apps.get(id=self.__target_app_id)
return self.__target_app | [
"def",
"target_app",
"(",
"self",
")",
":",
"if",
"self",
".",
"__target_app",
"is",
"None",
":",
"self",
".",
"__target_app",
"=",
"self",
".",
"_swimlane",
".",
"apps",
".",
"get",
"(",
"id",
"=",
"self",
".",
"__target_app_id",
")",
"return",
"self"... | Defer target app retrieval until requested | [
"Defer",
"target",
"app",
"retrieval",
"until",
"requested"
] | 588fc503a76799bcdb5aecdf2f64a6ee05e3922d | https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/fields/reference.py#L73-L78 | train |
swimlane/swimlane-python | swimlane/core/fields/reference.py | ReferenceField.validate_value | def validate_value(self, value):
"""Validate provided record is a part of the appropriate target app for the field"""
if value not in (None, self._unset):
super(ReferenceField, self).validate_value(value)
if value.app != self.target_app:
raise ValidationError(
... | python | def validate_value(self, value):
"""Validate provided record is a part of the appropriate target app for the field"""
if value not in (None, self._unset):
super(ReferenceField, self).validate_value(value)
if value.app != self.target_app:
raise ValidationError(
... | [
"def",
"validate_value",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"not",
"in",
"(",
"None",
",",
"self",
".",
"_unset",
")",
":",
"super",
"(",
"ReferenceField",
",",
"self",
")",
".",
"validate_value",
"(",
"value",
")",
"if",
"value",
".... | Validate provided record is a part of the appropriate target app for the field | [
"Validate",
"provided",
"record",
"is",
"a",
"part",
"of",
"the",
"appropriate",
"target",
"app",
"for",
"the",
"field"
] | 588fc503a76799bcdb5aecdf2f64a6ee05e3922d | https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/fields/reference.py#L80-L95 | train |
swimlane/swimlane-python | swimlane/core/fields/reference.py | ReferenceField.set_swimlane | def set_swimlane(self, value):
"""Store record ids in separate location for later use, but ignore initial value"""
# Move single record into list to be handled the same by cursor class
if not self.multiselect:
if value and not isinstance(value, list):
value = [value]... | python | def set_swimlane(self, value):
"""Store record ids in separate location for later use, but ignore initial value"""
# Move single record into list to be handled the same by cursor class
if not self.multiselect:
if value and not isinstance(value, list):
value = [value]... | [
"def",
"set_swimlane",
"(",
"self",
",",
"value",
")",
":",
"# Move single record into list to be handled the same by cursor class",
"if",
"not",
"self",
".",
"multiselect",
":",
"if",
"value",
"and",
"not",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"valu... | Store record ids in separate location for later use, but ignore initial value | [
"Store",
"record",
"ids",
"in",
"separate",
"location",
"for",
"later",
"use",
"but",
"ignore",
"initial",
"value"
] | 588fc503a76799bcdb5aecdf2f64a6ee05e3922d | https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/fields/reference.py#L101-L117 | train |
swimlane/swimlane-python | swimlane/core/fields/reference.py | ReferenceField.set_python | def set_python(self, value):
"""Expect list of record instances, convert to a SortedDict for internal representation"""
if not self.multiselect:
if value and not isinstance(value, list):
value = [value]
value = value or []
records = SortedDict()
for... | python | def set_python(self, value):
"""Expect list of record instances, convert to a SortedDict for internal representation"""
if not self.multiselect:
if value and not isinstance(value, list):
value = [value]
value = value or []
records = SortedDict()
for... | [
"def",
"set_python",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"self",
".",
"multiselect",
":",
"if",
"value",
"and",
"not",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"value",
"=",
"[",
"value",
"]",
"value",
"=",
"value",
"or",
"[... | Expect list of record instances, convert to a SortedDict for internal representation | [
"Expect",
"list",
"of",
"record",
"instances",
"convert",
"to",
"a",
"SortedDict",
"for",
"internal",
"representation"
] | 588fc503a76799bcdb5aecdf2f64a6ee05e3922d | https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/fields/reference.py#L119-L136 | train |
swimlane/swimlane-python | swimlane/core/fields/reference.py | ReferenceField.get_swimlane | def get_swimlane(self):
"""Return list of record ids"""
value = super(ReferenceField, self).get_swimlane()
if value:
ids = list(value.keys())
if self.multiselect:
return ids
return ids[0]
return None | python | def get_swimlane(self):
"""Return list of record ids"""
value = super(ReferenceField, self).get_swimlane()
if value:
ids = list(value.keys())
if self.multiselect:
return ids
return ids[0]
return None | [
"def",
"get_swimlane",
"(",
"self",
")",
":",
"value",
"=",
"super",
"(",
"ReferenceField",
",",
"self",
")",
".",
"get_swimlane",
"(",
")",
"if",
"value",
":",
"ids",
"=",
"list",
"(",
"value",
".",
"keys",
"(",
")",
")",
"if",
"self",
".",
"multi... | Return list of record ids | [
"Return",
"list",
"of",
"record",
"ids"
] | 588fc503a76799bcdb5aecdf2f64a6ee05e3922d | https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/fields/reference.py#L138-L149 | train |
swimlane/swimlane-python | swimlane/core/fields/reference.py | ReferenceField.get_python | def get_python(self):
"""Return cursor if multi-select, direct value if single-select"""
cursor = super(ReferenceField, self).get_python()
if self.multiselect:
return cursor
else:
try:
return cursor[0]
except IndexError:
... | python | def get_python(self):
"""Return cursor if multi-select, direct value if single-select"""
cursor = super(ReferenceField, self).get_python()
if self.multiselect:
return cursor
else:
try:
return cursor[0]
except IndexError:
... | [
"def",
"get_python",
"(",
"self",
")",
":",
"cursor",
"=",
"super",
"(",
"ReferenceField",
",",
"self",
")",
".",
"get_python",
"(",
")",
"if",
"self",
".",
"multiselect",
":",
"return",
"cursor",
"else",
":",
"try",
":",
"return",
"cursor",
"[",
"0",
... | Return cursor if multi-select, direct value if single-select | [
"Return",
"cursor",
"if",
"multi",
"-",
"select",
"direct",
"value",
"if",
"single",
"-",
"select"
] | 588fc503a76799bcdb5aecdf2f64a6ee05e3922d | https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/fields/reference.py#L151-L162 | train |
swimlane/swimlane-python | swimlane/core/adapters/app.py | AppAdapter.get | def get(self, key, value):
"""Get single app by one of id or name
Supports resource cache
Keyword Args:
id (str): Full app id
name (str): App name
Returns:
App: Corresponding App resource instance
Raises:
TypeError: No or multip... | python | def get(self, key, value):
"""Get single app by one of id or name
Supports resource cache
Keyword Args:
id (str): Full app id
name (str): App name
Returns:
App: Corresponding App resource instance
Raises:
TypeError: No or multip... | [
"def",
"get",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"if",
"key",
"==",
"'id'",
":",
"# Server returns 204 instead of 404 for a non-existent app id",
"response",
"=",
"self",
".",
"_swimlane",
".",
"request",
"(",
"'get'",
",",
"'app/{}'",
".",
"form... | Get single app by one of id or name
Supports resource cache
Keyword Args:
id (str): Full app id
name (str): App name
Returns:
App: Corresponding App resource instance
Raises:
TypeError: No or multiple keyword arguments provided
... | [
"Get",
"single",
"app",
"by",
"one",
"of",
"id",
"or",
"name"
] | 588fc503a76799bcdb5aecdf2f64a6ee05e3922d | https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/adapters/app.py#L12-L46 | train |
swimlane/swimlane-python | swimlane/core/adapters/app.py | AppAdapter.list | def list(self):
"""Retrieve list of all apps
Returns:
:class:`list` of :class:`~swimlane.core.resources.app.App`: List of all retrieved apps
"""
response = self._swimlane.request('get', 'app')
return [App(self._swimlane, item) for item in response.json()] | python | def list(self):
"""Retrieve list of all apps
Returns:
:class:`list` of :class:`~swimlane.core.resources.app.App`: List of all retrieved apps
"""
response = self._swimlane.request('get', 'app')
return [App(self._swimlane, item) for item in response.json()] | [
"def",
"list",
"(",
"self",
")",
":",
"response",
"=",
"self",
".",
"_swimlane",
".",
"request",
"(",
"'get'",
",",
"'app'",
")",
"return",
"[",
"App",
"(",
"self",
".",
"_swimlane",
",",
"item",
")",
"for",
"item",
"in",
"response",
".",
"json",
"... | Retrieve list of all apps
Returns:
:class:`list` of :class:`~swimlane.core.resources.app.App`: List of all retrieved apps | [
"Retrieve",
"list",
"of",
"all",
"apps"
] | 588fc503a76799bcdb5aecdf2f64a6ee05e3922d | https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/adapters/app.py#L48-L55 | train |
swimlane/swimlane-python | swimlane/core/resources/usergroup.py | Group.users | def users(self):
"""Returns a GroupUsersCursor with list of User instances for this Group
.. versionadded:: 2.16.2
"""
if self.__users is None:
self.__users = GroupUsersCursor(swimlane=self._swimlane, user_ids=self.__user_ids)
return self.__users | python | def users(self):
"""Returns a GroupUsersCursor with list of User instances for this Group
.. versionadded:: 2.16.2
"""
if self.__users is None:
self.__users = GroupUsersCursor(swimlane=self._swimlane, user_ids=self.__user_ids)
return self.__users | [
"def",
"users",
"(",
"self",
")",
":",
"if",
"self",
".",
"__users",
"is",
"None",
":",
"self",
".",
"__users",
"=",
"GroupUsersCursor",
"(",
"swimlane",
"=",
"self",
".",
"_swimlane",
",",
"user_ids",
"=",
"self",
".",
"__user_ids",
")",
"return",
"se... | Returns a GroupUsersCursor with list of User instances for this Group
.. versionadded:: 2.16.2 | [
"Returns",
"a",
"GroupUsersCursor",
"with",
"list",
"of",
"User",
"instances",
"for",
"this",
"Group"
] | 588fc503a76799bcdb5aecdf2f64a6ee05e3922d | https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/resources/usergroup.py#L104-L111 | train |
swimlane/swimlane-python | swimlane/core/resources/usergroup.py | GroupUsersCursor._evaluate | def _evaluate(self):
"""Lazily retrieve and build User instances from returned data"""
if self._elements:
for element in self._elements:
yield element
else:
for user_id in self.__user_ids:
element = self._swimlane.users.get(id=user_id)
... | python | def _evaluate(self):
"""Lazily retrieve and build User instances from returned data"""
if self._elements:
for element in self._elements:
yield element
else:
for user_id in self.__user_ids:
element = self._swimlane.users.get(id=user_id)
... | [
"def",
"_evaluate",
"(",
"self",
")",
":",
"if",
"self",
".",
"_elements",
":",
"for",
"element",
"in",
"self",
".",
"_elements",
":",
"yield",
"element",
"else",
":",
"for",
"user_id",
"in",
"self",
".",
"__user_ids",
":",
"element",
"=",
"self",
".",... | Lazily retrieve and build User instances from returned data | [
"Lazily",
"retrieve",
"and",
"build",
"User",
"instances",
"from",
"returned",
"data"
] | 588fc503a76799bcdb5aecdf2f64a6ee05e3922d | https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/resources/usergroup.py#L154-L163 | train |
swimlane/swimlane-python | swimlane/core/client.py | _user_raw_from_login_content | def _user_raw_from_login_content(login_content):
"""Returns a User instance with appropriate raw data parsed from login response content"""
matching_keys = [
'displayName',
'lastLogin',
'active',
'name',
'isMe',
'lastPasswordChangedDate',
'passwordResetReq... | python | def _user_raw_from_login_content(login_content):
"""Returns a User instance with appropriate raw data parsed from login response content"""
matching_keys = [
'displayName',
'lastLogin',
'active',
'name',
'isMe',
'lastPasswordChangedDate',
'passwordResetReq... | [
"def",
"_user_raw_from_login_content",
"(",
"login_content",
")",
":",
"matching_keys",
"=",
"[",
"'displayName'",
",",
"'lastLogin'",
",",
"'active'",
",",
"'name'",
",",
"'isMe'",
",",
"'lastPasswordChangedDate'",
",",
"'passwordResetRequired'",
",",
"'groups'",
","... | Returns a User instance with appropriate raw data parsed from login response content | [
"Returns",
"a",
"User",
"instance",
"with",
"appropriate",
"raw",
"data",
"parsed",
"from",
"login",
"response",
"content"
] | 588fc503a76799bcdb5aecdf2f64a6ee05e3922d | https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/client.py#L384-L415 | train |
swimlane/swimlane-python | swimlane/core/client.py | Swimlane.__verify_server_version | def __verify_server_version(self):
"""Verify connected to supported server product version
Notes:
Logs warning if connecting to a newer minor server version
Raises:
swimlane.exceptions.InvalidServerVersion: If server major version is higher than package major version
... | python | def __verify_server_version(self):
"""Verify connected to supported server product version
Notes:
Logs warning if connecting to a newer minor server version
Raises:
swimlane.exceptions.InvalidServerVersion: If server major version is higher than package major version
... | [
"def",
"__verify_server_version",
"(",
"self",
")",
":",
"if",
"compare_versions",
"(",
"'.'",
".",
"join",
"(",
"[",
"_lib_major_version",
",",
"_lib_minor_version",
"]",
")",
",",
"self",
".",
"product_version",
")",
">",
"0",
":",
"logger",
".",
"warning"... | Verify connected to supported server product version
Notes:
Logs warning if connecting to a newer minor server version
Raises:
swimlane.exceptions.InvalidServerVersion: If server major version is higher than package major version | [
"Verify",
"connected",
"to",
"supported",
"server",
"product",
"version"
] | 588fc503a76799bcdb5aecdf2f64a6ee05e3922d | https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/client.py#L141-L161 | train |
swimlane/swimlane-python | swimlane/core/client.py | Swimlane.settings | def settings(self):
"""Retrieve and cache settings from server"""
if not self.__settings:
self.__settings = self.request('get', 'settings').json()
return self.__settings | python | def settings(self):
"""Retrieve and cache settings from server"""
if not self.__settings:
self.__settings = self.request('get', 'settings').json()
return self.__settings | [
"def",
"settings",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"__settings",
":",
"self",
".",
"__settings",
"=",
"self",
".",
"request",
"(",
"'get'",
",",
"'settings'",
")",
".",
"json",
"(",
")",
"return",
"self",
".",
"__settings"
] | Retrieve and cache settings from server | [
"Retrieve",
"and",
"cache",
"settings",
"from",
"server"
] | 588fc503a76799bcdb5aecdf2f64a6ee05e3922d | https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/client.py#L229-L233 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.