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 = zlib.decompress(decoded)
points = []
i = 0
while i < len(data):
points.append({
'timestamp': int(1e3 * ArloBaseStation._parse_statistic(
data[i:(i + 4)], 0)),
'temperature': ArloBaseStation._parse_statistic(
data[(i + 8):(i + 10)], 1),
'humidity': ArloBaseStation._parse_statistic(
data[(i + 14):(i + 16)], 1),
'airQuality': ArloBaseStation._parse_statistic(
data[(i + 20):(i + 22)], 1)
})
i += 22
return points
|
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 = zlib.decompress(decoded)
points = []
i = 0
while i < len(data):
points.append({
'timestamp': int(1e3 * ArloBaseStation._parse_statistic(
data[i:(i + 4)], 0)),
'temperature': ArloBaseStation._parse_statistic(
data[(i + 8):(i + 10)], 1),
'humidity': ArloBaseStation._parse_statistic(
data[(i + 14):(i + 16)], 1),
'airQuality': ArloBaseStation._parse_statistic(
data[(i + 20):(i + 22)], 1)
})
i += 22
return points
|
[
"def",
"_decode_sensor_data",
"(",
"properties",
")",
":",
"b64_input",
"=",
"\"\"",
"for",
"s",
"in",
"properties",
".",
"get",
"(",
"'payload'",
")",
":",
"# pylint: disable=consider-using-join",
"b64_input",
"+=",
"s",
"decoded",
"=",
"base64",
".",
"b64decode",
"(",
"b64_input",
")",
"data",
"=",
"zlib",
".",
"decompress",
"(",
"decoded",
")",
"points",
"=",
"[",
"]",
"i",
"=",
"0",
"while",
"i",
"<",
"len",
"(",
"data",
")",
":",
"points",
".",
"append",
"(",
"{",
"'timestamp'",
":",
"int",
"(",
"1e3",
"*",
"ArloBaseStation",
".",
"_parse_statistic",
"(",
"data",
"[",
"i",
":",
"(",
"i",
"+",
"4",
")",
"]",
",",
"0",
")",
")",
",",
"'temperature'",
":",
"ArloBaseStation",
".",
"_parse_statistic",
"(",
"data",
"[",
"(",
"i",
"+",
"8",
")",
":",
"(",
"i",
"+",
"10",
")",
"]",
",",
"1",
")",
",",
"'humidity'",
":",
"ArloBaseStation",
".",
"_parse_statistic",
"(",
"data",
"[",
"(",
"i",
"+",
"14",
")",
":",
"(",
"i",
"+",
"16",
")",
"]",
",",
"1",
")",
",",
"'airQuality'",
":",
"ArloBaseStation",
".",
"_parse_statistic",
"(",
"data",
"[",
"(",
"i",
"+",
"20",
")",
":",
"(",
"i",
"+",
"22",
")",
"]",
",",
"1",
")",
"}",
")",
"i",
"+=",
"22",
"return",
"points"
] |
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",
"scale",
"==",
"0",
":",
"return",
"i",
"return",
"float",
"(",
"i",
")",
"/",
"(",
"scale",
"*",
"10",
")"
] |
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",
",",
"properties",
"=",
"{",
"'trackId'",
":",
"track_id",
",",
"'position'",
":",
"position",
"}",
")"
] |
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'",
":",
"True",
"}",
"}",
")"
] |
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'",
":",
"False",
"}",
"}",
")"
] |
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",
"=",
"{",
"'nightLight'",
":",
"{",
"'enabled'",
":",
"True",
"}",
"}",
")"
] |
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",
"=",
"{",
"'nightLight'",
":",
"{",
"'enabled'",
":",
"False",
"}",
"}",
")"
] |
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',
mode=mode,
publish_response=True)
self.update()
|
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',
mode=mode,
publish_response=True)
self.update()
|
[
"def",
"mode",
"(",
"self",
",",
"mode",
")",
":",
"modes",
"=",
"self",
".",
"available_modes",
"if",
"(",
"not",
"modes",
")",
"or",
"(",
"mode",
"not",
"in",
"modes",
")",
":",
"return",
"self",
".",
"publish",
"(",
"action",
"=",
"'set'",
",",
"resource",
"=",
"'modes'",
"if",
"mode",
"!=",
"'schedule'",
"else",
"'schedule'",
",",
"mode",
"=",
"mode",
",",
"publish_response",
"=",
"True",
")",
"self",
".",
"update",
"(",
")"
] |
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",
"[",
"line",
"[",
"indent",
":",
"]",
".",
"rstrip",
"(",
")",
"for",
"line",
"in",
"lines",
"]"
] |
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, self.ast.Call):
offsets = []
for arg in node.args:
# In Python 3.4 the col_offset is calculated wrong. See
# https://bugs.python.org/issue21295
if isinstance(arg, self.ast.Attribute) and (
(3, 4, 0) <= self.sys.version_info <= (3, 4, 3)):
offsets.append(arg.col_offset - len(arg.value.id) - 1)
else:
offsets.append(arg.col_offset)
if node.keywords:
line = line[:node.keywords[0].value.col_offset]
line = self.re.sub(r'\w+\s*=\s*$', '', line)
else:
line = self.re.sub(r'\s*\)\s*$', '', line)
offsets.append(len(line))
args = []
for i in range(len(node.args)):
args.append(line[offsets[i]:offsets[i + 1]].rstrip(', '))
return args
|
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, self.ast.Call):
offsets = []
for arg in node.args:
# In Python 3.4 the col_offset is calculated wrong. See
# https://bugs.python.org/issue21295
if isinstance(arg, self.ast.Attribute) and (
(3, 4, 0) <= self.sys.version_info <= (3, 4, 3)):
offsets.append(arg.col_offset - len(arg.value.id) - 1)
else:
offsets.append(arg.col_offset)
if node.keywords:
line = line[:node.keywords[0].value.col_offset]
line = self.re.sub(r'\w+\s*=\s*$', '', line)
else:
line = self.re.sub(r'\s*\)\s*$', '', line)
offsets.append(len(line))
args = []
for i in range(len(node.args)):
args.append(line[offsets[i]:offsets[i + 1]].rstrip(', '))
return args
|
[
"def",
"get_call_exprs",
"(",
"self",
",",
"line",
")",
":",
"line",
"=",
"line",
".",
"lstrip",
"(",
")",
"try",
":",
"tree",
"=",
"self",
".",
"ast",
".",
"parse",
"(",
"line",
")",
"except",
"SyntaxError",
":",
"return",
"None",
"for",
"node",
"in",
"self",
".",
"ast",
".",
"walk",
"(",
"tree",
")",
":",
"if",
"isinstance",
"(",
"node",
",",
"self",
".",
"ast",
".",
"Call",
")",
":",
"offsets",
"=",
"[",
"]",
"for",
"arg",
"in",
"node",
".",
"args",
":",
"# In Python 3.4 the col_offset is calculated wrong. See",
"# https://bugs.python.org/issue21295",
"if",
"isinstance",
"(",
"arg",
",",
"self",
".",
"ast",
".",
"Attribute",
")",
"and",
"(",
"(",
"3",
",",
"4",
",",
"0",
")",
"<=",
"self",
".",
"sys",
".",
"version_info",
"<=",
"(",
"3",
",",
"4",
",",
"3",
")",
")",
":",
"offsets",
".",
"append",
"(",
"arg",
".",
"col_offset",
"-",
"len",
"(",
"arg",
".",
"value",
".",
"id",
")",
"-",
"1",
")",
"else",
":",
"offsets",
".",
"append",
"(",
"arg",
".",
"col_offset",
")",
"if",
"node",
".",
"keywords",
":",
"line",
"=",
"line",
"[",
":",
"node",
".",
"keywords",
"[",
"0",
"]",
".",
"value",
".",
"col_offset",
"]",
"line",
"=",
"self",
".",
"re",
".",
"sub",
"(",
"r'\\w+\\s*=\\s*$'",
",",
"''",
",",
"line",
")",
"else",
":",
"line",
"=",
"self",
".",
"re",
".",
"sub",
"(",
"r'\\s*\\)\\s*$'",
",",
"''",
",",
"line",
")",
"offsets",
".",
"append",
"(",
"len",
"(",
"line",
")",
")",
"args",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"node",
".",
"args",
")",
")",
":",
"args",
".",
"append",
"(",
"line",
"[",
"offsets",
"[",
"i",
"]",
":",
"offsets",
"[",
"i",
"+",
"1",
"]",
"]",
".",
"rstrip",
"(",
"', '",
")",
")",
"return",
"args"
] |
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)
if labels:
sep = ''
for label, repr in zip(labels, reprs):
s.add([label + '=', self.CYAN, repr, self.NORMAL], sep)
sep = ', '
else:
sep = ''
for repr in reprs:
s.add([self.CYAN, repr, self.NORMAL], sep)
sep = ', '
self.writer.write(s.chunks)
|
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)
if labels:
sep = ''
for label, repr in zip(labels, reprs):
s.add([label + '=', self.CYAN, repr, self.NORMAL], sep)
sep = ', '
else:
sep = ''
for repr in reprs:
s.add([self.CYAN, repr, self.NORMAL], sep)
sep = ', '
self.writer.write(s.chunks)
|
[
"def",
"show",
"(",
"self",
",",
"func_name",
",",
"values",
",",
"labels",
"=",
"None",
")",
":",
"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",
")",
"if",
"labels",
":",
"sep",
"=",
"''",
"for",
"label",
",",
"repr",
"in",
"zip",
"(",
"labels",
",",
"reprs",
")",
":",
"s",
".",
"add",
"(",
"[",
"label",
"+",
"'='",
",",
"self",
".",
"CYAN",
",",
"repr",
",",
"self",
".",
"NORMAL",
"]",
",",
"sep",
")",
"sep",
"=",
"', '",
"else",
":",
"sep",
"=",
"''",
"for",
"repr",
"in",
"reprs",
":",
"s",
".",
"add",
"(",
"[",
"self",
".",
"CYAN",
",",
"repr",
",",
"self",
".",
"NORMAL",
"]",
",",
"sep",
")",
"sep",
"=",
"', '",
"self",
".",
"writer",
".",
"write",
"(",
"s",
".",
"chunks",
")"
] |
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, '('])
s.indent += 4
sep = ''
for arg in args:
s.add([self.CYAN, self.safe_repr(arg), self.NORMAL], sep)
sep = ', '
for name, value in sorted(kwargs.items()):
s.add([name + '=', self.CYAN, self.safe_repr(value),
self.NORMAL], sep)
sep = ', '
s.add(')', wrap=False)
self.writer.write(s.chunks)
# Call the function.
self.indent += 2
try:
result = func(*args, **kwargs)
except:
# Display an exception.
self.indent -= 2
etype, evalue, etb = self.sys.exc_info()
info = self.inspect.getframeinfo(etb.tb_next, context=3)
s = self.Stanza(self.indent)
s.add([self.RED, '!> ', self.safe_repr(evalue), self.NORMAL])
s.add(['at ', info.filename, ':', info.lineno], ' ')
lines = self.unindent(info.code_context)
firstlineno = info.lineno - info.index
fmt = '%' + str(len(str(firstlineno + len(lines)))) + 'd'
for i, line in enumerate(lines):
s.newline()
s.add([
i == info.index and self.MAGENTA or '',
fmt % (i + firstlineno),
i == info.index and '> ' or ': ', line, self.NORMAL])
self.writer.write(s.chunks)
raise
# Display the return value.
self.indent -= 2
s = self.Stanza(self.indent)
s.add([self.GREEN, '-> ', self.CYAN, self.safe_repr(result),
self.NORMAL])
self.writer.write(s.chunks)
return result
return self.functools.update_wrapper(wrapper, func)
|
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, '('])
s.indent += 4
sep = ''
for arg in args:
s.add([self.CYAN, self.safe_repr(arg), self.NORMAL], sep)
sep = ', '
for name, value in sorted(kwargs.items()):
s.add([name + '=', self.CYAN, self.safe_repr(value),
self.NORMAL], sep)
sep = ', '
s.add(')', wrap=False)
self.writer.write(s.chunks)
# Call the function.
self.indent += 2
try:
result = func(*args, **kwargs)
except:
# Display an exception.
self.indent -= 2
etype, evalue, etb = self.sys.exc_info()
info = self.inspect.getframeinfo(etb.tb_next, context=3)
s = self.Stanza(self.indent)
s.add([self.RED, '!> ', self.safe_repr(evalue), self.NORMAL])
s.add(['at ', info.filename, ':', info.lineno], ' ')
lines = self.unindent(info.code_context)
firstlineno = info.lineno - info.index
fmt = '%' + str(len(str(firstlineno + len(lines)))) + 'd'
for i, line in enumerate(lines):
s.newline()
s.add([
i == info.index and self.MAGENTA or '',
fmt % (i + firstlineno),
i == info.index and '> ' or ': ', line, self.NORMAL])
self.writer.write(s.chunks)
raise
# Display the return value.
self.indent -= 2
s = self.Stanza(self.indent)
s.add([self.GREEN, '-> ', self.CYAN, self.safe_repr(result),
self.NORMAL])
self.writer.write(s.chunks)
return result
return self.functools.update_wrapper(wrapper, func)
|
[
"def",
"trace",
"(",
"self",
",",
"func",
")",
":",
"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",
",",
"'('",
"]",
")",
"s",
".",
"indent",
"+=",
"4",
"sep",
"=",
"''",
"for",
"arg",
"in",
"args",
":",
"s",
".",
"add",
"(",
"[",
"self",
".",
"CYAN",
",",
"self",
".",
"safe_repr",
"(",
"arg",
")",
",",
"self",
".",
"NORMAL",
"]",
",",
"sep",
")",
"sep",
"=",
"', '",
"for",
"name",
",",
"value",
"in",
"sorted",
"(",
"kwargs",
".",
"items",
"(",
")",
")",
":",
"s",
".",
"add",
"(",
"[",
"name",
"+",
"'='",
",",
"self",
".",
"CYAN",
",",
"self",
".",
"safe_repr",
"(",
"value",
")",
",",
"self",
".",
"NORMAL",
"]",
",",
"sep",
")",
"sep",
"=",
"', '",
"s",
".",
"add",
"(",
"')'",
",",
"wrap",
"=",
"False",
")",
"self",
".",
"writer",
".",
"write",
"(",
"s",
".",
"chunks",
")",
"# Call the function.",
"self",
".",
"indent",
"+=",
"2",
"try",
":",
"result",
"=",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
":",
"# Display an exception.",
"self",
".",
"indent",
"-=",
"2",
"etype",
",",
"evalue",
",",
"etb",
"=",
"self",
".",
"sys",
".",
"exc_info",
"(",
")",
"info",
"=",
"self",
".",
"inspect",
".",
"getframeinfo",
"(",
"etb",
".",
"tb_next",
",",
"context",
"=",
"3",
")",
"s",
"=",
"self",
".",
"Stanza",
"(",
"self",
".",
"indent",
")",
"s",
".",
"add",
"(",
"[",
"self",
".",
"RED",
",",
"'!> '",
",",
"self",
".",
"safe_repr",
"(",
"evalue",
")",
",",
"self",
".",
"NORMAL",
"]",
")",
"s",
".",
"add",
"(",
"[",
"'at '",
",",
"info",
".",
"filename",
",",
"':'",
",",
"info",
".",
"lineno",
"]",
",",
"' '",
")",
"lines",
"=",
"self",
".",
"unindent",
"(",
"info",
".",
"code_context",
")",
"firstlineno",
"=",
"info",
".",
"lineno",
"-",
"info",
".",
"index",
"fmt",
"=",
"'%'",
"+",
"str",
"(",
"len",
"(",
"str",
"(",
"firstlineno",
"+",
"len",
"(",
"lines",
")",
")",
")",
")",
"+",
"'d'",
"for",
"i",
",",
"line",
"in",
"enumerate",
"(",
"lines",
")",
":",
"s",
".",
"newline",
"(",
")",
"s",
".",
"add",
"(",
"[",
"i",
"==",
"info",
".",
"index",
"and",
"self",
".",
"MAGENTA",
"or",
"''",
",",
"fmt",
"%",
"(",
"i",
"+",
"firstlineno",
")",
",",
"i",
"==",
"info",
".",
"index",
"and",
"'> '",
"or",
"': '",
",",
"line",
",",
"self",
".",
"NORMAL",
"]",
")",
"self",
".",
"writer",
".",
"write",
"(",
"s",
".",
"chunks",
")",
"raise",
"# Display the return value.",
"self",
".",
"indent",
"-=",
"2",
"s",
"=",
"self",
".",
"Stanza",
"(",
"self",
".",
"indent",
")",
"s",
".",
"add",
"(",
"[",
"self",
".",
"GREEN",
",",
"'-> '",
",",
"self",
".",
"CYAN",
",",
"self",
".",
"safe_repr",
"(",
"result",
")",
",",
"self",
".",
"NORMAL",
"]",
")",
"self",
".",
"writer",
".",
"write",
"(",
"s",
".",
"chunks",
")",
"return",
"result",
"return",
"self",
".",
"functools",
".",
"update_wrapper",
"(",
"wrapper",
",",
"func",
")"
] |
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])
self.writer.write(s.chunks)
frame = self.sys._getframe(depth)
env = frame.f_globals.copy()
env.update(frame.f_locals)
self.indent += 2
self.in_console = True
self.code.interact(
'Python console opened by q.d() in ' + info.function, local=env)
self.in_console = False
self.indent -= 2
s = self.Stanza(self.indent)
s.add([info.function + ': '])
s.add([self.MAGENTA, 'Interactive console closed', self.NORMAL])
self.writer.write(s.chunks)
|
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])
self.writer.write(s.chunks)
frame = self.sys._getframe(depth)
env = frame.f_globals.copy()
env.update(frame.f_locals)
self.indent += 2
self.in_console = True
self.code.interact(
'Python console opened by q.d() in ' + info.function, local=env)
self.in_console = False
self.indent -= 2
s = self.Stanza(self.indent)
s.add([info.function + ': '])
s.add([self.MAGENTA, 'Interactive console closed', self.NORMAL])
self.writer.write(s.chunks)
|
[
"def",
"d",
"(",
"self",
",",
"depth",
"=",
"1",
")",
":",
"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",
"]",
")",
"self",
".",
"writer",
".",
"write",
"(",
"s",
".",
"chunks",
")",
"frame",
"=",
"self",
".",
"sys",
".",
"_getframe",
"(",
"depth",
")",
"env",
"=",
"frame",
".",
"f_globals",
".",
"copy",
"(",
")",
"env",
".",
"update",
"(",
"frame",
".",
"f_locals",
")",
"self",
".",
"indent",
"+=",
"2",
"self",
".",
"in_console",
"=",
"True",
"self",
".",
"code",
".",
"interact",
"(",
"'Python console opened by q.d() in '",
"+",
"info",
".",
"function",
",",
"local",
"=",
"env",
")",
"self",
".",
"in_console",
"=",
"False",
"self",
".",
"indent",
"-=",
"2",
"s",
"=",
"self",
".",
"Stanza",
"(",
"self",
".",
"indent",
")",
"s",
".",
"add",
"(",
"[",
"info",
".",
"function",
"+",
"': '",
"]",
")",
"s",
".",
"add",
"(",
"[",
"self",
".",
"MAGENTA",
",",
"'Interactive console closed'",
",",
"self",
".",
"NORMAL",
"]",
")",
"self",
".",
"writer",
".",
"write",
"(",
"s",
".",
"chunks",
")"
] |
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 all paths in Paths Object would prefixed with slah.
common_path = common_path[:-1] if common_path[-1] == '/' else common_path
if len(common_path) > 0:
p = six.moves.urllib.parse.urlparse(common_path)
self.__swagger.update_field('host', p.netloc)
new_common_path = six.moves.urllib.parse.urlunparse((
p.scheme, p.netloc, '', '', '', ''))
new_path = {}
for k in self.__swagger.paths.keys():
new_path[k[len(new_common_path):]] = self.__swagger.paths[k]
self.__swagger.update_field('paths', new_path)
return self.__swagger
|
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 all paths in Paths Object would prefixed with slah.
common_path = common_path[:-1] if common_path[-1] == '/' else common_path
if len(common_path) > 0:
p = six.moves.urllib.parse.urlparse(common_path)
self.__swagger.update_field('host', p.netloc)
new_common_path = six.moves.urllib.parse.urlunparse((
p.scheme, p.netloc, '', '', '', ''))
new_path = {}
for k in self.__swagger.paths.keys():
new_path[k[len(new_common_path):]] = self.__swagger.paths[k]
self.__swagger.update_field('paths', new_path)
return self.__swagger
|
[
"def",
"swagger",
"(",
"self",
")",
":",
"# prepare Swagger.host & Swagger.basePath",
"if",
"not",
"self",
".",
"__swagger",
":",
"return",
"None",
"common_path",
"=",
"os",
".",
"path",
".",
"commonprefix",
"(",
"list",
"(",
"self",
".",
"__swagger",
".",
"paths",
")",
")",
"# remove tailing slash,",
"# because all paths in Paths Object would prefixed with slah.",
"common_path",
"=",
"common_path",
"[",
":",
"-",
"1",
"]",
"if",
"common_path",
"[",
"-",
"1",
"]",
"==",
"'/'",
"else",
"common_path",
"if",
"len",
"(",
"common_path",
")",
">",
"0",
":",
"p",
"=",
"six",
".",
"moves",
".",
"urllib",
".",
"parse",
".",
"urlparse",
"(",
"common_path",
")",
"self",
".",
"__swagger",
".",
"update_field",
"(",
"'host'",
",",
"p",
".",
"netloc",
")",
"new_common_path",
"=",
"six",
".",
"moves",
".",
"urllib",
".",
"parse",
".",
"urlunparse",
"(",
"(",
"p",
".",
"scheme",
",",
"p",
".",
"netloc",
",",
"''",
",",
"''",
",",
"''",
",",
"''",
")",
")",
"new_path",
"=",
"{",
"}",
"for",
"k",
"in",
"self",
".",
"__swagger",
".",
"paths",
".",
"keys",
"(",
")",
":",
"new_path",
"[",
"k",
"[",
"len",
"(",
"new_common_path",
")",
":",
"]",
"]",
"=",
"self",
".",
"__swagger",
".",
"paths",
"[",
"k",
"]",
"self",
".",
"__swagger",
".",
"update_field",
"(",
"'paths'",
",",
"new_path",
")",
"return",
"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
if scope and name:
new_scope = scope + sep + name
return new_scope
|
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
if scope and name:
new_scope = scope + sep + name
return new_scope
|
[
"def",
"scope_compose",
"(",
"scope",
",",
"name",
",",
"sep",
"=",
"private",
".",
"SCOPE_SEPARATOR",
")",
":",
"if",
"name",
"==",
"None",
":",
"new_scope",
"=",
"scope",
"else",
":",
"new_scope",
"=",
"scope",
"if",
"scope",
"else",
"name",
"if",
"scope",
"and",
"name",
":",
"new_scope",
"=",
"scope",
"+",
"sep",
"+",
"name",
"return",
"new_scope"
] |
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",
"_found",
"=",
"True",
"if",
"not",
"_found",
":",
"l",
".",
"append",
"(",
"v",
")"
] |
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.path.dirname(p.path),)+
p[3:]
)
return url
|
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.path.dirname(p.path),)+
p[3:]
)
return url
|
[
"def",
"url_dirname",
"(",
"url",
")",
":",
"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",
".",
"path",
".",
"dirname",
"(",
"p",
".",
"path",
")",
",",
")",
"+",
"p",
"[",
"3",
":",
"]",
")",
"return",
"url"
] |
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] == '/' else '/').join([p.path, path])
return six.moves.urllib.parse.urlunparse(
p[:2]+
(t,)+ # os.sep is different on windows, don't use it here.
p[3:]
)
|
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] == '/' else '/').join([p.path, path])
return six.moves.urllib.parse.urlunparse(
p[:2]+
(t,)+ # os.sep is different on windows, don't use it here.
p[3:]
)
|
[
"def",
"url_join",
"(",
"url",
",",
"path",
")",
":",
"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",
"]",
"==",
"'/'",
"else",
"'/'",
")",
".",
"join",
"(",
"[",
"p",
".",
"path",
",",
"path",
"]",
")",
"return",
"six",
".",
"moves",
".",
"urllib",
".",
"parse",
".",
"urlunparse",
"(",
"p",
"[",
":",
"2",
"]",
"+",
"(",
"t",
",",
")",
"+",
"# os.sep is different on windows, don't use it here.",
"p",
"[",
"3",
":",
"]",
")"
] |
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=newpath[:-1]
continue
# TODO: Verify this behaviour.
elif _fullmatch(r'\.{3,}', chunk) is not None:
# parent dir.
newpath=newpath[:-1]
continue
newpath += [chunk]
return six.moves.urllib.parse.urlunparse(parsed[:2]+('/'+('/'.join(newpath)),)+parsed[3:])
|
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=newpath[:-1]
continue
# TODO: Verify this behaviour.
elif _fullmatch(r'\.{3,}', chunk) is not None:
# parent dir.
newpath=newpath[:-1]
continue
newpath += [chunk]
return six.moves.urllib.parse.urlunparse(parsed[:2]+('/'+('/'.join(newpath)),)+parsed[3:])
|
[
"def",
"derelativise_url",
"(",
"url",
")",
":",
"parsed",
"=",
"six",
".",
"moves",
".",
"urllib",
".",
"parse",
".",
"urlparse",
"(",
"url",
")",
"newpath",
"=",
"[",
"]",
"for",
"chunk",
"in",
"parsed",
".",
"path",
"[",
"1",
":",
"]",
".",
"split",
"(",
"'/'",
")",
":",
"if",
"chunk",
"==",
"'.'",
":",
"continue",
"elif",
"chunk",
"==",
"'..'",
":",
"# parent dir.",
"newpath",
"=",
"newpath",
"[",
":",
"-",
"1",
"]",
"continue",
"# TODO: Verify this behaviour.",
"elif",
"_fullmatch",
"(",
"r'\\.{3,}'",
",",
"chunk",
")",
"is",
"not",
"None",
":",
"# parent dir.",
"newpath",
"=",
"newpath",
"[",
":",
"-",
"1",
"]",
"continue",
"newpath",
"+=",
"[",
"chunk",
"]",
"return",
"six",
".",
"moves",
".",
"urllib",
".",
"parse",
".",
"urlunparse",
"(",
"parsed",
"[",
":",
"2",
"]",
"+",
"(",
"'/'",
"+",
"(",
"'/'",
".",
"join",
"(",
"newpath",
")",
")",
",",
")",
"+",
"parsed",
"[",
"3",
":",
"]",
")"
] |
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 BaseObj
return obj.swaggerVersion if hasattr(obj, 'swaggerVersion') else obj.swagger
|
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 BaseObj
return obj.swaggerVersion if hasattr(obj, 'swaggerVersion') else obj.swagger
|
[
"def",
"get_swagger_version",
"(",
"obj",
")",
":",
"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 BaseObj",
"return",
"obj",
".",
"swaggerVersion",
"if",
"hasattr",
"(",
"obj",
",",
"'swaggerVersion'",
")",
"else",
"obj",
".",
"swagger"
] |
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: list of lists
"""
ctx, stk = {}, [start]
cyc = [] if cyc == None else cyc
while len(stk):
top = stk[-1]
if top not in ctx:
ctx.update({top:list(ofn(top))})
if len(ctx[top]):
n = ctx[top][0]
if n in stk:
# cycles found,
# normalize the representation of cycles,
# start from the smallest vertex, ex.
# 4 -> 5 -> 2 -> 7 -> 9 would produce
# (2, 7, 9, 4, 5)
nc = stk[stk.index(n):]
ni = nc.index(min(nc))
nc = nc[ni:] + nc[:ni] + [min(nc)]
if nc not in cyc:
cyc.append(nc)
ctx[top].pop(0)
else:
stk.append(n)
else:
ctx.pop(top)
stk.pop()
if len(stk):
ctx[stk[-1]].remove(top)
return cyc
|
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: list of lists
"""
ctx, stk = {}, [start]
cyc = [] if cyc == None else cyc
while len(stk):
top = stk[-1]
if top not in ctx:
ctx.update({top:list(ofn(top))})
if len(ctx[top]):
n = ctx[top][0]
if n in stk:
# cycles found,
# normalize the representation of cycles,
# start from the smallest vertex, ex.
# 4 -> 5 -> 2 -> 7 -> 9 would produce
# (2, 7, 9, 4, 5)
nc = stk[stk.index(n):]
ni = nc.index(min(nc))
nc = nc[ni:] + nc[:ni] + [min(nc)]
if nc not in cyc:
cyc.append(nc)
ctx[top].pop(0)
else:
stk.append(n)
else:
ctx.pop(top)
stk.pop()
if len(stk):
ctx[stk[-1]].remove(top)
return cyc
|
[
"def",
"walk",
"(",
"start",
",",
"ofn",
",",
"cyc",
"=",
"None",
")",
":",
"ctx",
",",
"stk",
"=",
"{",
"}",
",",
"[",
"start",
"]",
"cyc",
"=",
"[",
"]",
"if",
"cyc",
"==",
"None",
"else",
"cyc",
"while",
"len",
"(",
"stk",
")",
":",
"top",
"=",
"stk",
"[",
"-",
"1",
"]",
"if",
"top",
"not",
"in",
"ctx",
":",
"ctx",
".",
"update",
"(",
"{",
"top",
":",
"list",
"(",
"ofn",
"(",
"top",
")",
")",
"}",
")",
"if",
"len",
"(",
"ctx",
"[",
"top",
"]",
")",
":",
"n",
"=",
"ctx",
"[",
"top",
"]",
"[",
"0",
"]",
"if",
"n",
"in",
"stk",
":",
"# cycles found,",
"# normalize the representation of cycles,",
"# start from the smallest vertex, ex.",
"# 4 -> 5 -> 2 -> 7 -> 9 would produce",
"# (2, 7, 9, 4, 5)",
"nc",
"=",
"stk",
"[",
"stk",
".",
"index",
"(",
"n",
")",
":",
"]",
"ni",
"=",
"nc",
".",
"index",
"(",
"min",
"(",
"nc",
")",
")",
"nc",
"=",
"nc",
"[",
"ni",
":",
"]",
"+",
"nc",
"[",
":",
"ni",
"]",
"+",
"[",
"min",
"(",
"nc",
")",
"]",
"if",
"nc",
"not",
"in",
"cyc",
":",
"cyc",
".",
"append",
"(",
"nc",
")",
"ctx",
"[",
"top",
"]",
".",
"pop",
"(",
"0",
")",
"else",
":",
"stk",
".",
"append",
"(",
"n",
")",
"else",
":",
"ctx",
".",
"pop",
"(",
"top",
")",
"stk",
".",
"pop",
"(",
")",
"if",
"len",
"(",
"stk",
")",
":",
"ctx",
"[",
"stk",
"[",
"-",
"1",
"]",
"]",
".",
"remove",
"(",
"top",
")",
"return",
"cyc"
] |
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')
if obj.type == 'array':
errs.append('array Type with allowMultiple is not supported.')
if obj.paramType == 'body' and obj.name not in ('', 'body'):
errs.append('body parameter with invalid name: {0}'.format(obj.name))
if obj.type == 'File':
if obj.paramType != 'form':
errs.append('File parameter should be form type: {0}'.format(obj.name))
if 'multipart/form-data' not in obj._parent_.consumes:
errs.append('File parameter should consume multipart/form-data: {0}'.format(obj.name))
if obj.type == 'void':
errs.append('void is only allowed in Operation object.')
return path, obj.__class__.__name__, errs
|
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')
if obj.type == 'array':
errs.append('array Type with allowMultiple is not supported.')
if obj.paramType == 'body' and obj.name not in ('', 'body'):
errs.append('body parameter with invalid name: {0}'.format(obj.name))
if obj.type == 'File':
if obj.paramType != 'form':
errs.append('File parameter should be form type: {0}'.format(obj.name))
if 'multipart/form-data' not in obj._parent_.consumes:
errs.append('File parameter should consume multipart/form-data: {0}'.format(obj.name))
if obj.type == 'void':
errs.append('void is only allowed in Operation object.')
return path, obj.__class__.__name__, errs
|
[
"def",
"_validate_param",
"(",
"self",
",",
"path",
",",
"obj",
",",
"_",
")",
":",
"errs",
"=",
"[",
"]",
"if",
"obj",
".",
"allowMultiple",
":",
"if",
"not",
"obj",
".",
"paramType",
"in",
"(",
"'path'",
",",
"'query'",
",",
"'header'",
")",
":",
"errs",
".",
"append",
"(",
"'allowMultiple should be applied on path, header, or query parameters'",
")",
"if",
"obj",
".",
"type",
"==",
"'array'",
":",
"errs",
".",
"append",
"(",
"'array Type with allowMultiple is not supported.'",
")",
"if",
"obj",
".",
"paramType",
"==",
"'body'",
"and",
"obj",
".",
"name",
"not",
"in",
"(",
"''",
",",
"'body'",
")",
":",
"errs",
".",
"append",
"(",
"'body parameter with invalid name: {0}'",
".",
"format",
"(",
"obj",
".",
"name",
")",
")",
"if",
"obj",
".",
"type",
"==",
"'File'",
":",
"if",
"obj",
".",
"paramType",
"!=",
"'form'",
":",
"errs",
".",
"append",
"(",
"'File parameter should be form type: {0}'",
".",
"format",
"(",
"obj",
".",
"name",
")",
")",
"if",
"'multipart/form-data'",
"not",
"in",
"obj",
".",
"_parent_",
".",
"consumes",
":",
"errs",
".",
"append",
"(",
"'File parameter should consume multipart/form-data: {0}'",
".",
"format",
"(",
"obj",
".",
"name",
")",
")",
"if",
"obj",
".",
"type",
"==",
"'void'",
":",
"errs",
".",
"append",
"(",
"'void is only allowed in Operation object.'",
")",
"return",
"path",
",",
"obj",
".",
"__class__",
".",
"__name__",
",",
"errs"
] |
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",
",",
"obj",
".",
"__class__",
".",
"__name__",
",",
"errs"
] |
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 apiKey')
elif obj.type == 'oauth2':
if not obj.grantTypes:
errs.append('need "grantTypes" for oauth2')
return path, obj.__class__.__name__, errs
|
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 apiKey')
elif obj.type == 'oauth2':
if not obj.grantTypes:
errs.append('need "grantTypes" for oauth2')
return path, obj.__class__.__name__, errs
|
[
"def",
"_validate_auth",
"(",
"self",
",",
"path",
",",
"obj",
",",
"_",
")",
":",
"errs",
"=",
"[",
"]",
"if",
"obj",
".",
"type",
"==",
"'apiKey'",
":",
"if",
"not",
"obj",
".",
"passAs",
":",
"errs",
".",
"append",
"(",
"'need \"passAs\" for apiKey'",
")",
"if",
"not",
"obj",
".",
"keyname",
":",
"errs",
".",
"append",
"(",
"'need \"keyname\" for apiKey'",
")",
"elif",
"obj",
".",
"type",
"==",
"'oauth2'",
":",
"if",
"not",
"obj",
".",
"grantTypes",
":",
"errs",
".",
"append",
"(",
"'need \"grantTypes\" for oauth2'",
")",
"return",
"path",
",",
"obj",
".",
"__class__",
".",
"__name__",
",",
"errs"
] |
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__.__name__, errs
|
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__.__name__, errs
|
[
"def",
"_validate_granttype",
"(",
"self",
",",
"path",
",",
"obj",
",",
"_",
")",
":",
"errs",
"=",
"[",
"]",
"if",
"not",
"obj",
".",
"implicit",
"and",
"not",
"obj",
".",
"authorization_code",
":",
"errs",
".",
"append",
"(",
"'Either implicit or authorization_code should be defined.'",
")",
"return",
"path",
",",
"obj",
".",
"__class__",
".",
"__name__",
",",
"errs"
] |
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 found in resource list'.format(k))
if app.raw.authorizations[k].type in ('basicAuth', 'apiKey') and v != []:
errs.append('auth {0} should be an empty list'.format(k))
return path, obj.__class__.__name__, errs
|
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 found in resource list'.format(k))
if app.raw.authorizations[k].type in ('basicAuth', 'apiKey') and v != []:
errs.append('auth {0} should be an empty list'.format(k))
return path, obj.__class__.__name__, errs
|
[
"def",
"_validate_auths",
"(",
"self",
",",
"path",
",",
"obj",
",",
"app",
")",
":",
"errs",
"=",
"[",
"]",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"obj",
".",
"authorizations",
"or",
"{",
"}",
")",
":",
"if",
"k",
"not",
"in",
"app",
".",
"raw",
".",
"authorizations",
":",
"errs",
".",
"append",
"(",
"'auth {0} not found in resource list'",
".",
"format",
"(",
"k",
")",
")",
"if",
"app",
".",
"raw",
".",
"authorizations",
"[",
"k",
"]",
".",
"type",
"in",
"(",
"'basicAuth'",
",",
"'apiKey'",
")",
"and",
"v",
"!=",
"[",
"]",
":",
"errs",
".",
"append",
"(",
"'auth {0} should be an empty list'",
".",
"format",
"(",
"k",
")",
")",
"return",
"path",
",",
"obj",
".",
"__class__",
".",
"__name__",
",",
"errs"
] |
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(lambda i: (path + '/' + i[0],) + (i[1],), six.iteritems(obj._children_)))
# the path we expose here follows JsonPointer described here
# http://tools.ietf.org/html/draft-ietf-appsawg-json-pointer-07
yield path, obj
|
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(lambda i: (path + '/' + i[0],) + (i[1],), six.iteritems(obj._children_)))
# the path we expose here follows JsonPointer described here
# http://tools.ietf.org/html/draft-ietf-appsawg-json-pointer-07
yield path, obj
|
[
"def",
"default_tree_traversal",
"(",
"root",
",",
"leaves",
")",
":",
"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",
"(",
"lambda",
"i",
":",
"(",
"path",
"+",
"'/'",
"+",
"i",
"[",
"0",
"]",
",",
")",
"+",
"(",
"i",
"[",
"1",
"]",
",",
")",
",",
"six",
".",
"iteritems",
"(",
"obj",
".",
"_children_",
")",
")",
")",
"# the path we expose here follows JsonPointer described here",
"# http://tools.ietf.org/html/draft-ietf-appsawg-json-pointer-07",
"yield",
"path",
",",
"obj"
] |
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 = self.default() if opt == None else opt
if not isinstance(op, Operation):
raise ValueError('Not a Operation: {0}'.format(op))
if not isinstance(opt, dict):
raise ValueError('Not a dict: {0}'.format(opt))
template = opt['parameter_template']
max_p = opt['max_parameter']
out = {}
for p in op.parameters:
if p.name in exclude:
continue
if p.name in template:
out.update({p.name: template[p.name]})
continue
if not max_p and not p.required:
if random.randint(0, 1) == 0 or opt['minimal_parameter']:
continue
out.update({p.name: self.render(p, opt=opt)})
return out
|
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 = self.default() if opt == None else opt
if not isinstance(op, Operation):
raise ValueError('Not a Operation: {0}'.format(op))
if not isinstance(opt, dict):
raise ValueError('Not a dict: {0}'.format(opt))
template = opt['parameter_template']
max_p = opt['max_parameter']
out = {}
for p in op.parameters:
if p.name in exclude:
continue
if p.name in template:
out.update({p.name: template[p.name]})
continue
if not max_p and not p.required:
if random.randint(0, 1) == 0 or opt['minimal_parameter']:
continue
out.update({p.name: self.render(p, opt=opt)})
return out
|
[
"def",
"render_all",
"(",
"self",
",",
"op",
",",
"exclude",
"=",
"[",
"]",
",",
"opt",
"=",
"None",
")",
":",
"opt",
"=",
"self",
".",
"default",
"(",
")",
"if",
"opt",
"==",
"None",
"else",
"opt",
"if",
"not",
"isinstance",
"(",
"op",
",",
"Operation",
")",
":",
"raise",
"ValueError",
"(",
"'Not a Operation: {0}'",
".",
"format",
"(",
"op",
")",
")",
"if",
"not",
"isinstance",
"(",
"opt",
",",
"dict",
")",
":",
"raise",
"ValueError",
"(",
"'Not a dict: {0}'",
".",
"format",
"(",
"opt",
")",
")",
"template",
"=",
"opt",
"[",
"'parameter_template'",
"]",
"max_p",
"=",
"opt",
"[",
"'max_parameter'",
"]",
"out",
"=",
"{",
"}",
"for",
"p",
"in",
"op",
".",
"parameters",
":",
"if",
"p",
".",
"name",
"in",
"exclude",
":",
"continue",
"if",
"p",
".",
"name",
"in",
"template",
":",
"out",
".",
"update",
"(",
"{",
"p",
".",
"name",
":",
"template",
"[",
"p",
".",
"name",
"]",
"}",
")",
"continue",
"if",
"not",
"max_p",
"and",
"not",
"p",
".",
"required",
":",
"if",
"random",
".",
"randint",
"(",
"0",
",",
"1",
")",
"==",
"0",
"or",
"opt",
"[",
"'minimal_parameter'",
"]",
":",
"continue",
"out",
".",
"update",
"(",
"{",
"p",
".",
"name",
":",
"self",
".",
"render",
"(",
"p",
",",
"opt",
"=",
"opt",
")",
"}",
")",
"return",
"out"
] |
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}'.format(content_type, self.__op.consumes))
return content_type, six.moves.urllib.parse.urlencode(self.__p['formData'])
|
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}'.format(content_type, self.__op.consumes))
return content_type, six.moves.urllib.parse.urlencode(self.__p['formData'])
|
[
"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",
".",
"SchemaError",
"(",
"'content type {0} does not present in {1}'",
".",
"format",
"(",
"content_type",
",",
"self",
".",
"__op",
".",
"consumes",
")",
")",
"return",
"content_type",
",",
"six",
".",
"moves",
".",
"urllib",
".",
"parse",
".",
"urlencode",
"(",
"self",
".",
"__p",
"[",
"'formData'",
"]",
")"
] |
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 self.__op.consumes:
raise errs.SchemaError('content type {0} does not present in {1}'.format(content_type, self.__op.consumes))
# according to spec, payload should be one and only,
# so we just return the first value in dict.
for parameter in self.__op.parameters:
parameter = final(parameter)
if getattr(parameter, 'in') == 'body':
schema = deref(parameter.schema)
_type = schema.type
_format = schema.format
name = schema.name
body = self.__p['body'][parameter.name]
return content_type, self.__op._mime_codec.marshal(content_type, body, _type=_type, _format=_format, name=name)
return None, None
|
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 self.__op.consumes:
raise errs.SchemaError('content type {0} does not present in {1}'.format(content_type, self.__op.consumes))
# according to spec, payload should be one and only,
# so we just return the first value in dict.
for parameter in self.__op.parameters:
parameter = final(parameter)
if getattr(parameter, 'in') == 'body':
schema = deref(parameter.schema)
_type = schema.type
_format = schema.format
name = schema.name
body = self.__p['body'][parameter.name]
return content_type, self.__op._mime_codec.marshal(content_type, body, _type=_type, _format=_format, name=name)
return None, None
|
[
"def",
"_prepare_body",
"(",
"self",
")",
":",
"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",
"self",
".",
"__op",
".",
"consumes",
":",
"raise",
"errs",
".",
"SchemaError",
"(",
"'content type {0} does not present in {1}'",
".",
"format",
"(",
"content_type",
",",
"self",
".",
"__op",
".",
"consumes",
")",
")",
"# according to spec, payload should be one and only,",
"# so we just return the first value in dict.",
"for",
"parameter",
"in",
"self",
".",
"__op",
".",
"parameters",
":",
"parameter",
"=",
"final",
"(",
"parameter",
")",
"if",
"getattr",
"(",
"parameter",
",",
"'in'",
")",
"==",
"'body'",
":",
"schema",
"=",
"deref",
"(",
"parameter",
".",
"schema",
")",
"_type",
"=",
"schema",
".",
"type",
"_format",
"=",
"schema",
".",
"format",
"name",
"=",
"schema",
".",
"name",
"body",
"=",
"self",
".",
"__p",
"[",
"'body'",
"]",
"[",
"parameter",
".",
"name",
"]",
"return",
"content_type",
",",
"self",
".",
"__op",
".",
"_mime_codec",
".",
"marshal",
"(",
"content_type",
",",
"body",
",",
"_type",
"=",
"_type",
",",
"_format",
"=",
"_format",
",",
"name",
"=",
"name",
")",
"return",
"None",
",",
"None"
] |
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}'.format(content_type, self.__op.consumes))
boundary = uuid4().hex
content_type += '; boundary={0}'
content_type = content_type.format(boundary)
# init stream
body = io.BytesIO()
w = codecs.getwriter(encoding)
def append(name, obj):
body.write(six.b('--{0}\r\n'.format(boundary)))
# header
w(body).write('Content-Disposition: form-data; name="{0}"; filename="{1}"'.format(name, obj.filename))
body.write(six.b('\r\n'))
if 'Content-Type' in obj.header:
w(body).write('Content-Type: {0}'.format(obj.header['Content-Type']))
body.write(six.b('\r\n'))
if 'Content-Transfer-Encoding' in obj.header:
w(body).write('Content-Transfer-Encoding: {0}'.format(obj.header['Content-Transfer-Encoding']))
body.write(six.b('\r\n'))
body.write(six.b('\r\n'))
# body
if not obj.data:
with open(obj.filename, 'rb') as f:
body.write(f.read())
else:
data = obj.data.read()
if isinstance(data, six.text_type):
w(body).write(data)
else:
body.write(data)
body.write(six.b('\r\n'))
for k, v in self.__p['formData']:
body.write(six.b('--{0}\r\n'.format(boundary)))
w(body).write('Content-Disposition: form-data; name="{0}"'.format(k))
body.write(six.b('\r\n'))
body.write(six.b('\r\n'))
w(body).write(v)
body.write(six.b('\r\n'))
# begin of file section
for k, v in six.iteritems(self.__p['file']):
if isinstance(v, list):
for vv in v:
append(k, vv)
else:
append(k, v)
# final boundary
body.write(six.b('--{0}--\r\n'.format(boundary)))
return content_type, body.getvalue()
|
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}'.format(content_type, self.__op.consumes))
boundary = uuid4().hex
content_type += '; boundary={0}'
content_type = content_type.format(boundary)
# init stream
body = io.BytesIO()
w = codecs.getwriter(encoding)
def append(name, obj):
body.write(six.b('--{0}\r\n'.format(boundary)))
# header
w(body).write('Content-Disposition: form-data; name="{0}"; filename="{1}"'.format(name, obj.filename))
body.write(six.b('\r\n'))
if 'Content-Type' in obj.header:
w(body).write('Content-Type: {0}'.format(obj.header['Content-Type']))
body.write(six.b('\r\n'))
if 'Content-Transfer-Encoding' in obj.header:
w(body).write('Content-Transfer-Encoding: {0}'.format(obj.header['Content-Transfer-Encoding']))
body.write(six.b('\r\n'))
body.write(six.b('\r\n'))
# body
if not obj.data:
with open(obj.filename, 'rb') as f:
body.write(f.read())
else:
data = obj.data.read()
if isinstance(data, six.text_type):
w(body).write(data)
else:
body.write(data)
body.write(six.b('\r\n'))
for k, v in self.__p['formData']:
body.write(six.b('--{0}\r\n'.format(boundary)))
w(body).write('Content-Disposition: form-data; name="{0}"'.format(k))
body.write(six.b('\r\n'))
body.write(six.b('\r\n'))
w(body).write(v)
body.write(six.b('\r\n'))
# begin of file section
for k, v in six.iteritems(self.__p['file']):
if isinstance(v, list):
for vv in v:
append(k, vv)
else:
append(k, v)
# final boundary
body.write(six.b('--{0}--\r\n'.format(boundary)))
return content_type, body.getvalue()
|
[
"def",
"_prepare_files",
"(",
"self",
",",
"encoding",
")",
":",
"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}'",
".",
"format",
"(",
"content_type",
",",
"self",
".",
"__op",
".",
"consumes",
")",
")",
"boundary",
"=",
"uuid4",
"(",
")",
".",
"hex",
"content_type",
"+=",
"'; boundary={0}'",
"content_type",
"=",
"content_type",
".",
"format",
"(",
"boundary",
")",
"# init stream",
"body",
"=",
"io",
".",
"BytesIO",
"(",
")",
"w",
"=",
"codecs",
".",
"getwriter",
"(",
"encoding",
")",
"def",
"append",
"(",
"name",
",",
"obj",
")",
":",
"body",
".",
"write",
"(",
"six",
".",
"b",
"(",
"'--{0}\\r\\n'",
".",
"format",
"(",
"boundary",
")",
")",
")",
"# header",
"w",
"(",
"body",
")",
".",
"write",
"(",
"'Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"'",
".",
"format",
"(",
"name",
",",
"obj",
".",
"filename",
")",
")",
"body",
".",
"write",
"(",
"six",
".",
"b",
"(",
"'\\r\\n'",
")",
")",
"if",
"'Content-Type'",
"in",
"obj",
".",
"header",
":",
"w",
"(",
"body",
")",
".",
"write",
"(",
"'Content-Type: {0}'",
".",
"format",
"(",
"obj",
".",
"header",
"[",
"'Content-Type'",
"]",
")",
")",
"body",
".",
"write",
"(",
"six",
".",
"b",
"(",
"'\\r\\n'",
")",
")",
"if",
"'Content-Transfer-Encoding'",
"in",
"obj",
".",
"header",
":",
"w",
"(",
"body",
")",
".",
"write",
"(",
"'Content-Transfer-Encoding: {0}'",
".",
"format",
"(",
"obj",
".",
"header",
"[",
"'Content-Transfer-Encoding'",
"]",
")",
")",
"body",
".",
"write",
"(",
"six",
".",
"b",
"(",
"'\\r\\n'",
")",
")",
"body",
".",
"write",
"(",
"six",
".",
"b",
"(",
"'\\r\\n'",
")",
")",
"# body",
"if",
"not",
"obj",
".",
"data",
":",
"with",
"open",
"(",
"obj",
".",
"filename",
",",
"'rb'",
")",
"as",
"f",
":",
"body",
".",
"write",
"(",
"f",
".",
"read",
"(",
")",
")",
"else",
":",
"data",
"=",
"obj",
".",
"data",
".",
"read",
"(",
")",
"if",
"isinstance",
"(",
"data",
",",
"six",
".",
"text_type",
")",
":",
"w",
"(",
"body",
")",
".",
"write",
"(",
"data",
")",
"else",
":",
"body",
".",
"write",
"(",
"data",
")",
"body",
".",
"write",
"(",
"six",
".",
"b",
"(",
"'\\r\\n'",
")",
")",
"for",
"k",
",",
"v",
"in",
"self",
".",
"__p",
"[",
"'formData'",
"]",
":",
"body",
".",
"write",
"(",
"six",
".",
"b",
"(",
"'--{0}\\r\\n'",
".",
"format",
"(",
"boundary",
")",
")",
")",
"w",
"(",
"body",
")",
".",
"write",
"(",
"'Content-Disposition: form-data; name=\"{0}\"'",
".",
"format",
"(",
"k",
")",
")",
"body",
".",
"write",
"(",
"six",
".",
"b",
"(",
"'\\r\\n'",
")",
")",
"body",
".",
"write",
"(",
"six",
".",
"b",
"(",
"'\\r\\n'",
")",
")",
"w",
"(",
"body",
")",
".",
"write",
"(",
"v",
")",
"body",
".",
"write",
"(",
"six",
".",
"b",
"(",
"'\\r\\n'",
")",
")",
"# begin of file section",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"self",
".",
"__p",
"[",
"'file'",
"]",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"list",
")",
":",
"for",
"vv",
"in",
"v",
":",
"append",
"(",
"k",
",",
"vv",
")",
"else",
":",
"append",
"(",
"k",
",",
"v",
")",
"# final boundary",
"body",
".",
"write",
"(",
"six",
".",
"b",
"(",
"'--{0}--\\r\\n'",
".",
"format",
"(",
"boundary",
")",
")",
")",
"return",
"content_type",
",",
"body",
".",
"getvalue",
"(",
")"
] |
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.
:rtype: Request
"""
if isinstance(scheme, list):
if self.__scheme is None:
scheme = scheme.pop()
else:
if self.__scheme in scheme:
scheme = self.__scheme
else:
raise Exception('preferred scheme:{} is not supported by the client or spec:{}'.format(self.__scheme, scheme))
elif not isinstance(scheme, six.string_types):
raise ValueError('"scheme" should be a list or string')
# combine path parameters into path
# TODO: 'dot' is allowed in swagger, but it won't work in python-format
path_params = {}
for k, v in six.iteritems(self.__p['path']):
path_params[k] = six.moves.urllib.parse.quote_plus(v)
self.__path = self.__path.format(**path_params)
# combine path parameters into url
self.__url = ''.join([scheme, ':', self.__url.format(**path_params)])
# header parameters
self.__header.update(self.__p['header'])
# update data parameter
content_type = None
if self.__p['file']:
if handle_files:
content_type, self.__data = self._prepare_files(encoding)
else:
# client that can encode multipart/form-data, should
# access form-data via data property and file from file
# property.
# only form data can be carried along with files,
self.__data = self.__p['formData']
elif self.__p['formData']:
content_type, self.__data = self._prepare_forms()
elif self.__p['body']:
content_type, self.__data = self._prepare_body()
else:
self.__data = None
if content_type:
self.__header.update({'Content-Type': content_type})
accept = self.__produce
if not accept and self.__op.produces:
accept = self.__op.produces[0]
if accept:
if self.__op.produces and accept not in self.__op.produces:
raise errs.SchemaError('accept {0} does not present in {1}'.format(accept, self.__op.produces))
self.__header.update({'Accept': accept})
return self
|
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.
:rtype: Request
"""
if isinstance(scheme, list):
if self.__scheme is None:
scheme = scheme.pop()
else:
if self.__scheme in scheme:
scheme = self.__scheme
else:
raise Exception('preferred scheme:{} is not supported by the client or spec:{}'.format(self.__scheme, scheme))
elif not isinstance(scheme, six.string_types):
raise ValueError('"scheme" should be a list or string')
# combine path parameters into path
# TODO: 'dot' is allowed in swagger, but it won't work in python-format
path_params = {}
for k, v in six.iteritems(self.__p['path']):
path_params[k] = six.moves.urllib.parse.quote_plus(v)
self.__path = self.__path.format(**path_params)
# combine path parameters into url
self.__url = ''.join([scheme, ':', self.__url.format(**path_params)])
# header parameters
self.__header.update(self.__p['header'])
# update data parameter
content_type = None
if self.__p['file']:
if handle_files:
content_type, self.__data = self._prepare_files(encoding)
else:
# client that can encode multipart/form-data, should
# access form-data via data property and file from file
# property.
# only form data can be carried along with files,
self.__data = self.__p['formData']
elif self.__p['formData']:
content_type, self.__data = self._prepare_forms()
elif self.__p['body']:
content_type, self.__data = self._prepare_body()
else:
self.__data = None
if content_type:
self.__header.update({'Content-Type': content_type})
accept = self.__produce
if not accept and self.__op.produces:
accept = self.__op.produces[0]
if accept:
if self.__op.produces and accept not in self.__op.produces:
raise errs.SchemaError('accept {0} does not present in {1}'.format(accept, self.__op.produces))
self.__header.update({'Accept': accept})
return self
|
[
"def",
"prepare",
"(",
"self",
",",
"scheme",
"=",
"'http'",
",",
"handle_files",
"=",
"True",
",",
"encoding",
"=",
"'utf-8'",
")",
":",
"if",
"isinstance",
"(",
"scheme",
",",
"list",
")",
":",
"if",
"self",
".",
"__scheme",
"is",
"None",
":",
"scheme",
"=",
"scheme",
".",
"pop",
"(",
")",
"else",
":",
"if",
"self",
".",
"__scheme",
"in",
"scheme",
":",
"scheme",
"=",
"self",
".",
"__scheme",
"else",
":",
"raise",
"Exception",
"(",
"'preferred scheme:{} is not supported by the client or spec:{}'",
".",
"format",
"(",
"self",
".",
"__scheme",
",",
"scheme",
")",
")",
"elif",
"not",
"isinstance",
"(",
"scheme",
",",
"six",
".",
"string_types",
")",
":",
"raise",
"ValueError",
"(",
"'\"scheme\" should be a list or string'",
")",
"# combine path parameters into path",
"# TODO: 'dot' is allowed in swagger, but it won't work in python-format",
"path_params",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"self",
".",
"__p",
"[",
"'path'",
"]",
")",
":",
"path_params",
"[",
"k",
"]",
"=",
"six",
".",
"moves",
".",
"urllib",
".",
"parse",
".",
"quote_plus",
"(",
"v",
")",
"self",
".",
"__path",
"=",
"self",
".",
"__path",
".",
"format",
"(",
"*",
"*",
"path_params",
")",
"# combine path parameters into url",
"self",
".",
"__url",
"=",
"''",
".",
"join",
"(",
"[",
"scheme",
",",
"':'",
",",
"self",
".",
"__url",
".",
"format",
"(",
"*",
"*",
"path_params",
")",
"]",
")",
"# header parameters",
"self",
".",
"__header",
".",
"update",
"(",
"self",
".",
"__p",
"[",
"'header'",
"]",
")",
"# update data parameter",
"content_type",
"=",
"None",
"if",
"self",
".",
"__p",
"[",
"'file'",
"]",
":",
"if",
"handle_files",
":",
"content_type",
",",
"self",
".",
"__data",
"=",
"self",
".",
"_prepare_files",
"(",
"encoding",
")",
"else",
":",
"# client that can encode multipart/form-data, should",
"# access form-data via data property and file from file",
"# property.",
"# only form data can be carried along with files,",
"self",
".",
"__data",
"=",
"self",
".",
"__p",
"[",
"'formData'",
"]",
"elif",
"self",
".",
"__p",
"[",
"'formData'",
"]",
":",
"content_type",
",",
"self",
".",
"__data",
"=",
"self",
".",
"_prepare_forms",
"(",
")",
"elif",
"self",
".",
"__p",
"[",
"'body'",
"]",
":",
"content_type",
",",
"self",
".",
"__data",
"=",
"self",
".",
"_prepare_body",
"(",
")",
"else",
":",
"self",
".",
"__data",
"=",
"None",
"if",
"content_type",
":",
"self",
".",
"__header",
".",
"update",
"(",
"{",
"'Content-Type'",
":",
"content_type",
"}",
")",
"accept",
"=",
"self",
".",
"__produce",
"if",
"not",
"accept",
"and",
"self",
".",
"__op",
".",
"produces",
":",
"accept",
"=",
"self",
".",
"__op",
".",
"produces",
"[",
"0",
"]",
"if",
"accept",
":",
"if",
"self",
".",
"__op",
".",
"produces",
"and",
"accept",
"not",
"in",
"self",
".",
"__op",
".",
"produces",
":",
"raise",
"errs",
".",
"SchemaError",
"(",
"'accept {0} does not present in {1}'",
".",
"format",
"(",
"accept",
",",
"self",
".",
"__op",
".",
"produces",
")",
")",
"self",
".",
"__header",
".",
"update",
"(",
"{",
"'Accept'",
":",
"accept",
"}",
")",
"return",
"self"
] |
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
"""
if status != None:
self.__status = status
r = (final(self.__op.responses.get(str(self.__status), None)) or
final(self.__op.responses.get('default', None)))
if header != None:
if isinstance(header, (collections.Mapping, collections.MutableMapping)):
for k, v in six.iteritems(header):
self._convert_header(r, k, v)
else:
for k, v in header:
self._convert_header(r, k, v)
if raw != None:
# update 'raw'
self.__raw = raw
if self.__status == None:
raise Exception('Update status code before assigning raw data')
if r and r.schema and not self.__raw_body_only:
# update data from Opeartion if succeed else from responseMessage.responseModel
content_type = 'application/json'
for k, v in six.iteritems(self.header):
if k.lower() == 'content-type':
content_type = v[0].lower()
break
schema = deref(r.schema)
_type = schema.type
_format = schema.format
name = schema.name
data = self.__op._mime_codec.unmarshal(content_type, self.raw, _type=_type, _format=_format, name=name)
self.__data = r.schema._prim_(data, self.__op._prim_factory, ctx=dict(read=True))
return self
|
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
"""
if status != None:
self.__status = status
r = (final(self.__op.responses.get(str(self.__status), None)) or
final(self.__op.responses.get('default', None)))
if header != None:
if isinstance(header, (collections.Mapping, collections.MutableMapping)):
for k, v in six.iteritems(header):
self._convert_header(r, k, v)
else:
for k, v in header:
self._convert_header(r, k, v)
if raw != None:
# update 'raw'
self.__raw = raw
if self.__status == None:
raise Exception('Update status code before assigning raw data')
if r and r.schema and not self.__raw_body_only:
# update data from Opeartion if succeed else from responseMessage.responseModel
content_type = 'application/json'
for k, v in six.iteritems(self.header):
if k.lower() == 'content-type':
content_type = v[0].lower()
break
schema = deref(r.schema)
_type = schema.type
_format = schema.format
name = schema.name
data = self.__op._mime_codec.unmarshal(content_type, self.raw, _type=_type, _format=_format, name=name)
self.__data = r.schema._prim_(data, self.__op._prim_factory, ctx=dict(read=True))
return self
|
[
"def",
"apply_with",
"(",
"self",
",",
"status",
"=",
"None",
",",
"raw",
"=",
"None",
",",
"header",
"=",
"None",
")",
":",
"if",
"status",
"!=",
"None",
":",
"self",
".",
"__status",
"=",
"status",
"r",
"=",
"(",
"final",
"(",
"self",
".",
"__op",
".",
"responses",
".",
"get",
"(",
"str",
"(",
"self",
".",
"__status",
")",
",",
"None",
")",
")",
"or",
"final",
"(",
"self",
".",
"__op",
".",
"responses",
".",
"get",
"(",
"'default'",
",",
"None",
")",
")",
")",
"if",
"header",
"!=",
"None",
":",
"if",
"isinstance",
"(",
"header",
",",
"(",
"collections",
".",
"Mapping",
",",
"collections",
".",
"MutableMapping",
")",
")",
":",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"header",
")",
":",
"self",
".",
"_convert_header",
"(",
"r",
",",
"k",
",",
"v",
")",
"else",
":",
"for",
"k",
",",
"v",
"in",
"header",
":",
"self",
".",
"_convert_header",
"(",
"r",
",",
"k",
",",
"v",
")",
"if",
"raw",
"!=",
"None",
":",
"# update 'raw'",
"self",
".",
"__raw",
"=",
"raw",
"if",
"self",
".",
"__status",
"==",
"None",
":",
"raise",
"Exception",
"(",
"'Update status code before assigning raw data'",
")",
"if",
"r",
"and",
"r",
".",
"schema",
"and",
"not",
"self",
".",
"__raw_body_only",
":",
"# update data from Opeartion if succeed else from responseMessage.responseModel",
"content_type",
"=",
"'application/json'",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"self",
".",
"header",
")",
":",
"if",
"k",
".",
"lower",
"(",
")",
"==",
"'content-type'",
":",
"content_type",
"=",
"v",
"[",
"0",
"]",
".",
"lower",
"(",
")",
"break",
"schema",
"=",
"deref",
"(",
"r",
".",
"schema",
")",
"_type",
"=",
"schema",
".",
"type",
"_format",
"=",
"schema",
".",
"format",
"name",
"=",
"schema",
".",
"name",
"data",
"=",
"self",
".",
"__op",
".",
"_mime_codec",
".",
"unmarshal",
"(",
"content_type",
",",
"self",
".",
"raw",
",",
"_type",
"=",
"_type",
",",
"_format",
"=",
"_format",
",",
"name",
"=",
"name",
")",
"self",
".",
"__data",
"=",
"r",
".",
"schema",
".",
"_prim_",
"(",
"data",
",",
"self",
".",
"__op",
".",
"_prim_factory",
",",
"ctx",
"=",
"dict",
"(",
"read",
"=",
"True",
")",
")",
"return",
"self"
] |
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(type(obj)))
def _apply(x, kk, ct, v):
if key not in self._obj:
self._obj[kk] = {} if ct == None else []
with x(self._obj, kk) as ctx:
ctx.parse(obj=v)
def _apply_dict(x, kk, ct, v, k):
if k not in self._obj[kk]:
self._obj[kk][k] = {} if ct == ContainerType.dict_ else []
with x(self._obj[kk], k) as ctx:
ctx.parse(obj=v)
def _apply_dict_before_list(kk, ct, v, k):
self._obj[kk][k] = []
if hasattr(self, '__swagger_child__'):
# to nested objects
for key, (ct, ctx_kls) in six.iteritems(self.__swagger_child__):
items = obj.get(key, None)
# create an empty child, even it's None in input.
# this makes other logic easier.
if ct == ContainerType.list_:
self._obj[key] = []
elif ct:
self._obj[key] = {}
if items == None:
continue
container_apply(ct, items,
functools.partial(_apply, ctx_kls, key),
functools.partial(_apply_dict, ctx_kls, key),
functools.partial(_apply_dict_before_list, key)
)
# update _obj with obj
if self._obj != None:
for key in (set(obj.keys()) - set(self._obj.keys())):
self._obj[key] = obj[key]
else:
self._obj = obj
|
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(type(obj)))
def _apply(x, kk, ct, v):
if key not in self._obj:
self._obj[kk] = {} if ct == None else []
with x(self._obj, kk) as ctx:
ctx.parse(obj=v)
def _apply_dict(x, kk, ct, v, k):
if k not in self._obj[kk]:
self._obj[kk][k] = {} if ct == ContainerType.dict_ else []
with x(self._obj[kk], k) as ctx:
ctx.parse(obj=v)
def _apply_dict_before_list(kk, ct, v, k):
self._obj[kk][k] = []
if hasattr(self, '__swagger_child__'):
# to nested objects
for key, (ct, ctx_kls) in six.iteritems(self.__swagger_child__):
items = obj.get(key, None)
# create an empty child, even it's None in input.
# this makes other logic easier.
if ct == ContainerType.list_:
self._obj[key] = []
elif ct:
self._obj[key] = {}
if items == None:
continue
container_apply(ct, items,
functools.partial(_apply, ctx_kls, key),
functools.partial(_apply_dict, ctx_kls, key),
functools.partial(_apply_dict_before_list, key)
)
# update _obj with obj
if self._obj != None:
for key in (set(obj.keys()) - set(self._obj.keys())):
self._obj[key] = obj[key]
else:
self._obj = obj
|
[
"def",
"parse",
"(",
"self",
",",
"obj",
"=",
"None",
")",
":",
"if",
"obj",
"==",
"None",
":",
"return",
"if",
"not",
"isinstance",
"(",
"obj",
",",
"dict",
")",
":",
"raise",
"ValueError",
"(",
"'invalid obj passed: '",
"+",
"str",
"(",
"type",
"(",
"obj",
")",
")",
")",
"def",
"_apply",
"(",
"x",
",",
"kk",
",",
"ct",
",",
"v",
")",
":",
"if",
"key",
"not",
"in",
"self",
".",
"_obj",
":",
"self",
".",
"_obj",
"[",
"kk",
"]",
"=",
"{",
"}",
"if",
"ct",
"==",
"None",
"else",
"[",
"]",
"with",
"x",
"(",
"self",
".",
"_obj",
",",
"kk",
")",
"as",
"ctx",
":",
"ctx",
".",
"parse",
"(",
"obj",
"=",
"v",
")",
"def",
"_apply_dict",
"(",
"x",
",",
"kk",
",",
"ct",
",",
"v",
",",
"k",
")",
":",
"if",
"k",
"not",
"in",
"self",
".",
"_obj",
"[",
"kk",
"]",
":",
"self",
".",
"_obj",
"[",
"kk",
"]",
"[",
"k",
"]",
"=",
"{",
"}",
"if",
"ct",
"==",
"ContainerType",
".",
"dict_",
"else",
"[",
"]",
"with",
"x",
"(",
"self",
".",
"_obj",
"[",
"kk",
"]",
",",
"k",
")",
"as",
"ctx",
":",
"ctx",
".",
"parse",
"(",
"obj",
"=",
"v",
")",
"def",
"_apply_dict_before_list",
"(",
"kk",
",",
"ct",
",",
"v",
",",
"k",
")",
":",
"self",
".",
"_obj",
"[",
"kk",
"]",
"[",
"k",
"]",
"=",
"[",
"]",
"if",
"hasattr",
"(",
"self",
",",
"'__swagger_child__'",
")",
":",
"# to nested objects",
"for",
"key",
",",
"(",
"ct",
",",
"ctx_kls",
")",
"in",
"six",
".",
"iteritems",
"(",
"self",
".",
"__swagger_child__",
")",
":",
"items",
"=",
"obj",
".",
"get",
"(",
"key",
",",
"None",
")",
"# create an empty child, even it's None in input.",
"# this makes other logic easier.",
"if",
"ct",
"==",
"ContainerType",
".",
"list_",
":",
"self",
".",
"_obj",
"[",
"key",
"]",
"=",
"[",
"]",
"elif",
"ct",
":",
"self",
".",
"_obj",
"[",
"key",
"]",
"=",
"{",
"}",
"if",
"items",
"==",
"None",
":",
"continue",
"container_apply",
"(",
"ct",
",",
"items",
",",
"functools",
".",
"partial",
"(",
"_apply",
",",
"ctx_kls",
",",
"key",
")",
",",
"functools",
".",
"partial",
"(",
"_apply_dict",
",",
"ctx_kls",
",",
"key",
")",
",",
"functools",
".",
"partial",
"(",
"_apply_dict_before_list",
",",
"key",
")",
")",
"# update _obj with obj",
"if",
"self",
".",
"_obj",
"!=",
"None",
":",
"for",
"key",
"in",
"(",
"set",
"(",
"obj",
".",
"keys",
"(",
")",
")",
"-",
"set",
"(",
"self",
".",
"_obj",
".",
"keys",
"(",
")",
")",
")",
":",
"self",
".",
"_obj",
"[",
"key",
"]",
"=",
"obj",
"[",
"key",
"]",
"else",
":",
"self",
".",
"_obj",
"=",
"obj"
] |
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:
raise ValueError('Object is not instance of {0} but {1}'.format(cls.__swagger_ref_object__.__name__, obj.__class__.__name__))
# set self as childrent's parent
for name, (ct, ctx) in six.iteritems(ctx.__swagger_child__):
obj = getattr(self, name)
if obj == None:
continue
container_apply(ct, obj, functools.partial(_assign, ctx))
|
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:
raise ValueError('Object is not instance of {0} but {1}'.format(cls.__swagger_ref_object__.__name__, obj.__class__.__name__))
# set self as childrent's parent
for name, (ct, ctx) in six.iteritems(ctx.__swagger_child__):
obj = getattr(self, name)
if obj == None:
continue
container_apply(ct, obj, functools.partial(_assign, ctx))
|
[
"def",
"_assign_parent",
"(",
"self",
",",
"ctx",
")",
":",
"def",
"_assign",
"(",
"cls",
",",
"_",
",",
"obj",
")",
":",
"if",
"obj",
"==",
"None",
":",
"return",
"if",
"cls",
".",
"is_produced",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"BaseObj",
")",
":",
"obj",
".",
"_parent__",
"=",
"self",
"else",
":",
"raise",
"ValueError",
"(",
"'Object is not instance of {0} but {1}'",
".",
"format",
"(",
"cls",
".",
"__swagger_ref_object__",
".",
"__name__",
",",
"obj",
".",
"__class__",
".",
"__name__",
")",
")",
"# set self as childrent's parent",
"for",
"name",
",",
"(",
"ct",
",",
"ctx",
")",
"in",
"six",
".",
"iteritems",
"(",
"ctx",
".",
"__swagger_child__",
")",
":",
"obj",
"=",
"getattr",
"(",
"self",
",",
"name",
")",
"if",
"obj",
"==",
"None",
":",
"continue",
"container_apply",
"(",
"ct",
",",
"obj",
",",
"functools",
".",
"partial",
"(",
"_assign",
",",
"ctx",
")",
")"
] |
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",
".",
"__class__",
".",
"__name__",
"+",
"'__'",
"+",
"f"
] |
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__.__name__))
setattr(self, n, obj)
self.__origin_keys.add(f)
|
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__.__name__))
setattr(self, n, obj)
self.__origin_keys.add(f)
|
[
"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",
"(",
"n",
",",
"self",
".",
"__class__",
".",
"__name__",
")",
")",
"setattr",
"(",
"self",
",",
"n",
",",
"obj",
")",
"self",
".",
"__origin_keys",
".",
"add",
"(",
"f",
")"
] |
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):
obj = getattr(obj, t)
elif isinstance(obj, list):
obj = obj[int(t)]
elif isinstance(obj, dict):
obj = obj[t]
return obj
|
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):
obj = getattr(obj, t)
elif isinstance(obj, list):
obj = obj[int(t)]
elif isinstance(obj, dict):
obj = obj[t]
return obj
|
[
"def",
"resolve",
"(",
"self",
",",
"ts",
")",
":",
"if",
"isinstance",
"(",
"ts",
",",
"six",
".",
"string_types",
")",
":",
"ts",
"=",
"[",
"ts",
"]",
"obj",
"=",
"self",
"while",
"len",
"(",
"ts",
")",
">",
"0",
":",
"t",
"=",
"ts",
".",
"pop",
"(",
"0",
")",
"if",
"issubclass",
"(",
"obj",
".",
"__class__",
",",
"BaseObj",
")",
":",
"obj",
"=",
"getattr",
"(",
"obj",
",",
"t",
")",
"elif",
"isinstance",
"(",
"obj",
",",
"list",
")",
":",
"obj",
"=",
"obj",
"[",
"int",
"(",
"t",
")",
"]",
"elif",
"isinstance",
"(",
"obj",
",",
"dict",
")",
":",
"obj",
"=",
"obj",
"[",
"t",
"]",
"return",
"obj"
] |
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.string_types) and isinstance(o, six.string_types):
return s == o, name
if s.__class__ != o.__class__:
return False, name
if isinstance(s, BaseObj):
if not isinstance(s, weakref.ProxyTypes):
return s.compare(o, name)
elif isinstance(s, list):
for i, v in zip(range(len(s)), s):
same, n = cmp_func(jp_compose(str(i), name), v, o[i])
if not same:
return same, n
elif isinstance(s, dict):
# compare if any key diff
diff = list(set(s.keys()) - set(o.keys()))
if diff:
return False, jp_compose(str(diff[0]), name)
diff = list(set(o.keys()) - set(s.keys()))
if diff:
return False, jp_compose(str(diff[0]), name)
for k, v in six.iteritems(s):
same, n = cmp_func(jp_compose(k, name), v, o[k])
if not same:
return same, n
else:
return s == o, name
return True, name
for n in names:
same, n = cmp_func(jp_compose(n, base), getattr(self, n), getattr(other, n))
if not same:
return same, n
return True, ''
|
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.string_types) and isinstance(o, six.string_types):
return s == o, name
if s.__class__ != o.__class__:
return False, name
if isinstance(s, BaseObj):
if not isinstance(s, weakref.ProxyTypes):
return s.compare(o, name)
elif isinstance(s, list):
for i, v in zip(range(len(s)), s):
same, n = cmp_func(jp_compose(str(i), name), v, o[i])
if not same:
return same, n
elif isinstance(s, dict):
# compare if any key diff
diff = list(set(s.keys()) - set(o.keys()))
if diff:
return False, jp_compose(str(diff[0]), name)
diff = list(set(o.keys()) - set(s.keys()))
if diff:
return False, jp_compose(str(diff[0]), name)
for k, v in six.iteritems(s):
same, n = cmp_func(jp_compose(k, name), v, o[k])
if not same:
return same, n
else:
return s == o, name
return True, name
for n in names:
same, n = cmp_func(jp_compose(n, base), getattr(self, n), getattr(other, n))
if not same:
return same, n
return True, ''
|
[
"def",
"compare",
"(",
"self",
",",
"other",
",",
"base",
"=",
"None",
")",
":",
"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",
".",
"string_types",
")",
"and",
"isinstance",
"(",
"o",
",",
"six",
".",
"string_types",
")",
":",
"return",
"s",
"==",
"o",
",",
"name",
"if",
"s",
".",
"__class__",
"!=",
"o",
".",
"__class__",
":",
"return",
"False",
",",
"name",
"if",
"isinstance",
"(",
"s",
",",
"BaseObj",
")",
":",
"if",
"not",
"isinstance",
"(",
"s",
",",
"weakref",
".",
"ProxyTypes",
")",
":",
"return",
"s",
".",
"compare",
"(",
"o",
",",
"name",
")",
"elif",
"isinstance",
"(",
"s",
",",
"list",
")",
":",
"for",
"i",
",",
"v",
"in",
"zip",
"(",
"range",
"(",
"len",
"(",
"s",
")",
")",
",",
"s",
")",
":",
"same",
",",
"n",
"=",
"cmp_func",
"(",
"jp_compose",
"(",
"str",
"(",
"i",
")",
",",
"name",
")",
",",
"v",
",",
"o",
"[",
"i",
"]",
")",
"if",
"not",
"same",
":",
"return",
"same",
",",
"n",
"elif",
"isinstance",
"(",
"s",
",",
"dict",
")",
":",
"# compare if any key diff",
"diff",
"=",
"list",
"(",
"set",
"(",
"s",
".",
"keys",
"(",
")",
")",
"-",
"set",
"(",
"o",
".",
"keys",
"(",
")",
")",
")",
"if",
"diff",
":",
"return",
"False",
",",
"jp_compose",
"(",
"str",
"(",
"diff",
"[",
"0",
"]",
")",
",",
"name",
")",
"diff",
"=",
"list",
"(",
"set",
"(",
"o",
".",
"keys",
"(",
")",
")",
"-",
"set",
"(",
"s",
".",
"keys",
"(",
")",
")",
")",
"if",
"diff",
":",
"return",
"False",
",",
"jp_compose",
"(",
"str",
"(",
"diff",
"[",
"0",
"]",
")",
",",
"name",
")",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"s",
")",
":",
"same",
",",
"n",
"=",
"cmp_func",
"(",
"jp_compose",
"(",
"k",
",",
"name",
")",
",",
"v",
",",
"o",
"[",
"k",
"]",
")",
"if",
"not",
"same",
":",
"return",
"same",
",",
"n",
"else",
":",
"return",
"s",
"==",
"o",
",",
"name",
"return",
"True",
",",
"name",
"for",
"n",
"in",
"names",
":",
"same",
",",
"n",
"=",
"cmp_func",
"(",
"jp_compose",
"(",
"n",
",",
"base",
")",
",",
"getattr",
"(",
"self",
",",
"n",
")",
",",
"getattr",
"(",
"other",
",",
"n",
")",
")",
"if",
"not",
"same",
":",
"return",
"same",
",",
"n",
"return",
"True",
",",
"''"
] |
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(new_n) if new_n else ret.append(n)
return ret
|
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(new_n) if new_n else ret.append(n)
return ret
|
[
"def",
"_field_names_",
"(",
"self",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"n",
"in",
"six",
".",
"iterkeys",
"(",
"self",
".",
"__swagger_fields__",
")",
":",
"new_n",
"=",
"self",
".",
"__swagger_rename__",
".",
"get",
"(",
"n",
",",
"None",
")",
"ret",
".",
"append",
"(",
"new_n",
")",
"if",
"new_n",
"else",
"ret",
".",
"append",
"(",
"n",
")",
"return",
"ret"
] |
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):
ret[name] = obj
elif isinstance(obj, list):
for i, v in zip(range(len(obj)), obj):
down(jp_compose(str(i), name), v)
elif isinstance(obj, dict):
for k, v in six.iteritems(obj):
down(jp_compose(k, name), v)
for n in names:
down(jp_compose(n), getattr(self, n))
return ret
|
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):
ret[name] = obj
elif isinstance(obj, list):
for i, v in zip(range(len(obj)), obj):
down(jp_compose(str(i), name), v)
elif isinstance(obj, dict):
for k, v in six.iteritems(obj):
down(jp_compose(k, name), v)
for n in names:
down(jp_compose(n), getattr(self, n))
return ret
|
[
"def",
"_children_",
"(",
"self",
")",
":",
"ret",
"=",
"{",
"}",
"names",
"=",
"self",
".",
"_field_names_",
"def",
"down",
"(",
"name",
",",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"BaseObj",
")",
":",
"if",
"not",
"isinstance",
"(",
"obj",
",",
"weakref",
".",
"ProxyTypes",
")",
":",
"ret",
"[",
"name",
"]",
"=",
"obj",
"elif",
"isinstance",
"(",
"obj",
",",
"list",
")",
":",
"for",
"i",
",",
"v",
"in",
"zip",
"(",
"range",
"(",
"len",
"(",
"obj",
")",
")",
",",
"obj",
")",
":",
"down",
"(",
"jp_compose",
"(",
"str",
"(",
"i",
")",
",",
"name",
")",
",",
"v",
")",
"elif",
"isinstance",
"(",
"obj",
",",
"dict",
")",
":",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"obj",
")",
":",
"down",
"(",
"jp_compose",
"(",
"k",
",",
"name",
")",
",",
"v",
")",
"for",
"n",
"in",
"names",
":",
"down",
"(",
"jp_compose",
"(",
"n",
")",
",",
"getattr",
"(",
"self",
",",
"n",
")",
")",
"return",
"ret"
] |
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/instance of Getter
:param parser: the parser to parse the loaded json.
:type parser: pyswagger.base.Context
:param dict app_cache: the cache shared by related App
:param func url_load_hook: hook to patch the url to load json
:param str sep: scope-separater used in this App
:param prim pyswager.primitives.Primitive: factory for primitives in Swagger
:param mime_codec pyswagger.primitives.MimeCodec: MIME codec
:param resolver: pyswagger.resolve.Resolver: customized resolver used as default when none is provided when resolving
:return: the created App object
:rtype: App
:raises ValueError: if url is wrong
:raises NotImplementedError: the swagger version is not supported.
"""
logger.info('load with [{0}]'.format(url))
url = utils.normalize_url(url)
app = kls(url, url_load_hook=url_load_hook, sep=sep, prim=prim, mime_codec=mime_codec, resolver=resolver)
app.__raw, app.__version = app.load_obj(url, getter=getter, parser=parser)
if app.__version not in ['1.2', '2.0']:
raise NotImplementedError('Unsupported Version: {0}'.format(self.__version))
# update scheme if any
p = six.moves.urllib.parse.urlparse(url)
if p.scheme:
app.schemes.append(p.scheme)
return app
|
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/instance of Getter
:param parser: the parser to parse the loaded json.
:type parser: pyswagger.base.Context
:param dict app_cache: the cache shared by related App
:param func url_load_hook: hook to patch the url to load json
:param str sep: scope-separater used in this App
:param prim pyswager.primitives.Primitive: factory for primitives in Swagger
:param mime_codec pyswagger.primitives.MimeCodec: MIME codec
:param resolver: pyswagger.resolve.Resolver: customized resolver used as default when none is provided when resolving
:return: the created App object
:rtype: App
:raises ValueError: if url is wrong
:raises NotImplementedError: the swagger version is not supported.
"""
logger.info('load with [{0}]'.format(url))
url = utils.normalize_url(url)
app = kls(url, url_load_hook=url_load_hook, sep=sep, prim=prim, mime_codec=mime_codec, resolver=resolver)
app.__raw, app.__version = app.load_obj(url, getter=getter, parser=parser)
if app.__version not in ['1.2', '2.0']:
raise NotImplementedError('Unsupported Version: {0}'.format(self.__version))
# update scheme if any
p = six.moves.urllib.parse.urlparse(url)
if p.scheme:
app.schemes.append(p.scheme)
return app
|
[
"def",
"load",
"(",
"kls",
",",
"url",
",",
"getter",
"=",
"None",
",",
"parser",
"=",
"None",
",",
"url_load_hook",
"=",
"None",
",",
"sep",
"=",
"consts",
".",
"private",
".",
"SCOPE_SEPARATOR",
",",
"prim",
"=",
"None",
",",
"mime_codec",
"=",
"None",
",",
"resolver",
"=",
"None",
")",
":",
"logger",
".",
"info",
"(",
"'load with [{0}]'",
".",
"format",
"(",
"url",
")",
")",
"url",
"=",
"utils",
".",
"normalize_url",
"(",
"url",
")",
"app",
"=",
"kls",
"(",
"url",
",",
"url_load_hook",
"=",
"url_load_hook",
",",
"sep",
"=",
"sep",
",",
"prim",
"=",
"prim",
",",
"mime_codec",
"=",
"mime_codec",
",",
"resolver",
"=",
"resolver",
")",
"app",
".",
"__raw",
",",
"app",
".",
"__version",
"=",
"app",
".",
"load_obj",
"(",
"url",
",",
"getter",
"=",
"getter",
",",
"parser",
"=",
"parser",
")",
"if",
"app",
".",
"__version",
"not",
"in",
"[",
"'1.2'",
",",
"'2.0'",
"]",
":",
"raise",
"NotImplementedError",
"(",
"'Unsupported Version: {0}'",
".",
"format",
"(",
"self",
".",
"__version",
")",
")",
"# update scheme if any",
"p",
"=",
"six",
".",
"moves",
".",
"urllib",
".",
"parse",
".",
"urlparse",
"(",
"url",
")",
"if",
"p",
".",
"scheme",
":",
"app",
".",
"schemes",
".",
"append",
"(",
"p",
".",
"scheme",
")",
"return",
"app"
] |
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 cache shared by related App
:param func url_load_hook: hook to patch the url to load json
:param str sep: scope-separater used in this App
:param prim pyswager.primitives.Primitive: factory for primitives in Swagger
:param mime_codec pyswagger.primitives.MimeCodec: MIME codec
:param resolver: pyswagger.resolve.Resolver: customized resolver used as default when none is provided when resolving
:return: the created App object
:rtype: App
:raises ValueError: if url is wrong
:raises NotImplementedError: the swagger version is not supported.
|
[
"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 self.__root.schemes:
if len(self.__root.schemes) > 0:
self.__schemes = self.__root.schemes
else:
# extract schemes from the url to load spec
self.__schemes = [six.moves.urlparse(self.__url).schemes]
s = Scanner(self)
s.scan(root=self.__root, route=[Merge()])
s.scan(root=self.__root, route=[PatchObject()])
s.scan(root=self.__root, route=[Aggregate()])
# reducer for Operation
tr = TypeReduce(self.__sep)
cy = CycleDetector()
s.scan(root=self.__root, route=[tr, cy])
# 'op' -- shortcut for Operation with tag and operaionId
self.__op = utils.ScopeDict(tr.op)
# 'm' -- shortcut for model in Swagger 1.2
if hasattr(self.__root, 'definitions') and self.__root.definitions != None:
self.__m = utils.ScopeDict(self.__root.definitions)
else:
self.__m = utils.ScopeDict({})
# update scope-separater
self.__m.sep = self.__sep
self.__op.sep = self.__sep
# cycle detection
if len(cy.cycles['schema']) > 0 and strict:
raise errs.CycleDetectionError('Cycles detected in Schema Object: {0}'.format(cy.cycles['schema']))
|
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 self.__root.schemes:
if len(self.__root.schemes) > 0:
self.__schemes = self.__root.schemes
else:
# extract schemes from the url to load spec
self.__schemes = [six.moves.urlparse(self.__url).schemes]
s = Scanner(self)
s.scan(root=self.__root, route=[Merge()])
s.scan(root=self.__root, route=[PatchObject()])
s.scan(root=self.__root, route=[Aggregate()])
# reducer for Operation
tr = TypeReduce(self.__sep)
cy = CycleDetector()
s.scan(root=self.__root, route=[tr, cy])
# 'op' -- shortcut for Operation with tag and operaionId
self.__op = utils.ScopeDict(tr.op)
# 'm' -- shortcut for model in Swagger 1.2
if hasattr(self.__root, 'definitions') and self.__root.definitions != None:
self.__m = utils.ScopeDict(self.__root.definitions)
else:
self.__m = utils.ScopeDict({})
# update scope-separater
self.__m.sep = self.__sep
self.__op.sep = self.__sep
# cycle detection
if len(cy.cycles['schema']) > 0 and strict:
raise errs.CycleDetectionError('Cycles detected in Schema Object: {0}'.format(cy.cycles['schema']))
|
[
"def",
"prepare",
"(",
"self",
",",
"strict",
"=",
"True",
")",
":",
"self",
".",
"__root",
"=",
"self",
".",
"prepare_obj",
"(",
"self",
".",
"raw",
",",
"self",
".",
"__url",
")",
"self",
".",
"validate",
"(",
"strict",
"=",
"strict",
")",
"if",
"hasattr",
"(",
"self",
".",
"__root",
",",
"'schemes'",
")",
"and",
"self",
".",
"__root",
".",
"schemes",
":",
"if",
"len",
"(",
"self",
".",
"__root",
".",
"schemes",
")",
">",
"0",
":",
"self",
".",
"__schemes",
"=",
"self",
".",
"__root",
".",
"schemes",
"else",
":",
"# extract schemes from the url to load spec",
"self",
".",
"__schemes",
"=",
"[",
"six",
".",
"moves",
".",
"urlparse",
"(",
"self",
".",
"__url",
")",
".",
"schemes",
"]",
"s",
"=",
"Scanner",
"(",
"self",
")",
"s",
".",
"scan",
"(",
"root",
"=",
"self",
".",
"__root",
",",
"route",
"=",
"[",
"Merge",
"(",
")",
"]",
")",
"s",
".",
"scan",
"(",
"root",
"=",
"self",
".",
"__root",
",",
"route",
"=",
"[",
"PatchObject",
"(",
")",
"]",
")",
"s",
".",
"scan",
"(",
"root",
"=",
"self",
".",
"__root",
",",
"route",
"=",
"[",
"Aggregate",
"(",
")",
"]",
")",
"# reducer for Operation",
"tr",
"=",
"TypeReduce",
"(",
"self",
".",
"__sep",
")",
"cy",
"=",
"CycleDetector",
"(",
")",
"s",
".",
"scan",
"(",
"root",
"=",
"self",
".",
"__root",
",",
"route",
"=",
"[",
"tr",
",",
"cy",
"]",
")",
"# 'op' -- shortcut for Operation with tag and operaionId",
"self",
".",
"__op",
"=",
"utils",
".",
"ScopeDict",
"(",
"tr",
".",
"op",
")",
"# 'm' -- shortcut for model in Swagger 1.2",
"if",
"hasattr",
"(",
"self",
".",
"__root",
",",
"'definitions'",
")",
"and",
"self",
".",
"__root",
".",
"definitions",
"!=",
"None",
":",
"self",
".",
"__m",
"=",
"utils",
".",
"ScopeDict",
"(",
"self",
".",
"__root",
".",
"definitions",
")",
"else",
":",
"self",
".",
"__m",
"=",
"utils",
".",
"ScopeDict",
"(",
"{",
"}",
")",
"# update scope-separater",
"self",
".",
"__m",
".",
"sep",
"=",
"self",
".",
"__sep",
"self",
".",
"__op",
".",
"sep",
"=",
"self",
".",
"__sep",
"# cycle detection",
"if",
"len",
"(",
"cy",
".",
"cycles",
"[",
"'schema'",
"]",
")",
">",
"0",
"and",
"strict",
":",
"raise",
"errs",
".",
"CycleDetectionError",
"(",
"'Cycles detected in Schema Object: {0}'",
".",
"format",
"(",
"cy",
".",
"cycles",
"[",
"'schema'",
"]",
")",
")"
] |
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
:raises NotImplementedError: the swagger version is not supported.
"""
app = kls.load(url)
app.prepare(strict=strict)
return app
|
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
:raises NotImplementedError: the swagger version is not supported.
"""
app = kls.load(url)
app.prepare(strict=strict)
return app
|
[
"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 version is not supported.
|
[
"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
:return: the referenced object, wrapped by weakref.ProxyType
:rtype: weakref.ProxyType
:raises ValueError: if path is not valid
"""
logger.info('resolving: [{0}]'.format(jref))
if jref == None or len(jref) == 0:
raise ValueError('Empty Path is not allowed')
obj = None
url, jp = utils.jr_split(jref)
# check cacahed object against json reference by
# comparing url first, and find those object prefixed with
# the JSON pointer.
o = self.__objs.get(url, None)
if o:
if isinstance(o, BaseObj):
obj = o.resolve(utils.jp_split(jp)[1:])
elif isinstance(o, dict):
for k, v in six.iteritems(o):
if jp.startswith(k):
obj = v.resolve(utils.jp_split(jp[len(k):])[1:])
break
else:
raise Exception('Unknown Cached Object: {0}'.format(str(type(o))))
# this object is not found in cache
if obj == None:
if url:
obj, _ = self.load_obj(jref, parser=parser)
if obj:
obj = self.prepare_obj(obj, jref)
else:
# a local reference, 'jref' is just a json-pointer
if not jp.startswith('#'):
raise ValueError('Invalid Path, root element should be \'#\', but [{0}]'.format(jref))
obj = self.root.resolve(utils.jp_split(jp)[1:]) # heading element is #, mapping to self.root
if obj == None:
raise ValueError('Unable to resolve path, [{0}]'.format(jref))
if isinstance(obj, (six.string_types, six.integer_types, list, dict)):
return obj
return weakref.proxy(obj)
|
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
:return: the referenced object, wrapped by weakref.ProxyType
:rtype: weakref.ProxyType
:raises ValueError: if path is not valid
"""
logger.info('resolving: [{0}]'.format(jref))
if jref == None or len(jref) == 0:
raise ValueError('Empty Path is not allowed')
obj = None
url, jp = utils.jr_split(jref)
# check cacahed object against json reference by
# comparing url first, and find those object prefixed with
# the JSON pointer.
o = self.__objs.get(url, None)
if o:
if isinstance(o, BaseObj):
obj = o.resolve(utils.jp_split(jp)[1:])
elif isinstance(o, dict):
for k, v in six.iteritems(o):
if jp.startswith(k):
obj = v.resolve(utils.jp_split(jp[len(k):])[1:])
break
else:
raise Exception('Unknown Cached Object: {0}'.format(str(type(o))))
# this object is not found in cache
if obj == None:
if url:
obj, _ = self.load_obj(jref, parser=parser)
if obj:
obj = self.prepare_obj(obj, jref)
else:
# a local reference, 'jref' is just a json-pointer
if not jp.startswith('#'):
raise ValueError('Invalid Path, root element should be \'#\', but [{0}]'.format(jref))
obj = self.root.resolve(utils.jp_split(jp)[1:]) # heading element is #, mapping to self.root
if obj == None:
raise ValueError('Unable to resolve path, [{0}]'.format(jref))
if isinstance(obj, (six.string_types, six.integer_types, list, dict)):
return obj
return weakref.proxy(obj)
|
[
"def",
"resolve",
"(",
"self",
",",
"jref",
",",
"parser",
"=",
"None",
")",
":",
"logger",
".",
"info",
"(",
"'resolving: [{0}]'",
".",
"format",
"(",
"jref",
")",
")",
"if",
"jref",
"==",
"None",
"or",
"len",
"(",
"jref",
")",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"'Empty Path is not allowed'",
")",
"obj",
"=",
"None",
"url",
",",
"jp",
"=",
"utils",
".",
"jr_split",
"(",
"jref",
")",
"# check cacahed object against json reference by",
"# comparing url first, and find those object prefixed with",
"# the JSON pointer.",
"o",
"=",
"self",
".",
"__objs",
".",
"get",
"(",
"url",
",",
"None",
")",
"if",
"o",
":",
"if",
"isinstance",
"(",
"o",
",",
"BaseObj",
")",
":",
"obj",
"=",
"o",
".",
"resolve",
"(",
"utils",
".",
"jp_split",
"(",
"jp",
")",
"[",
"1",
":",
"]",
")",
"elif",
"isinstance",
"(",
"o",
",",
"dict",
")",
":",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"o",
")",
":",
"if",
"jp",
".",
"startswith",
"(",
"k",
")",
":",
"obj",
"=",
"v",
".",
"resolve",
"(",
"utils",
".",
"jp_split",
"(",
"jp",
"[",
"len",
"(",
"k",
")",
":",
"]",
")",
"[",
"1",
":",
"]",
")",
"break",
"else",
":",
"raise",
"Exception",
"(",
"'Unknown Cached Object: {0}'",
".",
"format",
"(",
"str",
"(",
"type",
"(",
"o",
")",
")",
")",
")",
"# this object is not found in cache",
"if",
"obj",
"==",
"None",
":",
"if",
"url",
":",
"obj",
",",
"_",
"=",
"self",
".",
"load_obj",
"(",
"jref",
",",
"parser",
"=",
"parser",
")",
"if",
"obj",
":",
"obj",
"=",
"self",
".",
"prepare_obj",
"(",
"obj",
",",
"jref",
")",
"else",
":",
"# a local reference, 'jref' is just a json-pointer",
"if",
"not",
"jp",
".",
"startswith",
"(",
"'#'",
")",
":",
"raise",
"ValueError",
"(",
"'Invalid Path, root element should be \\'#\\', but [{0}]'",
".",
"format",
"(",
"jref",
")",
")",
"obj",
"=",
"self",
".",
"root",
".",
"resolve",
"(",
"utils",
".",
"jp_split",
"(",
"jp",
")",
"[",
"1",
":",
"]",
")",
"# heading element is #, mapping to self.root",
"if",
"obj",
"==",
"None",
":",
"raise",
"ValueError",
"(",
"'Unable to resolve path, [{0}]'",
".",
"format",
"(",
"jref",
")",
")",
"if",
"isinstance",
"(",
"obj",
",",
"(",
"six",
".",
"string_types",
",",
"six",
".",
"integer_types",
",",
"list",
",",
"dict",
")",
")",
":",
"return",
"obj",
"return",
"weakref",
".",
"proxy",
"(",
"obj",
")"
] |
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.ProxyType
:rtype: weakref.ProxyType
:raises ValueError: if path is not valid
|
[
"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), reverse=True)
if len(ret) == 0:
raise ValueError('No schemes available: {0}'.format(req.schemes))
return ret
|
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), reverse=True)
if len(ret) == 0:
raise ValueError('No schemes available: {0}'.format(req.schemes))
return ret
|
[
"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",
")",
"if",
"len",
"(",
"ret",
")",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"'No schemes available: {0}'",
".",
"format",
"(",
"req",
".",
"schemes",
")",
")",
"return",
"ret"
] |
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()) if not as_dict else req.header
opt = opt or {}
join_headers = opt.pop(BaseClient.join_headers, None)
if as_dict and not join_headers:
# pick the most efficient way for special case
headers = dict(headers) if isinstance(headers, list) else headers
headers.update(req.header)
return headers
# include Request.headers
aggregated_headers = list(req.header.items())
# include customized headers
if isinstance(headers, list):
aggregated_headers.extend(headers)
elif isinstance(headers, dict):
aggregated_headers.extend(headers.items())
else:
raise Exception('unknown type as header: {}'.format(str(type(headers))))
if join_headers:
joined = {}
for h in aggregated_headers:
key = h[0]
if key in joined:
joined[key] = ','.join([joined[key], h[1]])
else:
joined[key] = h[1]
aggregated_headers = list(joined.items())
return dict(aggregated_headers) if as_dict else aggregated_headers
|
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()) if not as_dict else req.header
opt = opt or {}
join_headers = opt.pop(BaseClient.join_headers, None)
if as_dict and not join_headers:
# pick the most efficient way for special case
headers = dict(headers) if isinstance(headers, list) else headers
headers.update(req.header)
return headers
# include Request.headers
aggregated_headers = list(req.header.items())
# include customized headers
if isinstance(headers, list):
aggregated_headers.extend(headers)
elif isinstance(headers, dict):
aggregated_headers.extend(headers.items())
else:
raise Exception('unknown type as header: {}'.format(str(type(headers))))
if join_headers:
joined = {}
for h in aggregated_headers:
key = h[0]
if key in joined:
joined[key] = ','.join([joined[key], h[1]])
else:
joined[key] = h[1]
aggregated_headers = list(joined.items())
return dict(aggregated_headers) if as_dict else aggregated_headers
|
[
"def",
"compose_headers",
"(",
"self",
",",
"req",
",",
"headers",
"=",
"None",
",",
"opt",
"=",
"None",
",",
"as_dict",
"=",
"False",
")",
":",
"if",
"headers",
"is",
"None",
":",
"return",
"list",
"(",
"req",
".",
"header",
".",
"items",
"(",
")",
")",
"if",
"not",
"as_dict",
"else",
"req",
".",
"header",
"opt",
"=",
"opt",
"or",
"{",
"}",
"join_headers",
"=",
"opt",
".",
"pop",
"(",
"BaseClient",
".",
"join_headers",
",",
"None",
")",
"if",
"as_dict",
"and",
"not",
"join_headers",
":",
"# pick the most efficient way for special case",
"headers",
"=",
"dict",
"(",
"headers",
")",
"if",
"isinstance",
"(",
"headers",
",",
"list",
")",
"else",
"headers",
"headers",
".",
"update",
"(",
"req",
".",
"header",
")",
"return",
"headers",
"# include Request.headers",
"aggregated_headers",
"=",
"list",
"(",
"req",
".",
"header",
".",
"items",
"(",
")",
")",
"# include customized headers",
"if",
"isinstance",
"(",
"headers",
",",
"list",
")",
":",
"aggregated_headers",
".",
"extend",
"(",
"headers",
")",
"elif",
"isinstance",
"(",
"headers",
",",
"dict",
")",
":",
"aggregated_headers",
".",
"extend",
"(",
"headers",
".",
"items",
"(",
")",
")",
"else",
":",
"raise",
"Exception",
"(",
"'unknown type as header: {}'",
".",
"format",
"(",
"str",
"(",
"type",
"(",
"headers",
")",
")",
")",
")",
"if",
"join_headers",
":",
"joined",
"=",
"{",
"}",
"for",
"h",
"in",
"aggregated_headers",
":",
"key",
"=",
"h",
"[",
"0",
"]",
"if",
"key",
"in",
"joined",
":",
"joined",
"[",
"key",
"]",
"=",
"','",
".",
"join",
"(",
"[",
"joined",
"[",
"key",
"]",
",",
"h",
"[",
"1",
"]",
"]",
")",
"else",
":",
"joined",
"[",
"key",
"]",
"=",
"h",
"[",
"1",
"]",
"aggregated_headers",
"=",
"list",
"(",
"joined",
".",
"items",
"(",
")",
")",
"return",
"dict",
"(",
"aggregated_headers",
")",
"if",
"as_dict",
"else",
"aggregated_headers"
] |
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
:type opt: dict
:param headers: customized headers
:type headers: dict of 'string', or list of tuple: (string, string) for multiple values for one key
:return: patched request and response
:rtype: Request, Response
"""
req, resp = req_and_resp
# dump info for debugging
logger.info('request.url: {0}'.format(req.url))
logger.info('request.header: {0}'.format(req.header))
logger.info('request.query: {0}'.format(req.query))
logger.info('request.file: {0}'.format(req.files))
logger.info('request.schemes: {0}'.format(req.schemes))
# apply authorizations
if self.__security:
self.__security(req)
return req, resp
|
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
:type opt: dict
:param headers: customized headers
:type headers: dict of 'string', or list of tuple: (string, string) for multiple values for one key
:return: patched request and response
:rtype: Request, Response
"""
req, resp = req_and_resp
# dump info for debugging
logger.info('request.url: {0}'.format(req.url))
logger.info('request.header: {0}'.format(req.header))
logger.info('request.query: {0}'.format(req.query))
logger.info('request.file: {0}'.format(req.files))
logger.info('request.schemes: {0}'.format(req.schemes))
# apply authorizations
if self.__security:
self.__security(req)
return req, resp
|
[
"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",
"(",
"req",
".",
"url",
")",
")",
"logger",
".",
"info",
"(",
"'request.header: {0}'",
".",
"format",
"(",
"req",
".",
"header",
")",
")",
"logger",
".",
"info",
"(",
"'request.query: {0}'",
".",
"format",
"(",
"req",
".",
"query",
")",
")",
"logger",
".",
"info",
"(",
"'request.file: {0}'",
".",
"format",
"(",
"req",
".",
"files",
")",
")",
"logger",
".",
"info",
"(",
"'request.schemes: {0}'",
".",
"format",
"(",
"req",
".",
"schemes",
")",
")",
"# apply authorizations",
"if",
"self",
".",
"__security",
":",
"self",
".",
"__security",
"(",
"req",
")",
"return",
"req",
",",
"resp"
] |
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
:type headers: dict of 'string', or list of tuple: (string, string) for multiple values for one key
:return: patched request and response
:rtype: Request, Response
|
[
"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:
pobj = obj.properties.get(k)
if pobj.readOnly == True and ctx['read'] == False:
raise Exception('read-only property is set in write context.')
self[k] = ctx['factory'].produce(pobj, v)
# TODO: patternProperties here
# TODO: fix bug, everything would not go into additionalProperties, instead of recursive
elif obj.additionalProperties == True:
ctx['addp'] = True
elif obj.additionalProperties not in (None, False):
ctx['addp_schema'] = obj
in_obj = set(six.iterkeys(obj.properties))
in_self = set(six.iterkeys(self))
other_prop = in_obj - in_self
for k in other_prop:
p = obj.properties[k]
if p.is_set("default"):
self[k] = ctx['factory'].produce(p, p.default)
not_found = set(obj.required) - set(six.iterkeys(self))
if len(not_found):
raise ValueError('Model missing required key(s): {0}'.format(', '.join(not_found)))
# remove assigned properties to avoid duplicated
# primitive creation
_val = {}
for k in set(six.iterkeys(val)) - in_obj:
_val[k] = val[k]
if obj.discriminator:
self[obj.discriminator] = ctx['name']
return _val
|
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:
pobj = obj.properties.get(k)
if pobj.readOnly == True and ctx['read'] == False:
raise Exception('read-only property is set in write context.')
self[k] = ctx['factory'].produce(pobj, v)
# TODO: patternProperties here
# TODO: fix bug, everything would not go into additionalProperties, instead of recursive
elif obj.additionalProperties == True:
ctx['addp'] = True
elif obj.additionalProperties not in (None, False):
ctx['addp_schema'] = obj
in_obj = set(six.iterkeys(obj.properties))
in_self = set(six.iterkeys(self))
other_prop = in_obj - in_self
for k in other_prop:
p = obj.properties[k]
if p.is_set("default"):
self[k] = ctx['factory'].produce(p, p.default)
not_found = set(obj.required) - set(six.iterkeys(self))
if len(not_found):
raise ValueError('Model missing required key(s): {0}'.format(', '.join(not_found)))
# remove assigned properties to avoid duplicated
# primitive creation
_val = {}
for k in set(six.iterkeys(val)) - in_obj:
_val[k] = val[k]
if obj.discriminator:
self[obj.discriminator] = ctx['name']
return _val
|
[
"def",
"apply_with",
"(",
"self",
",",
"obj",
",",
"val",
",",
"ctx",
")",
":",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"val",
")",
":",
"if",
"k",
"in",
"obj",
".",
"properties",
":",
"pobj",
"=",
"obj",
".",
"properties",
".",
"get",
"(",
"k",
")",
"if",
"pobj",
".",
"readOnly",
"==",
"True",
"and",
"ctx",
"[",
"'read'",
"]",
"==",
"False",
":",
"raise",
"Exception",
"(",
"'read-only property is set in write context.'",
")",
"self",
"[",
"k",
"]",
"=",
"ctx",
"[",
"'factory'",
"]",
".",
"produce",
"(",
"pobj",
",",
"v",
")",
"# TODO: patternProperties here",
"# TODO: fix bug, everything would not go into additionalProperties, instead of recursive",
"elif",
"obj",
".",
"additionalProperties",
"==",
"True",
":",
"ctx",
"[",
"'addp'",
"]",
"=",
"True",
"elif",
"obj",
".",
"additionalProperties",
"not",
"in",
"(",
"None",
",",
"False",
")",
":",
"ctx",
"[",
"'addp_schema'",
"]",
"=",
"obj",
"in_obj",
"=",
"set",
"(",
"six",
".",
"iterkeys",
"(",
"obj",
".",
"properties",
")",
")",
"in_self",
"=",
"set",
"(",
"six",
".",
"iterkeys",
"(",
"self",
")",
")",
"other_prop",
"=",
"in_obj",
"-",
"in_self",
"for",
"k",
"in",
"other_prop",
":",
"p",
"=",
"obj",
".",
"properties",
"[",
"k",
"]",
"if",
"p",
".",
"is_set",
"(",
"\"default\"",
")",
":",
"self",
"[",
"k",
"]",
"=",
"ctx",
"[",
"'factory'",
"]",
".",
"produce",
"(",
"p",
",",
"p",
".",
"default",
")",
"not_found",
"=",
"set",
"(",
"obj",
".",
"required",
")",
"-",
"set",
"(",
"six",
".",
"iterkeys",
"(",
"self",
")",
")",
"if",
"len",
"(",
"not_found",
")",
":",
"raise",
"ValueError",
"(",
"'Model missing required key(s): {0}'",
".",
"format",
"(",
"', '",
".",
"join",
"(",
"not_found",
")",
")",
")",
"# remove assigned properties to avoid duplicated",
"# primitive creation",
"_val",
"=",
"{",
"}",
"for",
"k",
"in",
"set",
"(",
"six",
".",
"iterkeys",
"(",
"val",
")",
")",
"-",
"in_obj",
":",
"_val",
"[",
"k",
"]",
"=",
"val",
"[",
"k",
"]",
"if",
"obj",
".",
"discriminator",
":",
"self",
"[",
"obj",
".",
"discriminator",
"]",
"=",
"ctx",
"[",
"'name'",
"]",
"return",
"_val"
] |
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:
tmp[k] = v
obj.update_field('responses', tmp)
|
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:
tmp[k] = v
obj.update_field('responses', tmp)
|
[
"def",
"_op",
"(",
"self",
",",
"_",
",",
"obj",
",",
"app",
")",
":",
"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",
":",
"tmp",
"[",
"k",
"]",
"=",
"v",
"obj",
".",
"update_field",
"(",
"'responses'",
",",
"tmp",
")"
] |
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 else val
if val == None:
return None
obj = deref(obj)
ctx = {} if ctx == None else ctx
if 'name' not in ctx and hasattr(obj, 'name'):
ctx['name'] = obj.name
if 'guard' not in ctx:
ctx['guard'] = CycleGuard()
if 'addp_schema' not in ctx:
# Schema Object of additionalProperties
ctx['addp_schema'] = None
if 'addp' not in ctx:
# additionalProperties
ctx['addp'] = False
if '2nd_pass' not in ctx:
# 2nd pass processing function
ctx['2nd_pass'] = None
if 'factory' not in ctx:
# primitive factory
ctx['factory'] = self
if 'read' not in ctx:
# default is in 'read' context
ctx['read'] = True
# cycle guard
ctx['guard'].update(obj)
ret = None
if obj.type:
creater, _2nd = self.get(_type=obj.type, _format=obj.format)
if not creater:
raise ValueError('Can\'t resolve type from:(' + str(obj.type) + ', ' + str(obj.format) + ')')
ret = creater(obj, val, ctx)
if _2nd:
val = _2nd(obj, ret, val, ctx)
ctx['2nd_pass'] = _2nd
elif len(obj.properties) or obj.additionalProperties:
ret = Model()
val = ret.apply_with(obj, val, ctx)
if isinstance(ret, (Date, Datetime, Byte, File)):
# it's meanless to handle allOf for these types.
return ret
def _apply(o, r, v, c):
if hasattr(ret, 'apply_with'):
v = r.apply_with(o, v, c)
else:
_2nd = c['2nd_pass']
if _2nd == None:
_, _2nd = self.get(_type=o.type, _format=o.format)
if _2nd:
_2nd(o, r, v, c)
# update it back to context
c['2nd_pass'] = _2nd
return v
# handle allOf for Schema Object
allOf = getattr(obj, 'allOf', None)
if allOf:
not_applied = []
for a in allOf:
a = deref(a)
if not ret:
# try to find right type for this primitive.
ret = self.produce(a, val, ctx)
is_member = hasattr(ret, 'apply_with')
else:
val = _apply(a, ret, val, ctx)
if not ret:
# if we still can't determine the type,
# keep this Schema object for later use.
not_applied.append(a)
if ret:
for a in not_applied:
val = _apply(a, ret, val, ctx)
if ret != None and hasattr(ret, 'cleanup'):
val = ret.cleanup(val, ctx)
return ret
|
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 else val
if val == None:
return None
obj = deref(obj)
ctx = {} if ctx == None else ctx
if 'name' not in ctx and hasattr(obj, 'name'):
ctx['name'] = obj.name
if 'guard' not in ctx:
ctx['guard'] = CycleGuard()
if 'addp_schema' not in ctx:
# Schema Object of additionalProperties
ctx['addp_schema'] = None
if 'addp' not in ctx:
# additionalProperties
ctx['addp'] = False
if '2nd_pass' not in ctx:
# 2nd pass processing function
ctx['2nd_pass'] = None
if 'factory' not in ctx:
# primitive factory
ctx['factory'] = self
if 'read' not in ctx:
# default is in 'read' context
ctx['read'] = True
# cycle guard
ctx['guard'].update(obj)
ret = None
if obj.type:
creater, _2nd = self.get(_type=obj.type, _format=obj.format)
if not creater:
raise ValueError('Can\'t resolve type from:(' + str(obj.type) + ', ' + str(obj.format) + ')')
ret = creater(obj, val, ctx)
if _2nd:
val = _2nd(obj, ret, val, ctx)
ctx['2nd_pass'] = _2nd
elif len(obj.properties) or obj.additionalProperties:
ret = Model()
val = ret.apply_with(obj, val, ctx)
if isinstance(ret, (Date, Datetime, Byte, File)):
# it's meanless to handle allOf for these types.
return ret
def _apply(o, r, v, c):
if hasattr(ret, 'apply_with'):
v = r.apply_with(o, v, c)
else:
_2nd = c['2nd_pass']
if _2nd == None:
_, _2nd = self.get(_type=o.type, _format=o.format)
if _2nd:
_2nd(o, r, v, c)
# update it back to context
c['2nd_pass'] = _2nd
return v
# handle allOf for Schema Object
allOf = getattr(obj, 'allOf', None)
if allOf:
not_applied = []
for a in allOf:
a = deref(a)
if not ret:
# try to find right type for this primitive.
ret = self.produce(a, val, ctx)
is_member = hasattr(ret, 'apply_with')
else:
val = _apply(a, ret, val, ctx)
if not ret:
# if we still can't determine the type,
# keep this Schema object for later use.
not_applied.append(a)
if ret:
for a in not_applied:
val = _apply(a, ret, val, ctx)
if ret != None and hasattr(ret, 'cleanup'):
val = ret.cleanup(val, ctx)
return ret
|
[
"def",
"produce",
"(",
"self",
",",
"obj",
",",
"val",
",",
"ctx",
"=",
"None",
")",
":",
"val",
"=",
"obj",
".",
"default",
"if",
"val",
"==",
"None",
"else",
"val",
"if",
"val",
"==",
"None",
":",
"return",
"None",
"obj",
"=",
"deref",
"(",
"obj",
")",
"ctx",
"=",
"{",
"}",
"if",
"ctx",
"==",
"None",
"else",
"ctx",
"if",
"'name'",
"not",
"in",
"ctx",
"and",
"hasattr",
"(",
"obj",
",",
"'name'",
")",
":",
"ctx",
"[",
"'name'",
"]",
"=",
"obj",
".",
"name",
"if",
"'guard'",
"not",
"in",
"ctx",
":",
"ctx",
"[",
"'guard'",
"]",
"=",
"CycleGuard",
"(",
")",
"if",
"'addp_schema'",
"not",
"in",
"ctx",
":",
"# Schema Object of additionalProperties",
"ctx",
"[",
"'addp_schema'",
"]",
"=",
"None",
"if",
"'addp'",
"not",
"in",
"ctx",
":",
"# additionalProperties",
"ctx",
"[",
"'addp'",
"]",
"=",
"False",
"if",
"'2nd_pass'",
"not",
"in",
"ctx",
":",
"# 2nd pass processing function",
"ctx",
"[",
"'2nd_pass'",
"]",
"=",
"None",
"if",
"'factory'",
"not",
"in",
"ctx",
":",
"# primitive factory",
"ctx",
"[",
"'factory'",
"]",
"=",
"self",
"if",
"'read'",
"not",
"in",
"ctx",
":",
"# default is in 'read' context",
"ctx",
"[",
"'read'",
"]",
"=",
"True",
"# cycle guard",
"ctx",
"[",
"'guard'",
"]",
".",
"update",
"(",
"obj",
")",
"ret",
"=",
"None",
"if",
"obj",
".",
"type",
":",
"creater",
",",
"_2nd",
"=",
"self",
".",
"get",
"(",
"_type",
"=",
"obj",
".",
"type",
",",
"_format",
"=",
"obj",
".",
"format",
")",
"if",
"not",
"creater",
":",
"raise",
"ValueError",
"(",
"'Can\\'t resolve type from:('",
"+",
"str",
"(",
"obj",
".",
"type",
")",
"+",
"', '",
"+",
"str",
"(",
"obj",
".",
"format",
")",
"+",
"')'",
")",
"ret",
"=",
"creater",
"(",
"obj",
",",
"val",
",",
"ctx",
")",
"if",
"_2nd",
":",
"val",
"=",
"_2nd",
"(",
"obj",
",",
"ret",
",",
"val",
",",
"ctx",
")",
"ctx",
"[",
"'2nd_pass'",
"]",
"=",
"_2nd",
"elif",
"len",
"(",
"obj",
".",
"properties",
")",
"or",
"obj",
".",
"additionalProperties",
":",
"ret",
"=",
"Model",
"(",
")",
"val",
"=",
"ret",
".",
"apply_with",
"(",
"obj",
",",
"val",
",",
"ctx",
")",
"if",
"isinstance",
"(",
"ret",
",",
"(",
"Date",
",",
"Datetime",
",",
"Byte",
",",
"File",
")",
")",
":",
"# it's meanless to handle allOf for these types.",
"return",
"ret",
"def",
"_apply",
"(",
"o",
",",
"r",
",",
"v",
",",
"c",
")",
":",
"if",
"hasattr",
"(",
"ret",
",",
"'apply_with'",
")",
":",
"v",
"=",
"r",
".",
"apply_with",
"(",
"o",
",",
"v",
",",
"c",
")",
"else",
":",
"_2nd",
"=",
"c",
"[",
"'2nd_pass'",
"]",
"if",
"_2nd",
"==",
"None",
":",
"_",
",",
"_2nd",
"=",
"self",
".",
"get",
"(",
"_type",
"=",
"o",
".",
"type",
",",
"_format",
"=",
"o",
".",
"format",
")",
"if",
"_2nd",
":",
"_2nd",
"(",
"o",
",",
"r",
",",
"v",
",",
"c",
")",
"# update it back to context",
"c",
"[",
"'2nd_pass'",
"]",
"=",
"_2nd",
"return",
"v",
"# handle allOf for Schema Object",
"allOf",
"=",
"getattr",
"(",
"obj",
",",
"'allOf'",
",",
"None",
")",
"if",
"allOf",
":",
"not_applied",
"=",
"[",
"]",
"for",
"a",
"in",
"allOf",
":",
"a",
"=",
"deref",
"(",
"a",
")",
"if",
"not",
"ret",
":",
"# try to find right type for this primitive.",
"ret",
"=",
"self",
".",
"produce",
"(",
"a",
",",
"val",
",",
"ctx",
")",
"is_member",
"=",
"hasattr",
"(",
"ret",
",",
"'apply_with'",
")",
"else",
":",
"val",
"=",
"_apply",
"(",
"a",
",",
"ret",
",",
"val",
",",
"ctx",
")",
"if",
"not",
"ret",
":",
"# if we still can't determine the type,",
"# keep this Schema object for later use.",
"not_applied",
".",
"append",
"(",
"a",
")",
"if",
"ret",
":",
"for",
"a",
"in",
"not_applied",
":",
"val",
"=",
"_apply",
"(",
"a",
",",
"ret",
",",
"val",
",",
"ctx",
")",
"if",
"ret",
"!=",
"None",
"and",
"hasattr",
"(",
"ret",
",",
"'cleanup'",
")",
":",
"val",
"=",
"ret",
".",
"cleanup",
"(",
"val",
",",
"ctx",
")",
"return",
"ret"
] |
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()) and not ('a' <= letter <= 'z'):
return False
return True
|
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()) and not ('a' <= letter <= 'z'):
return False
return True
|
[
"def",
"_check_elementary_axis_name",
"(",
"name",
":",
"str",
")",
"->",
"bool",
":",
"if",
"len",
"(",
"name",
")",
"==",
"0",
":",
"return",
"False",
"if",
"not",
"'a'",
"<=",
"name",
"[",
"0",
"]",
"<=",
"'z'",
":",
"return",
"False",
"for",
"letter",
"in",
"name",
":",
"if",
"(",
"not",
"letter",
".",
"isdigit",
"(",
")",
")",
"and",
"not",
"(",
"'a'",
"<=",
"letter",
"<=",
"'z'",
")",
":",
"return",
"False",
"return",
"True"
] |
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",
",",
"resizable",
"=",
"True",
",",
")"
] |
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 ValueError('frame should have shape with only 3 dimensions')
# open the window if it isn't open already
if not self.is_open:
self.open()
# prepare the window for the next frame
self._window.clear()
self._window.switch_to()
self._window.dispatch_events()
# create an image data object
image = ImageData(
frame.shape[1],
frame.shape[0],
'RGB',
frame.tobytes(),
pitch=frame.shape[1]*-3
)
# send the image to the window
image.blit(0, 0, width=self._window.width, height=self._window.height)
self._window.flip()
|
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 ValueError('frame should have shape with only 3 dimensions')
# open the window if it isn't open already
if not self.is_open:
self.open()
# prepare the window for the next frame
self._window.clear()
self._window.switch_to()
self._window.dispatch_events()
# create an image data object
image = ImageData(
frame.shape[1],
frame.shape[0],
'RGB',
frame.tobytes(),
pitch=frame.shape[1]*-3
)
# send the image to the window
image.blit(0, 0, width=self._window.width, height=self._window.height)
self._window.flip()
|
[
"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 window if it isn't open already",
"if",
"not",
"self",
".",
"is_open",
":",
"self",
".",
"open",
"(",
")",
"# prepare the window for the next frame",
"self",
".",
"_window",
".",
"clear",
"(",
")",
"self",
".",
"_window",
".",
"switch_to",
"(",
")",
"self",
".",
"_window",
".",
"dispatch_events",
"(",
")",
"# create an image data object",
"image",
"=",
"ImageData",
"(",
"frame",
".",
"shape",
"[",
"1",
"]",
",",
"frame",
".",
"shape",
"[",
"0",
"]",
",",
"'RGB'",
",",
"frame",
".",
"tobytes",
"(",
")",
",",
"pitch",
"=",
"frame",
".",
"shape",
"[",
"1",
"]",
"*",
"-",
"3",
")",
"# send the image to the window",
"image",
".",
"blit",
"(",
"0",
",",
"0",
",",
"width",
"=",
"self",
".",
"_window",
".",
"width",
",",
"height",
"=",
"self",
".",
"_window",
".",
"height",
")",
"self",
".",
"_window",
".",
"flip",
"(",
")"
] |
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 as
transpose (bool): whether to transpose the frame before displaying
Returns:
None
"""
# take the transpose if necessary
if transpose:
pyg_img = pygame.surfarray.make_surface(arr.swapaxes(0, 1))
else:
pyg_img = arr
# resize the image according to given image size
pyg_img = pygame.transform.scale(pyg_img, video_size)
# blit the image to the surface
screen.blit(pyg_img, (0, 0))
|
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 as
transpose (bool): whether to transpose the frame before displaying
Returns:
None
"""
# take the transpose if necessary
if transpose:
pyg_img = pygame.surfarray.make_surface(arr.swapaxes(0, 1))
else:
pyg_img = arr
# resize the image according to given image size
pyg_img = pygame.transform.scale(pyg_img, video_size)
# blit the image to the surface
screen.blit(pyg_img, (0, 0))
|
[
"def",
"display_arr",
"(",
"screen",
",",
"arr",
",",
"video_size",
",",
"transpose",
")",
":",
"# take the transpose if necessary",
"if",
"transpose",
":",
"pyg_img",
"=",
"pygame",
".",
"surfarray",
".",
"make_surface",
"(",
"arr",
".",
"swapaxes",
"(",
"0",
",",
"1",
")",
")",
"else",
":",
"pyg_img",
"=",
"arr",
"# resize the image according to given image size",
"pyg_img",
"=",
"pygame",
".",
"transform",
".",
"scale",
"(",
"pyg_img",
",",
"video_size",
")",
"# blit the image to the surface",
"screen",
".",
"blit",
"(",
"pyg_img",
",",
"(",
"0",
",",
"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 before displaying
Returns:
None
|
[
"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
nop_ (any): the object to use as a null op action for the environment
Returns:
None
"""
# ensure the observation space is a box of pixels
assert isinstance(env.observation_space, gym.spaces.box.Box)
# ensure the observation space is either B&W pixels or RGB Pixels
obs_s = env.observation_space
is_bw = len(obs_s.shape) == 2
is_rgb = len(obs_s.shape) == 3 and obs_s.shape[2] in [1, 3]
assert is_bw or is_rgb
# get the mapping of keyboard keys to actions in the environment
if hasattr(env, 'get_keys_to_action'):
keys_to_action = env.get_keys_to_action()
# get the mapping of keyboard keys to actions in the unwrapped environment
elif hasattr(env.unwrapped, 'get_keys_to_action'):
keys_to_action = env.unwrapped.get_keys_to_action()
else:
raise ValueError('env has no get_keys_to_action method')
relevant_keys = set(sum(map(list, keys_to_action.keys()), []))
# determine the size of the video in pixels
video_size = env.observation_space.shape[0], env.observation_space.shape[1]
if transpose:
video_size = tuple(reversed(video_size))
# generate variables to determine the running state of the game
pressed_keys = []
running = True
env_done = True
# setup the screen using pygame
flags = pygame.RESIZABLE | pygame.HWSURFACE | pygame.DOUBLEBUF
screen = pygame.display.set_mode(video_size, flags)
pygame.event.set_blocked(pygame.MOUSEMOTION)
# set the caption for the pygame window. if the env has a spec use its id
if env.spec is not None:
pygame.display.set_caption(env.spec.id)
# otherwise just use the default nes-py caption
else:
pygame.display.set_caption('nes-py')
# start a clock for limiting the frame rate to the given FPS
clock = pygame.time.Clock()
# start the main game loop
while running:
# reset if the environment is done
if env_done:
env_done = False
obs = env.reset()
# otherwise take a normal step
else:
# unwrap the action based on pressed relevant keys
action = keys_to_action.get(tuple(sorted(pressed_keys)), nop_)
obs, rew, env_done, info = env.step(action)
# make sure the observation exists
if obs is not None:
# if the observation is just height and width (B&W)
if len(obs.shape) == 2:
# add a dummy channel for pygame display
obs = obs[:, :, None]
# if the observation is single channel (B&W)
if obs.shape[2] == 1:
# repeat the single channel 3 times for RGB encoding of B&W
obs = obs.repeat(3, axis=2)
# display the observation on the pygame screen
display_arr(screen, obs, video_size, transpose)
# process keyboard events
for event in pygame.event.get():
# handle a key being pressed
if event.type == pygame.KEYDOWN:
# make sure the key is in the relevant key list
if event.key in relevant_keys:
# add the key to pressed keys
pressed_keys.append(event.key)
# ASCII code 27 is the "escape" key
elif event.key == 27:
running = False
# handle the backup and reset functions
elif event.key == ord('e'):
env.unwrapped._backup()
elif event.key == ord('r'):
env.unwrapped._restore()
# handle a key being released
elif event.type == pygame.KEYUP:
# make sure the key is in the relevant key list
if event.key in relevant_keys:
# remove the key from the pressed keys
pressed_keys.remove(event.key)
# if the event is quit, set running to False
elif event.type == pygame.QUIT:
running = False
# flip the pygame screen
pygame.display.flip()
# throttle to maintain the framerate
clock.tick(fps)
# quite the pygame setup
pygame.quit()
|
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
nop_ (any): the object to use as a null op action for the environment
Returns:
None
"""
# ensure the observation space is a box of pixels
assert isinstance(env.observation_space, gym.spaces.box.Box)
# ensure the observation space is either B&W pixels or RGB Pixels
obs_s = env.observation_space
is_bw = len(obs_s.shape) == 2
is_rgb = len(obs_s.shape) == 3 and obs_s.shape[2] in [1, 3]
assert is_bw or is_rgb
# get the mapping of keyboard keys to actions in the environment
if hasattr(env, 'get_keys_to_action'):
keys_to_action = env.get_keys_to_action()
# get the mapping of keyboard keys to actions in the unwrapped environment
elif hasattr(env.unwrapped, 'get_keys_to_action'):
keys_to_action = env.unwrapped.get_keys_to_action()
else:
raise ValueError('env has no get_keys_to_action method')
relevant_keys = set(sum(map(list, keys_to_action.keys()), []))
# determine the size of the video in pixels
video_size = env.observation_space.shape[0], env.observation_space.shape[1]
if transpose:
video_size = tuple(reversed(video_size))
# generate variables to determine the running state of the game
pressed_keys = []
running = True
env_done = True
# setup the screen using pygame
flags = pygame.RESIZABLE | pygame.HWSURFACE | pygame.DOUBLEBUF
screen = pygame.display.set_mode(video_size, flags)
pygame.event.set_blocked(pygame.MOUSEMOTION)
# set the caption for the pygame window. if the env has a spec use its id
if env.spec is not None:
pygame.display.set_caption(env.spec.id)
# otherwise just use the default nes-py caption
else:
pygame.display.set_caption('nes-py')
# start a clock for limiting the frame rate to the given FPS
clock = pygame.time.Clock()
# start the main game loop
while running:
# reset if the environment is done
if env_done:
env_done = False
obs = env.reset()
# otherwise take a normal step
else:
# unwrap the action based on pressed relevant keys
action = keys_to_action.get(tuple(sorted(pressed_keys)), nop_)
obs, rew, env_done, info = env.step(action)
# make sure the observation exists
if obs is not None:
# if the observation is just height and width (B&W)
if len(obs.shape) == 2:
# add a dummy channel for pygame display
obs = obs[:, :, None]
# if the observation is single channel (B&W)
if obs.shape[2] == 1:
# repeat the single channel 3 times for RGB encoding of B&W
obs = obs.repeat(3, axis=2)
# display the observation on the pygame screen
display_arr(screen, obs, video_size, transpose)
# process keyboard events
for event in pygame.event.get():
# handle a key being pressed
if event.type == pygame.KEYDOWN:
# make sure the key is in the relevant key list
if event.key in relevant_keys:
# add the key to pressed keys
pressed_keys.append(event.key)
# ASCII code 27 is the "escape" key
elif event.key == 27:
running = False
# handle the backup and reset functions
elif event.key == ord('e'):
env.unwrapped._backup()
elif event.key == ord('r'):
env.unwrapped._restore()
# handle a key being released
elif event.type == pygame.KEYUP:
# make sure the key is in the relevant key list
if event.key in relevant_keys:
# remove the key from the pressed keys
pressed_keys.remove(event.key)
# if the event is quit, set running to False
elif event.type == pygame.QUIT:
running = False
# flip the pygame screen
pygame.display.flip()
# throttle to maintain the framerate
clock.tick(fps)
# quite the pygame setup
pygame.quit()
|
[
"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",
".",
"box",
".",
"Box",
")",
"# ensure the observation space is either B&W pixels or RGB Pixels",
"obs_s",
"=",
"env",
".",
"observation_space",
"is_bw",
"=",
"len",
"(",
"obs_s",
".",
"shape",
")",
"==",
"2",
"is_rgb",
"=",
"len",
"(",
"obs_s",
".",
"shape",
")",
"==",
"3",
"and",
"obs_s",
".",
"shape",
"[",
"2",
"]",
"in",
"[",
"1",
",",
"3",
"]",
"assert",
"is_bw",
"or",
"is_rgb",
"# get the mapping of keyboard keys to actions in the environment",
"if",
"hasattr",
"(",
"env",
",",
"'get_keys_to_action'",
")",
":",
"keys_to_action",
"=",
"env",
".",
"get_keys_to_action",
"(",
")",
"# get the mapping of keyboard keys to actions in the unwrapped environment",
"elif",
"hasattr",
"(",
"env",
".",
"unwrapped",
",",
"'get_keys_to_action'",
")",
":",
"keys_to_action",
"=",
"env",
".",
"unwrapped",
".",
"get_keys_to_action",
"(",
")",
"else",
":",
"raise",
"ValueError",
"(",
"'env has no get_keys_to_action method'",
")",
"relevant_keys",
"=",
"set",
"(",
"sum",
"(",
"map",
"(",
"list",
",",
"keys_to_action",
".",
"keys",
"(",
")",
")",
",",
"[",
"]",
")",
")",
"# determine the size of the video in pixels",
"video_size",
"=",
"env",
".",
"observation_space",
".",
"shape",
"[",
"0",
"]",
",",
"env",
".",
"observation_space",
".",
"shape",
"[",
"1",
"]",
"if",
"transpose",
":",
"video_size",
"=",
"tuple",
"(",
"reversed",
"(",
"video_size",
")",
")",
"# generate variables to determine the running state of the game",
"pressed_keys",
"=",
"[",
"]",
"running",
"=",
"True",
"env_done",
"=",
"True",
"# setup the screen using pygame",
"flags",
"=",
"pygame",
".",
"RESIZABLE",
"|",
"pygame",
".",
"HWSURFACE",
"|",
"pygame",
".",
"DOUBLEBUF",
"screen",
"=",
"pygame",
".",
"display",
".",
"set_mode",
"(",
"video_size",
",",
"flags",
")",
"pygame",
".",
"event",
".",
"set_blocked",
"(",
"pygame",
".",
"MOUSEMOTION",
")",
"# set the caption for the pygame window. if the env has a spec use its id",
"if",
"env",
".",
"spec",
"is",
"not",
"None",
":",
"pygame",
".",
"display",
".",
"set_caption",
"(",
"env",
".",
"spec",
".",
"id",
")",
"# otherwise just use the default nes-py caption",
"else",
":",
"pygame",
".",
"display",
".",
"set_caption",
"(",
"'nes-py'",
")",
"# start a clock for limiting the frame rate to the given FPS",
"clock",
"=",
"pygame",
".",
"time",
".",
"Clock",
"(",
")",
"# start the main game loop",
"while",
"running",
":",
"# reset if the environment is done",
"if",
"env_done",
":",
"env_done",
"=",
"False",
"obs",
"=",
"env",
".",
"reset",
"(",
")",
"# otherwise take a normal step",
"else",
":",
"# unwrap the action based on pressed relevant keys",
"action",
"=",
"keys_to_action",
".",
"get",
"(",
"tuple",
"(",
"sorted",
"(",
"pressed_keys",
")",
")",
",",
"nop_",
")",
"obs",
",",
"rew",
",",
"env_done",
",",
"info",
"=",
"env",
".",
"step",
"(",
"action",
")",
"# make sure the observation exists",
"if",
"obs",
"is",
"not",
"None",
":",
"# if the observation is just height and width (B&W)",
"if",
"len",
"(",
"obs",
".",
"shape",
")",
"==",
"2",
":",
"# add a dummy channel for pygame display",
"obs",
"=",
"obs",
"[",
":",
",",
":",
",",
"None",
"]",
"# if the observation is single channel (B&W)",
"if",
"obs",
".",
"shape",
"[",
"2",
"]",
"==",
"1",
":",
"# repeat the single channel 3 times for RGB encoding of B&W",
"obs",
"=",
"obs",
".",
"repeat",
"(",
"3",
",",
"axis",
"=",
"2",
")",
"# display the observation on the pygame screen",
"display_arr",
"(",
"screen",
",",
"obs",
",",
"video_size",
",",
"transpose",
")",
"# process keyboard events",
"for",
"event",
"in",
"pygame",
".",
"event",
".",
"get",
"(",
")",
":",
"# handle a key being pressed",
"if",
"event",
".",
"type",
"==",
"pygame",
".",
"KEYDOWN",
":",
"# make sure the key is in the relevant key list",
"if",
"event",
".",
"key",
"in",
"relevant_keys",
":",
"# add the key to pressed keys",
"pressed_keys",
".",
"append",
"(",
"event",
".",
"key",
")",
"# ASCII code 27 is the \"escape\" key",
"elif",
"event",
".",
"key",
"==",
"27",
":",
"running",
"=",
"False",
"# handle the backup and reset functions",
"elif",
"event",
".",
"key",
"==",
"ord",
"(",
"'e'",
")",
":",
"env",
".",
"unwrapped",
".",
"_backup",
"(",
")",
"elif",
"event",
".",
"key",
"==",
"ord",
"(",
"'r'",
")",
":",
"env",
".",
"unwrapped",
".",
"_restore",
"(",
")",
"# handle a key being released",
"elif",
"event",
".",
"type",
"==",
"pygame",
".",
"KEYUP",
":",
"# make sure the key is in the relevant key list",
"if",
"event",
".",
"key",
"in",
"relevant_keys",
":",
"# remove the key from the pressed keys",
"pressed_keys",
".",
"remove",
"(",
"event",
".",
"key",
")",
"# if the event is quit, set running to False",
"elif",
"event",
".",
"type",
"==",
"pygame",
".",
"QUIT",
":",
"running",
"=",
"False",
"# flip the pygame screen",
"pygame",
".",
"display",
".",
"flip",
"(",
")",
"# throttle to maintain the framerate",
"clock",
".",
"tick",
"(",
"fps",
")",
"# quite the pygame setup",
"pygame",
".",
"quit",
"(",
")"
] |
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 action for the environment
Returns:
None
|
[
"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'])
except KeyboardInterrupt:
pass
# reset and close the environment
env.close()
|
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'])
except KeyboardInterrupt:
pass
# reset and close the environment
env.close()
|
[
"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",
"# reset and close the environment",
"env",
".",
"close",
"(",
")"
] |
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
# create a NumPy array from the buffer
screen = np.frombuffer(buffer_, dtype='uint8')
# reshape the screen from a column vector to a tensor
screen = screen.reshape(SCREEN_SHAPE_32_BIT)
# flip the bytes if the machine is little-endian (which it likely is)
if sys.byteorder == 'little':
# invert the little-endian BGRx channels to big-endian xRGB
screen = screen[:, :, ::-1]
# remove the 0th axis (padding from storing colors in 32 bit)
return screen[:, :, 1:]
|
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
# create a NumPy array from the buffer
screen = np.frombuffer(buffer_, dtype='uint8')
# reshape the screen from a column vector to a tensor
screen = screen.reshape(SCREEN_SHAPE_32_BIT)
# flip the bytes if the machine is little-endian (which it likely is)
if sys.byteorder == 'little':
# invert the little-endian BGRx channels to big-endian xRGB
screen = screen[:, :, ::-1]
# remove the 0th axis (padding from storing colors in 32 bit)
return screen[:, :, 1:]
|
[
"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",
",",
"ctypes",
".",
"POINTER",
"(",
"SCREEN_TENSOR",
")",
")",
".",
"contents",
"# create a NumPy array from the buffer",
"screen",
"=",
"np",
".",
"frombuffer",
"(",
"buffer_",
",",
"dtype",
"=",
"'uint8'",
")",
"# reshape the screen from a column vector to a tensor",
"screen",
"=",
"screen",
".",
"reshape",
"(",
"SCREEN_SHAPE_32_BIT",
")",
"# flip the bytes if the machine is little-endian (which it likely is)",
"if",
"sys",
".",
"byteorder",
"==",
"'little'",
":",
"# invert the little-endian BGRx channels to big-endian xRGB",
"screen",
"=",
"screen",
"[",
":",
",",
":",
",",
":",
":",
"-",
"1",
"]",
"# remove the 0th axis (padding from storing colors in 32 bit)",
"return",
"screen",
"[",
":",
",",
":",
",",
"1",
":",
"]"
] |
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 NumPy array from the buffer
return np.frombuffer(buffer_, dtype='uint8')
|
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 NumPy array from the buffer
return np.frombuffer(buffer_, dtype='uint8')
|
[
"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",
",",
"ctypes",
".",
"POINTER",
"(",
"RAM_VECTOR",
")",
")",
".",
"contents",
"# create a NumPy array from the buffer",
"return",
"np",
".",
"frombuffer",
"(",
"buffer_",
",",
"dtype",
"=",
"'uint8'",
")"
] |
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
address = _LIB.Controller(self._env, port)
# create a memory buffer using the ctypes pointer for this vector
buffer_ = ctypes.cast(address, ctypes.POINTER(CONTROLLER_VECTOR)).contents
# create a NumPy buffer from the binary data and return it
return np.frombuffer(buffer_, dtype='uint8')
|
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
address = _LIB.Controller(self._env, port)
# create a memory buffer using the ctypes pointer for this vector
buffer_ = ctypes.cast(address, ctypes.POINTER(CONTROLLER_VECTOR)).contents
# create a NumPy buffer from the binary data and return it
return np.frombuffer(buffer_, dtype='uint8')
|
[
"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_",
"=",
"ctypes",
".",
"cast",
"(",
"address",
",",
"ctypes",
".",
"POINTER",
"(",
"CONTROLLER_VECTOR",
")",
")",
".",
"contents",
"# create a NumPy buffer from the binary data and return it",
"return",
"np",
".",
"frombuffer",
"(",
"buffer_",
",",
"dtype",
"=",
"'uint8'",
")"
] |
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
# perform a step on the emulator
_LIB.Step(self._env)
|
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
# perform a step on the emulator
_LIB.Step(self._env)
|
[
"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
if self._has_backup:
self._restore()
else:
_LIB.Reset(self._env)
# call the after reset callback
self._did_reset()
# set the done flag to false
self.done = False
# return the screen from the emulator
return self.screen
|
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
if self._has_backup:
self._restore()
else:
_LIB.Reset(self._env)
# call the after reset callback
self._did_reset()
# set the done flag to false
self.done = False
# return the screen from the emulator
return self.screen
|
[
"def",
"reset",
"(",
"self",
")",
":",
"# call the before reset callback",
"self",
".",
"_will_reset",
"(",
")",
"# reset the emulator",
"if",
"self",
".",
"_has_backup",
":",
"self",
".",
"_restore",
"(",
")",
"else",
":",
"_LIB",
".",
"Reset",
"(",
"self",
".",
"_env",
")",
"# call the after reset callback",
"self",
".",
"_did_reset",
"(",
")",
"# set the done flag to false",
"self",
".",
"done",
"=",
"False",
"# return the screen from the emulator",
"return",
"self",
".",
"screen"
] |
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
- reward (float) : amount of reward returned after given action
- done (boolean): whether the episode has ended
- info (dict): contains auxiliary diagnostic information
"""
# 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.controllers[0][:] = action
# pass the action to the emulator as an unsigned byte
_LIB.Step(self._env)
# get the reward for this step
reward = self._get_reward()
# get the done flag for this step
self.done = self._get_done()
# get the info for this step
info = self._get_info()
# call the after step callback
self._did_step(self.done)
# bound the reward in [min, max]
if reward < self.reward_range[0]:
reward = self.reward_range[0]
elif reward > self.reward_range[1]:
reward = self.reward_range[1]
# return the screen from the emulator and other relevant data
return self.screen, reward, self.done, info
|
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
- reward (float) : amount of reward returned after given action
- done (boolean): whether the episode has ended
- info (dict): contains auxiliary diagnostic information
"""
# 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.controllers[0][:] = action
# pass the action to the emulator as an unsigned byte
_LIB.Step(self._env)
# get the reward for this step
reward = self._get_reward()
# get the done flag for this step
self.done = self._get_done()
# get the info for this step
info = self._get_info()
# call the after step callback
self._did_step(self.done)
# bound the reward in [min, max]
if reward < self.reward_range[0]:
reward = self.reward_range[0]
elif reward > self.reward_range[1]:
reward = self.reward_range[1]
# return the screen from the emulator and other relevant data
return self.screen, reward, self.done, info
|
[
"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",
".",
"controllers",
"[",
"0",
"]",
"[",
":",
"]",
"=",
"action",
"# pass the action to the emulator as an unsigned byte",
"_LIB",
".",
"Step",
"(",
"self",
".",
"_env",
")",
"# get the reward for this step",
"reward",
"=",
"self",
".",
"_get_reward",
"(",
")",
"# get the done flag for this step",
"self",
".",
"done",
"=",
"self",
".",
"_get_done",
"(",
")",
"# get the info for this step",
"info",
"=",
"self",
".",
"_get_info",
"(",
")",
"# call the after step callback",
"self",
".",
"_did_step",
"(",
"self",
".",
"done",
")",
"# bound the reward in [min, max]",
"if",
"reward",
"<",
"self",
".",
"reward_range",
"[",
"0",
"]",
":",
"reward",
"=",
"self",
".",
"reward_range",
"[",
"0",
"]",
"elif",
"reward",
">",
"self",
".",
"reward_range",
"[",
"1",
"]",
":",
"reward",
"=",
"self",
".",
"reward_range",
"[",
"1",
"]",
"# return the screen from the emulator and other relevant data",
"return",
"self",
".",
"screen",
",",
"reward",
",",
"self",
".",
"done",
",",
"info"
] |
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 reward returned after given action
- done (boolean): whether the episode has ended
- info (dict): contains auxiliary diagnostic information
|
[
"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 locally
self._env = None
# if there is an image viewer open, delete it
if self.viewer is not None:
self.viewer.close()
|
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 locally
self._env = None
# if there is an image viewer open, delete it
if self.viewer is not None:
self.viewer.close()
|
[
"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",
"(",
"self",
".",
"_env",
")",
"# deallocate the object locally",
"self",
".",
"_env",
"=",
"None",
"# if there is an image viewer open, delete it",
"if",
"self",
".",
"viewer",
"is",
"not",
"None",
":",
"self",
".",
"viewer",
".",
"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 image
Returns:
a numpy array if mode is 'rgb_array', None otherwise
"""
if mode == 'human':
# if the viewer isn't setup, import it and create one
if self.viewer is None:
from ._image_viewer import ImageViewer
# get the caption for the ImageViewer
if self.spec is None:
# if there is no spec, just use the .nes filename
caption = self._rom_path.split('/')[-1]
else:
# set the caption to the OpenAI Gym id
caption = self.spec.id
# create the ImageViewer to display frames
self.viewer = ImageViewer(
caption=caption,
height=SCREEN_HEIGHT,
width=SCREEN_WIDTH,
)
# show the screen on the image viewer
self.viewer.show(self.screen)
elif mode == 'rgb_array':
return self.screen
else:
# unpack the modes as comma delineated strings ('a', 'b', ...)
render_modes = [repr(x) for x in self.metadata['render.modes']]
msg = 'valid render modes are: {}'.format(', '.join(render_modes))
raise NotImplementedError(msg)
|
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 image
Returns:
a numpy array if mode is 'rgb_array', None otherwise
"""
if mode == 'human':
# if the viewer isn't setup, import it and create one
if self.viewer is None:
from ._image_viewer import ImageViewer
# get the caption for the ImageViewer
if self.spec is None:
# if there is no spec, just use the .nes filename
caption = self._rom_path.split('/')[-1]
else:
# set the caption to the OpenAI Gym id
caption = self.spec.id
# create the ImageViewer to display frames
self.viewer = ImageViewer(
caption=caption,
height=SCREEN_HEIGHT,
width=SCREEN_WIDTH,
)
# show the screen on the image viewer
self.viewer.show(self.screen)
elif mode == 'rgb_array':
return self.screen
else:
# unpack the modes as comma delineated strings ('a', 'b', ...)
render_modes = [repr(x) for x in self.metadata['render.modes']]
msg = 'valid render modes are: {}'.format(', '.join(render_modes))
raise NotImplementedError(msg)
|
[
"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",
"# get the caption for the ImageViewer",
"if",
"self",
".",
"spec",
"is",
"None",
":",
"# if there is no spec, just use the .nes filename",
"caption",
"=",
"self",
".",
"_rom_path",
".",
"split",
"(",
"'/'",
")",
"[",
"-",
"1",
"]",
"else",
":",
"# set the caption to the OpenAI Gym id",
"caption",
"=",
"self",
".",
"spec",
".",
"id",
"# create the ImageViewer to display frames",
"self",
".",
"viewer",
"=",
"ImageViewer",
"(",
"caption",
"=",
"caption",
",",
"height",
"=",
"SCREEN_HEIGHT",
",",
"width",
"=",
"SCREEN_WIDTH",
",",
")",
"# show the screen on the image viewer",
"self",
".",
"viewer",
".",
"show",
"(",
"self",
".",
"screen",
")",
"elif",
"mode",
"==",
"'rgb_array'",
":",
"return",
"self",
".",
"screen",
"else",
":",
"# unpack the modes as comma delineated strings ('a', 'b', ...)",
"render_modes",
"=",
"[",
"repr",
"(",
"x",
")",
"for",
"x",
"in",
"self",
".",
"metadata",
"[",
"'render.modes'",
"]",
"]",
"msg",
"=",
"'valid render modes are: {}'",
".",
"format",
"(",
"', '",
".",
"join",
"(",
"render_modes",
")",
")",
"raise",
"NotImplementedError",
"(",
"msg",
")"
] |
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 mode is 'rgb_array', None otherwise
|
[
"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.',
required=True,
)
# add the argument for the mode of execution as either human or random
parser.add_argument('--mode', '-m',
type=str,
default='human',
choices=['human', 'random'],
help='The execution mode for the emulation.',
)
# add the argument for the number of steps to take in random mode
parser.add_argument('--steps', '-s',
type=int,
default=500,
help='The number of random steps to take.',
)
return parser.parse_args()
|
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.',
required=True,
)
# add the argument for the mode of execution as either human or random
parser.add_argument('--mode', '-m',
type=str,
default='human',
choices=['human', 'random'],
help='The execution mode for the emulation.',
)
# add the argument for the number of steps to take in random mode
parser.add_argument('--steps', '-s',
type=int,
default=500,
help='The number of random steps to take.',
)
return parser.parse_args()
|
[
"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",
"=",
"str",
",",
"help",
"=",
"'The path to the ROM to play.'",
",",
"required",
"=",
"True",
",",
")",
"# add the argument for the mode of execution as either human or random",
"parser",
".",
"add_argument",
"(",
"'--mode'",
",",
"'-m'",
",",
"type",
"=",
"str",
",",
"default",
"=",
"'human'",
",",
"choices",
"=",
"[",
"'human'",
",",
"'random'",
"]",
",",
"help",
"=",
"'The execution mode for the emulation.'",
",",
")",
"# add the argument for the number of steps to take in random mode",
"parser",
".",
"add_argument",
"(",
"'--steps'",
",",
"'-s'",
",",
"type",
"=",
"int",
",",
"default",
"=",
"500",
",",
"help",
"=",
"'The number of random steps to take.'",
",",
")",
"return",
"parser",
".",
"parse_args",
"(",
")"
] |
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_random(env, args.steps)
|
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_random(env, args.steps)
|
[
"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",
"==",
"'human'",
":",
"play_human",
"(",
"env",
")",
"else",
":",
"play_random",
"(",
"env",
",",
"args",
".",
"steps",
")"
] |
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(range(steps))
for _ in progress:
if done:
_ = env.reset()
action = env.action_space.sample()
_, reward, done, info = env.step(action)
progress.set_postfix(reward=reward, info=info)
env.render()
except KeyboardInterrupt:
pass
# close the environment
env.close()
|
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(range(steps))
for _ in progress:
if done:
_ = env.reset()
action = env.action_space.sample()
_, reward, done, info = env.step(action)
progress.set_postfix(reward=reward, info=info)
env.render()
except KeyboardInterrupt:
pass
# close the environment
env.close()
|
[
"def",
"play_random",
"(",
"env",
",",
"steps",
")",
":",
"try",
":",
"done",
"=",
"True",
"progress",
"=",
"tqdm",
"(",
"range",
"(",
"steps",
")",
")",
"for",
"_",
"in",
"progress",
":",
"if",
"done",
":",
"_",
"=",
"env",
".",
"reset",
"(",
")",
"action",
"=",
"env",
".",
"action_space",
".",
"sample",
"(",
")",
"_",
",",
"reward",
",",
"done",
",",
"info",
"=",
"env",
".",
"step",
"(",
"action",
")",
"progress",
".",
"set_postfix",
"(",
"reward",
"=",
"reward",
",",
"info",
"=",
"info",
")",
"env",
".",
"render",
"(",
")",
"except",
"KeyboardInterrupt",
":",
"pass",
"# close the environment",
"env",
".",
"close",
"(",
")"
] |
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 returns (often historical returns).
target_ret: float
Target return of portfolio.
allow_short: bool, optional
If 'False' construct a long-only portfolio.
If 'True' allow shorting, i.e. negative weights.
market_neutral: bool, optional
If 'False' sum of weights equals one.
If 'True' sum of weights equal zero, i.e. create a
market neutral portfolio (implies allow_short=True).
Returns
-------
weights: pandas.Series
Optimal asset weights.
"""
if not isinstance(cov_mat, pd.DataFrame):
raise ValueError("Covariance matrix is not a DataFrame")
if not isinstance(exp_rets, pd.Series):
raise ValueError("Expected returns is not a Series")
if not isinstance(target_ret, float):
raise ValueError("Target return is not a float")
if not cov_mat.index.equals(exp_rets.index):
raise ValueError("Indices do not match")
if market_neutral and not allow_short:
warnings.warn("A market neutral portfolio implies shorting")
allow_short=True
n = len(cov_mat)
P = opt.matrix(cov_mat.values)
q = opt.matrix(0.0, (n, 1))
# Constraints Gx <= h
if not allow_short:
# exp_rets*x >= target_ret and x >= 0
G = opt.matrix(np.vstack((-exp_rets.values,
-np.identity(n))))
h = opt.matrix(np.vstack((-target_ret,
+np.zeros((n, 1)))))
else:
# exp_rets*x >= target_ret
G = opt.matrix(-exp_rets.values).T
h = opt.matrix(-target_ret)
# Constraints Ax = b
# sum(x) = 1
A = opt.matrix(1.0, (1, n))
if not market_neutral:
b = opt.matrix(1.0)
else:
b = opt.matrix(0.0)
# Solve
optsolvers.options['show_progress'] = False
sol = optsolvers.qp(P, q, G, h, A, b)
if sol['status'] != 'optimal':
warnings.warn("Convergence problem")
# Put weights into a labeled series
weights = pd.Series(sol['x'], index=cov_mat.index)
return weights
|
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 returns (often historical returns).
target_ret: float
Target return of portfolio.
allow_short: bool, optional
If 'False' construct a long-only portfolio.
If 'True' allow shorting, i.e. negative weights.
market_neutral: bool, optional
If 'False' sum of weights equals one.
If 'True' sum of weights equal zero, i.e. create a
market neutral portfolio (implies allow_short=True).
Returns
-------
weights: pandas.Series
Optimal asset weights.
"""
if not isinstance(cov_mat, pd.DataFrame):
raise ValueError("Covariance matrix is not a DataFrame")
if not isinstance(exp_rets, pd.Series):
raise ValueError("Expected returns is not a Series")
if not isinstance(target_ret, float):
raise ValueError("Target return is not a float")
if not cov_mat.index.equals(exp_rets.index):
raise ValueError("Indices do not match")
if market_neutral and not allow_short:
warnings.warn("A market neutral portfolio implies shorting")
allow_short=True
n = len(cov_mat)
P = opt.matrix(cov_mat.values)
q = opt.matrix(0.0, (n, 1))
# Constraints Gx <= h
if not allow_short:
# exp_rets*x >= target_ret and x >= 0
G = opt.matrix(np.vstack((-exp_rets.values,
-np.identity(n))))
h = opt.matrix(np.vstack((-target_ret,
+np.zeros((n, 1)))))
else:
# exp_rets*x >= target_ret
G = opt.matrix(-exp_rets.values).T
h = opt.matrix(-target_ret)
# Constraints Ax = b
# sum(x) = 1
A = opt.matrix(1.0, (1, n))
if not market_neutral:
b = opt.matrix(1.0)
else:
b = opt.matrix(0.0)
# Solve
optsolvers.options['show_progress'] = False
sol = optsolvers.qp(P, q, G, h, A, b)
if sol['status'] != 'optimal':
warnings.warn("Convergence problem")
# Put weights into a labeled series
weights = pd.Series(sol['x'], index=cov_mat.index)
return weights
|
[
"def",
"markowitz_portfolio",
"(",
"cov_mat",
",",
"exp_rets",
",",
"target_ret",
",",
"allow_short",
"=",
"False",
",",
"market_neutral",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"cov_mat",
",",
"pd",
".",
"DataFrame",
")",
":",
"raise",
"ValueError",
"(",
"\"Covariance matrix is not a DataFrame\"",
")",
"if",
"not",
"isinstance",
"(",
"exp_rets",
",",
"pd",
".",
"Series",
")",
":",
"raise",
"ValueError",
"(",
"\"Expected returns is not a Series\"",
")",
"if",
"not",
"isinstance",
"(",
"target_ret",
",",
"float",
")",
":",
"raise",
"ValueError",
"(",
"\"Target return is not a float\"",
")",
"if",
"not",
"cov_mat",
".",
"index",
".",
"equals",
"(",
"exp_rets",
".",
"index",
")",
":",
"raise",
"ValueError",
"(",
"\"Indices do not match\"",
")",
"if",
"market_neutral",
"and",
"not",
"allow_short",
":",
"warnings",
".",
"warn",
"(",
"\"A market neutral portfolio implies shorting\"",
")",
"allow_short",
"=",
"True",
"n",
"=",
"len",
"(",
"cov_mat",
")",
"P",
"=",
"opt",
".",
"matrix",
"(",
"cov_mat",
".",
"values",
")",
"q",
"=",
"opt",
".",
"matrix",
"(",
"0.0",
",",
"(",
"n",
",",
"1",
")",
")",
"# Constraints Gx <= h",
"if",
"not",
"allow_short",
":",
"# exp_rets*x >= target_ret and x >= 0",
"G",
"=",
"opt",
".",
"matrix",
"(",
"np",
".",
"vstack",
"(",
"(",
"-",
"exp_rets",
".",
"values",
",",
"-",
"np",
".",
"identity",
"(",
"n",
")",
")",
")",
")",
"h",
"=",
"opt",
".",
"matrix",
"(",
"np",
".",
"vstack",
"(",
"(",
"-",
"target_ret",
",",
"+",
"np",
".",
"zeros",
"(",
"(",
"n",
",",
"1",
")",
")",
")",
")",
")",
"else",
":",
"# exp_rets*x >= target_ret",
"G",
"=",
"opt",
".",
"matrix",
"(",
"-",
"exp_rets",
".",
"values",
")",
".",
"T",
"h",
"=",
"opt",
".",
"matrix",
"(",
"-",
"target_ret",
")",
"# Constraints Ax = b",
"# sum(x) = 1",
"A",
"=",
"opt",
".",
"matrix",
"(",
"1.0",
",",
"(",
"1",
",",
"n",
")",
")",
"if",
"not",
"market_neutral",
":",
"b",
"=",
"opt",
".",
"matrix",
"(",
"1.0",
")",
"else",
":",
"b",
"=",
"opt",
".",
"matrix",
"(",
"0.0",
")",
"# Solve",
"optsolvers",
".",
"options",
"[",
"'show_progress'",
"]",
"=",
"False",
"sol",
"=",
"optsolvers",
".",
"qp",
"(",
"P",
",",
"q",
",",
"G",
",",
"h",
",",
"A",
",",
"b",
")",
"if",
"sol",
"[",
"'status'",
"]",
"!=",
"'optimal'",
":",
"warnings",
".",
"warn",
"(",
"\"Convergence problem\"",
")",
"# Put weights into a labeled series",
"weights",
"=",
"pd",
".",
"Series",
"(",
"sol",
"[",
"'x'",
"]",
",",
"index",
"=",
"cov_mat",
".",
"index",
")",
"return",
"weights"
] |
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
If 'False' construct a long-only portfolio.
If 'True' allow shorting, i.e. negative weights.
market_neutral: bool, optional
If 'False' sum of weights equals one.
If 'True' sum of weights equal zero, i.e. create a
market neutral portfolio (implies allow_short=True).
Returns
-------
weights: pandas.Series
Optimal asset weights.
|
[
"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 with decreasing leverage,
i.e. the market neutral portfolio with minimum variance
is not invested at all.
Parameters
----------
cov_mat: pandas.DataFrame
Covariance matrix of asset returns.
allow_short: bool, optional
If 'False' construct a long-only portfolio.
If 'True' allow shorting, i.e. negative weights.
Returns
-------
weights: pandas.Series
Optimal asset weights.
"""
if not isinstance(cov_mat, pd.DataFrame):
raise ValueError("Covariance matrix is not a DataFrame")
n = len(cov_mat)
P = opt.matrix(cov_mat.values)
q = opt.matrix(0.0, (n, 1))
# Constraints Gx <= h
if not allow_short:
# x >= 0
G = opt.matrix(-np.identity(n))
h = opt.matrix(0.0, (n, 1))
else:
G = None
h = None
# Constraints Ax = b
# sum(x) = 1
A = opt.matrix(1.0, (1, n))
b = opt.matrix(1.0)
# Solve
optsolvers.options['show_progress'] = False
sol = optsolvers.qp(P, q, G, h, A, b)
if sol['status'] != 'optimal':
warnings.warn("Convergence problem")
# Put weights into a labeled series
weights = pd.Series(sol['x'], index=cov_mat.index)
return weights
|
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 with decreasing leverage,
i.e. the market neutral portfolio with minimum variance
is not invested at all.
Parameters
----------
cov_mat: pandas.DataFrame
Covariance matrix of asset returns.
allow_short: bool, optional
If 'False' construct a long-only portfolio.
If 'True' allow shorting, i.e. negative weights.
Returns
-------
weights: pandas.Series
Optimal asset weights.
"""
if not isinstance(cov_mat, pd.DataFrame):
raise ValueError("Covariance matrix is not a DataFrame")
n = len(cov_mat)
P = opt.matrix(cov_mat.values)
q = opt.matrix(0.0, (n, 1))
# Constraints Gx <= h
if not allow_short:
# x >= 0
G = opt.matrix(-np.identity(n))
h = opt.matrix(0.0, (n, 1))
else:
G = None
h = None
# Constraints Ax = b
# sum(x) = 1
A = opt.matrix(1.0, (1, n))
b = opt.matrix(1.0)
# Solve
optsolvers.options['show_progress'] = False
sol = optsolvers.qp(P, q, G, h, A, b)
if sol['status'] != 'optimal':
warnings.warn("Convergence problem")
# Put weights into a labeled series
weights = pd.Series(sol['x'], index=cov_mat.index)
return weights
|
[
"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",
"=",
"len",
"(",
"cov_mat",
")",
"P",
"=",
"opt",
".",
"matrix",
"(",
"cov_mat",
".",
"values",
")",
"q",
"=",
"opt",
".",
"matrix",
"(",
"0.0",
",",
"(",
"n",
",",
"1",
")",
")",
"# Constraints Gx <= h",
"if",
"not",
"allow_short",
":",
"# x >= 0",
"G",
"=",
"opt",
".",
"matrix",
"(",
"-",
"np",
".",
"identity",
"(",
"n",
")",
")",
"h",
"=",
"opt",
".",
"matrix",
"(",
"0.0",
",",
"(",
"n",
",",
"1",
")",
")",
"else",
":",
"G",
"=",
"None",
"h",
"=",
"None",
"# Constraints Ax = b",
"# sum(x) = 1",
"A",
"=",
"opt",
".",
"matrix",
"(",
"1.0",
",",
"(",
"1",
",",
"n",
")",
")",
"b",
"=",
"opt",
".",
"matrix",
"(",
"1.0",
")",
"# Solve",
"optsolvers",
".",
"options",
"[",
"'show_progress'",
"]",
"=",
"False",
"sol",
"=",
"optsolvers",
".",
"qp",
"(",
"P",
",",
"q",
",",
"G",
",",
"h",
",",
"A",
",",
"b",
")",
"if",
"sol",
"[",
"'status'",
"]",
"!=",
"'optimal'",
":",
"warnings",
".",
"warn",
"(",
"\"Convergence problem\"",
")",
"# Put weights into a labeled series",
"weights",
"=",
"pd",
".",
"Series",
"(",
"sol",
"[",
"'x'",
"]",
",",
"index",
"=",
"cov_mat",
".",
"index",
")",
"return",
"weights"
] |
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 with minimum variance
is not invested at all.
Parameters
----------
cov_mat: pandas.DataFrame
Covariance matrix of asset returns.
allow_short: bool, optional
If 'False' construct a long-only portfolio.
If 'True' allow shorting, i.e. negative weights.
Returns
-------
weights: pandas.Series
Optimal asset weights.
|
[
"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: {}".format(ret))
print("Expected variance: {}".format(std**2))
print("Expected Sharpe: {}".format(sharpe))
|
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: {}".format(ret))
print("Expected variance: {}".format(std**2))
print("Expected Sharpe: {}".format(sharpe))
|
[
"def",
"print_portfolio_info",
"(",
"returns",
",",
"avg_rets",
",",
"weights",
")",
":",
"ret",
"=",
"(",
"weights",
"*",
"avg_rets",
")",
".",
"sum",
"(",
")",
"std",
"=",
"(",
"weights",
"*",
"returns",
")",
".",
"sum",
"(",
"1",
")",
".",
"std",
"(",
")",
"sharpe",
"=",
"ret",
"/",
"std",
"print",
"(",
"\"Optimal weights:\\n{}\\n\"",
".",
"format",
"(",
"weights",
")",
")",
"print",
"(",
"\"Expected return: {}\"",
".",
"format",
"(",
"ret",
")",
")",
"print",
"(",
"\"Expected variance: {}\"",
".",
"format",
"(",
"std",
"**",
"2",
")",
")",
"print",
"(",
"\"Expected Sharpe: {}\"",
".",
"format",
"(",
"sharpe",
")",
")"
] |
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):
return self.methods[0]
return None
|
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):
return self.methods[0]
return None
|
[
"def",
"main",
"(",
"self",
")",
":",
"for",
"m",
"in",
"self",
".",
"methods",
":",
"if",
"m",
".",
"name",
"in",
"[",
"'Main'",
",",
"'main'",
"]",
":",
"return",
"m",
"if",
"len",
"(",
"self",
".",
"methods",
")",
":",
"return",
"self",
".",
"methods",
"[",
"0",
"]",
"return",
"None"
] |
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 == self.main:
continue
oms.append(m)
return oms
|
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 == self.main:
continue
oms.append(m)
return oms
|
[
"def",
"orderered_methods",
"(",
"self",
")",
":",
"oms",
"=",
"[",
"]",
"self",
".",
"methods",
".",
"reverse",
"(",
")",
"if",
"self",
".",
"main",
":",
"oms",
"=",
"[",
"self",
".",
"main",
"]",
"for",
"m",
"in",
"self",
".",
"methods",
":",
"if",
"m",
"==",
"self",
".",
"main",
":",
"continue",
"oms",
".",
"append",
"(",
"m",
")",
"return",
"oms"
] |
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.append(vm_token.out_op)
if vm_token.data is not None and vm_token.vm_op != VMOp.NOP:
b_array = b_array + vm_token.data
# self.to_s()
return b_array
|
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.append(vm_token.out_op)
if vm_token.data is not None and vm_token.vm_op != VMOp.NOP:
b_array = b_array + vm_token.data
# self.to_s()
return b_array
|
[
"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",
"vm_token",
".",
"data",
"is",
"not",
"None",
"and",
"vm_token",
".",
"vm_op",
"!=",
"VMOp",
".",
"NOP",
":",
"b_array",
"=",
"b_array",
"+",
"vm_token",
".",
"data",
"# self.to_s()",
"return",
"b_array"
] |
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:
if not method.is_interop:
# print("ADDING METHOD %s " % method.full_name)
method.address = address
for key, vmtoken in method.vm_tokens.items():
self.all_vm_tokens[address] = vmtoken
address += 1
if vmtoken.data is not None and vmtoken.vm_op != VMOp.NOP:
address += len(vmtoken.data)
vmtoken.addr = vmtoken.addr + method.address
for key, vmtoken in self.all_vm_tokens.items():
if vmtoken.src_method is not None:
target_method = self.method_by_name(vmtoken.target_method)
if target_method:
jump_len = target_method.address - vmtoken.addr
param_ret_counts = bytearray()
if Compiler.instance().nep8:
param_ret_counts = vmtoken.data[0:2]
jump_len -= 2
if jump_len > -32767 and jump_len < 32767:
vmtoken.data = param_ret_counts + jump_len.to_bytes(2, 'little', signed=True)
else:
vmtoken.data = param_ret_counts + jump_len.to_bytes(4, 'little', signed=True)
else:
raise Exception("Target method %s not found" % vmtoken.target_method)
|
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:
if not method.is_interop:
# print("ADDING METHOD %s " % method.full_name)
method.address = address
for key, vmtoken in method.vm_tokens.items():
self.all_vm_tokens[address] = vmtoken
address += 1
if vmtoken.data is not None and vmtoken.vm_op != VMOp.NOP:
address += len(vmtoken.data)
vmtoken.addr = vmtoken.addr + method.address
for key, vmtoken in self.all_vm_tokens.items():
if vmtoken.src_method is not None:
target_method = self.method_by_name(vmtoken.target_method)
if target_method:
jump_len = target_method.address - vmtoken.addr
param_ret_counts = bytearray()
if Compiler.instance().nep8:
param_ret_counts = vmtoken.data[0:2]
jump_len -= 2
if jump_len > -32767 and jump_len < 32767:
vmtoken.data = param_ret_counts + jump_len.to_bytes(2, 'little', signed=True)
else:
vmtoken.data = param_ret_counts + jump_len.to_bytes(4, 'little', signed=True)
else:
raise Exception("Target method %s not found" % vmtoken.target_method)
|
[
"def",
"link_methods",
"(",
"self",
")",
":",
"from",
".",
".",
"compiler",
"import",
"Compiler",
"for",
"method",
"in",
"self",
".",
"methods",
":",
"method",
".",
"prepare",
"(",
")",
"self",
".",
"all_vm_tokens",
"=",
"OrderedDict",
"(",
")",
"address",
"=",
"0",
"for",
"method",
"in",
"self",
".",
"orderered_methods",
":",
"if",
"not",
"method",
".",
"is_interop",
":",
"# print(\"ADDING METHOD %s \" % method.full_name)",
"method",
".",
"address",
"=",
"address",
"for",
"key",
",",
"vmtoken",
"in",
"method",
".",
"vm_tokens",
".",
"items",
"(",
")",
":",
"self",
".",
"all_vm_tokens",
"[",
"address",
"]",
"=",
"vmtoken",
"address",
"+=",
"1",
"if",
"vmtoken",
".",
"data",
"is",
"not",
"None",
"and",
"vmtoken",
".",
"vm_op",
"!=",
"VMOp",
".",
"NOP",
":",
"address",
"+=",
"len",
"(",
"vmtoken",
".",
"data",
")",
"vmtoken",
".",
"addr",
"=",
"vmtoken",
".",
"addr",
"+",
"method",
".",
"address",
"for",
"key",
",",
"vmtoken",
"in",
"self",
".",
"all_vm_tokens",
".",
"items",
"(",
")",
":",
"if",
"vmtoken",
".",
"src_method",
"is",
"not",
"None",
":",
"target_method",
"=",
"self",
".",
"method_by_name",
"(",
"vmtoken",
".",
"target_method",
")",
"if",
"target_method",
":",
"jump_len",
"=",
"target_method",
".",
"address",
"-",
"vmtoken",
".",
"addr",
"param_ret_counts",
"=",
"bytearray",
"(",
")",
"if",
"Compiler",
".",
"instance",
"(",
")",
".",
"nep8",
":",
"param_ret_counts",
"=",
"vmtoken",
".",
"data",
"[",
"0",
":",
"2",
"]",
"jump_len",
"-=",
"2",
"if",
"jump_len",
">",
"-",
"32767",
"and",
"jump_len",
"<",
"32767",
":",
"vmtoken",
".",
"data",
"=",
"param_ret_counts",
"+",
"jump_len",
".",
"to_bytes",
"(",
"2",
",",
"'little'",
",",
"signed",
"=",
"True",
")",
"else",
":",
"vmtoken",
".",
"data",
"=",
"param_ret_counts",
"+",
"jump_len",
".",
"to_bytes",
"(",
"4",
",",
"'little'",
",",
"signed",
"=",
"True",
")",
"else",
":",
"raise",
"Exception",
"(",
"\"Target method %s not found\"",
"%",
"vmtoken",
".",
"target_method",
")"
] |
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_json(avm_name, file_hash)
mapfilename = output_path.replace('.avm', '.debug.json')
with open(mapfilename, 'w+') as out_file:
out_file.write(json_data)
|
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_json(avm_name, file_hash)
mapfilename = output_path.replace('.avm', '.debug.json')
with open(mapfilename, 'w+') as out_file:
out_file.write(json_data)
|
[
"def",
"export_debug",
"(",
"self",
",",
"output_path",
")",
":",
"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_json",
"(",
"avm_name",
",",
"file_hash",
")",
"mapfilename",
"=",
"output_path",
".",
"replace",
"(",
"'.avm'",
",",
"'.debug.json'",
")",
"with",
"open",
"(",
"mapfilename",
",",
"'w+'",
")",
"as",
"out_file",
":",
"out_file",
".",
"write",
"(",
"json_data",
")"
] |
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
:param output_path: Optional path to save the compiled `.avm` file
:return: the instance of the compiler
The following returns the compiler object for inspection
.. code-block:: python
from boa.compiler import Compiler
Compiler.load_and_save('path/to/your/file.py')
"""
compiler = Compiler.load(os.path.abspath(path), use_nep8=use_nep8)
data = compiler.write()
if output_path is None:
fullpath = os.path.realpath(path)
path, filename = os.path.split(fullpath)
newfilename = filename.replace('.py', '.avm')
output_path = '%s/%s' % (path, newfilename)
Compiler.write_file(data, output_path)
compiler.entry_module.export_debug(output_path)
return data
|
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
:param output_path: Optional path to save the compiled `.avm` file
:return: the instance of the compiler
The following returns the compiler object for inspection
.. code-block:: python
from boa.compiler import Compiler
Compiler.load_and_save('path/to/your/file.py')
"""
compiler = Compiler.load(os.path.abspath(path), use_nep8=use_nep8)
data = compiler.write()
if output_path is None:
fullpath = os.path.realpath(path)
path, filename = os.path.split(fullpath)
newfilename = filename.replace('.py', '.avm')
output_path = '%s/%s' % (path, newfilename)
Compiler.write_file(data, output_path)
compiler.entry_module.export_debug(output_path)
return data
|
[
"def",
"load_and_save",
"(",
"path",
",",
"output_path",
"=",
"None",
",",
"use_nep8",
"=",
"True",
")",
":",
"compiler",
"=",
"Compiler",
".",
"load",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"path",
")",
",",
"use_nep8",
"=",
"use_nep8",
")",
"data",
"=",
"compiler",
".",
"write",
"(",
")",
"if",
"output_path",
"is",
"None",
":",
"fullpath",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"path",
")",
"path",
",",
"filename",
"=",
"os",
".",
"path",
".",
"split",
"(",
"fullpath",
")",
"newfilename",
"=",
"filename",
".",
"replace",
"(",
"'.py'",
",",
"'.avm'",
")",
"output_path",
"=",
"'%s/%s'",
"%",
"(",
"path",
",",
"newfilename",
")",
"Compiler",
".",
"write_file",
"(",
"data",
",",
"output_path",
")",
"compiler",
".",
"entry_module",
".",
"export_debug",
"(",
"output_path",
")",
"return",
"data"
] |
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
:return: the instance of the compiler
The following returns the compiler object for inspection
.. code-block:: python
from boa.compiler import Compiler
Compiler.load_and_save('path/to/your/file.py')
|
[
"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",
"."
] |
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-block:: python
from boa.compiler import Compiler
compiler = Compiler.load('path/to/your/file.py')
"""
Compiler.__instance = None
compiler = Compiler.instance()
compiler.nep8 = use_nep8
compiler.entry_module = Module(path)
return compiler
|
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-block:: python
from boa.compiler import Compiler
compiler = Compiler.load('path/to/your/file.py')
"""
Compiler.__instance = None
compiler = Compiler.instance()
compiler.nep8 = use_nep8
compiler.entry_module = Module(path)
return compiler
|
[
"def",
"load",
"(",
"path",
",",
"use_nep8",
"=",
"True",
")",
":",
"Compiler",
".",
"__instance",
"=",
"None",
"compiler",
"=",
"Compiler",
".",
"instance",
"(",
")",
"compiler",
".",
"nep8",
"=",
"use_nep8",
"compiler",
".",
"entry_module",
"=",
"Module",
"(",
"path",
")",
"return",
"compiler"
] |
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 Compiler
compiler = Compiler.load('path/to/your/file.py')
|
[
"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): Full App ID string
record_id (str): Full parent Record ID string
field_id (str): Full field ID to target reference field on parent Record string
target_record_ids (List(str)): List of full target reference Record ID strings
"""
self._swimlane.request(
'post',
'app/{0}/record/{1}/add-references'.format(app_id, record_id),
json={
'fieldId': field_id,
'targetRecordIds': target_record_ids
}
)
|
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): Full App ID string
record_id (str): Full parent Record ID string
field_id (str): Full field ID to target reference field on parent Record string
target_record_ids (List(str)): List of full target reference Record ID strings
"""
self._swimlane.request(
'post',
'app/{0}/record/{1}/add-references'.format(app_id, record_id),
json={
'fieldId': field_id,
'targetRecordIds': target_record_ids
}
)
|
[
"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",
",",
"record_id",
")",
",",
"json",
"=",
"{",
"'fieldId'",
":",
"field_id",
",",
"'targetRecordIds'",
":",
"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): Full App ID string
record_id (str): Full parent Record ID string
field_id (str): Full field ID to target reference field on parent Record string
target_record_ids (List(str)): List of full target reference Record ID strings
|
[
"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 (str): Full parent Record ID string
field_id (str): Full field ID to target reference field on parent Record string
message (str): New comment message body
"""
self._swimlane.request(
'post',
'app/{0}/record/{1}/{2}/comment'.format(
app_id,
record_id,
field_id
),
json={
'message': message,
'createdDate': pendulum.now().to_rfc3339_string()
}
)
|
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 (str): Full parent Record ID string
field_id (str): Full field ID to target reference field on parent Record string
message (str): New comment message body
"""
self._swimlane.request(
'post',
'app/{0}/record/{1}/{2}/comment'.format(
app_id,
record_id,
field_id
),
json={
'message': message,
'createdDate': pendulum.now().to_rfc3339_string()
}
)
|
[
"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",
",",
"field_id",
")",
",",
"json",
"=",
"{",
"'message'",
":",
"message",
",",
"'createdDate'",
":",
"pendulum",
".",
"now",
"(",
")",
".",
"to_rfc3339_string",
"(",
")",
"}",
")"
] |
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 field ID to target reference field on parent Record string
message (str): New comment message body
|
[
"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 retrieved, get it
try:
record = self.target_app.records.get(id=record_id)
except SwimlaneHTTP400Error:
# Record appears to be orphaned, don't include in set of elements
logger.debug("Received 400 response retrieving record '{}', ignoring assumed orphaned record")
continue
retrieved_records[record_id] = record
self._elements = retrieved_records
return self._elements.values()
|
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 retrieved, get it
try:
record = self.target_app.records.get(id=record_id)
except SwimlaneHTTP400Error:
# Record appears to be orphaned, don't include in set of elements
logger.debug("Received 400 response retrieving record '{}', ignoring assumed orphaned record")
continue
retrieved_records[record_id] = record
self._elements = retrieved_records
return self._elements.values()
|
[
"def",
"_evaluate",
"(",
"self",
")",
":",
"retrieved_records",
"=",
"SortedDict",
"(",
")",
"for",
"record_id",
",",
"record",
"in",
"six",
".",
"iteritems",
"(",
"self",
".",
"_elements",
")",
":",
"if",
"record",
"is",
"self",
".",
"_field",
".",
"_unset",
":",
"# Record has not yet been retrieved, get it",
"try",
":",
"record",
"=",
"self",
".",
"target_app",
".",
"records",
".",
"get",
"(",
"id",
"=",
"record_id",
")",
"except",
"SwimlaneHTTP400Error",
":",
"# Record appears to be orphaned, don't include in set of elements",
"logger",
".",
"debug",
"(",
"\"Received 400 response retrieving record '{}', ignoring assumed orphaned record\"",
")",
"continue",
"retrieved_records",
"[",
"record_id",
"]",
"=",
"record",
"self",
".",
"_elements",
"=",
"retrieved_records",
"return",
"self",
".",
"_elements",
".",
"values",
"(",
")"
] |
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",
".",
"__target_app"
] |
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(
self.record,
"Reference field '{}' has target app '{}', cannot reference record '{}' from app '{}'".format(
self.name,
self.target_app,
value,
value.app
)
)
|
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(
self.record,
"Reference field '{}' has target app '{}', cannot reference record '{}' from app '{}'".format(
self.name,
self.target_app,
value,
value.app
)
)
|
[
"def",
"validate_value",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"not",
"in",
"(",
"None",
",",
"self",
".",
"_unset",
")",
":",
"super",
"(",
"ReferenceField",
",",
"self",
")",
".",
"validate_value",
"(",
"value",
")",
"if",
"value",
".",
"app",
"!=",
"self",
".",
"target_app",
":",
"raise",
"ValidationError",
"(",
"self",
".",
"record",
",",
"\"Reference field '{}' has target app '{}', cannot reference record '{}' from app '{}'\"",
".",
"format",
"(",
"self",
".",
"name",
",",
"self",
".",
"target_app",
",",
"value",
",",
"value",
".",
"app",
")",
")"
] |
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]
# Values come in as a list of record ids or None
value = value or []
records = SortedDict()
for record_id in value:
records[record_id] = self._unset
return super(ReferenceField, self).set_swimlane(records)
|
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]
# Values come in as a list of record ids or None
value = value or []
records = SortedDict()
for record_id in value:
records[record_id] = self._unset
return super(ReferenceField, self).set_swimlane(records)
|
[
"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",
")",
":",
"value",
"=",
"[",
"value",
"]",
"# Values come in as a list of record ids or None",
"value",
"=",
"value",
"or",
"[",
"]",
"records",
"=",
"SortedDict",
"(",
")",
"for",
"record_id",
"in",
"value",
":",
"records",
"[",
"record_id",
"]",
"=",
"self",
".",
"_unset",
"return",
"super",
"(",
"ReferenceField",
",",
"self",
")",
".",
"set_swimlane",
"(",
"records",
")"
] |
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 record in value:
self.validate_value(record)
records[record.id] = record
return_value = self._set(records)
self.record._raw['values'][self.id] = self.get_swimlane()
return return_value
|
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 record in value:
self.validate_value(record)
records[record.id] = record
return_value = self._set(records)
self.record._raw['values'][self.id] = self.get_swimlane()
return return_value
|
[
"def",
"set_python",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"self",
".",
"multiselect",
":",
"if",
"value",
"and",
"not",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"value",
"=",
"[",
"value",
"]",
"value",
"=",
"value",
"or",
"[",
"]",
"records",
"=",
"SortedDict",
"(",
")",
"for",
"record",
"in",
"value",
":",
"self",
".",
"validate_value",
"(",
"record",
")",
"records",
"[",
"record",
".",
"id",
"]",
"=",
"record",
"return_value",
"=",
"self",
".",
"_set",
"(",
"records",
")",
"self",
".",
"record",
".",
"_raw",
"[",
"'values'",
"]",
"[",
"self",
".",
"id",
"]",
"=",
"self",
".",
"get_swimlane",
"(",
")",
"return",
"return_value"
] |
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",
".",
"multiselect",
":",
"return",
"ids",
"return",
"ids",
"[",
"0",
"]",
"return",
"None"
] |
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:
return None
|
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:
return None
|
[
"def",
"get_python",
"(",
"self",
")",
":",
"cursor",
"=",
"super",
"(",
"ReferenceField",
",",
"self",
")",
".",
"get_python",
"(",
")",
"if",
"self",
".",
"multiselect",
":",
"return",
"cursor",
"else",
":",
"try",
":",
"return",
"cursor",
"[",
"0",
"]",
"except",
"IndexError",
":",
"return",
"None"
] |
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 multiple keyword arguments provided
ValueError: No matching app found on server
"""
if key == 'id':
# Server returns 204 instead of 404 for a non-existent app id
response = self._swimlane.request('get', 'app/{}'.format(value))
if response.status_code == 204:
raise ValueError('No app with id "{}"'.format(value))
return App(
self._swimlane,
response.json()
)
else:
# Workaround for lack of support for get by name
# Holdover from previous driver support, to be fixed as part of 3.x
for app in self.list():
if value and value == app.name:
return app
# No matching app found
raise ValueError('No app with name "{}"'.format(value))
|
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 multiple keyword arguments provided
ValueError: No matching app found on server
"""
if key == 'id':
# Server returns 204 instead of 404 for a non-existent app id
response = self._swimlane.request('get', 'app/{}'.format(value))
if response.status_code == 204:
raise ValueError('No app with id "{}"'.format(value))
return App(
self._swimlane,
response.json()
)
else:
# Workaround for lack of support for get by name
# Holdover from previous driver support, to be fixed as part of 3.x
for app in self.list():
if value and value == app.name:
return app
# No matching app found
raise ValueError('No app with name "{}"'.format(value))
|
[
"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/{}'",
".",
"format",
"(",
"value",
")",
")",
"if",
"response",
".",
"status_code",
"==",
"204",
":",
"raise",
"ValueError",
"(",
"'No app with id \"{}\"'",
".",
"format",
"(",
"value",
")",
")",
"return",
"App",
"(",
"self",
".",
"_swimlane",
",",
"response",
".",
"json",
"(",
")",
")",
"else",
":",
"# Workaround for lack of support for get by name",
"# Holdover from previous driver support, to be fixed as part of 3.x",
"for",
"app",
"in",
"self",
".",
"list",
"(",
")",
":",
"if",
"value",
"and",
"value",
"==",
"app",
".",
"name",
":",
"return",
"app",
"# No matching app found",
"raise",
"ValueError",
"(",
"'No app with name \"{}\"'",
".",
"format",
"(",
"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 multiple keyword arguments provided
ValueError: No matching app found on server
|
[
"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",
"self",
".",
"__users"
] |
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)
self._elements.append(element)
yield element
|
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)
self._elements.append(element)
yield element
|
[
"def",
"_evaluate",
"(",
"self",
")",
":",
"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",
")",
"self",
".",
"_elements",
".",
"append",
"(",
"element",
")",
"yield",
"element"
] |
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',
'passwordResetRequired',
'groups',
'roles',
'email',
'isAdmin',
'createdDate',
'modifiedDate',
'createdByUser',
'modifiedByUser',
'userName',
'id',
'disabled'
]
raw_data = {
'$type': User._type,
}
for key in matching_keys:
if key in login_content:
raw_data[key] = login_content[key]
return raw_data
|
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',
'passwordResetRequired',
'groups',
'roles',
'email',
'isAdmin',
'createdDate',
'modifiedDate',
'createdByUser',
'modifiedByUser',
'userName',
'id',
'disabled'
]
raw_data = {
'$type': User._type,
}
for key in matching_keys:
if key in login_content:
raw_data[key] = login_content[key]
return raw_data
|
[
"def",
"_user_raw_from_login_content",
"(",
"login_content",
")",
":",
"matching_keys",
"=",
"[",
"'displayName'",
",",
"'lastLogin'",
",",
"'active'",
",",
"'name'",
",",
"'isMe'",
",",
"'lastPasswordChangedDate'",
",",
"'passwordResetRequired'",
",",
"'groups'",
",",
"'roles'",
",",
"'email'",
",",
"'isAdmin'",
",",
"'createdDate'",
",",
"'modifiedDate'",
",",
"'createdByUser'",
",",
"'modifiedByUser'",
",",
"'userName'",
",",
"'id'",
",",
"'disabled'",
"]",
"raw_data",
"=",
"{",
"'$type'",
":",
"User",
".",
"_type",
",",
"}",
"for",
"key",
"in",
"matching_keys",
":",
"if",
"key",
"in",
"login_content",
":",
"raw_data",
"[",
"key",
"]",
"=",
"login_content",
"[",
"key",
"]",
"return",
"raw_data"
] |
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
"""
if compare_versions('.'.join([_lib_major_version, _lib_minor_version]), self.product_version) > 0:
logger.warning('Client version {} connecting to server with newer minor release {}.'.format(
_lib_full_version,
self.product_version
))
if compare_versions(_lib_major_version, self.product_version) != 0:
raise InvalidSwimlaneProductVersion(
self,
'{}.0'.format(_lib_major_version),
'{}.0'.format(str(int(_lib_major_version) + 1))
)
|
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
"""
if compare_versions('.'.join([_lib_major_version, _lib_minor_version]), self.product_version) > 0:
logger.warning('Client version {} connecting to server with newer minor release {}.'.format(
_lib_full_version,
self.product_version
))
if compare_versions(_lib_major_version, self.product_version) != 0:
raise InvalidSwimlaneProductVersion(
self,
'{}.0'.format(_lib_major_version),
'{}.0'.format(str(int(_lib_major_version) + 1))
)
|
[
"def",
"__verify_server_version",
"(",
"self",
")",
":",
"if",
"compare_versions",
"(",
"'.'",
".",
"join",
"(",
"[",
"_lib_major_version",
",",
"_lib_minor_version",
"]",
")",
",",
"self",
".",
"product_version",
")",
">",
"0",
":",
"logger",
".",
"warning",
"(",
"'Client version {} connecting to server with newer minor release {}.'",
".",
"format",
"(",
"_lib_full_version",
",",
"self",
".",
"product_version",
")",
")",
"if",
"compare_versions",
"(",
"_lib_major_version",
",",
"self",
".",
"product_version",
")",
"!=",
"0",
":",
"raise",
"InvalidSwimlaneProductVersion",
"(",
"self",
",",
"'{}.0'",
".",
"format",
"(",
"_lib_major_version",
")",
",",
"'{}.0'",
".",
"format",
"(",
"str",
"(",
"int",
"(",
"_lib_major_version",
")",
"+",
"1",
")",
")",
")"
] |
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.