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 |
---|---|---|---|---|---|---|---|---|---|---|---|
KrzyHonk/bpmn-python
|
bpmn_python/bpmn_diagram_visualizer.py
|
visualize_diagram
|
def visualize_diagram(bpmn_diagram):
"""
Shows a simple visualization of diagram
:param bpmn_diagram: an instance of BPMNDiagramGraph class.
"""
g = bpmn_diagram.diagram_graph
pos = bpmn_diagram.get_nodes_positions()
nx.draw_networkx_nodes(g, pos, node_shape='s', node_color='white',
nodelist=bpmn_diagram.get_nodes_id_list_by_type(consts.Consts.task))
nx.draw_networkx_nodes(g, pos, node_shape='s', node_color='white',
nodelist=bpmn_diagram.get_nodes_id_list_by_type(consts.Consts.subprocess))
nx.draw_networkx_nodes(g, pos, node_shape='d', node_color='white',
nodelist=bpmn_diagram.get_nodes_id_list_by_type(consts.Consts.complex_gateway))
nx.draw_networkx_nodes(g, pos, node_shape='o', node_color='white',
nodelist=bpmn_diagram.get_nodes_id_list_by_type(consts.Consts.event_based_gateway))
nx.draw_networkx_nodes(g, pos, node_shape='d', node_color='white',
nodelist=bpmn_diagram.get_nodes_id_list_by_type(consts.Consts.inclusive_gateway))
nx.draw_networkx_nodes(g, pos, node_shape='d', node_color='white',
nodelist=bpmn_diagram.get_nodes_id_list_by_type(consts.Consts.exclusive_gateway))
nx.draw_networkx_nodes(g, pos, node_shape='d', node_color='white',
nodelist=bpmn_diagram.get_nodes_id_list_by_type(consts.Consts.parallel_gateway))
nx.draw_networkx_nodes(g, pos, node_shape='o', node_color='white',
nodelist=bpmn_diagram.get_nodes_id_list_by_type(consts.Consts.start_event))
nx.draw_networkx_nodes(g, pos, node_shape='o', node_color='white',
nodelist=bpmn_diagram.get_nodes_id_list_by_type(consts.Consts.intermediate_catch_event))
nx.draw_networkx_nodes(g, pos, node_shape='o', node_color='white',
nodelist=bpmn_diagram.get_nodes_id_list_by_type(consts.Consts.end_event))
nx.draw_networkx_nodes(g, pos, node_shape='o', node_color='white',
nodelist=bpmn_diagram.get_nodes_id_list_by_type(consts.Consts.intermediate_throw_event))
node_labels = {}
for node in g.nodes(data=True):
node_labels[node[0]] = node[1].get(consts.Consts.node_name)
nx.draw_networkx_labels(g, pos, node_labels)
nx.draw_networkx_edges(g, pos)
edge_labels = {}
for edge in g.edges(data=True):
edge_labels[(edge[0], edge[1])] = edge[2].get(consts.Consts.name)
nx.draw_networkx_edge_labels(g, pos, edge_labels)
plt.show()
|
python
|
def visualize_diagram(bpmn_diagram):
"""
Shows a simple visualization of diagram
:param bpmn_diagram: an instance of BPMNDiagramGraph class.
"""
g = bpmn_diagram.diagram_graph
pos = bpmn_diagram.get_nodes_positions()
nx.draw_networkx_nodes(g, pos, node_shape='s', node_color='white',
nodelist=bpmn_diagram.get_nodes_id_list_by_type(consts.Consts.task))
nx.draw_networkx_nodes(g, pos, node_shape='s', node_color='white',
nodelist=bpmn_diagram.get_nodes_id_list_by_type(consts.Consts.subprocess))
nx.draw_networkx_nodes(g, pos, node_shape='d', node_color='white',
nodelist=bpmn_diagram.get_nodes_id_list_by_type(consts.Consts.complex_gateway))
nx.draw_networkx_nodes(g, pos, node_shape='o', node_color='white',
nodelist=bpmn_diagram.get_nodes_id_list_by_type(consts.Consts.event_based_gateway))
nx.draw_networkx_nodes(g, pos, node_shape='d', node_color='white',
nodelist=bpmn_diagram.get_nodes_id_list_by_type(consts.Consts.inclusive_gateway))
nx.draw_networkx_nodes(g, pos, node_shape='d', node_color='white',
nodelist=bpmn_diagram.get_nodes_id_list_by_type(consts.Consts.exclusive_gateway))
nx.draw_networkx_nodes(g, pos, node_shape='d', node_color='white',
nodelist=bpmn_diagram.get_nodes_id_list_by_type(consts.Consts.parallel_gateway))
nx.draw_networkx_nodes(g, pos, node_shape='o', node_color='white',
nodelist=bpmn_diagram.get_nodes_id_list_by_type(consts.Consts.start_event))
nx.draw_networkx_nodes(g, pos, node_shape='o', node_color='white',
nodelist=bpmn_diagram.get_nodes_id_list_by_type(consts.Consts.intermediate_catch_event))
nx.draw_networkx_nodes(g, pos, node_shape='o', node_color='white',
nodelist=bpmn_diagram.get_nodes_id_list_by_type(consts.Consts.end_event))
nx.draw_networkx_nodes(g, pos, node_shape='o', node_color='white',
nodelist=bpmn_diagram.get_nodes_id_list_by_type(consts.Consts.intermediate_throw_event))
node_labels = {}
for node in g.nodes(data=True):
node_labels[node[0]] = node[1].get(consts.Consts.node_name)
nx.draw_networkx_labels(g, pos, node_labels)
nx.draw_networkx_edges(g, pos)
edge_labels = {}
for edge in g.edges(data=True):
edge_labels[(edge[0], edge[1])] = edge[2].get(consts.Consts.name)
nx.draw_networkx_edge_labels(g, pos, edge_labels)
plt.show()
|
[
"def",
"visualize_diagram",
"(",
"bpmn_diagram",
")",
":",
"g",
"=",
"bpmn_diagram",
".",
"diagram_graph",
"pos",
"=",
"bpmn_diagram",
".",
"get_nodes_positions",
"(",
")",
"nx",
".",
"draw_networkx_nodes",
"(",
"g",
",",
"pos",
",",
"node_shape",
"=",
"'s'",
",",
"node_color",
"=",
"'white'",
",",
"nodelist",
"=",
"bpmn_diagram",
".",
"get_nodes_id_list_by_type",
"(",
"consts",
".",
"Consts",
".",
"task",
")",
")",
"nx",
".",
"draw_networkx_nodes",
"(",
"g",
",",
"pos",
",",
"node_shape",
"=",
"'s'",
",",
"node_color",
"=",
"'white'",
",",
"nodelist",
"=",
"bpmn_diagram",
".",
"get_nodes_id_list_by_type",
"(",
"consts",
".",
"Consts",
".",
"subprocess",
")",
")",
"nx",
".",
"draw_networkx_nodes",
"(",
"g",
",",
"pos",
",",
"node_shape",
"=",
"'d'",
",",
"node_color",
"=",
"'white'",
",",
"nodelist",
"=",
"bpmn_diagram",
".",
"get_nodes_id_list_by_type",
"(",
"consts",
".",
"Consts",
".",
"complex_gateway",
")",
")",
"nx",
".",
"draw_networkx_nodes",
"(",
"g",
",",
"pos",
",",
"node_shape",
"=",
"'o'",
",",
"node_color",
"=",
"'white'",
",",
"nodelist",
"=",
"bpmn_diagram",
".",
"get_nodes_id_list_by_type",
"(",
"consts",
".",
"Consts",
".",
"event_based_gateway",
")",
")",
"nx",
".",
"draw_networkx_nodes",
"(",
"g",
",",
"pos",
",",
"node_shape",
"=",
"'d'",
",",
"node_color",
"=",
"'white'",
",",
"nodelist",
"=",
"bpmn_diagram",
".",
"get_nodes_id_list_by_type",
"(",
"consts",
".",
"Consts",
".",
"inclusive_gateway",
")",
")",
"nx",
".",
"draw_networkx_nodes",
"(",
"g",
",",
"pos",
",",
"node_shape",
"=",
"'d'",
",",
"node_color",
"=",
"'white'",
",",
"nodelist",
"=",
"bpmn_diagram",
".",
"get_nodes_id_list_by_type",
"(",
"consts",
".",
"Consts",
".",
"exclusive_gateway",
")",
")",
"nx",
".",
"draw_networkx_nodes",
"(",
"g",
",",
"pos",
",",
"node_shape",
"=",
"'d'",
",",
"node_color",
"=",
"'white'",
",",
"nodelist",
"=",
"bpmn_diagram",
".",
"get_nodes_id_list_by_type",
"(",
"consts",
".",
"Consts",
".",
"parallel_gateway",
")",
")",
"nx",
".",
"draw_networkx_nodes",
"(",
"g",
",",
"pos",
",",
"node_shape",
"=",
"'o'",
",",
"node_color",
"=",
"'white'",
",",
"nodelist",
"=",
"bpmn_diagram",
".",
"get_nodes_id_list_by_type",
"(",
"consts",
".",
"Consts",
".",
"start_event",
")",
")",
"nx",
".",
"draw_networkx_nodes",
"(",
"g",
",",
"pos",
",",
"node_shape",
"=",
"'o'",
",",
"node_color",
"=",
"'white'",
",",
"nodelist",
"=",
"bpmn_diagram",
".",
"get_nodes_id_list_by_type",
"(",
"consts",
".",
"Consts",
".",
"intermediate_catch_event",
")",
")",
"nx",
".",
"draw_networkx_nodes",
"(",
"g",
",",
"pos",
",",
"node_shape",
"=",
"'o'",
",",
"node_color",
"=",
"'white'",
",",
"nodelist",
"=",
"bpmn_diagram",
".",
"get_nodes_id_list_by_type",
"(",
"consts",
".",
"Consts",
".",
"end_event",
")",
")",
"nx",
".",
"draw_networkx_nodes",
"(",
"g",
",",
"pos",
",",
"node_shape",
"=",
"'o'",
",",
"node_color",
"=",
"'white'",
",",
"nodelist",
"=",
"bpmn_diagram",
".",
"get_nodes_id_list_by_type",
"(",
"consts",
".",
"Consts",
".",
"intermediate_throw_event",
")",
")",
"node_labels",
"=",
"{",
"}",
"for",
"node",
"in",
"g",
".",
"nodes",
"(",
"data",
"=",
"True",
")",
":",
"node_labels",
"[",
"node",
"[",
"0",
"]",
"]",
"=",
"node",
"[",
"1",
"]",
".",
"get",
"(",
"consts",
".",
"Consts",
".",
"node_name",
")",
"nx",
".",
"draw_networkx_labels",
"(",
"g",
",",
"pos",
",",
"node_labels",
")",
"nx",
".",
"draw_networkx_edges",
"(",
"g",
",",
"pos",
")",
"edge_labels",
"=",
"{",
"}",
"for",
"edge",
"in",
"g",
".",
"edges",
"(",
"data",
"=",
"True",
")",
":",
"edge_labels",
"[",
"(",
"edge",
"[",
"0",
"]",
",",
"edge",
"[",
"1",
"]",
")",
"]",
"=",
"edge",
"[",
"2",
"]",
".",
"get",
"(",
"consts",
".",
"Consts",
".",
"name",
")",
"nx",
".",
"draw_networkx_edge_labels",
"(",
"g",
",",
"pos",
",",
"edge_labels",
")",
"plt",
".",
"show",
"(",
")"
] |
Shows a simple visualization of diagram
:param bpmn_diagram: an instance of BPMNDiagramGraph class.
|
[
"Shows",
"a",
"simple",
"visualization",
"of",
"diagram"
] |
6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629
|
https://github.com/KrzyHonk/bpmn-python/blob/6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629/bpmn_python/bpmn_diagram_visualizer.py#L13-L56
|
train
|
KrzyHonk/bpmn-python
|
bpmn_python/bpmn_diagram_visualizer.py
|
bpmn_diagram_to_png
|
def bpmn_diagram_to_png(bpmn_diagram, file_name):
"""
Create a png picture for given diagram
:param bpmn_diagram: an instance of BPMNDiagramGraph class,
:param file_name: name of generated file.
"""
g = bpmn_diagram.diagram_graph
graph = pydotplus.Dot()
for node in g.nodes(data=True):
if node[1].get(consts.Consts.type) == consts.Consts.task:
n = pydotplus.Node(name=node[0], shape="box", style="rounded", label=node[1].get(consts.Consts.node_name))
elif node[1].get(consts.Consts.type) == consts.Consts.exclusive_gateway:
n = pydotplus.Node(name=node[0], shape="diamond", label=node[1].get(consts.Consts.node_name))
else:
n = pydotplus.Node(name=node[0], label=node[1].get(consts.Consts.node_name))
graph.add_node(n)
for edge in g.edges(data=True):
e = pydotplus.Edge(src=edge[0], dst=edge[1], label=edge[2].get(consts.Consts.name))
graph.add_edge(e)
graph.write(file_name + ".png", format='png')
|
python
|
def bpmn_diagram_to_png(bpmn_diagram, file_name):
"""
Create a png picture for given diagram
:param bpmn_diagram: an instance of BPMNDiagramGraph class,
:param file_name: name of generated file.
"""
g = bpmn_diagram.diagram_graph
graph = pydotplus.Dot()
for node in g.nodes(data=True):
if node[1].get(consts.Consts.type) == consts.Consts.task:
n = pydotplus.Node(name=node[0], shape="box", style="rounded", label=node[1].get(consts.Consts.node_name))
elif node[1].get(consts.Consts.type) == consts.Consts.exclusive_gateway:
n = pydotplus.Node(name=node[0], shape="diamond", label=node[1].get(consts.Consts.node_name))
else:
n = pydotplus.Node(name=node[0], label=node[1].get(consts.Consts.node_name))
graph.add_node(n)
for edge in g.edges(data=True):
e = pydotplus.Edge(src=edge[0], dst=edge[1], label=edge[2].get(consts.Consts.name))
graph.add_edge(e)
graph.write(file_name + ".png", format='png')
|
[
"def",
"bpmn_diagram_to_png",
"(",
"bpmn_diagram",
",",
"file_name",
")",
":",
"g",
"=",
"bpmn_diagram",
".",
"diagram_graph",
"graph",
"=",
"pydotplus",
".",
"Dot",
"(",
")",
"for",
"node",
"in",
"g",
".",
"nodes",
"(",
"data",
"=",
"True",
")",
":",
"if",
"node",
"[",
"1",
"]",
".",
"get",
"(",
"consts",
".",
"Consts",
".",
"type",
")",
"==",
"consts",
".",
"Consts",
".",
"task",
":",
"n",
"=",
"pydotplus",
".",
"Node",
"(",
"name",
"=",
"node",
"[",
"0",
"]",
",",
"shape",
"=",
"\"box\"",
",",
"style",
"=",
"\"rounded\"",
",",
"label",
"=",
"node",
"[",
"1",
"]",
".",
"get",
"(",
"consts",
".",
"Consts",
".",
"node_name",
")",
")",
"elif",
"node",
"[",
"1",
"]",
".",
"get",
"(",
"consts",
".",
"Consts",
".",
"type",
")",
"==",
"consts",
".",
"Consts",
".",
"exclusive_gateway",
":",
"n",
"=",
"pydotplus",
".",
"Node",
"(",
"name",
"=",
"node",
"[",
"0",
"]",
",",
"shape",
"=",
"\"diamond\"",
",",
"label",
"=",
"node",
"[",
"1",
"]",
".",
"get",
"(",
"consts",
".",
"Consts",
".",
"node_name",
")",
")",
"else",
":",
"n",
"=",
"pydotplus",
".",
"Node",
"(",
"name",
"=",
"node",
"[",
"0",
"]",
",",
"label",
"=",
"node",
"[",
"1",
"]",
".",
"get",
"(",
"consts",
".",
"Consts",
".",
"node_name",
")",
")",
"graph",
".",
"add_node",
"(",
"n",
")",
"for",
"edge",
"in",
"g",
".",
"edges",
"(",
"data",
"=",
"True",
")",
":",
"e",
"=",
"pydotplus",
".",
"Edge",
"(",
"src",
"=",
"edge",
"[",
"0",
"]",
",",
"dst",
"=",
"edge",
"[",
"1",
"]",
",",
"label",
"=",
"edge",
"[",
"2",
"]",
".",
"get",
"(",
"consts",
".",
"Consts",
".",
"name",
")",
")",
"graph",
".",
"add_edge",
"(",
"e",
")",
"graph",
".",
"write",
"(",
"file_name",
"+",
"\".png\"",
",",
"format",
"=",
"'png'",
")"
] |
Create a png picture for given diagram
:param bpmn_diagram: an instance of BPMNDiagramGraph class,
:param file_name: name of generated file.
|
[
"Create",
"a",
"png",
"picture",
"for",
"given",
"diagram"
] |
6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629
|
https://github.com/KrzyHonk/bpmn-python/blob/6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629/bpmn_python/bpmn_diagram_visualizer.py#L70-L94
|
train
|
KrzyHonk/bpmn-python
|
bpmn_python/bpmn_diagram_rep.py
|
BpmnDiagramGraph.get_node_by_id
|
def get_node_by_id(self, node_id):
"""
Gets a node with requested ID.
Returns a tuple, where first value is node ID, second - a dictionary of all node attributes.
:param node_id: string with ID of node.
"""
tmp_nodes = self.diagram_graph.nodes(data=True)
for node in tmp_nodes:
if node[0] == node_id:
return node
|
python
|
def get_node_by_id(self, node_id):
"""
Gets a node with requested ID.
Returns a tuple, where first value is node ID, second - a dictionary of all node attributes.
:param node_id: string with ID of node.
"""
tmp_nodes = self.diagram_graph.nodes(data=True)
for node in tmp_nodes:
if node[0] == node_id:
return node
|
[
"def",
"get_node_by_id",
"(",
"self",
",",
"node_id",
")",
":",
"tmp_nodes",
"=",
"self",
".",
"diagram_graph",
".",
"nodes",
"(",
"data",
"=",
"True",
")",
"for",
"node",
"in",
"tmp_nodes",
":",
"if",
"node",
"[",
"0",
"]",
"==",
"node_id",
":",
"return",
"node"
] |
Gets a node with requested ID.
Returns a tuple, where first value is node ID, second - a dictionary of all node attributes.
:param node_id: string with ID of node.
|
[
"Gets",
"a",
"node",
"with",
"requested",
"ID",
".",
"Returns",
"a",
"tuple",
"where",
"first",
"value",
"is",
"node",
"ID",
"second",
"-",
"a",
"dictionary",
"of",
"all",
"node",
"attributes",
"."
] |
6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629
|
https://github.com/KrzyHonk/bpmn-python/blob/6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629/bpmn_python/bpmn_diagram_rep.py#L136-L146
|
train
|
KrzyHonk/bpmn-python
|
bpmn_python/bpmn_diagram_rep.py
|
BpmnDiagramGraph.get_nodes_id_list_by_type
|
def get_nodes_id_list_by_type(self, node_type):
"""
Get a list of node's id by requested type.
Returns a list of ids
:param node_type: string with valid BPMN XML tag name (e.g. 'task', 'sequenceFlow').
"""
tmp_nodes = self.diagram_graph.nodes(data=True)
id_list = []
for node in tmp_nodes:
if node[1][consts.Consts.type] == node_type:
id_list.append(node[0])
return id_list
|
python
|
def get_nodes_id_list_by_type(self, node_type):
"""
Get a list of node's id by requested type.
Returns a list of ids
:param node_type: string with valid BPMN XML tag name (e.g. 'task', 'sequenceFlow').
"""
tmp_nodes = self.diagram_graph.nodes(data=True)
id_list = []
for node in tmp_nodes:
if node[1][consts.Consts.type] == node_type:
id_list.append(node[0])
return id_list
|
[
"def",
"get_nodes_id_list_by_type",
"(",
"self",
",",
"node_type",
")",
":",
"tmp_nodes",
"=",
"self",
".",
"diagram_graph",
".",
"nodes",
"(",
"data",
"=",
"True",
")",
"id_list",
"=",
"[",
"]",
"for",
"node",
"in",
"tmp_nodes",
":",
"if",
"node",
"[",
"1",
"]",
"[",
"consts",
".",
"Consts",
".",
"type",
"]",
"==",
"node_type",
":",
"id_list",
".",
"append",
"(",
"node",
"[",
"0",
"]",
")",
"return",
"id_list"
] |
Get a list of node's id by requested type.
Returns a list of ids
:param node_type: string with valid BPMN XML tag name (e.g. 'task', 'sequenceFlow').
|
[
"Get",
"a",
"list",
"of",
"node",
"s",
"id",
"by",
"requested",
"type",
".",
"Returns",
"a",
"list",
"of",
"ids"
] |
6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629
|
https://github.com/KrzyHonk/bpmn-python/blob/6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629/bpmn_python/bpmn_diagram_rep.py#L148-L160
|
train
|
KrzyHonk/bpmn-python
|
bpmn_python/bpmn_diagram_rep.py
|
BpmnDiagramGraph.add_process_to_diagram
|
def add_process_to_diagram(self, process_name="", process_is_closed=False, process_is_executable=False,
process_type="None"):
"""
Adds a new process to diagram and corresponding participant
process, diagram and plane
Accepts a user-defined values for following attributes:
(Process element)
- isClosed - default value false,
- isExecutable - default value false,
- processType - default value None.
:param process_name: string obejct, process name. Default value - empty string,
:param process_is_closed: boolean type. Represents a user-defined value of 'process' element
attribute 'isClosed'. Default value false,
:param process_is_executable: boolean type. Represents a user-defined value of 'process' element
attribute 'isExecutable'. Default value false,
:param process_type: string type. Represents a user-defined value of 'process' element
attribute 'procesType'. Default value "None",
"""
plane_id = BpmnDiagramGraph.id_prefix + str(uuid.uuid4())
process_id = BpmnDiagramGraph.id_prefix + str(uuid.uuid4())
self.process_elements[process_id] = {consts.Consts.name: process_name,
consts.Consts.is_closed: "true" if process_is_closed else "false",
consts.Consts.is_executable: "true" if process_is_executable else "false",
consts.Consts.process_type: process_type}
self.plane_attributes[consts.Consts.id] = plane_id
self.plane_attributes[consts.Consts.bpmn_element] = process_id
return process_id
|
python
|
def add_process_to_diagram(self, process_name="", process_is_closed=False, process_is_executable=False,
process_type="None"):
"""
Adds a new process to diagram and corresponding participant
process, diagram and plane
Accepts a user-defined values for following attributes:
(Process element)
- isClosed - default value false,
- isExecutable - default value false,
- processType - default value None.
:param process_name: string obejct, process name. Default value - empty string,
:param process_is_closed: boolean type. Represents a user-defined value of 'process' element
attribute 'isClosed'. Default value false,
:param process_is_executable: boolean type. Represents a user-defined value of 'process' element
attribute 'isExecutable'. Default value false,
:param process_type: string type. Represents a user-defined value of 'process' element
attribute 'procesType'. Default value "None",
"""
plane_id = BpmnDiagramGraph.id_prefix + str(uuid.uuid4())
process_id = BpmnDiagramGraph.id_prefix + str(uuid.uuid4())
self.process_elements[process_id] = {consts.Consts.name: process_name,
consts.Consts.is_closed: "true" if process_is_closed else "false",
consts.Consts.is_executable: "true" if process_is_executable else "false",
consts.Consts.process_type: process_type}
self.plane_attributes[consts.Consts.id] = plane_id
self.plane_attributes[consts.Consts.bpmn_element] = process_id
return process_id
|
[
"def",
"add_process_to_diagram",
"(",
"self",
",",
"process_name",
"=",
"\"\"",
",",
"process_is_closed",
"=",
"False",
",",
"process_is_executable",
"=",
"False",
",",
"process_type",
"=",
"\"None\"",
")",
":",
"plane_id",
"=",
"BpmnDiagramGraph",
".",
"id_prefix",
"+",
"str",
"(",
"uuid",
".",
"uuid4",
"(",
")",
")",
"process_id",
"=",
"BpmnDiagramGraph",
".",
"id_prefix",
"+",
"str",
"(",
"uuid",
".",
"uuid4",
"(",
")",
")",
"self",
".",
"process_elements",
"[",
"process_id",
"]",
"=",
"{",
"consts",
".",
"Consts",
".",
"name",
":",
"process_name",
",",
"consts",
".",
"Consts",
".",
"is_closed",
":",
"\"true\"",
"if",
"process_is_closed",
"else",
"\"false\"",
",",
"consts",
".",
"Consts",
".",
"is_executable",
":",
"\"true\"",
"if",
"process_is_executable",
"else",
"\"false\"",
",",
"consts",
".",
"Consts",
".",
"process_type",
":",
"process_type",
"}",
"self",
".",
"plane_attributes",
"[",
"consts",
".",
"Consts",
".",
"id",
"]",
"=",
"plane_id",
"self",
".",
"plane_attributes",
"[",
"consts",
".",
"Consts",
".",
"bpmn_element",
"]",
"=",
"process_id",
"return",
"process_id"
] |
Adds a new process to diagram and corresponding participant
process, diagram and plane
Accepts a user-defined values for following attributes:
(Process element)
- isClosed - default value false,
- isExecutable - default value false,
- processType - default value None.
:param process_name: string obejct, process name. Default value - empty string,
:param process_is_closed: boolean type. Represents a user-defined value of 'process' element
attribute 'isClosed'. Default value false,
:param process_is_executable: boolean type. Represents a user-defined value of 'process' element
attribute 'isExecutable'. Default value false,
:param process_type: string type. Represents a user-defined value of 'process' element
attribute 'procesType'. Default value "None",
|
[
"Adds",
"a",
"new",
"process",
"to",
"diagram",
"and",
"corresponding",
"participant",
"process",
"diagram",
"and",
"plane"
] |
6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629
|
https://github.com/KrzyHonk/bpmn-python/blob/6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629/bpmn_python/bpmn_diagram_rep.py#L214-L244
|
train
|
KrzyHonk/bpmn-python
|
bpmn_python/bpmn_diagram_rep.py
|
BpmnDiagramGraph.add_flow_node_to_diagram
|
def add_flow_node_to_diagram(self, process_id, node_type, name, node_id=None):
"""
Helper function that adds a new Flow Node to diagram. It is used to add a new node of specified type.
Adds a basic information inherited from Flow Node type.
:param process_id: string object. ID of parent process,
:param node_type: string object. Represents type of BPMN node passed to method,
:param name: string object. Name of the node,
:param node_id: string object. ID of node. Default value - None.
"""
if node_id is None:
node_id = BpmnDiagramGraph.id_prefix + str(uuid.uuid4())
self.diagram_graph.add_node(node_id)
self.diagram_graph.node[node_id][consts.Consts.id] = node_id
self.diagram_graph.node[node_id][consts.Consts.type] = node_type
self.diagram_graph.node[node_id][consts.Consts.node_name] = name
self.diagram_graph.node[node_id][consts.Consts.incoming_flow] = []
self.diagram_graph.node[node_id][consts.Consts.outgoing_flow] = []
self.diagram_graph.node[node_id][consts.Consts.process] = process_id
# Adding some dummy constant values
self.diagram_graph.node[node_id][consts.Consts.width] = "100"
self.diagram_graph.node[node_id][consts.Consts.height] = "100"
self.diagram_graph.node[node_id][consts.Consts.x] = "100"
self.diagram_graph.node[node_id][consts.Consts.y] = "100"
return node_id, self.diagram_graph.node[node_id]
|
python
|
def add_flow_node_to_diagram(self, process_id, node_type, name, node_id=None):
"""
Helper function that adds a new Flow Node to diagram. It is used to add a new node of specified type.
Adds a basic information inherited from Flow Node type.
:param process_id: string object. ID of parent process,
:param node_type: string object. Represents type of BPMN node passed to method,
:param name: string object. Name of the node,
:param node_id: string object. ID of node. Default value - None.
"""
if node_id is None:
node_id = BpmnDiagramGraph.id_prefix + str(uuid.uuid4())
self.diagram_graph.add_node(node_id)
self.diagram_graph.node[node_id][consts.Consts.id] = node_id
self.diagram_graph.node[node_id][consts.Consts.type] = node_type
self.diagram_graph.node[node_id][consts.Consts.node_name] = name
self.diagram_graph.node[node_id][consts.Consts.incoming_flow] = []
self.diagram_graph.node[node_id][consts.Consts.outgoing_flow] = []
self.diagram_graph.node[node_id][consts.Consts.process] = process_id
# Adding some dummy constant values
self.diagram_graph.node[node_id][consts.Consts.width] = "100"
self.diagram_graph.node[node_id][consts.Consts.height] = "100"
self.diagram_graph.node[node_id][consts.Consts.x] = "100"
self.diagram_graph.node[node_id][consts.Consts.y] = "100"
return node_id, self.diagram_graph.node[node_id]
|
[
"def",
"add_flow_node_to_diagram",
"(",
"self",
",",
"process_id",
",",
"node_type",
",",
"name",
",",
"node_id",
"=",
"None",
")",
":",
"if",
"node_id",
"is",
"None",
":",
"node_id",
"=",
"BpmnDiagramGraph",
".",
"id_prefix",
"+",
"str",
"(",
"uuid",
".",
"uuid4",
"(",
")",
")",
"self",
".",
"diagram_graph",
".",
"add_node",
"(",
"node_id",
")",
"self",
".",
"diagram_graph",
".",
"node",
"[",
"node_id",
"]",
"[",
"consts",
".",
"Consts",
".",
"id",
"]",
"=",
"node_id",
"self",
".",
"diagram_graph",
".",
"node",
"[",
"node_id",
"]",
"[",
"consts",
".",
"Consts",
".",
"type",
"]",
"=",
"node_type",
"self",
".",
"diagram_graph",
".",
"node",
"[",
"node_id",
"]",
"[",
"consts",
".",
"Consts",
".",
"node_name",
"]",
"=",
"name",
"self",
".",
"diagram_graph",
".",
"node",
"[",
"node_id",
"]",
"[",
"consts",
".",
"Consts",
".",
"incoming_flow",
"]",
"=",
"[",
"]",
"self",
".",
"diagram_graph",
".",
"node",
"[",
"node_id",
"]",
"[",
"consts",
".",
"Consts",
".",
"outgoing_flow",
"]",
"=",
"[",
"]",
"self",
".",
"diagram_graph",
".",
"node",
"[",
"node_id",
"]",
"[",
"consts",
".",
"Consts",
".",
"process",
"]",
"=",
"process_id",
"# Adding some dummy constant values",
"self",
".",
"diagram_graph",
".",
"node",
"[",
"node_id",
"]",
"[",
"consts",
".",
"Consts",
".",
"width",
"]",
"=",
"\"100\"",
"self",
".",
"diagram_graph",
".",
"node",
"[",
"node_id",
"]",
"[",
"consts",
".",
"Consts",
".",
"height",
"]",
"=",
"\"100\"",
"self",
".",
"diagram_graph",
".",
"node",
"[",
"node_id",
"]",
"[",
"consts",
".",
"Consts",
".",
"x",
"]",
"=",
"\"100\"",
"self",
".",
"diagram_graph",
".",
"node",
"[",
"node_id",
"]",
"[",
"consts",
".",
"Consts",
".",
"y",
"]",
"=",
"\"100\"",
"return",
"node_id",
",",
"self",
".",
"diagram_graph",
".",
"node",
"[",
"node_id",
"]"
] |
Helper function that adds a new Flow Node to diagram. It is used to add a new node of specified type.
Adds a basic information inherited from Flow Node type.
:param process_id: string object. ID of parent process,
:param node_type: string object. Represents type of BPMN node passed to method,
:param name: string object. Name of the node,
:param node_id: string object. ID of node. Default value - None.
|
[
"Helper",
"function",
"that",
"adds",
"a",
"new",
"Flow",
"Node",
"to",
"diagram",
".",
"It",
"is",
"used",
"to",
"add",
"a",
"new",
"node",
"of",
"specified",
"type",
".",
"Adds",
"a",
"basic",
"information",
"inherited",
"from",
"Flow",
"Node",
"type",
"."
] |
6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629
|
https://github.com/KrzyHonk/bpmn-python/blob/6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629/bpmn_python/bpmn_diagram_rep.py#L246-L271
|
train
|
KrzyHonk/bpmn-python
|
bpmn_python/bpmn_diagram_rep.py
|
BpmnDiagramGraph.add_start_event_to_diagram
|
def add_start_event_to_diagram(self, process_id, start_event_name="", start_event_definition=None,
parallel_multiple=False, is_interrupting=True, node_id=None):
"""
Adds a StartEvent element to BPMN diagram.
User-defined attributes:
- name
- parallel_multiple
- is_interrupting
- event definition (creates a special type of start event). Supported event definitions -
* 'message': 'messageEventDefinition',
* 'timer': 'timerEventDefinition',
* 'signal': 'signalEventDefinition',
* 'conditional': 'conditionalEventDefinition',
* 'escalation': 'escalationEventDefinition'.
:param process_id: string object. ID of parent process,
:param start_event_name: string object. Name of start event,
:param start_event_definition: list of event definitions. By default - empty,
:param parallel_multiple: boolean value for attribute "parallelMultiple",
:param is_interrupting: boolean value for attribute "isInterrupting,
:param node_id: string object. ID of node. Default value - None.
:return: a tuple, where first value is startEvent ID, second a reference to created object.
"""
start_event_id, start_event = self.add_flow_node_to_diagram(process_id, consts.Consts.start_event,
start_event_name, node_id)
self.diagram_graph.node[start_event_id][consts.Consts.parallel_multiple] = \
"true" if parallel_multiple else "false"
self.diagram_graph.node[start_event_id][consts.Consts.is_interrupting] = "true" if is_interrupting else "false"
start_event_definitions = {"message": "messageEventDefinition", "timer": "timerEventDefinition",
"conditional": "conditionalEventDefinition", "signal": "signalEventDefinition",
"escalation": "escalationEventDefinition"}
event_def_list = []
if start_event_definition == "message":
event_def_list.append(BpmnDiagramGraph.add_event_definition_element("message", start_event_definitions))
elif start_event_definition == "timer":
event_def_list.append(BpmnDiagramGraph.add_event_definition_element("timer", start_event_definitions))
elif start_event_definition == "conditional":
event_def_list.append(BpmnDiagramGraph.add_event_definition_element("conditional", start_event_definitions))
elif start_event_definition == "signal":
event_def_list.append(BpmnDiagramGraph.add_event_definition_element("signal", start_event_definitions))
elif start_event_definition == "escalation":
event_def_list.append(BpmnDiagramGraph.add_event_definition_element("escalation", start_event_definitions))
self.diagram_graph.node[start_event_id][consts.Consts.event_definitions] = event_def_list
return start_event_id, start_event
|
python
|
def add_start_event_to_diagram(self, process_id, start_event_name="", start_event_definition=None,
parallel_multiple=False, is_interrupting=True, node_id=None):
"""
Adds a StartEvent element to BPMN diagram.
User-defined attributes:
- name
- parallel_multiple
- is_interrupting
- event definition (creates a special type of start event). Supported event definitions -
* 'message': 'messageEventDefinition',
* 'timer': 'timerEventDefinition',
* 'signal': 'signalEventDefinition',
* 'conditional': 'conditionalEventDefinition',
* 'escalation': 'escalationEventDefinition'.
:param process_id: string object. ID of parent process,
:param start_event_name: string object. Name of start event,
:param start_event_definition: list of event definitions. By default - empty,
:param parallel_multiple: boolean value for attribute "parallelMultiple",
:param is_interrupting: boolean value for attribute "isInterrupting,
:param node_id: string object. ID of node. Default value - None.
:return: a tuple, where first value is startEvent ID, second a reference to created object.
"""
start_event_id, start_event = self.add_flow_node_to_diagram(process_id, consts.Consts.start_event,
start_event_name, node_id)
self.diagram_graph.node[start_event_id][consts.Consts.parallel_multiple] = \
"true" if parallel_multiple else "false"
self.diagram_graph.node[start_event_id][consts.Consts.is_interrupting] = "true" if is_interrupting else "false"
start_event_definitions = {"message": "messageEventDefinition", "timer": "timerEventDefinition",
"conditional": "conditionalEventDefinition", "signal": "signalEventDefinition",
"escalation": "escalationEventDefinition"}
event_def_list = []
if start_event_definition == "message":
event_def_list.append(BpmnDiagramGraph.add_event_definition_element("message", start_event_definitions))
elif start_event_definition == "timer":
event_def_list.append(BpmnDiagramGraph.add_event_definition_element("timer", start_event_definitions))
elif start_event_definition == "conditional":
event_def_list.append(BpmnDiagramGraph.add_event_definition_element("conditional", start_event_definitions))
elif start_event_definition == "signal":
event_def_list.append(BpmnDiagramGraph.add_event_definition_element("signal", start_event_definitions))
elif start_event_definition == "escalation":
event_def_list.append(BpmnDiagramGraph.add_event_definition_element("escalation", start_event_definitions))
self.diagram_graph.node[start_event_id][consts.Consts.event_definitions] = event_def_list
return start_event_id, start_event
|
[
"def",
"add_start_event_to_diagram",
"(",
"self",
",",
"process_id",
",",
"start_event_name",
"=",
"\"\"",
",",
"start_event_definition",
"=",
"None",
",",
"parallel_multiple",
"=",
"False",
",",
"is_interrupting",
"=",
"True",
",",
"node_id",
"=",
"None",
")",
":",
"start_event_id",
",",
"start_event",
"=",
"self",
".",
"add_flow_node_to_diagram",
"(",
"process_id",
",",
"consts",
".",
"Consts",
".",
"start_event",
",",
"start_event_name",
",",
"node_id",
")",
"self",
".",
"diagram_graph",
".",
"node",
"[",
"start_event_id",
"]",
"[",
"consts",
".",
"Consts",
".",
"parallel_multiple",
"]",
"=",
"\"true\"",
"if",
"parallel_multiple",
"else",
"\"false\"",
"self",
".",
"diagram_graph",
".",
"node",
"[",
"start_event_id",
"]",
"[",
"consts",
".",
"Consts",
".",
"is_interrupting",
"]",
"=",
"\"true\"",
"if",
"is_interrupting",
"else",
"\"false\"",
"start_event_definitions",
"=",
"{",
"\"message\"",
":",
"\"messageEventDefinition\"",
",",
"\"timer\"",
":",
"\"timerEventDefinition\"",
",",
"\"conditional\"",
":",
"\"conditionalEventDefinition\"",
",",
"\"signal\"",
":",
"\"signalEventDefinition\"",
",",
"\"escalation\"",
":",
"\"escalationEventDefinition\"",
"}",
"event_def_list",
"=",
"[",
"]",
"if",
"start_event_definition",
"==",
"\"message\"",
":",
"event_def_list",
".",
"append",
"(",
"BpmnDiagramGraph",
".",
"add_event_definition_element",
"(",
"\"message\"",
",",
"start_event_definitions",
")",
")",
"elif",
"start_event_definition",
"==",
"\"timer\"",
":",
"event_def_list",
".",
"append",
"(",
"BpmnDiagramGraph",
".",
"add_event_definition_element",
"(",
"\"timer\"",
",",
"start_event_definitions",
")",
")",
"elif",
"start_event_definition",
"==",
"\"conditional\"",
":",
"event_def_list",
".",
"append",
"(",
"BpmnDiagramGraph",
".",
"add_event_definition_element",
"(",
"\"conditional\"",
",",
"start_event_definitions",
")",
")",
"elif",
"start_event_definition",
"==",
"\"signal\"",
":",
"event_def_list",
".",
"append",
"(",
"BpmnDiagramGraph",
".",
"add_event_definition_element",
"(",
"\"signal\"",
",",
"start_event_definitions",
")",
")",
"elif",
"start_event_definition",
"==",
"\"escalation\"",
":",
"event_def_list",
".",
"append",
"(",
"BpmnDiagramGraph",
".",
"add_event_definition_element",
"(",
"\"escalation\"",
",",
"start_event_definitions",
")",
")",
"self",
".",
"diagram_graph",
".",
"node",
"[",
"start_event_id",
"]",
"[",
"consts",
".",
"Consts",
".",
"event_definitions",
"]",
"=",
"event_def_list",
"return",
"start_event_id",
",",
"start_event"
] |
Adds a StartEvent element to BPMN diagram.
User-defined attributes:
- name
- parallel_multiple
- is_interrupting
- event definition (creates a special type of start event). Supported event definitions -
* 'message': 'messageEventDefinition',
* 'timer': 'timerEventDefinition',
* 'signal': 'signalEventDefinition',
* 'conditional': 'conditionalEventDefinition',
* 'escalation': 'escalationEventDefinition'.
:param process_id: string object. ID of parent process,
:param start_event_name: string object. Name of start event,
:param start_event_definition: list of event definitions. By default - empty,
:param parallel_multiple: boolean value for attribute "parallelMultiple",
:param is_interrupting: boolean value for attribute "isInterrupting,
:param node_id: string object. ID of node. Default value - None.
:return: a tuple, where first value is startEvent ID, second a reference to created object.
|
[
"Adds",
"a",
"StartEvent",
"element",
"to",
"BPMN",
"diagram",
"."
] |
6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629
|
https://github.com/KrzyHonk/bpmn-python/blob/6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629/bpmn_python/bpmn_diagram_rep.py#L312-L359
|
train
|
KrzyHonk/bpmn-python
|
bpmn_python/bpmn_diagram_rep.py
|
BpmnDiagramGraph.add_inclusive_gateway_to_diagram
|
def add_inclusive_gateway_to_diagram(self, process_id, gateway_name="", gateway_direction="Unspecified",
default=None, node_id=None):
"""
Adds an inclusiveGateway element to BPMN diagram.
:param process_id: string object. ID of parent process,
:param gateway_name: string object. Name of inclusive gateway,
:param gateway_direction: string object. Accepted values - "Unspecified", "Converging", "Diverging", "Mixed".
Default value - "Unspecified",
:param default: string object. ID of flow node, target of gateway default path. Default value - None,
:param node_id: string object. ID of node. Default value - None.
:return: a tuple, where first value is inclusiveGateway ID, second a reference to created object.
"""
inclusive_gateway_id, inclusive_gateway = self.add_gateway_to_diagram(process_id,
consts.Consts.inclusive_gateway,
gateway_name=gateway_name,
gateway_direction=gateway_direction,
node_id=node_id)
self.diagram_graph.node[inclusive_gateway_id][consts.Consts.default] = default
return inclusive_gateway_id, inclusive_gateway
|
python
|
def add_inclusive_gateway_to_diagram(self, process_id, gateway_name="", gateway_direction="Unspecified",
default=None, node_id=None):
"""
Adds an inclusiveGateway element to BPMN diagram.
:param process_id: string object. ID of parent process,
:param gateway_name: string object. Name of inclusive gateway,
:param gateway_direction: string object. Accepted values - "Unspecified", "Converging", "Diverging", "Mixed".
Default value - "Unspecified",
:param default: string object. ID of flow node, target of gateway default path. Default value - None,
:param node_id: string object. ID of node. Default value - None.
:return: a tuple, where first value is inclusiveGateway ID, second a reference to created object.
"""
inclusive_gateway_id, inclusive_gateway = self.add_gateway_to_diagram(process_id,
consts.Consts.inclusive_gateway,
gateway_name=gateway_name,
gateway_direction=gateway_direction,
node_id=node_id)
self.diagram_graph.node[inclusive_gateway_id][consts.Consts.default] = default
return inclusive_gateway_id, inclusive_gateway
|
[
"def",
"add_inclusive_gateway_to_diagram",
"(",
"self",
",",
"process_id",
",",
"gateway_name",
"=",
"\"\"",
",",
"gateway_direction",
"=",
"\"Unspecified\"",
",",
"default",
"=",
"None",
",",
"node_id",
"=",
"None",
")",
":",
"inclusive_gateway_id",
",",
"inclusive_gateway",
"=",
"self",
".",
"add_gateway_to_diagram",
"(",
"process_id",
",",
"consts",
".",
"Consts",
".",
"inclusive_gateway",
",",
"gateway_name",
"=",
"gateway_name",
",",
"gateway_direction",
"=",
"gateway_direction",
",",
"node_id",
"=",
"node_id",
")",
"self",
".",
"diagram_graph",
".",
"node",
"[",
"inclusive_gateway_id",
"]",
"[",
"consts",
".",
"Consts",
".",
"default",
"]",
"=",
"default",
"return",
"inclusive_gateway_id",
",",
"inclusive_gateway"
] |
Adds an inclusiveGateway element to BPMN diagram.
:param process_id: string object. ID of parent process,
:param gateway_name: string object. Name of inclusive gateway,
:param gateway_direction: string object. Accepted values - "Unspecified", "Converging", "Diverging", "Mixed".
Default value - "Unspecified",
:param default: string object. ID of flow node, target of gateway default path. Default value - None,
:param node_id: string object. ID of node. Default value - None.
:return: a tuple, where first value is inclusiveGateway ID, second a reference to created object.
|
[
"Adds",
"an",
"inclusiveGateway",
"element",
"to",
"BPMN",
"diagram",
"."
] |
6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629
|
https://github.com/KrzyHonk/bpmn-python/blob/6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629/bpmn_python/bpmn_diagram_rep.py#L459-L479
|
train
|
KrzyHonk/bpmn-python
|
bpmn_python/bpmn_diagram_rep.py
|
BpmnDiagramGraph.add_parallel_gateway_to_diagram
|
def add_parallel_gateway_to_diagram(self, process_id, gateway_name="", gateway_direction="Unspecified",
node_id=None):
"""
Adds an parallelGateway element to BPMN diagram.
:param process_id: string object. ID of parent process,
:param gateway_name: string object. Name of inclusive gateway,
:param gateway_direction: string object. Accepted values - "Unspecified", "Converging", "Diverging", "Mixed".
Default value - "Unspecified",
:param node_id: string object. ID of node. Default value - None.
:return: a tuple, where first value is parallelGateway ID, second a reference to created object.
"""
parallel_gateway_id, parallel_gateway = self.add_gateway_to_diagram(process_id,
consts.Consts.parallel_gateway,
gateway_name=gateway_name,
gateway_direction=gateway_direction,
node_id=node_id)
return parallel_gateway_id, parallel_gateway
|
python
|
def add_parallel_gateway_to_diagram(self, process_id, gateway_name="", gateway_direction="Unspecified",
node_id=None):
"""
Adds an parallelGateway element to BPMN diagram.
:param process_id: string object. ID of parent process,
:param gateway_name: string object. Name of inclusive gateway,
:param gateway_direction: string object. Accepted values - "Unspecified", "Converging", "Diverging", "Mixed".
Default value - "Unspecified",
:param node_id: string object. ID of node. Default value - None.
:return: a tuple, where first value is parallelGateway ID, second a reference to created object.
"""
parallel_gateway_id, parallel_gateway = self.add_gateway_to_diagram(process_id,
consts.Consts.parallel_gateway,
gateway_name=gateway_name,
gateway_direction=gateway_direction,
node_id=node_id)
return parallel_gateway_id, parallel_gateway
|
[
"def",
"add_parallel_gateway_to_diagram",
"(",
"self",
",",
"process_id",
",",
"gateway_name",
"=",
"\"\"",
",",
"gateway_direction",
"=",
"\"Unspecified\"",
",",
"node_id",
"=",
"None",
")",
":",
"parallel_gateway_id",
",",
"parallel_gateway",
"=",
"self",
".",
"add_gateway_to_diagram",
"(",
"process_id",
",",
"consts",
".",
"Consts",
".",
"parallel_gateway",
",",
"gateway_name",
"=",
"gateway_name",
",",
"gateway_direction",
"=",
"gateway_direction",
",",
"node_id",
"=",
"node_id",
")",
"return",
"parallel_gateway_id",
",",
"parallel_gateway"
] |
Adds an parallelGateway element to BPMN diagram.
:param process_id: string object. ID of parent process,
:param gateway_name: string object. Name of inclusive gateway,
:param gateway_direction: string object. Accepted values - "Unspecified", "Converging", "Diverging", "Mixed".
Default value - "Unspecified",
:param node_id: string object. ID of node. Default value - None.
:return: a tuple, where first value is parallelGateway ID, second a reference to created object.
|
[
"Adds",
"an",
"parallelGateway",
"element",
"to",
"BPMN",
"diagram",
"."
] |
6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629
|
https://github.com/KrzyHonk/bpmn-python/blob/6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629/bpmn_python/bpmn_diagram_rep.py#L481-L499
|
train
|
KrzyHonk/bpmn-python
|
bpmn_python/bpmn_diagram_rep.py
|
BpmnDiagramGraph.get_nodes_positions
|
def get_nodes_positions(self):
"""
Getter method for nodes positions.
:return: A dictionary with nodes as keys and positions as values
"""
nodes = self.get_nodes()
output = {}
for node in nodes:
output[node[0]] = (float(node[1][consts.Consts.x]), float(node[1][consts.Consts.y]))
return output
|
python
|
def get_nodes_positions(self):
"""
Getter method for nodes positions.
:return: A dictionary with nodes as keys and positions as values
"""
nodes = self.get_nodes()
output = {}
for node in nodes:
output[node[0]] = (float(node[1][consts.Consts.x]), float(node[1][consts.Consts.y]))
return output
|
[
"def",
"get_nodes_positions",
"(",
"self",
")",
":",
"nodes",
"=",
"self",
".",
"get_nodes",
"(",
")",
"output",
"=",
"{",
"}",
"for",
"node",
"in",
"nodes",
":",
"output",
"[",
"node",
"[",
"0",
"]",
"]",
"=",
"(",
"float",
"(",
"node",
"[",
"1",
"]",
"[",
"consts",
".",
"Consts",
".",
"x",
"]",
")",
",",
"float",
"(",
"node",
"[",
"1",
"]",
"[",
"consts",
".",
"Consts",
".",
"y",
"]",
")",
")",
"return",
"output"
] |
Getter method for nodes positions.
:return: A dictionary with nodes as keys and positions as values
|
[
"Getter",
"method",
"for",
"nodes",
"positions",
"."
] |
6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629
|
https://github.com/KrzyHonk/bpmn-python/blob/6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629/bpmn_python/bpmn_diagram_rep.py#L539-L549
|
train
|
benhoyt/scandir
|
benchmark.py
|
create_tree
|
def create_tree(path, depth=DEPTH):
"""Create a directory tree at path with given depth, and NUM_DIRS and
NUM_FILES at each level.
"""
os.mkdir(path)
for i in range(NUM_FILES):
filename = os.path.join(path, 'file{0:03}.txt'.format(i))
with open(filename, 'wb') as f:
f.write(b'foo')
if depth <= 1:
return
for i in range(NUM_DIRS):
dirname = os.path.join(path, 'dir{0:03}'.format(i))
create_tree(dirname, depth - 1)
|
python
|
def create_tree(path, depth=DEPTH):
"""Create a directory tree at path with given depth, and NUM_DIRS and
NUM_FILES at each level.
"""
os.mkdir(path)
for i in range(NUM_FILES):
filename = os.path.join(path, 'file{0:03}.txt'.format(i))
with open(filename, 'wb') as f:
f.write(b'foo')
if depth <= 1:
return
for i in range(NUM_DIRS):
dirname = os.path.join(path, 'dir{0:03}'.format(i))
create_tree(dirname, depth - 1)
|
[
"def",
"create_tree",
"(",
"path",
",",
"depth",
"=",
"DEPTH",
")",
":",
"os",
".",
"mkdir",
"(",
"path",
")",
"for",
"i",
"in",
"range",
"(",
"NUM_FILES",
")",
":",
"filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"'file{0:03}.txt'",
".",
"format",
"(",
"i",
")",
")",
"with",
"open",
"(",
"filename",
",",
"'wb'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"b'foo'",
")",
"if",
"depth",
"<=",
"1",
":",
"return",
"for",
"i",
"in",
"range",
"(",
"NUM_DIRS",
")",
":",
"dirname",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"'dir{0:03}'",
".",
"format",
"(",
"i",
")",
")",
"create_tree",
"(",
"dirname",
",",
"depth",
"-",
"1",
")"
] |
Create a directory tree at path with given depth, and NUM_DIRS and
NUM_FILES at each level.
|
[
"Create",
"a",
"directory",
"tree",
"at",
"path",
"with",
"given",
"depth",
"and",
"NUM_DIRS",
"and",
"NUM_FILES",
"at",
"each",
"level",
"."
] |
982e6ba60e7165ef965567eacd7138149c9ce292
|
https://github.com/benhoyt/scandir/blob/982e6ba60e7165ef965567eacd7138149c9ce292/benchmark.py#L47-L60
|
train
|
benhoyt/scandir
|
benchmark.py
|
get_tree_size
|
def get_tree_size(path):
"""Return total size of all files in directory tree at path."""
size = 0
try:
for entry in scandir.scandir(path):
if entry.is_symlink():
pass
elif entry.is_dir():
size += get_tree_size(os.path.join(path, entry.name))
else:
size += entry.stat().st_size
except OSError:
pass
return size
|
python
|
def get_tree_size(path):
"""Return total size of all files in directory tree at path."""
size = 0
try:
for entry in scandir.scandir(path):
if entry.is_symlink():
pass
elif entry.is_dir():
size += get_tree_size(os.path.join(path, entry.name))
else:
size += entry.stat().st_size
except OSError:
pass
return size
|
[
"def",
"get_tree_size",
"(",
"path",
")",
":",
"size",
"=",
"0",
"try",
":",
"for",
"entry",
"in",
"scandir",
".",
"scandir",
"(",
"path",
")",
":",
"if",
"entry",
".",
"is_symlink",
"(",
")",
":",
"pass",
"elif",
"entry",
".",
"is_dir",
"(",
")",
":",
"size",
"+=",
"get_tree_size",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"entry",
".",
"name",
")",
")",
"else",
":",
"size",
"+=",
"entry",
".",
"stat",
"(",
")",
".",
"st_size",
"except",
"OSError",
":",
"pass",
"return",
"size"
] |
Return total size of all files in directory tree at path.
|
[
"Return",
"total",
"size",
"of",
"all",
"files",
"in",
"directory",
"tree",
"at",
"path",
"."
] |
982e6ba60e7165ef965567eacd7138149c9ce292
|
https://github.com/benhoyt/scandir/blob/982e6ba60e7165ef965567eacd7138149c9ce292/benchmark.py#L63-L76
|
train
|
ahwillia/tensortools
|
tensortools/operations.py
|
unfold
|
def unfold(tensor, mode):
"""Returns the mode-`mode` unfolding of `tensor`.
Parameters
----------
tensor : ndarray
mode : int
Returns
-------
ndarray
unfolded_tensor of shape ``(tensor.shape[mode], -1)``
Author
------
Jean Kossaifi <https://github.com/tensorly>
"""
return np.moveaxis(tensor, mode, 0).reshape((tensor.shape[mode], -1))
|
python
|
def unfold(tensor, mode):
"""Returns the mode-`mode` unfolding of `tensor`.
Parameters
----------
tensor : ndarray
mode : int
Returns
-------
ndarray
unfolded_tensor of shape ``(tensor.shape[mode], -1)``
Author
------
Jean Kossaifi <https://github.com/tensorly>
"""
return np.moveaxis(tensor, mode, 0).reshape((tensor.shape[mode], -1))
|
[
"def",
"unfold",
"(",
"tensor",
",",
"mode",
")",
":",
"return",
"np",
".",
"moveaxis",
"(",
"tensor",
",",
"mode",
",",
"0",
")",
".",
"reshape",
"(",
"(",
"tensor",
".",
"shape",
"[",
"mode",
"]",
",",
"-",
"1",
")",
")"
] |
Returns the mode-`mode` unfolding of `tensor`.
Parameters
----------
tensor : ndarray
mode : int
Returns
-------
ndarray
unfolded_tensor of shape ``(tensor.shape[mode], -1)``
Author
------
Jean Kossaifi <https://github.com/tensorly>
|
[
"Returns",
"the",
"mode",
"-",
"mode",
"unfolding",
"of",
"tensor",
"."
] |
f375633ec621caa96665a56205dcf932590d4a6e
|
https://github.com/ahwillia/tensortools/blob/f375633ec621caa96665a56205dcf932590d4a6e/tensortools/operations.py#L11-L28
|
train
|
ahwillia/tensortools
|
tensortools/operations.py
|
khatri_rao
|
def khatri_rao(matrices):
"""Khatri-Rao product of a list of matrices.
Parameters
----------
matrices : list of ndarray
Returns
-------
khatri_rao_product: matrix of shape ``(prod(n_i), m)``
where ``prod(n_i) = prod([m.shape[0] for m in matrices])``
i.e. the product of the number of rows of all the matrices in the
product.
Author
------
Jean Kossaifi <https://github.com/tensorly>
"""
n_columns = matrices[0].shape[1]
n_factors = len(matrices)
start = ord('a')
common_dim = 'z'
target = ''.join(chr(start + i) for i in range(n_factors))
source = ','.join(i+common_dim for i in target)
operation = source+'->'+target+common_dim
return np.einsum(operation, *matrices).reshape((-1, n_columns))
|
python
|
def khatri_rao(matrices):
"""Khatri-Rao product of a list of matrices.
Parameters
----------
matrices : list of ndarray
Returns
-------
khatri_rao_product: matrix of shape ``(prod(n_i), m)``
where ``prod(n_i) = prod([m.shape[0] for m in matrices])``
i.e. the product of the number of rows of all the matrices in the
product.
Author
------
Jean Kossaifi <https://github.com/tensorly>
"""
n_columns = matrices[0].shape[1]
n_factors = len(matrices)
start = ord('a')
common_dim = 'z'
target = ''.join(chr(start + i) for i in range(n_factors))
source = ','.join(i+common_dim for i in target)
operation = source+'->'+target+common_dim
return np.einsum(operation, *matrices).reshape((-1, n_columns))
|
[
"def",
"khatri_rao",
"(",
"matrices",
")",
":",
"n_columns",
"=",
"matrices",
"[",
"0",
"]",
".",
"shape",
"[",
"1",
"]",
"n_factors",
"=",
"len",
"(",
"matrices",
")",
"start",
"=",
"ord",
"(",
"'a'",
")",
"common_dim",
"=",
"'z'",
"target",
"=",
"''",
".",
"join",
"(",
"chr",
"(",
"start",
"+",
"i",
")",
"for",
"i",
"in",
"range",
"(",
"n_factors",
")",
")",
"source",
"=",
"','",
".",
"join",
"(",
"i",
"+",
"common_dim",
"for",
"i",
"in",
"target",
")",
"operation",
"=",
"source",
"+",
"'->'",
"+",
"target",
"+",
"common_dim",
"return",
"np",
".",
"einsum",
"(",
"operation",
",",
"*",
"matrices",
")",
".",
"reshape",
"(",
"(",
"-",
"1",
",",
"n_columns",
")",
")"
] |
Khatri-Rao product of a list of matrices.
Parameters
----------
matrices : list of ndarray
Returns
-------
khatri_rao_product: matrix of shape ``(prod(n_i), m)``
where ``prod(n_i) = prod([m.shape[0] for m in matrices])``
i.e. the product of the number of rows of all the matrices in the
product.
Author
------
Jean Kossaifi <https://github.com/tensorly>
|
[
"Khatri",
"-",
"Rao",
"product",
"of",
"a",
"list",
"of",
"matrices",
"."
] |
f375633ec621caa96665a56205dcf932590d4a6e
|
https://github.com/ahwillia/tensortools/blob/f375633ec621caa96665a56205dcf932590d4a6e/tensortools/operations.py#L31-L58
|
train
|
ahwillia/tensortools
|
tensortools/utils.py
|
soft_cluster_factor
|
def soft_cluster_factor(factor):
"""Returns soft-clustering of data based on CP decomposition results.
Parameters
----------
data : ndarray, N x R matrix of nonnegative data
Datapoints are held in rows, features are held in columns
Returns
-------
cluster_ids : ndarray, vector of N integers in range(0, R)
List of soft cluster assignments for each row of data matrix
perm : ndarray, vector of N integers
Permutation / ordering of the rows of data induced by the soft
clustering.
"""
# copy factor of interest
f = np.copy(factor)
# cluster based on score of maximum absolute value
cluster_ids = np.argmax(np.abs(f), axis=1)
scores = f[range(f.shape[0]), cluster_ids]
# resort within each cluster
perm = []
for cluster in np.unique(cluster_ids):
idx = np.where(cluster_ids == cluster)[0]
perm += list(idx[np.argsort(scores[idx])][::-1])
return cluster_ids, perm
|
python
|
def soft_cluster_factor(factor):
"""Returns soft-clustering of data based on CP decomposition results.
Parameters
----------
data : ndarray, N x R matrix of nonnegative data
Datapoints are held in rows, features are held in columns
Returns
-------
cluster_ids : ndarray, vector of N integers in range(0, R)
List of soft cluster assignments for each row of data matrix
perm : ndarray, vector of N integers
Permutation / ordering of the rows of data induced by the soft
clustering.
"""
# copy factor of interest
f = np.copy(factor)
# cluster based on score of maximum absolute value
cluster_ids = np.argmax(np.abs(f), axis=1)
scores = f[range(f.shape[0]), cluster_ids]
# resort within each cluster
perm = []
for cluster in np.unique(cluster_ids):
idx = np.where(cluster_ids == cluster)[0]
perm += list(idx[np.argsort(scores[idx])][::-1])
return cluster_ids, perm
|
[
"def",
"soft_cluster_factor",
"(",
"factor",
")",
":",
"# copy factor of interest",
"f",
"=",
"np",
".",
"copy",
"(",
"factor",
")",
"# cluster based on score of maximum absolute value",
"cluster_ids",
"=",
"np",
".",
"argmax",
"(",
"np",
".",
"abs",
"(",
"f",
")",
",",
"axis",
"=",
"1",
")",
"scores",
"=",
"f",
"[",
"range",
"(",
"f",
".",
"shape",
"[",
"0",
"]",
")",
",",
"cluster_ids",
"]",
"# resort within each cluster",
"perm",
"=",
"[",
"]",
"for",
"cluster",
"in",
"np",
".",
"unique",
"(",
"cluster_ids",
")",
":",
"idx",
"=",
"np",
".",
"where",
"(",
"cluster_ids",
"==",
"cluster",
")",
"[",
"0",
"]",
"perm",
"+=",
"list",
"(",
"idx",
"[",
"np",
".",
"argsort",
"(",
"scores",
"[",
"idx",
"]",
")",
"]",
"[",
":",
":",
"-",
"1",
"]",
")",
"return",
"cluster_ids",
",",
"perm"
] |
Returns soft-clustering of data based on CP decomposition results.
Parameters
----------
data : ndarray, N x R matrix of nonnegative data
Datapoints are held in rows, features are held in columns
Returns
-------
cluster_ids : ndarray, vector of N integers in range(0, R)
List of soft cluster assignments for each row of data matrix
perm : ndarray, vector of N integers
Permutation / ordering of the rows of data induced by the soft
clustering.
|
[
"Returns",
"soft",
"-",
"clustering",
"of",
"data",
"based",
"on",
"CP",
"decomposition",
"results",
"."
] |
f375633ec621caa96665a56205dcf932590d4a6e
|
https://github.com/ahwillia/tensortools/blob/f375633ec621caa96665a56205dcf932590d4a6e/tensortools/utils.py#L12-L42
|
train
|
ahwillia/tensortools
|
tensortools/utils.py
|
hclust_linearize
|
def hclust_linearize(U):
"""Sorts the rows of a matrix by hierarchical clustering.
Parameters:
U (ndarray) : matrix of data
Returns:
prm (ndarray) : permutation of the rows
"""
from scipy.cluster import hierarchy
Z = hierarchy.ward(U)
return hierarchy.leaves_list(hierarchy.optimal_leaf_ordering(Z, U))
|
python
|
def hclust_linearize(U):
"""Sorts the rows of a matrix by hierarchical clustering.
Parameters:
U (ndarray) : matrix of data
Returns:
prm (ndarray) : permutation of the rows
"""
from scipy.cluster import hierarchy
Z = hierarchy.ward(U)
return hierarchy.leaves_list(hierarchy.optimal_leaf_ordering(Z, U))
|
[
"def",
"hclust_linearize",
"(",
"U",
")",
":",
"from",
"scipy",
".",
"cluster",
"import",
"hierarchy",
"Z",
"=",
"hierarchy",
".",
"ward",
"(",
"U",
")",
"return",
"hierarchy",
".",
"leaves_list",
"(",
"hierarchy",
".",
"optimal_leaf_ordering",
"(",
"Z",
",",
"U",
")",
")"
] |
Sorts the rows of a matrix by hierarchical clustering.
Parameters:
U (ndarray) : matrix of data
Returns:
prm (ndarray) : permutation of the rows
|
[
"Sorts",
"the",
"rows",
"of",
"a",
"matrix",
"by",
"hierarchical",
"clustering",
"."
] |
f375633ec621caa96665a56205dcf932590d4a6e
|
https://github.com/ahwillia/tensortools/blob/f375633ec621caa96665a56205dcf932590d4a6e/tensortools/utils.py#L84-L96
|
train
|
ahwillia/tensortools
|
tensortools/utils.py
|
reverse_segment
|
def reverse_segment(path, n1, n2):
"""Reverse the nodes between n1 and n2.
"""
q = path.copy()
if n2 > n1:
q[n1:(n2+1)] = path[n1:(n2+1)][::-1]
return q
else:
seg = np.hstack((path[n1:], path[:(n2+1)]))[::-1]
brk = len(q) - n1
q[n1:] = seg[:brk]
q[:(n2+1)] = seg[brk:]
return q
|
python
|
def reverse_segment(path, n1, n2):
"""Reverse the nodes between n1 and n2.
"""
q = path.copy()
if n2 > n1:
q[n1:(n2+1)] = path[n1:(n2+1)][::-1]
return q
else:
seg = np.hstack((path[n1:], path[:(n2+1)]))[::-1]
brk = len(q) - n1
q[n1:] = seg[:brk]
q[:(n2+1)] = seg[brk:]
return q
|
[
"def",
"reverse_segment",
"(",
"path",
",",
"n1",
",",
"n2",
")",
":",
"q",
"=",
"path",
".",
"copy",
"(",
")",
"if",
"n2",
">",
"n1",
":",
"q",
"[",
"n1",
":",
"(",
"n2",
"+",
"1",
")",
"]",
"=",
"path",
"[",
"n1",
":",
"(",
"n2",
"+",
"1",
")",
"]",
"[",
":",
":",
"-",
"1",
"]",
"return",
"q",
"else",
":",
"seg",
"=",
"np",
".",
"hstack",
"(",
"(",
"path",
"[",
"n1",
":",
"]",
",",
"path",
"[",
":",
"(",
"n2",
"+",
"1",
")",
"]",
")",
")",
"[",
":",
":",
"-",
"1",
"]",
"brk",
"=",
"len",
"(",
"q",
")",
"-",
"n1",
"q",
"[",
"n1",
":",
"]",
"=",
"seg",
"[",
":",
"brk",
"]",
"q",
"[",
":",
"(",
"n2",
"+",
"1",
")",
"]",
"=",
"seg",
"[",
"brk",
":",
"]",
"return",
"q"
] |
Reverse the nodes between n1 and n2.
|
[
"Reverse",
"the",
"nodes",
"between",
"n1",
"and",
"n2",
"."
] |
f375633ec621caa96665a56205dcf932590d4a6e
|
https://github.com/ahwillia/tensortools/blob/f375633ec621caa96665a56205dcf932590d4a6e/tensortools/utils.py#L99-L111
|
train
|
ahwillia/tensortools
|
tensortools/tensors.py
|
KTensor.full
|
def full(self):
"""Converts KTensor to a dense ndarray."""
# Compute tensor unfolding along first mode
unf = sci.dot(self.factors[0], khatri_rao(self.factors[1:]).T)
# Inverse unfolding along first mode
return sci.reshape(unf, self.shape)
|
python
|
def full(self):
"""Converts KTensor to a dense ndarray."""
# Compute tensor unfolding along first mode
unf = sci.dot(self.factors[0], khatri_rao(self.factors[1:]).T)
# Inverse unfolding along first mode
return sci.reshape(unf, self.shape)
|
[
"def",
"full",
"(",
"self",
")",
":",
"# Compute tensor unfolding along first mode",
"unf",
"=",
"sci",
".",
"dot",
"(",
"self",
".",
"factors",
"[",
"0",
"]",
",",
"khatri_rao",
"(",
"self",
".",
"factors",
"[",
"1",
":",
"]",
")",
".",
"T",
")",
"# Inverse unfolding along first mode",
"return",
"sci",
".",
"reshape",
"(",
"unf",
",",
"self",
".",
"shape",
")"
] |
Converts KTensor to a dense ndarray.
|
[
"Converts",
"KTensor",
"to",
"a",
"dense",
"ndarray",
"."
] |
f375633ec621caa96665a56205dcf932590d4a6e
|
https://github.com/ahwillia/tensortools/blob/f375633ec621caa96665a56205dcf932590d4a6e/tensortools/tensors.py#L41-L48
|
train
|
ahwillia/tensortools
|
tensortools/tensors.py
|
KTensor.rebalance
|
def rebalance(self):
"""Rescales factors across modes so that all norms match.
"""
# Compute norms along columns for each factor matrix
norms = [sci.linalg.norm(f, axis=0) for f in self.factors]
# Multiply norms across all modes
lam = sci.multiply.reduce(norms) ** (1/self.ndim)
# Update factors
self.factors = [f * (lam / fn) for f, fn in zip(self.factors, norms)]
return self
|
python
|
def rebalance(self):
"""Rescales factors across modes so that all norms match.
"""
# Compute norms along columns for each factor matrix
norms = [sci.linalg.norm(f, axis=0) for f in self.factors]
# Multiply norms across all modes
lam = sci.multiply.reduce(norms) ** (1/self.ndim)
# Update factors
self.factors = [f * (lam / fn) for f, fn in zip(self.factors, norms)]
return self
|
[
"def",
"rebalance",
"(",
"self",
")",
":",
"# Compute norms along columns for each factor matrix",
"norms",
"=",
"[",
"sci",
".",
"linalg",
".",
"norm",
"(",
"f",
",",
"axis",
"=",
"0",
")",
"for",
"f",
"in",
"self",
".",
"factors",
"]",
"# Multiply norms across all modes",
"lam",
"=",
"sci",
".",
"multiply",
".",
"reduce",
"(",
"norms",
")",
"**",
"(",
"1",
"/",
"self",
".",
"ndim",
")",
"# Update factors",
"self",
".",
"factors",
"=",
"[",
"f",
"*",
"(",
"lam",
"/",
"fn",
")",
"for",
"f",
",",
"fn",
"in",
"zip",
"(",
"self",
".",
"factors",
",",
"norms",
")",
"]",
"return",
"self"
] |
Rescales factors across modes so that all norms match.
|
[
"Rescales",
"factors",
"across",
"modes",
"so",
"that",
"all",
"norms",
"match",
"."
] |
f375633ec621caa96665a56205dcf932590d4a6e
|
https://github.com/ahwillia/tensortools/blob/f375633ec621caa96665a56205dcf932590d4a6e/tensortools/tensors.py#L50-L62
|
train
|
ahwillia/tensortools
|
tensortools/tensors.py
|
KTensor.permute
|
def permute(self, idx):
"""Permutes the columns of the factor matrices inplace
"""
# Check that input is a true permutation
if set(idx) != set(range(self.rank)):
raise ValueError('Invalid permutation specified.')
# Update factors
self.factors = [f[:, idx] for f in self.factors]
return self.factors
|
python
|
def permute(self, idx):
"""Permutes the columns of the factor matrices inplace
"""
# Check that input is a true permutation
if set(idx) != set(range(self.rank)):
raise ValueError('Invalid permutation specified.')
# Update factors
self.factors = [f[:, idx] for f in self.factors]
return self.factors
|
[
"def",
"permute",
"(",
"self",
",",
"idx",
")",
":",
"# Check that input is a true permutation",
"if",
"set",
"(",
"idx",
")",
"!=",
"set",
"(",
"range",
"(",
"self",
".",
"rank",
")",
")",
":",
"raise",
"ValueError",
"(",
"'Invalid permutation specified.'",
")",
"# Update factors",
"self",
".",
"factors",
"=",
"[",
"f",
"[",
":",
",",
"idx",
"]",
"for",
"f",
"in",
"self",
".",
"factors",
"]",
"return",
"self",
".",
"factors"
] |
Permutes the columns of the factor matrices inplace
|
[
"Permutes",
"the",
"columns",
"of",
"the",
"factor",
"matrices",
"inplace"
] |
f375633ec621caa96665a56205dcf932590d4a6e
|
https://github.com/ahwillia/tensortools/blob/f375633ec621caa96665a56205dcf932590d4a6e/tensortools/tensors.py#L64-L74
|
train
|
ahwillia/tensortools
|
tensortools/diagnostics.py
|
kruskal_align
|
def kruskal_align(U, V, permute_U=False, permute_V=False):
"""Aligns two KTensors and returns a similarity score.
Parameters
----------
U : KTensor
First kruskal tensor to align.
V : KTensor
Second kruskal tensor to align.
permute_U : bool
If True, modifies 'U' to align the KTensors (default is False).
permute_V : bool
If True, modifies 'V' to align the KTensors (default is False).
Notes
-----
If both `permute_U` and `permute_V` are both set to True, then the
factors are ordered from most to least similar. If only one is
True then the factors on the modified KTensor are re-ordered to
match the factors in the un-aligned KTensor.
Returns
-------
similarity : float
Similarity score between zero and one.
"""
# Compute similarity matrices.
unrm = [f / np.linalg.norm(f, axis=0) for f in U.factors]
vnrm = [f / np.linalg.norm(f, axis=0) for f in V.factors]
sim_matrices = [np.dot(u.T, v) for u, v in zip(unrm, vnrm)]
cost = 1 - np.mean(np.abs(sim_matrices), axis=0)
# Solve matching problem via Hungarian algorithm.
indices = Munkres().compute(cost.copy())
prmU, prmV = zip(*indices)
# Compute mean factor similarity given the optimal matching.
similarity = np.mean(1 - cost[prmU, prmV])
# If U and V are of different ranks, identify unmatched factors.
unmatched_U = list(set(range(U.rank)) - set(prmU))
unmatched_V = list(set(range(V.rank)) - set(prmV))
# If permuting both U and V, order factors from most to least similar.
if permute_U and permute_V:
idx = np.argsort(cost[prmU, prmV])
# If permute_U is False, then order the factors such that the ordering
# for U is unchanged.
elif permute_V:
idx = np.argsort(prmU)
# If permute_V is False, then order the factors such that the ordering
# for V is unchanged.
elif permute_U:
idx = np.argsort(prmV)
# If permute_U and permute_V are both False, then we are done and can
# simply return the similarity.
else:
return similarity
# Re-order the factor permutations.
prmU = [prmU[i] for i in idx]
prmV = [prmV[i] for i in idx]
# Permute the factors.
if permute_U:
U.permute(prmU)
if permute_V:
V.permute(prmV)
# Flip the signs of factors.
flips = np.sign([F[prmU, prmV] for F in sim_matrices])
flips[0] *= np.prod(flips, axis=0) # always flip an even number of factors
if permute_U:
for i, f in enumerate(flips):
U.factors[i] *= f
elif permute_V:
for i, f in enumerate(flips):
V.factors[i] *= f
# Return the similarity score
return similarity
|
python
|
def kruskal_align(U, V, permute_U=False, permute_V=False):
"""Aligns two KTensors and returns a similarity score.
Parameters
----------
U : KTensor
First kruskal tensor to align.
V : KTensor
Second kruskal tensor to align.
permute_U : bool
If True, modifies 'U' to align the KTensors (default is False).
permute_V : bool
If True, modifies 'V' to align the KTensors (default is False).
Notes
-----
If both `permute_U` and `permute_V` are both set to True, then the
factors are ordered from most to least similar. If only one is
True then the factors on the modified KTensor are re-ordered to
match the factors in the un-aligned KTensor.
Returns
-------
similarity : float
Similarity score between zero and one.
"""
# Compute similarity matrices.
unrm = [f / np.linalg.norm(f, axis=0) for f in U.factors]
vnrm = [f / np.linalg.norm(f, axis=0) for f in V.factors]
sim_matrices = [np.dot(u.T, v) for u, v in zip(unrm, vnrm)]
cost = 1 - np.mean(np.abs(sim_matrices), axis=0)
# Solve matching problem via Hungarian algorithm.
indices = Munkres().compute(cost.copy())
prmU, prmV = zip(*indices)
# Compute mean factor similarity given the optimal matching.
similarity = np.mean(1 - cost[prmU, prmV])
# If U and V are of different ranks, identify unmatched factors.
unmatched_U = list(set(range(U.rank)) - set(prmU))
unmatched_V = list(set(range(V.rank)) - set(prmV))
# If permuting both U and V, order factors from most to least similar.
if permute_U and permute_V:
idx = np.argsort(cost[prmU, prmV])
# If permute_U is False, then order the factors such that the ordering
# for U is unchanged.
elif permute_V:
idx = np.argsort(prmU)
# If permute_V is False, then order the factors such that the ordering
# for V is unchanged.
elif permute_U:
idx = np.argsort(prmV)
# If permute_U and permute_V are both False, then we are done and can
# simply return the similarity.
else:
return similarity
# Re-order the factor permutations.
prmU = [prmU[i] for i in idx]
prmV = [prmV[i] for i in idx]
# Permute the factors.
if permute_U:
U.permute(prmU)
if permute_V:
V.permute(prmV)
# Flip the signs of factors.
flips = np.sign([F[prmU, prmV] for F in sim_matrices])
flips[0] *= np.prod(flips, axis=0) # always flip an even number of factors
if permute_U:
for i, f in enumerate(flips):
U.factors[i] *= f
elif permute_V:
for i, f in enumerate(flips):
V.factors[i] *= f
# Return the similarity score
return similarity
|
[
"def",
"kruskal_align",
"(",
"U",
",",
"V",
",",
"permute_U",
"=",
"False",
",",
"permute_V",
"=",
"False",
")",
":",
"# Compute similarity matrices.",
"unrm",
"=",
"[",
"f",
"/",
"np",
".",
"linalg",
".",
"norm",
"(",
"f",
",",
"axis",
"=",
"0",
")",
"for",
"f",
"in",
"U",
".",
"factors",
"]",
"vnrm",
"=",
"[",
"f",
"/",
"np",
".",
"linalg",
".",
"norm",
"(",
"f",
",",
"axis",
"=",
"0",
")",
"for",
"f",
"in",
"V",
".",
"factors",
"]",
"sim_matrices",
"=",
"[",
"np",
".",
"dot",
"(",
"u",
".",
"T",
",",
"v",
")",
"for",
"u",
",",
"v",
"in",
"zip",
"(",
"unrm",
",",
"vnrm",
")",
"]",
"cost",
"=",
"1",
"-",
"np",
".",
"mean",
"(",
"np",
".",
"abs",
"(",
"sim_matrices",
")",
",",
"axis",
"=",
"0",
")",
"# Solve matching problem via Hungarian algorithm.",
"indices",
"=",
"Munkres",
"(",
")",
".",
"compute",
"(",
"cost",
".",
"copy",
"(",
")",
")",
"prmU",
",",
"prmV",
"=",
"zip",
"(",
"*",
"indices",
")",
"# Compute mean factor similarity given the optimal matching.",
"similarity",
"=",
"np",
".",
"mean",
"(",
"1",
"-",
"cost",
"[",
"prmU",
",",
"prmV",
"]",
")",
"# If U and V are of different ranks, identify unmatched factors.",
"unmatched_U",
"=",
"list",
"(",
"set",
"(",
"range",
"(",
"U",
".",
"rank",
")",
")",
"-",
"set",
"(",
"prmU",
")",
")",
"unmatched_V",
"=",
"list",
"(",
"set",
"(",
"range",
"(",
"V",
".",
"rank",
")",
")",
"-",
"set",
"(",
"prmV",
")",
")",
"# If permuting both U and V, order factors from most to least similar.",
"if",
"permute_U",
"and",
"permute_V",
":",
"idx",
"=",
"np",
".",
"argsort",
"(",
"cost",
"[",
"prmU",
",",
"prmV",
"]",
")",
"# If permute_U is False, then order the factors such that the ordering",
"# for U is unchanged.",
"elif",
"permute_V",
":",
"idx",
"=",
"np",
".",
"argsort",
"(",
"prmU",
")",
"# If permute_V is False, then order the factors such that the ordering",
"# for V is unchanged.",
"elif",
"permute_U",
":",
"idx",
"=",
"np",
".",
"argsort",
"(",
"prmV",
")",
"# If permute_U and permute_V are both False, then we are done and can",
"# simply return the similarity.",
"else",
":",
"return",
"similarity",
"# Re-order the factor permutations.",
"prmU",
"=",
"[",
"prmU",
"[",
"i",
"]",
"for",
"i",
"in",
"idx",
"]",
"prmV",
"=",
"[",
"prmV",
"[",
"i",
"]",
"for",
"i",
"in",
"idx",
"]",
"# Permute the factors.",
"if",
"permute_U",
":",
"U",
".",
"permute",
"(",
"prmU",
")",
"if",
"permute_V",
":",
"V",
".",
"permute",
"(",
"prmV",
")",
"# Flip the signs of factors.",
"flips",
"=",
"np",
".",
"sign",
"(",
"[",
"F",
"[",
"prmU",
",",
"prmV",
"]",
"for",
"F",
"in",
"sim_matrices",
"]",
")",
"flips",
"[",
"0",
"]",
"*=",
"np",
".",
"prod",
"(",
"flips",
",",
"axis",
"=",
"0",
")",
"# always flip an even number of factors",
"if",
"permute_U",
":",
"for",
"i",
",",
"f",
"in",
"enumerate",
"(",
"flips",
")",
":",
"U",
".",
"factors",
"[",
"i",
"]",
"*=",
"f",
"elif",
"permute_V",
":",
"for",
"i",
",",
"f",
"in",
"enumerate",
"(",
"flips",
")",
":",
"V",
".",
"factors",
"[",
"i",
"]",
"*=",
"f",
"# Return the similarity score",
"return",
"similarity"
] |
Aligns two KTensors and returns a similarity score.
Parameters
----------
U : KTensor
First kruskal tensor to align.
V : KTensor
Second kruskal tensor to align.
permute_U : bool
If True, modifies 'U' to align the KTensors (default is False).
permute_V : bool
If True, modifies 'V' to align the KTensors (default is False).
Notes
-----
If both `permute_U` and `permute_V` are both set to True, then the
factors are ordered from most to least similar. If only one is
True then the factors on the modified KTensor are re-ordered to
match the factors in the un-aligned KTensor.
Returns
-------
similarity : float
Similarity score between zero and one.
|
[
"Aligns",
"two",
"KTensors",
"and",
"returns",
"a",
"similarity",
"score",
"."
] |
f375633ec621caa96665a56205dcf932590d4a6e
|
https://github.com/ahwillia/tensortools/blob/f375633ec621caa96665a56205dcf932590d4a6e/tensortools/diagnostics.py#L9-L95
|
train
|
ahwillia/tensortools
|
tensortools/visualization.py
|
plot_objective
|
def plot_objective(ensemble, partition='train', ax=None, jitter=0.1,
scatter_kw=dict(), line_kw=dict()):
"""Plots objective function as a function of model rank.
Parameters
----------
ensemble : Ensemble object
holds optimization results across a range of model ranks
partition : string, one of: {'train', 'test'}
specifies whether to plot the objective function on the training
data or the held-out test set.
ax : matplotlib axis (optional)
axis to plot on (defaults to current axis object)
jitter : float (optional)
amount of horizontal jitter added to scatterpoints (default=0.1)
scatter_kw : dict (optional)
keyword arguments for styling the scatterpoints
line_kw : dict (optional)
keyword arguments for styling the line
"""
if ax is None:
ax = plt.gca()
if partition == 'train':
pass
elif partition == 'test':
raise NotImplementedError('Cross-validation is on the TODO list.')
else:
raise ValueError("partition must be 'train' or 'test'.")
# compile statistics for plotting
x, obj, min_obj = [], [], []
for rank in sorted(ensemble.results):
# reconstruction errors for rank-r models
o = ensemble.objectives(rank)
obj.extend(o)
x.extend(np.full(len(o), rank))
min_obj.append(min(o))
# add horizontal jitter
ux = np.unique(x)
x = np.array(x) + (np.random.rand(len(x))-0.5)*jitter
# make plot
ax.scatter(x, obj, **scatter_kw)
ax.plot(ux, min_obj, **line_kw)
ax.set_xlabel('model rank')
ax.set_ylabel('objective')
return ax
|
python
|
def plot_objective(ensemble, partition='train', ax=None, jitter=0.1,
scatter_kw=dict(), line_kw=dict()):
"""Plots objective function as a function of model rank.
Parameters
----------
ensemble : Ensemble object
holds optimization results across a range of model ranks
partition : string, one of: {'train', 'test'}
specifies whether to plot the objective function on the training
data or the held-out test set.
ax : matplotlib axis (optional)
axis to plot on (defaults to current axis object)
jitter : float (optional)
amount of horizontal jitter added to scatterpoints (default=0.1)
scatter_kw : dict (optional)
keyword arguments for styling the scatterpoints
line_kw : dict (optional)
keyword arguments for styling the line
"""
if ax is None:
ax = plt.gca()
if partition == 'train':
pass
elif partition == 'test':
raise NotImplementedError('Cross-validation is on the TODO list.')
else:
raise ValueError("partition must be 'train' or 'test'.")
# compile statistics for plotting
x, obj, min_obj = [], [], []
for rank in sorted(ensemble.results):
# reconstruction errors for rank-r models
o = ensemble.objectives(rank)
obj.extend(o)
x.extend(np.full(len(o), rank))
min_obj.append(min(o))
# add horizontal jitter
ux = np.unique(x)
x = np.array(x) + (np.random.rand(len(x))-0.5)*jitter
# make plot
ax.scatter(x, obj, **scatter_kw)
ax.plot(ux, min_obj, **line_kw)
ax.set_xlabel('model rank')
ax.set_ylabel('objective')
return ax
|
[
"def",
"plot_objective",
"(",
"ensemble",
",",
"partition",
"=",
"'train'",
",",
"ax",
"=",
"None",
",",
"jitter",
"=",
"0.1",
",",
"scatter_kw",
"=",
"dict",
"(",
")",
",",
"line_kw",
"=",
"dict",
"(",
")",
")",
":",
"if",
"ax",
"is",
"None",
":",
"ax",
"=",
"plt",
".",
"gca",
"(",
")",
"if",
"partition",
"==",
"'train'",
":",
"pass",
"elif",
"partition",
"==",
"'test'",
":",
"raise",
"NotImplementedError",
"(",
"'Cross-validation is on the TODO list.'",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"partition must be 'train' or 'test'.\"",
")",
"# compile statistics for plotting",
"x",
",",
"obj",
",",
"min_obj",
"=",
"[",
"]",
",",
"[",
"]",
",",
"[",
"]",
"for",
"rank",
"in",
"sorted",
"(",
"ensemble",
".",
"results",
")",
":",
"# reconstruction errors for rank-r models",
"o",
"=",
"ensemble",
".",
"objectives",
"(",
"rank",
")",
"obj",
".",
"extend",
"(",
"o",
")",
"x",
".",
"extend",
"(",
"np",
".",
"full",
"(",
"len",
"(",
"o",
")",
",",
"rank",
")",
")",
"min_obj",
".",
"append",
"(",
"min",
"(",
"o",
")",
")",
"# add horizontal jitter",
"ux",
"=",
"np",
".",
"unique",
"(",
"x",
")",
"x",
"=",
"np",
".",
"array",
"(",
"x",
")",
"+",
"(",
"np",
".",
"random",
".",
"rand",
"(",
"len",
"(",
"x",
")",
")",
"-",
"0.5",
")",
"*",
"jitter",
"# make plot",
"ax",
".",
"scatter",
"(",
"x",
",",
"obj",
",",
"*",
"*",
"scatter_kw",
")",
"ax",
".",
"plot",
"(",
"ux",
",",
"min_obj",
",",
"*",
"*",
"line_kw",
")",
"ax",
".",
"set_xlabel",
"(",
"'model rank'",
")",
"ax",
".",
"set_ylabel",
"(",
"'objective'",
")",
"return",
"ax"
] |
Plots objective function as a function of model rank.
Parameters
----------
ensemble : Ensemble object
holds optimization results across a range of model ranks
partition : string, one of: {'train', 'test'}
specifies whether to plot the objective function on the training
data or the held-out test set.
ax : matplotlib axis (optional)
axis to plot on (defaults to current axis object)
jitter : float (optional)
amount of horizontal jitter added to scatterpoints (default=0.1)
scatter_kw : dict (optional)
keyword arguments for styling the scatterpoints
line_kw : dict (optional)
keyword arguments for styling the line
|
[
"Plots",
"objective",
"function",
"as",
"a",
"function",
"of",
"model",
"rank",
"."
] |
f375633ec621caa96665a56205dcf932590d4a6e
|
https://github.com/ahwillia/tensortools/blob/f375633ec621caa96665a56205dcf932590d4a6e/tensortools/visualization.py#L11-L61
|
train
|
ahwillia/tensortools
|
tensortools/visualization.py
|
plot_similarity
|
def plot_similarity(ensemble, ax=None, jitter=0.1,
scatter_kw=dict(), line_kw=dict()):
"""Plots similarity across optimization runs as a function of model rank.
Parameters
----------
ensemble : Ensemble object
holds optimization results across a range of model ranks
ax : matplotlib axis (optional)
axis to plot on (defaults to current axis object)
jitter : float (optional)
amount of horizontal jitter added to scatterpoints (default=0.1)
scatter_kw : dict (optional)
keyword arguments for styling the scatterpoints
line_kw : dict (optional)
keyword arguments for styling the line
References
----------
Ulrike von Luxburg (2010). Clustering Stability: An Overview.
Foundations and Trends in Machine Learning.
https://arxiv.org/abs/1007.1075
"""
if ax is None:
ax = plt.gca()
# compile statistics for plotting
x, sim, mean_sim = [], [], []
for rank in sorted(ensemble.results):
# reconstruction errors for rank-r models
s = ensemble.similarities(rank)[1:]
sim.extend(s)
x.extend(np.full(len(s), rank))
mean_sim.append(np.mean(s))
# add horizontal jitter
ux = np.unique(x)
x = np.array(x) + (np.random.rand(len(x))-0.5)*jitter
# make plot
ax.scatter(x, sim, **scatter_kw)
ax.plot(ux, mean_sim, **line_kw)
ax.set_xlabel('model rank')
ax.set_ylabel('model similarity')
ax.set_ylim([0, 1.1])
return ax
|
python
|
def plot_similarity(ensemble, ax=None, jitter=0.1,
scatter_kw=dict(), line_kw=dict()):
"""Plots similarity across optimization runs as a function of model rank.
Parameters
----------
ensemble : Ensemble object
holds optimization results across a range of model ranks
ax : matplotlib axis (optional)
axis to plot on (defaults to current axis object)
jitter : float (optional)
amount of horizontal jitter added to scatterpoints (default=0.1)
scatter_kw : dict (optional)
keyword arguments for styling the scatterpoints
line_kw : dict (optional)
keyword arguments for styling the line
References
----------
Ulrike von Luxburg (2010). Clustering Stability: An Overview.
Foundations and Trends in Machine Learning.
https://arxiv.org/abs/1007.1075
"""
if ax is None:
ax = plt.gca()
# compile statistics for plotting
x, sim, mean_sim = [], [], []
for rank in sorted(ensemble.results):
# reconstruction errors for rank-r models
s = ensemble.similarities(rank)[1:]
sim.extend(s)
x.extend(np.full(len(s), rank))
mean_sim.append(np.mean(s))
# add horizontal jitter
ux = np.unique(x)
x = np.array(x) + (np.random.rand(len(x))-0.5)*jitter
# make plot
ax.scatter(x, sim, **scatter_kw)
ax.plot(ux, mean_sim, **line_kw)
ax.set_xlabel('model rank')
ax.set_ylabel('model similarity')
ax.set_ylim([0, 1.1])
return ax
|
[
"def",
"plot_similarity",
"(",
"ensemble",
",",
"ax",
"=",
"None",
",",
"jitter",
"=",
"0.1",
",",
"scatter_kw",
"=",
"dict",
"(",
")",
",",
"line_kw",
"=",
"dict",
"(",
")",
")",
":",
"if",
"ax",
"is",
"None",
":",
"ax",
"=",
"plt",
".",
"gca",
"(",
")",
"# compile statistics for plotting",
"x",
",",
"sim",
",",
"mean_sim",
"=",
"[",
"]",
",",
"[",
"]",
",",
"[",
"]",
"for",
"rank",
"in",
"sorted",
"(",
"ensemble",
".",
"results",
")",
":",
"# reconstruction errors for rank-r models",
"s",
"=",
"ensemble",
".",
"similarities",
"(",
"rank",
")",
"[",
"1",
":",
"]",
"sim",
".",
"extend",
"(",
"s",
")",
"x",
".",
"extend",
"(",
"np",
".",
"full",
"(",
"len",
"(",
"s",
")",
",",
"rank",
")",
")",
"mean_sim",
".",
"append",
"(",
"np",
".",
"mean",
"(",
"s",
")",
")",
"# add horizontal jitter",
"ux",
"=",
"np",
".",
"unique",
"(",
"x",
")",
"x",
"=",
"np",
".",
"array",
"(",
"x",
")",
"+",
"(",
"np",
".",
"random",
".",
"rand",
"(",
"len",
"(",
"x",
")",
")",
"-",
"0.5",
")",
"*",
"jitter",
"# make plot",
"ax",
".",
"scatter",
"(",
"x",
",",
"sim",
",",
"*",
"*",
"scatter_kw",
")",
"ax",
".",
"plot",
"(",
"ux",
",",
"mean_sim",
",",
"*",
"*",
"line_kw",
")",
"ax",
".",
"set_xlabel",
"(",
"'model rank'",
")",
"ax",
".",
"set_ylabel",
"(",
"'model similarity'",
")",
"ax",
".",
"set_ylim",
"(",
"[",
"0",
",",
"1.1",
"]",
")",
"return",
"ax"
] |
Plots similarity across optimization runs as a function of model rank.
Parameters
----------
ensemble : Ensemble object
holds optimization results across a range of model ranks
ax : matplotlib axis (optional)
axis to plot on (defaults to current axis object)
jitter : float (optional)
amount of horizontal jitter added to scatterpoints (default=0.1)
scatter_kw : dict (optional)
keyword arguments for styling the scatterpoints
line_kw : dict (optional)
keyword arguments for styling the line
References
----------
Ulrike von Luxburg (2010). Clustering Stability: An Overview.
Foundations and Trends in Machine Learning.
https://arxiv.org/abs/1007.1075
|
[
"Plots",
"similarity",
"across",
"optimization",
"runs",
"as",
"a",
"function",
"of",
"model",
"rank",
"."
] |
f375633ec621caa96665a56205dcf932590d4a6e
|
https://github.com/ahwillia/tensortools/blob/f375633ec621caa96665a56205dcf932590d4a6e/tensortools/visualization.py#L64-L113
|
train
|
ahwillia/tensortools
|
tensortools/visualization.py
|
_broadcast_arg
|
def _broadcast_arg(U, arg, argtype, name):
"""Broadcasts plotting option `arg` to all factors.
Args:
U : KTensor
arg : argument provided by the user
argtype : expected type for arg
name : name of the variable, used for error handling
Returns:
iterable version of arg of length U.ndim
"""
# if input is not iterable, broadcast it all dimensions of the tensor
if arg is None or isinstance(arg, argtype):
return [arg for _ in range(U.ndim)]
# check if iterable input is valid
elif np.iterable(arg):
if len(arg) != U.ndim:
raise ValueError('Parameter {} was specified as a sequence of '
'incorrect length. The length must match the '
'number of tensor dimensions '
'(U.ndim={})'.format(name, U.ndim))
elif not all([isinstance(a, argtype) for a in arg]):
raise TypeError('Parameter {} specified as a sequence of '
'incorrect type. '
'Expected {}.'.format(name, argtype))
else:
return arg
# input is not iterable and is not the corrent type.
else:
raise TypeError('Parameter {} specified as a {}.'
' Expected {}.'.format(name, type(arg), argtype))
|
python
|
def _broadcast_arg(U, arg, argtype, name):
"""Broadcasts plotting option `arg` to all factors.
Args:
U : KTensor
arg : argument provided by the user
argtype : expected type for arg
name : name of the variable, used for error handling
Returns:
iterable version of arg of length U.ndim
"""
# if input is not iterable, broadcast it all dimensions of the tensor
if arg is None or isinstance(arg, argtype):
return [arg for _ in range(U.ndim)]
# check if iterable input is valid
elif np.iterable(arg):
if len(arg) != U.ndim:
raise ValueError('Parameter {} was specified as a sequence of '
'incorrect length. The length must match the '
'number of tensor dimensions '
'(U.ndim={})'.format(name, U.ndim))
elif not all([isinstance(a, argtype) for a in arg]):
raise TypeError('Parameter {} specified as a sequence of '
'incorrect type. '
'Expected {}.'.format(name, argtype))
else:
return arg
# input is not iterable and is not the corrent type.
else:
raise TypeError('Parameter {} specified as a {}.'
' Expected {}.'.format(name, type(arg), argtype))
|
[
"def",
"_broadcast_arg",
"(",
"U",
",",
"arg",
",",
"argtype",
",",
"name",
")",
":",
"# if input is not iterable, broadcast it all dimensions of the tensor",
"if",
"arg",
"is",
"None",
"or",
"isinstance",
"(",
"arg",
",",
"argtype",
")",
":",
"return",
"[",
"arg",
"for",
"_",
"in",
"range",
"(",
"U",
".",
"ndim",
")",
"]",
"# check if iterable input is valid",
"elif",
"np",
".",
"iterable",
"(",
"arg",
")",
":",
"if",
"len",
"(",
"arg",
")",
"!=",
"U",
".",
"ndim",
":",
"raise",
"ValueError",
"(",
"'Parameter {} was specified as a sequence of '",
"'incorrect length. The length must match the '",
"'number of tensor dimensions '",
"'(U.ndim={})'",
".",
"format",
"(",
"name",
",",
"U",
".",
"ndim",
")",
")",
"elif",
"not",
"all",
"(",
"[",
"isinstance",
"(",
"a",
",",
"argtype",
")",
"for",
"a",
"in",
"arg",
"]",
")",
":",
"raise",
"TypeError",
"(",
"'Parameter {} specified as a sequence of '",
"'incorrect type. '",
"'Expected {}.'",
".",
"format",
"(",
"name",
",",
"argtype",
")",
")",
"else",
":",
"return",
"arg",
"# input is not iterable and is not the corrent type.",
"else",
":",
"raise",
"TypeError",
"(",
"'Parameter {} specified as a {}.'",
"' Expected {}.'",
".",
"format",
"(",
"name",
",",
"type",
"(",
"arg",
")",
",",
"argtype",
")",
")"
] |
Broadcasts plotting option `arg` to all factors.
Args:
U : KTensor
arg : argument provided by the user
argtype : expected type for arg
name : name of the variable, used for error handling
Returns:
iterable version of arg of length U.ndim
|
[
"Broadcasts",
"plotting",
"option",
"arg",
"to",
"all",
"factors",
"."
] |
f375633ec621caa96665a56205dcf932590d4a6e
|
https://github.com/ahwillia/tensortools/blob/f375633ec621caa96665a56205dcf932590d4a6e/tensortools/visualization.py#L248-L282
|
train
|
ahwillia/tensortools
|
tensortools/optimize/optim_utils.py
|
_check_cpd_inputs
|
def _check_cpd_inputs(X, rank):
"""Checks that inputs to optimization function are appropriate.
Parameters
----------
X : ndarray
Tensor used for fitting CP decomposition.
rank : int
Rank of low rank decomposition.
Raises
------
ValueError: If inputs are not suited for CP decomposition.
"""
if X.ndim < 3:
raise ValueError("Array with X.ndim > 2 expected.")
if rank <= 0 or not isinstance(rank, int):
raise ValueError("Rank is invalid.")
|
python
|
def _check_cpd_inputs(X, rank):
"""Checks that inputs to optimization function are appropriate.
Parameters
----------
X : ndarray
Tensor used for fitting CP decomposition.
rank : int
Rank of low rank decomposition.
Raises
------
ValueError: If inputs are not suited for CP decomposition.
"""
if X.ndim < 3:
raise ValueError("Array with X.ndim > 2 expected.")
if rank <= 0 or not isinstance(rank, int):
raise ValueError("Rank is invalid.")
|
[
"def",
"_check_cpd_inputs",
"(",
"X",
",",
"rank",
")",
":",
"if",
"X",
".",
"ndim",
"<",
"3",
":",
"raise",
"ValueError",
"(",
"\"Array with X.ndim > 2 expected.\"",
")",
"if",
"rank",
"<=",
"0",
"or",
"not",
"isinstance",
"(",
"rank",
",",
"int",
")",
":",
"raise",
"ValueError",
"(",
"\"Rank is invalid.\"",
")"
] |
Checks that inputs to optimization function are appropriate.
Parameters
----------
X : ndarray
Tensor used for fitting CP decomposition.
rank : int
Rank of low rank decomposition.
Raises
------
ValueError: If inputs are not suited for CP decomposition.
|
[
"Checks",
"that",
"inputs",
"to",
"optimization",
"function",
"are",
"appropriate",
"."
] |
f375633ec621caa96665a56205dcf932590d4a6e
|
https://github.com/ahwillia/tensortools/blob/f375633ec621caa96665a56205dcf932590d4a6e/tensortools/optimize/optim_utils.py#L11-L28
|
train
|
ahwillia/tensortools
|
tensortools/data/random_tensor.py
|
_check_random_state
|
def _check_random_state(random_state):
"""Checks and processes user input for seeding random numbers.
Parameters
----------
random_state : int, RandomState instance or None
If int, a RandomState instance is created with this integer seed.
If RandomState instance, random_state is returned;
If None, a RandomState instance is created with arbitrary seed.
Returns
-------
scipy.random.RandomState instance
Raises
------
TypeError
If ``random_state`` is not appropriately set.
"""
if random_state is None or isinstance(random_state, int):
return sci.random.RandomState(random_state)
elif isinstance(random_state, sci.random.RandomState):
return random_state
else:
raise TypeError('Seed should be None, int or np.random.RandomState')
|
python
|
def _check_random_state(random_state):
"""Checks and processes user input for seeding random numbers.
Parameters
----------
random_state : int, RandomState instance or None
If int, a RandomState instance is created with this integer seed.
If RandomState instance, random_state is returned;
If None, a RandomState instance is created with arbitrary seed.
Returns
-------
scipy.random.RandomState instance
Raises
------
TypeError
If ``random_state`` is not appropriately set.
"""
if random_state is None or isinstance(random_state, int):
return sci.random.RandomState(random_state)
elif isinstance(random_state, sci.random.RandomState):
return random_state
else:
raise TypeError('Seed should be None, int or np.random.RandomState')
|
[
"def",
"_check_random_state",
"(",
"random_state",
")",
":",
"if",
"random_state",
"is",
"None",
"or",
"isinstance",
"(",
"random_state",
",",
"int",
")",
":",
"return",
"sci",
".",
"random",
".",
"RandomState",
"(",
"random_state",
")",
"elif",
"isinstance",
"(",
"random_state",
",",
"sci",
".",
"random",
".",
"RandomState",
")",
":",
"return",
"random_state",
"else",
":",
"raise",
"TypeError",
"(",
"'Seed should be None, int or np.random.RandomState'",
")"
] |
Checks and processes user input for seeding random numbers.
Parameters
----------
random_state : int, RandomState instance or None
If int, a RandomState instance is created with this integer seed.
If RandomState instance, random_state is returned;
If None, a RandomState instance is created with arbitrary seed.
Returns
-------
scipy.random.RandomState instance
Raises
------
TypeError
If ``random_state`` is not appropriately set.
|
[
"Checks",
"and",
"processes",
"user",
"input",
"for",
"seeding",
"random",
"numbers",
"."
] |
f375633ec621caa96665a56205dcf932590d4a6e
|
https://github.com/ahwillia/tensortools/blob/f375633ec621caa96665a56205dcf932590d4a6e/tensortools/data/random_tensor.py#L10-L34
|
train
|
ahwillia/tensortools
|
tensortools/data/random_tensor.py
|
randn_ktensor
|
def randn_ktensor(shape, rank, norm=None, random_state=None):
"""
Generates a random N-way tensor with rank R, where the entries are
drawn from the standard normal distribution.
Parameters
----------
shape : tuple
shape of the tensor
rank : integer
rank of the tensor
norm : float or None, optional (defaults: None)
If not None, the factor matrices are rescaled so that the Frobenius
norm of the returned tensor is equal to ``norm``.
random_state : integer, RandomState instance or None, optional (default ``None``)
If integer, random_state is the seed used by the random number generator;
If RandomState instance, random_state is the random number generator;
If None, the random number generator is the RandomState instance used by np.random.
Returns
-------
X : (I_1, ..., I_N) array_like
N-way tensor with rank R.
Example
-------
>>> # Create a rank-2 tensor of dimension 5x5x5:
>>> import tensortools as tt
>>> X = tt.randn_tensor((5,5,5), rank=2)
"""
# Check input.
rns = _check_random_state(random_state)
# Draw low-rank factor matrices with i.i.d. Gaussian elements.
factors = KTensor([rns.standard_normal((i, rank)) for i in shape])
return _rescale_tensor(factors, norm)
|
python
|
def randn_ktensor(shape, rank, norm=None, random_state=None):
"""
Generates a random N-way tensor with rank R, where the entries are
drawn from the standard normal distribution.
Parameters
----------
shape : tuple
shape of the tensor
rank : integer
rank of the tensor
norm : float or None, optional (defaults: None)
If not None, the factor matrices are rescaled so that the Frobenius
norm of the returned tensor is equal to ``norm``.
random_state : integer, RandomState instance or None, optional (default ``None``)
If integer, random_state is the seed used by the random number generator;
If RandomState instance, random_state is the random number generator;
If None, the random number generator is the RandomState instance used by np.random.
Returns
-------
X : (I_1, ..., I_N) array_like
N-way tensor with rank R.
Example
-------
>>> # Create a rank-2 tensor of dimension 5x5x5:
>>> import tensortools as tt
>>> X = tt.randn_tensor((5,5,5), rank=2)
"""
# Check input.
rns = _check_random_state(random_state)
# Draw low-rank factor matrices with i.i.d. Gaussian elements.
factors = KTensor([rns.standard_normal((i, rank)) for i in shape])
return _rescale_tensor(factors, norm)
|
[
"def",
"randn_ktensor",
"(",
"shape",
",",
"rank",
",",
"norm",
"=",
"None",
",",
"random_state",
"=",
"None",
")",
":",
"# Check input.",
"rns",
"=",
"_check_random_state",
"(",
"random_state",
")",
"# Draw low-rank factor matrices with i.i.d. Gaussian elements.",
"factors",
"=",
"KTensor",
"(",
"[",
"rns",
".",
"standard_normal",
"(",
"(",
"i",
",",
"rank",
")",
")",
"for",
"i",
"in",
"shape",
"]",
")",
"return",
"_rescale_tensor",
"(",
"factors",
",",
"norm",
")"
] |
Generates a random N-way tensor with rank R, where the entries are
drawn from the standard normal distribution.
Parameters
----------
shape : tuple
shape of the tensor
rank : integer
rank of the tensor
norm : float or None, optional (defaults: None)
If not None, the factor matrices are rescaled so that the Frobenius
norm of the returned tensor is equal to ``norm``.
random_state : integer, RandomState instance or None, optional (default ``None``)
If integer, random_state is the seed used by the random number generator;
If RandomState instance, random_state is the random number generator;
If None, the random number generator is the RandomState instance used by np.random.
Returns
-------
X : (I_1, ..., I_N) array_like
N-way tensor with rank R.
Example
-------
>>> # Create a rank-2 tensor of dimension 5x5x5:
>>> import tensortools as tt
>>> X = tt.randn_tensor((5,5,5), rank=2)
|
[
"Generates",
"a",
"random",
"N",
"-",
"way",
"tensor",
"with",
"rank",
"R",
"where",
"the",
"entries",
"are",
"drawn",
"from",
"the",
"standard",
"normal",
"distribution",
"."
] |
f375633ec621caa96665a56205dcf932590d4a6e
|
https://github.com/ahwillia/tensortools/blob/f375633ec621caa96665a56205dcf932590d4a6e/tensortools/data/random_tensor.py#L47-L88
|
train
|
ahwillia/tensortools
|
tensortools/ensemble.py
|
Ensemble.fit
|
def fit(self, X, ranks, replicates=1, verbose=True):
"""
Fits CP tensor decompositions for different choices of rank.
Parameters
----------
X : array_like
Real tensor
ranks : int, or iterable
iterable specifying number of components in each model
replicates: int
number of models to fit at each rank
verbose : bool
If True, prints summaries and optimization progress.
"""
# Make ranks iterable if necessary.
if not isinstance(ranks, collections.Iterable):
ranks = (ranks,)
# Iterate over model ranks, optimize multiple replicates at each rank.
for r in ranks:
# Initialize storage
if r not in self.results:
self.results[r] = []
# Display fitting progress.
if verbose:
itr = trange(replicates,
desc='Fitting rank-{} models'.format(r),
leave=False)
else:
itr = range(replicates)
# Fit replicates.
for i in itr:
model_fit = self._fit_method(X, r, **self._fit_options)
self.results[r].append(model_fit)
# Print summary of results.
if verbose:
min_obj = min([res.obj for res in self.results[r]])
max_obj = max([res.obj for res in self.results[r]])
elapsed = sum([res.total_time for res in self.results[r]])
print('Rank-{} models: min obj, {:.2f}; '
'max obj, {:.2f}; time to fit, '
'{:.1f}s'.format(r, min_obj, max_obj, elapsed))
# Sort results from lowest to largest loss.
for r in ranks:
idx = np.argsort([result.obj for result in self.results[r]])
self.results[r] = [self.results[r][i] for i in idx]
# Align best model within each rank to best model of next larger rank.
# Here r0 is the rank of the lower-dimensional model and r1 is the rank
# of the high-dimensional model.
for i in reversed(range(1, len(ranks))):
r0, r1 = ranks[i-1], ranks[i]
U = self.results[r0][0].factors
V = self.results[r1][0].factors
kruskal_align(U, V, permute_U=True)
# For each rank, align everything to the best model
for r in ranks:
# store best factors
U = self.results[r][0].factors # best model factors
self.results[r][0].similarity = 1.0 # similarity to itself
# align lesser fit models to best models
for res in self.results[r][1:]:
res.similarity = kruskal_align(U, res.factors, permute_V=True)
|
python
|
def fit(self, X, ranks, replicates=1, verbose=True):
"""
Fits CP tensor decompositions for different choices of rank.
Parameters
----------
X : array_like
Real tensor
ranks : int, or iterable
iterable specifying number of components in each model
replicates: int
number of models to fit at each rank
verbose : bool
If True, prints summaries and optimization progress.
"""
# Make ranks iterable if necessary.
if not isinstance(ranks, collections.Iterable):
ranks = (ranks,)
# Iterate over model ranks, optimize multiple replicates at each rank.
for r in ranks:
# Initialize storage
if r not in self.results:
self.results[r] = []
# Display fitting progress.
if verbose:
itr = trange(replicates,
desc='Fitting rank-{} models'.format(r),
leave=False)
else:
itr = range(replicates)
# Fit replicates.
for i in itr:
model_fit = self._fit_method(X, r, **self._fit_options)
self.results[r].append(model_fit)
# Print summary of results.
if verbose:
min_obj = min([res.obj for res in self.results[r]])
max_obj = max([res.obj for res in self.results[r]])
elapsed = sum([res.total_time for res in self.results[r]])
print('Rank-{} models: min obj, {:.2f}; '
'max obj, {:.2f}; time to fit, '
'{:.1f}s'.format(r, min_obj, max_obj, elapsed))
# Sort results from lowest to largest loss.
for r in ranks:
idx = np.argsort([result.obj for result in self.results[r]])
self.results[r] = [self.results[r][i] for i in idx]
# Align best model within each rank to best model of next larger rank.
# Here r0 is the rank of the lower-dimensional model and r1 is the rank
# of the high-dimensional model.
for i in reversed(range(1, len(ranks))):
r0, r1 = ranks[i-1], ranks[i]
U = self.results[r0][0].factors
V = self.results[r1][0].factors
kruskal_align(U, V, permute_U=True)
# For each rank, align everything to the best model
for r in ranks:
# store best factors
U = self.results[r][0].factors # best model factors
self.results[r][0].similarity = 1.0 # similarity to itself
# align lesser fit models to best models
for res in self.results[r][1:]:
res.similarity = kruskal_align(U, res.factors, permute_V=True)
|
[
"def",
"fit",
"(",
"self",
",",
"X",
",",
"ranks",
",",
"replicates",
"=",
"1",
",",
"verbose",
"=",
"True",
")",
":",
"# Make ranks iterable if necessary.",
"if",
"not",
"isinstance",
"(",
"ranks",
",",
"collections",
".",
"Iterable",
")",
":",
"ranks",
"=",
"(",
"ranks",
",",
")",
"# Iterate over model ranks, optimize multiple replicates at each rank.",
"for",
"r",
"in",
"ranks",
":",
"# Initialize storage",
"if",
"r",
"not",
"in",
"self",
".",
"results",
":",
"self",
".",
"results",
"[",
"r",
"]",
"=",
"[",
"]",
"# Display fitting progress.",
"if",
"verbose",
":",
"itr",
"=",
"trange",
"(",
"replicates",
",",
"desc",
"=",
"'Fitting rank-{} models'",
".",
"format",
"(",
"r",
")",
",",
"leave",
"=",
"False",
")",
"else",
":",
"itr",
"=",
"range",
"(",
"replicates",
")",
"# Fit replicates.",
"for",
"i",
"in",
"itr",
":",
"model_fit",
"=",
"self",
".",
"_fit_method",
"(",
"X",
",",
"r",
",",
"*",
"*",
"self",
".",
"_fit_options",
")",
"self",
".",
"results",
"[",
"r",
"]",
".",
"append",
"(",
"model_fit",
")",
"# Print summary of results.",
"if",
"verbose",
":",
"min_obj",
"=",
"min",
"(",
"[",
"res",
".",
"obj",
"for",
"res",
"in",
"self",
".",
"results",
"[",
"r",
"]",
"]",
")",
"max_obj",
"=",
"max",
"(",
"[",
"res",
".",
"obj",
"for",
"res",
"in",
"self",
".",
"results",
"[",
"r",
"]",
"]",
")",
"elapsed",
"=",
"sum",
"(",
"[",
"res",
".",
"total_time",
"for",
"res",
"in",
"self",
".",
"results",
"[",
"r",
"]",
"]",
")",
"print",
"(",
"'Rank-{} models: min obj, {:.2f}; '",
"'max obj, {:.2f}; time to fit, '",
"'{:.1f}s'",
".",
"format",
"(",
"r",
",",
"min_obj",
",",
"max_obj",
",",
"elapsed",
")",
")",
"# Sort results from lowest to largest loss.",
"for",
"r",
"in",
"ranks",
":",
"idx",
"=",
"np",
".",
"argsort",
"(",
"[",
"result",
".",
"obj",
"for",
"result",
"in",
"self",
".",
"results",
"[",
"r",
"]",
"]",
")",
"self",
".",
"results",
"[",
"r",
"]",
"=",
"[",
"self",
".",
"results",
"[",
"r",
"]",
"[",
"i",
"]",
"for",
"i",
"in",
"idx",
"]",
"# Align best model within each rank to best model of next larger rank.",
"# Here r0 is the rank of the lower-dimensional model and r1 is the rank",
"# of the high-dimensional model.",
"for",
"i",
"in",
"reversed",
"(",
"range",
"(",
"1",
",",
"len",
"(",
"ranks",
")",
")",
")",
":",
"r0",
",",
"r1",
"=",
"ranks",
"[",
"i",
"-",
"1",
"]",
",",
"ranks",
"[",
"i",
"]",
"U",
"=",
"self",
".",
"results",
"[",
"r0",
"]",
"[",
"0",
"]",
".",
"factors",
"V",
"=",
"self",
".",
"results",
"[",
"r1",
"]",
"[",
"0",
"]",
".",
"factors",
"kruskal_align",
"(",
"U",
",",
"V",
",",
"permute_U",
"=",
"True",
")",
"# For each rank, align everything to the best model",
"for",
"r",
"in",
"ranks",
":",
"# store best factors",
"U",
"=",
"self",
".",
"results",
"[",
"r",
"]",
"[",
"0",
"]",
".",
"factors",
"# best model factors",
"self",
".",
"results",
"[",
"r",
"]",
"[",
"0",
"]",
".",
"similarity",
"=",
"1.0",
"# similarity to itself",
"# align lesser fit models to best models",
"for",
"res",
"in",
"self",
".",
"results",
"[",
"r",
"]",
"[",
"1",
":",
"]",
":",
"res",
".",
"similarity",
"=",
"kruskal_align",
"(",
"U",
",",
"res",
".",
"factors",
",",
"permute_V",
"=",
"True",
")"
] |
Fits CP tensor decompositions for different choices of rank.
Parameters
----------
X : array_like
Real tensor
ranks : int, or iterable
iterable specifying number of components in each model
replicates: int
number of models to fit at each rank
verbose : bool
If True, prints summaries and optimization progress.
|
[
"Fits",
"CP",
"tensor",
"decompositions",
"for",
"different",
"choices",
"of",
"rank",
"."
] |
f375633ec621caa96665a56205dcf932590d4a6e
|
https://github.com/ahwillia/tensortools/blob/f375633ec621caa96665a56205dcf932590d4a6e/tensortools/ensemble.py#L57-L128
|
train
|
ahwillia/tensortools
|
tensortools/ensemble.py
|
Ensemble.objectives
|
def objectives(self, rank):
"""Returns objective values of models with specified rank.
"""
self._check_rank(rank)
return [result.obj for result in self.results[rank]]
|
python
|
def objectives(self, rank):
"""Returns objective values of models with specified rank.
"""
self._check_rank(rank)
return [result.obj for result in self.results[rank]]
|
[
"def",
"objectives",
"(",
"self",
",",
"rank",
")",
":",
"self",
".",
"_check_rank",
"(",
"rank",
")",
"return",
"[",
"result",
".",
"obj",
"for",
"result",
"in",
"self",
".",
"results",
"[",
"rank",
"]",
"]"
] |
Returns objective values of models with specified rank.
|
[
"Returns",
"objective",
"values",
"of",
"models",
"with",
"specified",
"rank",
"."
] |
f375633ec621caa96665a56205dcf932590d4a6e
|
https://github.com/ahwillia/tensortools/blob/f375633ec621caa96665a56205dcf932590d4a6e/tensortools/ensemble.py#L130-L134
|
train
|
ahwillia/tensortools
|
tensortools/ensemble.py
|
Ensemble.similarities
|
def similarities(self, rank):
"""Returns similarity scores for models with specified rank.
"""
self._check_rank(rank)
return [result.similarity for result in self.results[rank]]
|
python
|
def similarities(self, rank):
"""Returns similarity scores for models with specified rank.
"""
self._check_rank(rank)
return [result.similarity for result in self.results[rank]]
|
[
"def",
"similarities",
"(",
"self",
",",
"rank",
")",
":",
"self",
".",
"_check_rank",
"(",
"rank",
")",
"return",
"[",
"result",
".",
"similarity",
"for",
"result",
"in",
"self",
".",
"results",
"[",
"rank",
"]",
"]"
] |
Returns similarity scores for models with specified rank.
|
[
"Returns",
"similarity",
"scores",
"for",
"models",
"with",
"specified",
"rank",
"."
] |
f375633ec621caa96665a56205dcf932590d4a6e
|
https://github.com/ahwillia/tensortools/blob/f375633ec621caa96665a56205dcf932590d4a6e/tensortools/ensemble.py#L136-L140
|
train
|
ahwillia/tensortools
|
tensortools/ensemble.py
|
Ensemble.factors
|
def factors(self, rank):
"""Returns KTensor factors for models with specified rank.
"""
self._check_rank(rank)
return [result.factors for result in self.results[rank]]
|
python
|
def factors(self, rank):
"""Returns KTensor factors for models with specified rank.
"""
self._check_rank(rank)
return [result.factors for result in self.results[rank]]
|
[
"def",
"factors",
"(",
"self",
",",
"rank",
")",
":",
"self",
".",
"_check_rank",
"(",
"rank",
")",
"return",
"[",
"result",
".",
"factors",
"for",
"result",
"in",
"self",
".",
"results",
"[",
"rank",
"]",
"]"
] |
Returns KTensor factors for models with specified rank.
|
[
"Returns",
"KTensor",
"factors",
"for",
"models",
"with",
"specified",
"rank",
"."
] |
f375633ec621caa96665a56205dcf932590d4a6e
|
https://github.com/ahwillia/tensortools/blob/f375633ec621caa96665a56205dcf932590d4a6e/tensortools/ensemble.py#L142-L146
|
train
|
OCA/odoorpc
|
odoorpc/env.py
|
Environment._create_model_class
|
def _create_model_class(self, model):
"""Generate the model proxy class.
:return: a :class:`odoorpc.models.Model` class
"""
cls_name = model.replace('.', '_')
# Hack for Python 2 (no need to do this for Python 3)
if sys.version_info[0] < 3:
if isinstance(cls_name, unicode):
cls_name = cls_name.encode('utf-8')
# Retrieve server fields info and generate corresponding local fields
attrs = {
'_env': self,
'_odoo': self._odoo,
'_name': model,
'_columns': {},
}
fields_get = self._odoo.execute(model, 'fields_get')
for field_name, field_data in fields_get.items():
if field_name not in FIELDS_RESERVED:
Field = fields.generate_field(field_name, field_data)
attrs['_columns'][field_name] = Field
attrs[field_name] = Field
# Case where no field 'name' exists, we generate one (which will be
# in readonly mode) in purpose to be filled with the 'name_get' method
if 'name' not in attrs['_columns']:
field_data = {'type': 'text', 'string': 'Name', 'readonly': True}
Field = fields.generate_field('name', field_data)
attrs['_columns']['name'] = Field
attrs['name'] = Field
return type(cls_name, (Model,), attrs)
|
python
|
def _create_model_class(self, model):
"""Generate the model proxy class.
:return: a :class:`odoorpc.models.Model` class
"""
cls_name = model.replace('.', '_')
# Hack for Python 2 (no need to do this for Python 3)
if sys.version_info[0] < 3:
if isinstance(cls_name, unicode):
cls_name = cls_name.encode('utf-8')
# Retrieve server fields info and generate corresponding local fields
attrs = {
'_env': self,
'_odoo': self._odoo,
'_name': model,
'_columns': {},
}
fields_get = self._odoo.execute(model, 'fields_get')
for field_name, field_data in fields_get.items():
if field_name not in FIELDS_RESERVED:
Field = fields.generate_field(field_name, field_data)
attrs['_columns'][field_name] = Field
attrs[field_name] = Field
# Case where no field 'name' exists, we generate one (which will be
# in readonly mode) in purpose to be filled with the 'name_get' method
if 'name' not in attrs['_columns']:
field_data = {'type': 'text', 'string': 'Name', 'readonly': True}
Field = fields.generate_field('name', field_data)
attrs['_columns']['name'] = Field
attrs['name'] = Field
return type(cls_name, (Model,), attrs)
|
[
"def",
"_create_model_class",
"(",
"self",
",",
"model",
")",
":",
"cls_name",
"=",
"model",
".",
"replace",
"(",
"'.'",
",",
"'_'",
")",
"# Hack for Python 2 (no need to do this for Python 3)",
"if",
"sys",
".",
"version_info",
"[",
"0",
"]",
"<",
"3",
":",
"if",
"isinstance",
"(",
"cls_name",
",",
"unicode",
")",
":",
"cls_name",
"=",
"cls_name",
".",
"encode",
"(",
"'utf-8'",
")",
"# Retrieve server fields info and generate corresponding local fields",
"attrs",
"=",
"{",
"'_env'",
":",
"self",
",",
"'_odoo'",
":",
"self",
".",
"_odoo",
",",
"'_name'",
":",
"model",
",",
"'_columns'",
":",
"{",
"}",
",",
"}",
"fields_get",
"=",
"self",
".",
"_odoo",
".",
"execute",
"(",
"model",
",",
"'fields_get'",
")",
"for",
"field_name",
",",
"field_data",
"in",
"fields_get",
".",
"items",
"(",
")",
":",
"if",
"field_name",
"not",
"in",
"FIELDS_RESERVED",
":",
"Field",
"=",
"fields",
".",
"generate_field",
"(",
"field_name",
",",
"field_data",
")",
"attrs",
"[",
"'_columns'",
"]",
"[",
"field_name",
"]",
"=",
"Field",
"attrs",
"[",
"field_name",
"]",
"=",
"Field",
"# Case where no field 'name' exists, we generate one (which will be",
"# in readonly mode) in purpose to be filled with the 'name_get' method",
"if",
"'name'",
"not",
"in",
"attrs",
"[",
"'_columns'",
"]",
":",
"field_data",
"=",
"{",
"'type'",
":",
"'text'",
",",
"'string'",
":",
"'Name'",
",",
"'readonly'",
":",
"True",
"}",
"Field",
"=",
"fields",
".",
"generate_field",
"(",
"'name'",
",",
"field_data",
")",
"attrs",
"[",
"'_columns'",
"]",
"[",
"'name'",
"]",
"=",
"Field",
"attrs",
"[",
"'name'",
"]",
"=",
"Field",
"return",
"type",
"(",
"cls_name",
",",
"(",
"Model",
",",
")",
",",
"attrs",
")"
] |
Generate the model proxy class.
:return: a :class:`odoorpc.models.Model` class
|
[
"Generate",
"the",
"model",
"proxy",
"class",
"."
] |
d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0
|
https://github.com/OCA/odoorpc/blob/d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0/odoorpc/env.py#L313-L343
|
train
|
OCA/odoorpc
|
odoorpc/session.py
|
get_all
|
def get_all(rc_file='~/.odoorpcrc'):
"""Return all session configurations from the `rc_file` file.
>>> import odoorpc
>>> from pprint import pprint as pp
>>> pp(odoorpc.session.get_all()) # doctest: +SKIP
{'foo': {'database': 'db_name',
'host': 'localhost',
'passwd': 'password',
'port': 8069,
'protocol': 'jsonrpc',
'timeout': 120,
'type': 'ODOO',
'user': 'admin'},
...}
.. doctest::
:hide:
>>> import odoorpc
>>> session = '%s_session' % DB
>>> odoo.save(session)
>>> data = odoorpc.session.get_all()
>>> data[session]['host'] == HOST
True
>>> data[session]['protocol'] == PROTOCOL
True
>>> data[session]['port'] == int(PORT)
True
>>> data[session]['database'] == DB
True
>>> data[session]['user'] == USER
True
>>> data[session]['passwd'] == PWD
True
>>> data[session]['type'] == 'ODOO'
True
"""
conf = ConfigParser()
conf.read([os.path.expanduser(rc_file)])
sessions = {}
for name in conf.sections():
sessions[name] = {
'type': conf.get(name, 'type'),
'host': conf.get(name, 'host'),
'protocol': conf.get(name, 'protocol'),
'port': conf.getint(name, 'port'),
'timeout': conf.getfloat(name, 'timeout'),
'user': conf.get(name, 'user'),
'passwd': conf.get(name, 'passwd'),
'database': conf.get(name, 'database'),
}
return sessions
|
python
|
def get_all(rc_file='~/.odoorpcrc'):
"""Return all session configurations from the `rc_file` file.
>>> import odoorpc
>>> from pprint import pprint as pp
>>> pp(odoorpc.session.get_all()) # doctest: +SKIP
{'foo': {'database': 'db_name',
'host': 'localhost',
'passwd': 'password',
'port': 8069,
'protocol': 'jsonrpc',
'timeout': 120,
'type': 'ODOO',
'user': 'admin'},
...}
.. doctest::
:hide:
>>> import odoorpc
>>> session = '%s_session' % DB
>>> odoo.save(session)
>>> data = odoorpc.session.get_all()
>>> data[session]['host'] == HOST
True
>>> data[session]['protocol'] == PROTOCOL
True
>>> data[session]['port'] == int(PORT)
True
>>> data[session]['database'] == DB
True
>>> data[session]['user'] == USER
True
>>> data[session]['passwd'] == PWD
True
>>> data[session]['type'] == 'ODOO'
True
"""
conf = ConfigParser()
conf.read([os.path.expanduser(rc_file)])
sessions = {}
for name in conf.sections():
sessions[name] = {
'type': conf.get(name, 'type'),
'host': conf.get(name, 'host'),
'protocol': conf.get(name, 'protocol'),
'port': conf.getint(name, 'port'),
'timeout': conf.getfloat(name, 'timeout'),
'user': conf.get(name, 'user'),
'passwd': conf.get(name, 'passwd'),
'database': conf.get(name, 'database'),
}
return sessions
|
[
"def",
"get_all",
"(",
"rc_file",
"=",
"'~/.odoorpcrc'",
")",
":",
"conf",
"=",
"ConfigParser",
"(",
")",
"conf",
".",
"read",
"(",
"[",
"os",
".",
"path",
".",
"expanduser",
"(",
"rc_file",
")",
"]",
")",
"sessions",
"=",
"{",
"}",
"for",
"name",
"in",
"conf",
".",
"sections",
"(",
")",
":",
"sessions",
"[",
"name",
"]",
"=",
"{",
"'type'",
":",
"conf",
".",
"get",
"(",
"name",
",",
"'type'",
")",
",",
"'host'",
":",
"conf",
".",
"get",
"(",
"name",
",",
"'host'",
")",
",",
"'protocol'",
":",
"conf",
".",
"get",
"(",
"name",
",",
"'protocol'",
")",
",",
"'port'",
":",
"conf",
".",
"getint",
"(",
"name",
",",
"'port'",
")",
",",
"'timeout'",
":",
"conf",
".",
"getfloat",
"(",
"name",
",",
"'timeout'",
")",
",",
"'user'",
":",
"conf",
".",
"get",
"(",
"name",
",",
"'user'",
")",
",",
"'passwd'",
":",
"conf",
".",
"get",
"(",
"name",
",",
"'passwd'",
")",
",",
"'database'",
":",
"conf",
".",
"get",
"(",
"name",
",",
"'database'",
")",
",",
"}",
"return",
"sessions"
] |
Return all session configurations from the `rc_file` file.
>>> import odoorpc
>>> from pprint import pprint as pp
>>> pp(odoorpc.session.get_all()) # doctest: +SKIP
{'foo': {'database': 'db_name',
'host': 'localhost',
'passwd': 'password',
'port': 8069,
'protocol': 'jsonrpc',
'timeout': 120,
'type': 'ODOO',
'user': 'admin'},
...}
.. doctest::
:hide:
>>> import odoorpc
>>> session = '%s_session' % DB
>>> odoo.save(session)
>>> data = odoorpc.session.get_all()
>>> data[session]['host'] == HOST
True
>>> data[session]['protocol'] == PROTOCOL
True
>>> data[session]['port'] == int(PORT)
True
>>> data[session]['database'] == DB
True
>>> data[session]['user'] == USER
True
>>> data[session]['passwd'] == PWD
True
>>> data[session]['type'] == 'ODOO'
True
|
[
"Return",
"all",
"session",
"configurations",
"from",
"the",
"rc_file",
"file",
"."
] |
d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0
|
https://github.com/OCA/odoorpc/blob/d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0/odoorpc/session.py#L35-L87
|
train
|
OCA/odoorpc
|
odoorpc/session.py
|
get
|
def get(name, rc_file='~/.odoorpcrc'):
"""Return the session configuration identified by `name`
from the `rc_file` file.
>>> import odoorpc
>>> from pprint import pprint as pp
>>> pp(odoorpc.session.get('foo')) # doctest: +SKIP
{'database': 'db_name',
'host': 'localhost',
'passwd': 'password',
'port': 8069,
'protocol': 'jsonrpc',
'timeout': 120,
'type': 'ODOO',
'user': 'admin'}
.. doctest::
:hide:
>>> import odoorpc
>>> session = '%s_session' % DB
>>> odoo.save(session)
>>> data = odoorpc.session.get(session)
>>> data['host'] == HOST
True
>>> data['protocol'] == PROTOCOL
True
>>> data['port'] == int(PORT)
True
>>> data['database'] == DB
True
>>> data['user'] == USER
True
>>> data['passwd'] == PWD
True
>>> data['type'] == 'ODOO'
True
:raise: `ValueError` (wrong session name)
"""
conf = ConfigParser()
conf.read([os.path.expanduser(rc_file)])
if not conf.has_section(name):
raise ValueError(
"'%s' session does not exist in %s" % (name, rc_file))
return {
'type': conf.get(name, 'type'),
'host': conf.get(name, 'host'),
'protocol': conf.get(name, 'protocol'),
'port': conf.getint(name, 'port'),
'timeout': conf.getfloat(name, 'timeout'),
'user': conf.get(name, 'user'),
'passwd': conf.get(name, 'passwd'),
'database': conf.get(name, 'database'),
}
|
python
|
def get(name, rc_file='~/.odoorpcrc'):
"""Return the session configuration identified by `name`
from the `rc_file` file.
>>> import odoorpc
>>> from pprint import pprint as pp
>>> pp(odoorpc.session.get('foo')) # doctest: +SKIP
{'database': 'db_name',
'host': 'localhost',
'passwd': 'password',
'port': 8069,
'protocol': 'jsonrpc',
'timeout': 120,
'type': 'ODOO',
'user': 'admin'}
.. doctest::
:hide:
>>> import odoorpc
>>> session = '%s_session' % DB
>>> odoo.save(session)
>>> data = odoorpc.session.get(session)
>>> data['host'] == HOST
True
>>> data['protocol'] == PROTOCOL
True
>>> data['port'] == int(PORT)
True
>>> data['database'] == DB
True
>>> data['user'] == USER
True
>>> data['passwd'] == PWD
True
>>> data['type'] == 'ODOO'
True
:raise: `ValueError` (wrong session name)
"""
conf = ConfigParser()
conf.read([os.path.expanduser(rc_file)])
if not conf.has_section(name):
raise ValueError(
"'%s' session does not exist in %s" % (name, rc_file))
return {
'type': conf.get(name, 'type'),
'host': conf.get(name, 'host'),
'protocol': conf.get(name, 'protocol'),
'port': conf.getint(name, 'port'),
'timeout': conf.getfloat(name, 'timeout'),
'user': conf.get(name, 'user'),
'passwd': conf.get(name, 'passwd'),
'database': conf.get(name, 'database'),
}
|
[
"def",
"get",
"(",
"name",
",",
"rc_file",
"=",
"'~/.odoorpcrc'",
")",
":",
"conf",
"=",
"ConfigParser",
"(",
")",
"conf",
".",
"read",
"(",
"[",
"os",
".",
"path",
".",
"expanduser",
"(",
"rc_file",
")",
"]",
")",
"if",
"not",
"conf",
".",
"has_section",
"(",
"name",
")",
":",
"raise",
"ValueError",
"(",
"\"'%s' session does not exist in %s\"",
"%",
"(",
"name",
",",
"rc_file",
")",
")",
"return",
"{",
"'type'",
":",
"conf",
".",
"get",
"(",
"name",
",",
"'type'",
")",
",",
"'host'",
":",
"conf",
".",
"get",
"(",
"name",
",",
"'host'",
")",
",",
"'protocol'",
":",
"conf",
".",
"get",
"(",
"name",
",",
"'protocol'",
")",
",",
"'port'",
":",
"conf",
".",
"getint",
"(",
"name",
",",
"'port'",
")",
",",
"'timeout'",
":",
"conf",
".",
"getfloat",
"(",
"name",
",",
"'timeout'",
")",
",",
"'user'",
":",
"conf",
".",
"get",
"(",
"name",
",",
"'user'",
")",
",",
"'passwd'",
":",
"conf",
".",
"get",
"(",
"name",
",",
"'passwd'",
")",
",",
"'database'",
":",
"conf",
".",
"get",
"(",
"name",
",",
"'database'",
")",
",",
"}"
] |
Return the session configuration identified by `name`
from the `rc_file` file.
>>> import odoorpc
>>> from pprint import pprint as pp
>>> pp(odoorpc.session.get('foo')) # doctest: +SKIP
{'database': 'db_name',
'host': 'localhost',
'passwd': 'password',
'port': 8069,
'protocol': 'jsonrpc',
'timeout': 120,
'type': 'ODOO',
'user': 'admin'}
.. doctest::
:hide:
>>> import odoorpc
>>> session = '%s_session' % DB
>>> odoo.save(session)
>>> data = odoorpc.session.get(session)
>>> data['host'] == HOST
True
>>> data['protocol'] == PROTOCOL
True
>>> data['port'] == int(PORT)
True
>>> data['database'] == DB
True
>>> data['user'] == USER
True
>>> data['passwd'] == PWD
True
>>> data['type'] == 'ODOO'
True
:raise: `ValueError` (wrong session name)
|
[
"Return",
"the",
"session",
"configuration",
"identified",
"by",
"name",
"from",
"the",
"rc_file",
"file",
"."
] |
d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0
|
https://github.com/OCA/odoorpc/blob/d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0/odoorpc/session.py#L90-L144
|
train
|
OCA/odoorpc
|
odoorpc/session.py
|
save
|
def save(name, data, rc_file='~/.odoorpcrc'):
"""Save the `data` session configuration under the name `name`
in the `rc_file` file.
>>> import odoorpc
>>> odoorpc.session.save(
... 'foo',
... {'type': 'ODOO', 'host': 'localhost', 'protocol': 'jsonrpc',
... 'port': 8069, 'timeout': 120, 'database': 'db_name'
... 'user': 'admin', 'passwd': 'password'}) # doctest: +SKIP
.. doctest::
:hide:
>>> import odoorpc
>>> session = '%s_session' % DB
>>> odoorpc.session.save(
... session,
... {'type': 'ODOO', 'host': HOST, 'protocol': PROTOCOL,
... 'port': PORT, 'timeout': 120, 'database': DB,
... 'user': USER, 'passwd': PWD})
"""
conf = ConfigParser()
conf.read([os.path.expanduser(rc_file)])
if not conf.has_section(name):
conf.add_section(name)
for key in data:
value = data[key]
conf.set(name, key, str(value))
with open(os.path.expanduser(rc_file), 'w') as file_:
os.chmod(os.path.expanduser(rc_file), stat.S_IREAD | stat.S_IWRITE)
conf.write(file_)
|
python
|
def save(name, data, rc_file='~/.odoorpcrc'):
"""Save the `data` session configuration under the name `name`
in the `rc_file` file.
>>> import odoorpc
>>> odoorpc.session.save(
... 'foo',
... {'type': 'ODOO', 'host': 'localhost', 'protocol': 'jsonrpc',
... 'port': 8069, 'timeout': 120, 'database': 'db_name'
... 'user': 'admin', 'passwd': 'password'}) # doctest: +SKIP
.. doctest::
:hide:
>>> import odoorpc
>>> session = '%s_session' % DB
>>> odoorpc.session.save(
... session,
... {'type': 'ODOO', 'host': HOST, 'protocol': PROTOCOL,
... 'port': PORT, 'timeout': 120, 'database': DB,
... 'user': USER, 'passwd': PWD})
"""
conf = ConfigParser()
conf.read([os.path.expanduser(rc_file)])
if not conf.has_section(name):
conf.add_section(name)
for key in data:
value = data[key]
conf.set(name, key, str(value))
with open(os.path.expanduser(rc_file), 'w') as file_:
os.chmod(os.path.expanduser(rc_file), stat.S_IREAD | stat.S_IWRITE)
conf.write(file_)
|
[
"def",
"save",
"(",
"name",
",",
"data",
",",
"rc_file",
"=",
"'~/.odoorpcrc'",
")",
":",
"conf",
"=",
"ConfigParser",
"(",
")",
"conf",
".",
"read",
"(",
"[",
"os",
".",
"path",
".",
"expanduser",
"(",
"rc_file",
")",
"]",
")",
"if",
"not",
"conf",
".",
"has_section",
"(",
"name",
")",
":",
"conf",
".",
"add_section",
"(",
"name",
")",
"for",
"key",
"in",
"data",
":",
"value",
"=",
"data",
"[",
"key",
"]",
"conf",
".",
"set",
"(",
"name",
",",
"key",
",",
"str",
"(",
"value",
")",
")",
"with",
"open",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"rc_file",
")",
",",
"'w'",
")",
"as",
"file_",
":",
"os",
".",
"chmod",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"rc_file",
")",
",",
"stat",
".",
"S_IREAD",
"|",
"stat",
".",
"S_IWRITE",
")",
"conf",
".",
"write",
"(",
"file_",
")"
] |
Save the `data` session configuration under the name `name`
in the `rc_file` file.
>>> import odoorpc
>>> odoorpc.session.save(
... 'foo',
... {'type': 'ODOO', 'host': 'localhost', 'protocol': 'jsonrpc',
... 'port': 8069, 'timeout': 120, 'database': 'db_name'
... 'user': 'admin', 'passwd': 'password'}) # doctest: +SKIP
.. doctest::
:hide:
>>> import odoorpc
>>> session = '%s_session' % DB
>>> odoorpc.session.save(
... session,
... {'type': 'ODOO', 'host': HOST, 'protocol': PROTOCOL,
... 'port': PORT, 'timeout': 120, 'database': DB,
... 'user': USER, 'passwd': PWD})
|
[
"Save",
"the",
"data",
"session",
"configuration",
"under",
"the",
"name",
"name",
"in",
"the",
"rc_file",
"file",
"."
] |
d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0
|
https://github.com/OCA/odoorpc/blob/d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0/odoorpc/session.py#L147-L178
|
train
|
OCA/odoorpc
|
odoorpc/session.py
|
remove
|
def remove(name, rc_file='~/.odoorpcrc'):
"""Remove the session configuration identified by `name`
from the `rc_file` file.
>>> import odoorpc
>>> odoorpc.session.remove('foo') # doctest: +SKIP
.. doctest::
:hide:
>>> import odoorpc
>>> session = '%s_session' % DB
>>> odoorpc.session.remove(session)
:raise: `ValueError` (wrong session name)
"""
conf = ConfigParser()
conf.read([os.path.expanduser(rc_file)])
if not conf.has_section(name):
raise ValueError(
"'%s' session does not exist in %s" % (name, rc_file))
conf.remove_section(name)
with open(os.path.expanduser(rc_file), 'wb') as file_:
conf.write(file_)
|
python
|
def remove(name, rc_file='~/.odoorpcrc'):
"""Remove the session configuration identified by `name`
from the `rc_file` file.
>>> import odoorpc
>>> odoorpc.session.remove('foo') # doctest: +SKIP
.. doctest::
:hide:
>>> import odoorpc
>>> session = '%s_session' % DB
>>> odoorpc.session.remove(session)
:raise: `ValueError` (wrong session name)
"""
conf = ConfigParser()
conf.read([os.path.expanduser(rc_file)])
if not conf.has_section(name):
raise ValueError(
"'%s' session does not exist in %s" % (name, rc_file))
conf.remove_section(name)
with open(os.path.expanduser(rc_file), 'wb') as file_:
conf.write(file_)
|
[
"def",
"remove",
"(",
"name",
",",
"rc_file",
"=",
"'~/.odoorpcrc'",
")",
":",
"conf",
"=",
"ConfigParser",
"(",
")",
"conf",
".",
"read",
"(",
"[",
"os",
".",
"path",
".",
"expanduser",
"(",
"rc_file",
")",
"]",
")",
"if",
"not",
"conf",
".",
"has_section",
"(",
"name",
")",
":",
"raise",
"ValueError",
"(",
"\"'%s' session does not exist in %s\"",
"%",
"(",
"name",
",",
"rc_file",
")",
")",
"conf",
".",
"remove_section",
"(",
"name",
")",
"with",
"open",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"rc_file",
")",
",",
"'wb'",
")",
"as",
"file_",
":",
"conf",
".",
"write",
"(",
"file_",
")"
] |
Remove the session configuration identified by `name`
from the `rc_file` file.
>>> import odoorpc
>>> odoorpc.session.remove('foo') # doctest: +SKIP
.. doctest::
:hide:
>>> import odoorpc
>>> session = '%s_session' % DB
>>> odoorpc.session.remove(session)
:raise: `ValueError` (wrong session name)
|
[
"Remove",
"the",
"session",
"configuration",
"identified",
"by",
"name",
"from",
"the",
"rc_file",
"file",
"."
] |
d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0
|
https://github.com/OCA/odoorpc/blob/d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0/odoorpc/session.py#L181-L204
|
train
|
OCA/odoorpc
|
odoorpc/rpc/jsonrpclib.py
|
get_json_log_data
|
def get_json_log_data(data):
"""Returns a new `data` dictionary with hidden params
for log purpose.
"""
log_data = data
for param in LOG_HIDDEN_JSON_PARAMS:
if param in data['params']:
if log_data is data:
log_data = copy.deepcopy(data)
log_data['params'][param] = "**********"
return log_data
|
python
|
def get_json_log_data(data):
"""Returns a new `data` dictionary with hidden params
for log purpose.
"""
log_data = data
for param in LOG_HIDDEN_JSON_PARAMS:
if param in data['params']:
if log_data is data:
log_data = copy.deepcopy(data)
log_data['params'][param] = "**********"
return log_data
|
[
"def",
"get_json_log_data",
"(",
"data",
")",
":",
"log_data",
"=",
"data",
"for",
"param",
"in",
"LOG_HIDDEN_JSON_PARAMS",
":",
"if",
"param",
"in",
"data",
"[",
"'params'",
"]",
":",
"if",
"log_data",
"is",
"data",
":",
"log_data",
"=",
"copy",
".",
"deepcopy",
"(",
"data",
")",
"log_data",
"[",
"'params'",
"]",
"[",
"param",
"]",
"=",
"\"**********\"",
"return",
"log_data"
] |
Returns a new `data` dictionary with hidden params
for log purpose.
|
[
"Returns",
"a",
"new",
"data",
"dictionary",
"with",
"hidden",
"params",
"for",
"log",
"purpose",
"."
] |
d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0
|
https://github.com/OCA/odoorpc/blob/d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0/odoorpc/rpc/jsonrpclib.py#L61-L71
|
train
|
OCA/odoorpc
|
odoorpc/odoo.py
|
ODOO.http
|
def http(self, url, data=None, headers=None):
"""Low level method to execute raw HTTP queries.
.. note::
For low level JSON-RPC queries, see the more convenient
:func:`odoorpc.ODOO.json` method instead.
You have to know the names of each POST parameter required by the
URL, and set them in the `data` string/buffer.
The `data` argument must be built by yourself, following the expected
URL parameters (with :func:`urllib.urlencode` function for simple
parameters, or multipart/form-data structure to handle file upload).
E.g., the HTTP raw query to get the company logo on `Odoo 12.0`:
.. doctest::
>>> response = odoo.http('web/binary/company_logo')
>>> binary_data = response.read()
*Python 2:*
:return: `urllib.addinfourl`
:raise: `urllib2.HTTPError`
:raise: `urllib2.URLError` (connection error)
*Python 3:*
:return: `http.client.HTTPResponse`
:raise: `urllib.error.HTTPError`
:raise: `urllib.error.URLError` (connection error)
"""
return self._connector.proxy_http(url, data, headers)
|
python
|
def http(self, url, data=None, headers=None):
"""Low level method to execute raw HTTP queries.
.. note::
For low level JSON-RPC queries, see the more convenient
:func:`odoorpc.ODOO.json` method instead.
You have to know the names of each POST parameter required by the
URL, and set them in the `data` string/buffer.
The `data` argument must be built by yourself, following the expected
URL parameters (with :func:`urllib.urlencode` function for simple
parameters, or multipart/form-data structure to handle file upload).
E.g., the HTTP raw query to get the company logo on `Odoo 12.0`:
.. doctest::
>>> response = odoo.http('web/binary/company_logo')
>>> binary_data = response.read()
*Python 2:*
:return: `urllib.addinfourl`
:raise: `urllib2.HTTPError`
:raise: `urllib2.URLError` (connection error)
*Python 3:*
:return: `http.client.HTTPResponse`
:raise: `urllib.error.HTTPError`
:raise: `urllib.error.URLError` (connection error)
"""
return self._connector.proxy_http(url, data, headers)
|
[
"def",
"http",
"(",
"self",
",",
"url",
",",
"data",
"=",
"None",
",",
"headers",
"=",
"None",
")",
":",
"return",
"self",
".",
"_connector",
".",
"proxy_http",
"(",
"url",
",",
"data",
",",
"headers",
")"
] |
Low level method to execute raw HTTP queries.
.. note::
For low level JSON-RPC queries, see the more convenient
:func:`odoorpc.ODOO.json` method instead.
You have to know the names of each POST parameter required by the
URL, and set them in the `data` string/buffer.
The `data` argument must be built by yourself, following the expected
URL parameters (with :func:`urllib.urlencode` function for simple
parameters, or multipart/form-data structure to handle file upload).
E.g., the HTTP raw query to get the company logo on `Odoo 12.0`:
.. doctest::
>>> response = odoo.http('web/binary/company_logo')
>>> binary_data = response.read()
*Python 2:*
:return: `urllib.addinfourl`
:raise: `urllib2.HTTPError`
:raise: `urllib2.URLError` (connection error)
*Python 3:*
:return: `http.client.HTTPResponse`
:raise: `urllib.error.HTTPError`
:raise: `urllib.error.URLError` (connection error)
|
[
"Low",
"level",
"method",
"to",
"execute",
"raw",
"HTTP",
"queries",
"."
] |
d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0
|
https://github.com/OCA/odoorpc/blob/d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0/odoorpc/odoo.py#L288-L321
|
train
|
OCA/odoorpc
|
odoorpc/odoo.py
|
ODOO._check_logged_user
|
def _check_logged_user(self):
"""Check if a user is logged. Otherwise, an error is raised."""
if not self._env or not self._password or not self._login:
raise error.InternalError("Login required")
|
python
|
def _check_logged_user(self):
"""Check if a user is logged. Otherwise, an error is raised."""
if not self._env or not self._password or not self._login:
raise error.InternalError("Login required")
|
[
"def",
"_check_logged_user",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_env",
"or",
"not",
"self",
".",
"_password",
"or",
"not",
"self",
".",
"_login",
":",
"raise",
"error",
".",
"InternalError",
"(",
"\"Login required\"",
")"
] |
Check if a user is logged. Otherwise, an error is raised.
|
[
"Check",
"if",
"a",
"user",
"is",
"logged",
".",
"Otherwise",
"an",
"error",
"is",
"raised",
"."
] |
d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0
|
https://github.com/OCA/odoorpc/blob/d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0/odoorpc/odoo.py#L326-L329
|
train
|
OCA/odoorpc
|
odoorpc/odoo.py
|
ODOO.login
|
def login(self, db, login='admin', password='admin'):
"""Log in as the given `user` with the password `passwd` on the
database `db`.
.. doctest::
:options: +SKIP
>>> odoo.login('db_name', 'admin', 'admin')
>>> odoo.env.user.name
'Administrator'
*Python 2:*
:raise: :class:`odoorpc.error.RPCError`
:raise: `urllib2.URLError` (connection error)
*Python 3:*
:raise: :class:`odoorpc.error.RPCError`
:raise: `urllib.error.URLError` (connection error)
"""
# Get the user's ID and generate the corresponding user record
data = self.json(
'/web/session/authenticate',
{'db': db, 'login': login, 'password': password})
uid = data['result']['uid']
if uid:
context = data['result']['user_context']
self._env = Environment(self, db, uid, context=context)
self._login = login
self._password = password
else:
raise error.RPCError("Wrong login ID or password")
|
python
|
def login(self, db, login='admin', password='admin'):
"""Log in as the given `user` with the password `passwd` on the
database `db`.
.. doctest::
:options: +SKIP
>>> odoo.login('db_name', 'admin', 'admin')
>>> odoo.env.user.name
'Administrator'
*Python 2:*
:raise: :class:`odoorpc.error.RPCError`
:raise: `urllib2.URLError` (connection error)
*Python 3:*
:raise: :class:`odoorpc.error.RPCError`
:raise: `urllib.error.URLError` (connection error)
"""
# Get the user's ID and generate the corresponding user record
data = self.json(
'/web/session/authenticate',
{'db': db, 'login': login, 'password': password})
uid = data['result']['uid']
if uid:
context = data['result']['user_context']
self._env = Environment(self, db, uid, context=context)
self._login = login
self._password = password
else:
raise error.RPCError("Wrong login ID or password")
|
[
"def",
"login",
"(",
"self",
",",
"db",
",",
"login",
"=",
"'admin'",
",",
"password",
"=",
"'admin'",
")",
":",
"# Get the user's ID and generate the corresponding user record",
"data",
"=",
"self",
".",
"json",
"(",
"'/web/session/authenticate'",
",",
"{",
"'db'",
":",
"db",
",",
"'login'",
":",
"login",
",",
"'password'",
":",
"password",
"}",
")",
"uid",
"=",
"data",
"[",
"'result'",
"]",
"[",
"'uid'",
"]",
"if",
"uid",
":",
"context",
"=",
"data",
"[",
"'result'",
"]",
"[",
"'user_context'",
"]",
"self",
".",
"_env",
"=",
"Environment",
"(",
"self",
",",
"db",
",",
"uid",
",",
"context",
"=",
"context",
")",
"self",
".",
"_login",
"=",
"login",
"self",
".",
"_password",
"=",
"password",
"else",
":",
"raise",
"error",
".",
"RPCError",
"(",
"\"Wrong login ID or password\"",
")"
] |
Log in as the given `user` with the password `passwd` on the
database `db`.
.. doctest::
:options: +SKIP
>>> odoo.login('db_name', 'admin', 'admin')
>>> odoo.env.user.name
'Administrator'
*Python 2:*
:raise: :class:`odoorpc.error.RPCError`
:raise: `urllib2.URLError` (connection error)
*Python 3:*
:raise: :class:`odoorpc.error.RPCError`
:raise: `urllib.error.URLError` (connection error)
|
[
"Log",
"in",
"as",
"the",
"given",
"user",
"with",
"the",
"password",
"passwd",
"on",
"the",
"database",
"db",
"."
] |
d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0
|
https://github.com/OCA/odoorpc/blob/d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0/odoorpc/odoo.py#L331-L363
|
train
|
OCA/odoorpc
|
odoorpc/odoo.py
|
ODOO.exec_workflow
|
def exec_workflow(self, model, record_id, signal):
"""Execute the workflow `signal` on
the instance having the ID `record_id` of `model`.
*Python 2:*
:raise: :class:`odoorpc.error.RPCError`
:raise: :class:`odoorpc.error.InternalError` (if not logged)
:raise: `urllib2.URLError` (connection error)
*Python 3:*
:raise: :class:`odoorpc.error.RPCError`
:raise: :class:`odoorpc.error.InternalError` (if not logged)
:raise: `urllib.error.URLError` (connection error)
"""
if tools.v(self.version)[0] >= 11:
raise DeprecationWarning(
u"Workflows have been removed in Odoo >= 11.0")
self._check_logged_user()
# Execute the workflow query
args_to_send = [self.env.db, self.env.uid, self._password,
model, signal, record_id]
data = self.json(
'/jsonrpc',
{'service': 'object',
'method': 'exec_workflow',
'args': args_to_send})
return data.get('result')
|
python
|
def exec_workflow(self, model, record_id, signal):
"""Execute the workflow `signal` on
the instance having the ID `record_id` of `model`.
*Python 2:*
:raise: :class:`odoorpc.error.RPCError`
:raise: :class:`odoorpc.error.InternalError` (if not logged)
:raise: `urllib2.URLError` (connection error)
*Python 3:*
:raise: :class:`odoorpc.error.RPCError`
:raise: :class:`odoorpc.error.InternalError` (if not logged)
:raise: `urllib.error.URLError` (connection error)
"""
if tools.v(self.version)[0] >= 11:
raise DeprecationWarning(
u"Workflows have been removed in Odoo >= 11.0")
self._check_logged_user()
# Execute the workflow query
args_to_send = [self.env.db, self.env.uid, self._password,
model, signal, record_id]
data = self.json(
'/jsonrpc',
{'service': 'object',
'method': 'exec_workflow',
'args': args_to_send})
return data.get('result')
|
[
"def",
"exec_workflow",
"(",
"self",
",",
"model",
",",
"record_id",
",",
"signal",
")",
":",
"if",
"tools",
".",
"v",
"(",
"self",
".",
"version",
")",
"[",
"0",
"]",
">=",
"11",
":",
"raise",
"DeprecationWarning",
"(",
"u\"Workflows have been removed in Odoo >= 11.0\"",
")",
"self",
".",
"_check_logged_user",
"(",
")",
"# Execute the workflow query",
"args_to_send",
"=",
"[",
"self",
".",
"env",
".",
"db",
",",
"self",
".",
"env",
".",
"uid",
",",
"self",
".",
"_password",
",",
"model",
",",
"signal",
",",
"record_id",
"]",
"data",
"=",
"self",
".",
"json",
"(",
"'/jsonrpc'",
",",
"{",
"'service'",
":",
"'object'",
",",
"'method'",
":",
"'exec_workflow'",
",",
"'args'",
":",
"args_to_send",
"}",
")",
"return",
"data",
".",
"get",
"(",
"'result'",
")"
] |
Execute the workflow `signal` on
the instance having the ID `record_id` of `model`.
*Python 2:*
:raise: :class:`odoorpc.error.RPCError`
:raise: :class:`odoorpc.error.InternalError` (if not logged)
:raise: `urllib2.URLError` (connection error)
*Python 3:*
:raise: :class:`odoorpc.error.RPCError`
:raise: :class:`odoorpc.error.InternalError` (if not logged)
:raise: `urllib.error.URLError` (connection error)
|
[
"Execute",
"the",
"workflow",
"signal",
"on",
"the",
"instance",
"having",
"the",
"ID",
"record_id",
"of",
"model",
"."
] |
d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0
|
https://github.com/OCA/odoorpc/blob/d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0/odoorpc/odoo.py#L489-L517
|
train
|
OCA/odoorpc
|
odoorpc/db.py
|
DB.create
|
def create(self, password, db, demo=False, lang='en_US', admin_password='admin'):
"""Request the server to create a new database named `db`
which will have `admin_password` as administrator password and
localized with the `lang` parameter.
You have to set the flag `demo` to `True` in order to insert
demonstration data.
>>> odoo.db.create('super_admin_passwd', 'prod', False, 'fr_FR', 'my_admin_passwd') # doctest: +SKIP
If you get a timeout error, increase this one before performing the
request:
>>> timeout_backup = odoo.config['timeout']
>>> odoo.config['timeout'] = 600 # Timeout set to 10 minutes
>>> odoo.db.create('super_admin_passwd', 'prod', False, 'fr_FR', 'my_admin_passwd') # doctest: +SKIP
>>> odoo.config['timeout'] = timeout_backup
The super administrator password is required to perform this method.
*Python 2:*
:raise: :class:`odoorpc.error.RPCError` (access denied)
:raise: `urllib2.URLError` (connection error)
*Python 3:*
:raise: :class:`odoorpc.error.RPCError` (access denied)
:raise: `urllib.error.URLError` (connection error)
"""
self._odoo.json(
'/jsonrpc',
{'service': 'db',
'method': 'create_database',
'args': [password, db, demo, lang, admin_password]})
|
python
|
def create(self, password, db, demo=False, lang='en_US', admin_password='admin'):
"""Request the server to create a new database named `db`
which will have `admin_password` as administrator password and
localized with the `lang` parameter.
You have to set the flag `demo` to `True` in order to insert
demonstration data.
>>> odoo.db.create('super_admin_passwd', 'prod', False, 'fr_FR', 'my_admin_passwd') # doctest: +SKIP
If you get a timeout error, increase this one before performing the
request:
>>> timeout_backup = odoo.config['timeout']
>>> odoo.config['timeout'] = 600 # Timeout set to 10 minutes
>>> odoo.db.create('super_admin_passwd', 'prod', False, 'fr_FR', 'my_admin_passwd') # doctest: +SKIP
>>> odoo.config['timeout'] = timeout_backup
The super administrator password is required to perform this method.
*Python 2:*
:raise: :class:`odoorpc.error.RPCError` (access denied)
:raise: `urllib2.URLError` (connection error)
*Python 3:*
:raise: :class:`odoorpc.error.RPCError` (access denied)
:raise: `urllib.error.URLError` (connection error)
"""
self._odoo.json(
'/jsonrpc',
{'service': 'db',
'method': 'create_database',
'args': [password, db, demo, lang, admin_password]})
|
[
"def",
"create",
"(",
"self",
",",
"password",
",",
"db",
",",
"demo",
"=",
"False",
",",
"lang",
"=",
"'en_US'",
",",
"admin_password",
"=",
"'admin'",
")",
":",
"self",
".",
"_odoo",
".",
"json",
"(",
"'/jsonrpc'",
",",
"{",
"'service'",
":",
"'db'",
",",
"'method'",
":",
"'create_database'",
",",
"'args'",
":",
"[",
"password",
",",
"db",
",",
"demo",
",",
"lang",
",",
"admin_password",
"]",
"}",
")"
] |
Request the server to create a new database named `db`
which will have `admin_password` as administrator password and
localized with the `lang` parameter.
You have to set the flag `demo` to `True` in order to insert
demonstration data.
>>> odoo.db.create('super_admin_passwd', 'prod', False, 'fr_FR', 'my_admin_passwd') # doctest: +SKIP
If you get a timeout error, increase this one before performing the
request:
>>> timeout_backup = odoo.config['timeout']
>>> odoo.config['timeout'] = 600 # Timeout set to 10 minutes
>>> odoo.db.create('super_admin_passwd', 'prod', False, 'fr_FR', 'my_admin_passwd') # doctest: +SKIP
>>> odoo.config['timeout'] = timeout_backup
The super administrator password is required to perform this method.
*Python 2:*
:raise: :class:`odoorpc.error.RPCError` (access denied)
:raise: `urllib2.URLError` (connection error)
*Python 3:*
:raise: :class:`odoorpc.error.RPCError` (access denied)
:raise: `urllib.error.URLError` (connection error)
|
[
"Request",
"the",
"server",
"to",
"create",
"a",
"new",
"database",
"named",
"db",
"which",
"will",
"have",
"admin_password",
"as",
"administrator",
"password",
"and",
"localized",
"with",
"the",
"lang",
"parameter",
".",
"You",
"have",
"to",
"set",
"the",
"flag",
"demo",
"to",
"True",
"in",
"order",
"to",
"insert",
"demonstration",
"data",
"."
] |
d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0
|
https://github.com/OCA/odoorpc/blob/d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0/odoorpc/db.py#L167-L200
|
train
|
OCA/odoorpc
|
odoorpc/db.py
|
DB.duplicate
|
def duplicate(self, password, db, new_db):
"""Duplicate `db' as `new_db`.
>>> odoo.db.duplicate('super_admin_passwd', 'prod', 'test') # doctest: +SKIP
The super administrator password is required to perform this method.
*Python 2:*
:raise: :class:`odoorpc.error.RPCError` (access denied / wrong database)
:raise: `urllib2.URLError` (connection error)
*Python 3:*
:raise: :class:`odoorpc.error.RPCError` (access denied / wrong database)
:raise: `urllib.error.URLError` (connection error)
"""
self._odoo.json(
'/jsonrpc',
{'service': 'db',
'method': 'duplicate_database',
'args': [password, db, new_db]})
|
python
|
def duplicate(self, password, db, new_db):
"""Duplicate `db' as `new_db`.
>>> odoo.db.duplicate('super_admin_passwd', 'prod', 'test') # doctest: +SKIP
The super administrator password is required to perform this method.
*Python 2:*
:raise: :class:`odoorpc.error.RPCError` (access denied / wrong database)
:raise: `urllib2.URLError` (connection error)
*Python 3:*
:raise: :class:`odoorpc.error.RPCError` (access denied / wrong database)
:raise: `urllib.error.URLError` (connection error)
"""
self._odoo.json(
'/jsonrpc',
{'service': 'db',
'method': 'duplicate_database',
'args': [password, db, new_db]})
|
[
"def",
"duplicate",
"(",
"self",
",",
"password",
",",
"db",
",",
"new_db",
")",
":",
"self",
".",
"_odoo",
".",
"json",
"(",
"'/jsonrpc'",
",",
"{",
"'service'",
":",
"'db'",
",",
"'method'",
":",
"'duplicate_database'",
",",
"'args'",
":",
"[",
"password",
",",
"db",
",",
"new_db",
"]",
"}",
")"
] |
Duplicate `db' as `new_db`.
>>> odoo.db.duplicate('super_admin_passwd', 'prod', 'test') # doctest: +SKIP
The super administrator password is required to perform this method.
*Python 2:*
:raise: :class:`odoorpc.error.RPCError` (access denied / wrong database)
:raise: `urllib2.URLError` (connection error)
*Python 3:*
:raise: :class:`odoorpc.error.RPCError` (access denied / wrong database)
:raise: `urllib.error.URLError` (connection error)
|
[
"Duplicate",
"db",
"as",
"new_db",
"."
] |
d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0
|
https://github.com/OCA/odoorpc/blob/d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0/odoorpc/db.py#L233-L254
|
train
|
OCA/odoorpc
|
odoorpc/rpc/__init__.py
|
ConnectorJSONRPC.timeout
|
def timeout(self, timeout):
"""Set the timeout."""
self._proxy_json._timeout = timeout
self._proxy_http._timeout = timeout
|
python
|
def timeout(self, timeout):
"""Set the timeout."""
self._proxy_json._timeout = timeout
self._proxy_http._timeout = timeout
|
[
"def",
"timeout",
"(",
"self",
",",
"timeout",
")",
":",
"self",
".",
"_proxy_json",
".",
"_timeout",
"=",
"timeout",
"self",
".",
"_proxy_http",
".",
"_timeout",
"=",
"timeout"
] |
Set the timeout.
|
[
"Set",
"the",
"timeout",
"."
] |
d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0
|
https://github.com/OCA/odoorpc/blob/d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0/odoorpc/rpc/__init__.py#L245-L248
|
train
|
OCA/odoorpc
|
odoorpc/fields.py
|
is_int
|
def is_int(value):
"""Return `True` if ``value`` is an integer."""
if isinstance(value, bool):
return False
try:
int(value)
return True
except (ValueError, TypeError):
return False
|
python
|
def is_int(value):
"""Return `True` if ``value`` is an integer."""
if isinstance(value, bool):
return False
try:
int(value)
return True
except (ValueError, TypeError):
return False
|
[
"def",
"is_int",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"bool",
")",
":",
"return",
"False",
"try",
":",
"int",
"(",
"value",
")",
"return",
"True",
"except",
"(",
"ValueError",
",",
"TypeError",
")",
":",
"return",
"False"
] |
Return `True` if ``value`` is an integer.
|
[
"Return",
"True",
"if",
"value",
"is",
"an",
"integer",
"."
] |
d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0
|
https://github.com/OCA/odoorpc/blob/d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0/odoorpc/fields.py#L32-L40
|
train
|
OCA/odoorpc
|
odoorpc/fields.py
|
BaseField.check_value
|
def check_value(self, value):
"""Check the validity of a value for the field."""
#if self.readonly:
# raise error.Error(
# "'{field_name}' field is readonly".format(
# field_name=self.name))
if value and self.size:
if not is_string(value):
raise ValueError("Value supplied has to be a string")
if len(value) > self.size:
raise ValueError(
"Lenght of the '{0}' is limited to {1}".format(
self.name, self.size))
if not value and self.required:
raise ValueError("'{0}' field is required".format(self.name))
return value
|
python
|
def check_value(self, value):
"""Check the validity of a value for the field."""
#if self.readonly:
# raise error.Error(
# "'{field_name}' field is readonly".format(
# field_name=self.name))
if value and self.size:
if not is_string(value):
raise ValueError("Value supplied has to be a string")
if len(value) > self.size:
raise ValueError(
"Lenght of the '{0}' is limited to {1}".format(
self.name, self.size))
if not value and self.required:
raise ValueError("'{0}' field is required".format(self.name))
return value
|
[
"def",
"check_value",
"(",
"self",
",",
"value",
")",
":",
"#if self.readonly:",
"# raise error.Error(",
"# \"'{field_name}' field is readonly\".format(",
"# field_name=self.name))",
"if",
"value",
"and",
"self",
".",
"size",
":",
"if",
"not",
"is_string",
"(",
"value",
")",
":",
"raise",
"ValueError",
"(",
"\"Value supplied has to be a string\"",
")",
"if",
"len",
"(",
"value",
")",
">",
"self",
".",
"size",
":",
"raise",
"ValueError",
"(",
"\"Lenght of the '{0}' is limited to {1}\"",
".",
"format",
"(",
"self",
".",
"name",
",",
"self",
".",
"size",
")",
")",
"if",
"not",
"value",
"and",
"self",
".",
"required",
":",
"raise",
"ValueError",
"(",
"\"'{0}' field is required\"",
".",
"format",
"(",
"self",
".",
"name",
")",
")",
"return",
"value"
] |
Check the validity of a value for the field.
|
[
"Check",
"the",
"validity",
"of",
"a",
"value",
"for",
"the",
"field",
"."
] |
d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0
|
https://github.com/OCA/odoorpc/blob/d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0/odoorpc/fields.py#L147-L162
|
train
|
OCA/odoorpc
|
odoorpc/fields.py
|
Reference._check_relation
|
def _check_relation(self, relation):
"""Raise a `ValueError` if `relation` is not allowed among
the possible values.
"""
selection = [val[0] for val in self.selection]
if relation not in selection:
raise ValueError(
("The value '{value}' supplied doesn't match with the possible"
" values '{selection}' for the '{field_name}' field").format(
value=relation,
selection=selection,
field_name=self.name,
))
return relation
|
python
|
def _check_relation(self, relation):
"""Raise a `ValueError` if `relation` is not allowed among
the possible values.
"""
selection = [val[0] for val in self.selection]
if relation not in selection:
raise ValueError(
("The value '{value}' supplied doesn't match with the possible"
" values '{selection}' for the '{field_name}' field").format(
value=relation,
selection=selection,
field_name=self.name,
))
return relation
|
[
"def",
"_check_relation",
"(",
"self",
",",
"relation",
")",
":",
"selection",
"=",
"[",
"val",
"[",
"0",
"]",
"for",
"val",
"in",
"self",
".",
"selection",
"]",
"if",
"relation",
"not",
"in",
"selection",
":",
"raise",
"ValueError",
"(",
"(",
"\"The value '{value}' supplied doesn't match with the possible\"",
"\" values '{selection}' for the '{field_name}' field\"",
")",
".",
"format",
"(",
"value",
"=",
"relation",
",",
"selection",
"=",
"selection",
",",
"field_name",
"=",
"self",
".",
"name",
",",
")",
")",
"return",
"relation"
] |
Raise a `ValueError` if `relation` is not allowed among
the possible values.
|
[
"Raise",
"a",
"ValueError",
"if",
"relation",
"is",
"not",
"allowed",
"among",
"the",
"possible",
"values",
"."
] |
d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0
|
https://github.com/OCA/odoorpc/blob/d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0/odoorpc/fields.py#L612-L625
|
train
|
OCA/odoorpc
|
odoorpc/models.py
|
Model._with_context
|
def _with_context(self, *args, **kwargs):
"""As the `with_context` class method but for recordset."""
context = dict(args[0] if args else self.env.context, **kwargs)
return self.with_env(self.env(context=context))
|
python
|
def _with_context(self, *args, **kwargs):
"""As the `with_context` class method but for recordset."""
context = dict(args[0] if args else self.env.context, **kwargs)
return self.with_env(self.env(context=context))
|
[
"def",
"_with_context",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"context",
"=",
"dict",
"(",
"args",
"[",
"0",
"]",
"if",
"args",
"else",
"self",
".",
"env",
".",
"context",
",",
"*",
"*",
"kwargs",
")",
"return",
"self",
".",
"with_env",
"(",
"self",
".",
"env",
"(",
"context",
"=",
"context",
")",
")"
] |
As the `with_context` class method but for recordset.
|
[
"As",
"the",
"with_context",
"class",
"method",
"but",
"for",
"recordset",
"."
] |
d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0
|
https://github.com/OCA/odoorpc/blob/d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0/odoorpc/models.py#L326-L329
|
train
|
OCA/odoorpc
|
odoorpc/models.py
|
Model._with_env
|
def _with_env(self, env):
"""As the `with_env` class method but for recordset."""
res = self._browse(env, self._ids)
return res
|
python
|
def _with_env(self, env):
"""As the `with_env` class method but for recordset."""
res = self._browse(env, self._ids)
return res
|
[
"def",
"_with_env",
"(",
"self",
",",
"env",
")",
":",
"res",
"=",
"self",
".",
"_browse",
"(",
"env",
",",
"self",
".",
"_ids",
")",
"return",
"res"
] |
As the `with_env` class method but for recordset.
|
[
"As",
"the",
"with_env",
"class",
"method",
"but",
"for",
"recordset",
"."
] |
d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0
|
https://github.com/OCA/odoorpc/blob/d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0/odoorpc/models.py#L340-L343
|
train
|
OCA/odoorpc
|
odoorpc/models.py
|
Model._init_values
|
def _init_values(self, context=None):
"""Retrieve field values from the server.
May be used to restore the original values in the purpose to cancel
all changes made.
"""
if context is None:
context = self.env.context
# Get basic fields (no relational ones)
basic_fields = []
for field_name in self._columns:
field = self._columns[field_name]
if not getattr(field, 'relation', False):
basic_fields.append(field_name)
# Fetch values from the server
if self.ids:
rows = self.__class__.read(
self.ids, basic_fields, context=context, load='_classic_write')
ids_fetched = set()
for row in rows:
ids_fetched.add(row['id'])
for field_name in row:
if field_name == 'id':
continue
self._values[field_name][row['id']] = row[field_name]
ids_in_error = set(self.ids) - ids_fetched
if ids_in_error:
raise ValueError(
"There is no '{model}' record with IDs {ids}.".format(
model=self._name, ids=list(ids_in_error)))
# No ID: fields filled with default values
else:
default_get = self.__class__.default_get(
list(self._columns), context=context)
for field_name in self._columns:
self._values[field_name][None] = default_get.get(
field_name, False)
|
python
|
def _init_values(self, context=None):
"""Retrieve field values from the server.
May be used to restore the original values in the purpose to cancel
all changes made.
"""
if context is None:
context = self.env.context
# Get basic fields (no relational ones)
basic_fields = []
for field_name in self._columns:
field = self._columns[field_name]
if not getattr(field, 'relation', False):
basic_fields.append(field_name)
# Fetch values from the server
if self.ids:
rows = self.__class__.read(
self.ids, basic_fields, context=context, load='_classic_write')
ids_fetched = set()
for row in rows:
ids_fetched.add(row['id'])
for field_name in row:
if field_name == 'id':
continue
self._values[field_name][row['id']] = row[field_name]
ids_in_error = set(self.ids) - ids_fetched
if ids_in_error:
raise ValueError(
"There is no '{model}' record with IDs {ids}.".format(
model=self._name, ids=list(ids_in_error)))
# No ID: fields filled with default values
else:
default_get = self.__class__.default_get(
list(self._columns), context=context)
for field_name in self._columns:
self._values[field_name][None] = default_get.get(
field_name, False)
|
[
"def",
"_init_values",
"(",
"self",
",",
"context",
"=",
"None",
")",
":",
"if",
"context",
"is",
"None",
":",
"context",
"=",
"self",
".",
"env",
".",
"context",
"# Get basic fields (no relational ones)",
"basic_fields",
"=",
"[",
"]",
"for",
"field_name",
"in",
"self",
".",
"_columns",
":",
"field",
"=",
"self",
".",
"_columns",
"[",
"field_name",
"]",
"if",
"not",
"getattr",
"(",
"field",
",",
"'relation'",
",",
"False",
")",
":",
"basic_fields",
".",
"append",
"(",
"field_name",
")",
"# Fetch values from the server",
"if",
"self",
".",
"ids",
":",
"rows",
"=",
"self",
".",
"__class__",
".",
"read",
"(",
"self",
".",
"ids",
",",
"basic_fields",
",",
"context",
"=",
"context",
",",
"load",
"=",
"'_classic_write'",
")",
"ids_fetched",
"=",
"set",
"(",
")",
"for",
"row",
"in",
"rows",
":",
"ids_fetched",
".",
"add",
"(",
"row",
"[",
"'id'",
"]",
")",
"for",
"field_name",
"in",
"row",
":",
"if",
"field_name",
"==",
"'id'",
":",
"continue",
"self",
".",
"_values",
"[",
"field_name",
"]",
"[",
"row",
"[",
"'id'",
"]",
"]",
"=",
"row",
"[",
"field_name",
"]",
"ids_in_error",
"=",
"set",
"(",
"self",
".",
"ids",
")",
"-",
"ids_fetched",
"if",
"ids_in_error",
":",
"raise",
"ValueError",
"(",
"\"There is no '{model}' record with IDs {ids}.\"",
".",
"format",
"(",
"model",
"=",
"self",
".",
"_name",
",",
"ids",
"=",
"list",
"(",
"ids_in_error",
")",
")",
")",
"# No ID: fields filled with default values",
"else",
":",
"default_get",
"=",
"self",
".",
"__class__",
".",
"default_get",
"(",
"list",
"(",
"self",
".",
"_columns",
")",
",",
"context",
"=",
"context",
")",
"for",
"field_name",
"in",
"self",
".",
"_columns",
":",
"self",
".",
"_values",
"[",
"field_name",
"]",
"[",
"None",
"]",
"=",
"default_get",
".",
"get",
"(",
"field_name",
",",
"False",
")"
] |
Retrieve field values from the server.
May be used to restore the original values in the purpose to cancel
all changes made.
|
[
"Retrieve",
"field",
"values",
"from",
"the",
"server",
".",
"May",
"be",
"used",
"to",
"restore",
"the",
"original",
"values",
"in",
"the",
"purpose",
"to",
"cancel",
"all",
"changes",
"made",
"."
] |
d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0
|
https://github.com/OCA/odoorpc/blob/d90aa0b2bc4fafbab8bd8f50d50e3fb0b9ba91f0/odoorpc/models.py#L345-L380
|
train
|
ethereum/eth-utils
|
eth_utils/currency.py
|
from_wei
|
def from_wei(number: int, unit: str) -> Union[int, decimal.Decimal]:
"""
Takes a number of wei and converts it to any other ether unit.
"""
if unit.lower() not in units:
raise ValueError(
"Unknown unit. Must be one of {0}".format("/".join(units.keys()))
)
if number == 0:
return 0
if number < MIN_WEI or number > MAX_WEI:
raise ValueError("value must be between 1 and 2**256 - 1")
unit_value = units[unit.lower()]
with localcontext() as ctx:
ctx.prec = 999
d_number = decimal.Decimal(value=number, context=ctx)
result_value = d_number / unit_value
return result_value
|
python
|
def from_wei(number: int, unit: str) -> Union[int, decimal.Decimal]:
"""
Takes a number of wei and converts it to any other ether unit.
"""
if unit.lower() not in units:
raise ValueError(
"Unknown unit. Must be one of {0}".format("/".join(units.keys()))
)
if number == 0:
return 0
if number < MIN_WEI or number > MAX_WEI:
raise ValueError("value must be between 1 and 2**256 - 1")
unit_value = units[unit.lower()]
with localcontext() as ctx:
ctx.prec = 999
d_number = decimal.Decimal(value=number, context=ctx)
result_value = d_number / unit_value
return result_value
|
[
"def",
"from_wei",
"(",
"number",
":",
"int",
",",
"unit",
":",
"str",
")",
"->",
"Union",
"[",
"int",
",",
"decimal",
".",
"Decimal",
"]",
":",
"if",
"unit",
".",
"lower",
"(",
")",
"not",
"in",
"units",
":",
"raise",
"ValueError",
"(",
"\"Unknown unit. Must be one of {0}\"",
".",
"format",
"(",
"\"/\"",
".",
"join",
"(",
"units",
".",
"keys",
"(",
")",
")",
")",
")",
"if",
"number",
"==",
"0",
":",
"return",
"0",
"if",
"number",
"<",
"MIN_WEI",
"or",
"number",
">",
"MAX_WEI",
":",
"raise",
"ValueError",
"(",
"\"value must be between 1 and 2**256 - 1\"",
")",
"unit_value",
"=",
"units",
"[",
"unit",
".",
"lower",
"(",
")",
"]",
"with",
"localcontext",
"(",
")",
"as",
"ctx",
":",
"ctx",
".",
"prec",
"=",
"999",
"d_number",
"=",
"decimal",
".",
"Decimal",
"(",
"value",
"=",
"number",
",",
"context",
"=",
"ctx",
")",
"result_value",
"=",
"d_number",
"/",
"unit_value",
"return",
"result_value"
] |
Takes a number of wei and converts it to any other ether unit.
|
[
"Takes",
"a",
"number",
"of",
"wei",
"and",
"converts",
"it",
"to",
"any",
"other",
"ether",
"unit",
"."
] |
d9889753a8e016d2fcd64ade0e2db3844486551d
|
https://github.com/ethereum/eth-utils/blob/d9889753a8e016d2fcd64ade0e2db3844486551d/eth_utils/currency.py#L40-L62
|
train
|
ethereum/eth-utils
|
eth_utils/currency.py
|
to_wei
|
def to_wei(number: int, unit: str) -> int:
"""
Takes a number of a unit and converts it to wei.
"""
if unit.lower() not in units:
raise ValueError(
"Unknown unit. Must be one of {0}".format("/".join(units.keys()))
)
if is_integer(number) or is_string(number):
d_number = decimal.Decimal(value=number)
elif isinstance(number, float):
d_number = decimal.Decimal(value=str(number))
elif isinstance(number, decimal.Decimal):
d_number = number
else:
raise TypeError("Unsupported type. Must be one of integer, float, or string")
s_number = str(number)
unit_value = units[unit.lower()]
if d_number == 0:
return 0
if d_number < 1 and "." in s_number:
with localcontext() as ctx:
multiplier = len(s_number) - s_number.index(".") - 1
ctx.prec = multiplier
d_number = decimal.Decimal(value=number, context=ctx) * 10 ** multiplier
unit_value /= 10 ** multiplier
with localcontext() as ctx:
ctx.prec = 999
result_value = decimal.Decimal(value=d_number, context=ctx) * unit_value
if result_value < MIN_WEI or result_value > MAX_WEI:
raise ValueError("Resulting wei value must be between 1 and 2**256 - 1")
return int(result_value)
|
python
|
def to_wei(number: int, unit: str) -> int:
"""
Takes a number of a unit and converts it to wei.
"""
if unit.lower() not in units:
raise ValueError(
"Unknown unit. Must be one of {0}".format("/".join(units.keys()))
)
if is_integer(number) or is_string(number):
d_number = decimal.Decimal(value=number)
elif isinstance(number, float):
d_number = decimal.Decimal(value=str(number))
elif isinstance(number, decimal.Decimal):
d_number = number
else:
raise TypeError("Unsupported type. Must be one of integer, float, or string")
s_number = str(number)
unit_value = units[unit.lower()]
if d_number == 0:
return 0
if d_number < 1 and "." in s_number:
with localcontext() as ctx:
multiplier = len(s_number) - s_number.index(".") - 1
ctx.prec = multiplier
d_number = decimal.Decimal(value=number, context=ctx) * 10 ** multiplier
unit_value /= 10 ** multiplier
with localcontext() as ctx:
ctx.prec = 999
result_value = decimal.Decimal(value=d_number, context=ctx) * unit_value
if result_value < MIN_WEI or result_value > MAX_WEI:
raise ValueError("Resulting wei value must be between 1 and 2**256 - 1")
return int(result_value)
|
[
"def",
"to_wei",
"(",
"number",
":",
"int",
",",
"unit",
":",
"str",
")",
"->",
"int",
":",
"if",
"unit",
".",
"lower",
"(",
")",
"not",
"in",
"units",
":",
"raise",
"ValueError",
"(",
"\"Unknown unit. Must be one of {0}\"",
".",
"format",
"(",
"\"/\"",
".",
"join",
"(",
"units",
".",
"keys",
"(",
")",
")",
")",
")",
"if",
"is_integer",
"(",
"number",
")",
"or",
"is_string",
"(",
"number",
")",
":",
"d_number",
"=",
"decimal",
".",
"Decimal",
"(",
"value",
"=",
"number",
")",
"elif",
"isinstance",
"(",
"number",
",",
"float",
")",
":",
"d_number",
"=",
"decimal",
".",
"Decimal",
"(",
"value",
"=",
"str",
"(",
"number",
")",
")",
"elif",
"isinstance",
"(",
"number",
",",
"decimal",
".",
"Decimal",
")",
":",
"d_number",
"=",
"number",
"else",
":",
"raise",
"TypeError",
"(",
"\"Unsupported type. Must be one of integer, float, or string\"",
")",
"s_number",
"=",
"str",
"(",
"number",
")",
"unit_value",
"=",
"units",
"[",
"unit",
".",
"lower",
"(",
")",
"]",
"if",
"d_number",
"==",
"0",
":",
"return",
"0",
"if",
"d_number",
"<",
"1",
"and",
"\".\"",
"in",
"s_number",
":",
"with",
"localcontext",
"(",
")",
"as",
"ctx",
":",
"multiplier",
"=",
"len",
"(",
"s_number",
")",
"-",
"s_number",
".",
"index",
"(",
"\".\"",
")",
"-",
"1",
"ctx",
".",
"prec",
"=",
"multiplier",
"d_number",
"=",
"decimal",
".",
"Decimal",
"(",
"value",
"=",
"number",
",",
"context",
"=",
"ctx",
")",
"*",
"10",
"**",
"multiplier",
"unit_value",
"/=",
"10",
"**",
"multiplier",
"with",
"localcontext",
"(",
")",
"as",
"ctx",
":",
"ctx",
".",
"prec",
"=",
"999",
"result_value",
"=",
"decimal",
".",
"Decimal",
"(",
"value",
"=",
"d_number",
",",
"context",
"=",
"ctx",
")",
"*",
"unit_value",
"if",
"result_value",
"<",
"MIN_WEI",
"or",
"result_value",
">",
"MAX_WEI",
":",
"raise",
"ValueError",
"(",
"\"Resulting wei value must be between 1 and 2**256 - 1\"",
")",
"return",
"int",
"(",
"result_value",
")"
] |
Takes a number of a unit and converts it to wei.
|
[
"Takes",
"a",
"number",
"of",
"a",
"unit",
"and",
"converts",
"it",
"to",
"wei",
"."
] |
d9889753a8e016d2fcd64ade0e2db3844486551d
|
https://github.com/ethereum/eth-utils/blob/d9889753a8e016d2fcd64ade0e2db3844486551d/eth_utils/currency.py#L65-L103
|
train
|
ethereum/eth-utils
|
eth_utils/decorators.py
|
validate_conversion_arguments
|
def validate_conversion_arguments(to_wrap):
"""
Validates arguments for conversion functions.
- Only a single argument is present
- Kwarg must be 'primitive' 'hexstr' or 'text'
- If it is 'hexstr' or 'text' that it is a text type
"""
@functools.wraps(to_wrap)
def wrapper(*args, **kwargs):
_assert_one_val(*args, **kwargs)
if kwargs:
_validate_supported_kwarg(kwargs)
if len(args) == 0 and "primitive" not in kwargs:
_assert_hexstr_or_text_kwarg_is_text_type(**kwargs)
return to_wrap(*args, **kwargs)
return wrapper
|
python
|
def validate_conversion_arguments(to_wrap):
"""
Validates arguments for conversion functions.
- Only a single argument is present
- Kwarg must be 'primitive' 'hexstr' or 'text'
- If it is 'hexstr' or 'text' that it is a text type
"""
@functools.wraps(to_wrap)
def wrapper(*args, **kwargs):
_assert_one_val(*args, **kwargs)
if kwargs:
_validate_supported_kwarg(kwargs)
if len(args) == 0 and "primitive" not in kwargs:
_assert_hexstr_or_text_kwarg_is_text_type(**kwargs)
return to_wrap(*args, **kwargs)
return wrapper
|
[
"def",
"validate_conversion_arguments",
"(",
"to_wrap",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"to_wrap",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_assert_one_val",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"kwargs",
":",
"_validate_supported_kwarg",
"(",
"kwargs",
")",
"if",
"len",
"(",
"args",
")",
"==",
"0",
"and",
"\"primitive\"",
"not",
"in",
"kwargs",
":",
"_assert_hexstr_or_text_kwarg_is_text_type",
"(",
"*",
"*",
"kwargs",
")",
"return",
"to_wrap",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"wrapper"
] |
Validates arguments for conversion functions.
- Only a single argument is present
- Kwarg must be 'primitive' 'hexstr' or 'text'
- If it is 'hexstr' or 'text' that it is a text type
|
[
"Validates",
"arguments",
"for",
"conversion",
"functions",
".",
"-",
"Only",
"a",
"single",
"argument",
"is",
"present",
"-",
"Kwarg",
"must",
"be",
"primitive",
"hexstr",
"or",
"text",
"-",
"If",
"it",
"is",
"hexstr",
"or",
"text",
"that",
"it",
"is",
"a",
"text",
"type"
] |
d9889753a8e016d2fcd64ade0e2db3844486551d
|
https://github.com/ethereum/eth-utils/blob/d9889753a8e016d2fcd64ade0e2db3844486551d/eth_utils/decorators.py#L59-L77
|
train
|
ethereum/eth-utils
|
eth_utils/decorators.py
|
replace_exceptions
|
def replace_exceptions(
old_to_new_exceptions: Dict[Type[BaseException], Type[BaseException]]
) -> Callable[..., Any]:
"""
Replaces old exceptions with new exceptions to be raised in their place.
"""
old_exceptions = tuple(old_to_new_exceptions.keys())
def decorator(to_wrap: Callable[..., Any]) -> Callable[..., Any]:
@functools.wraps(to_wrap)
# String type b/c pypy3 throws SegmentationFault with Iterable as arg on nested fn
# Ignore so we don't have to import `Iterable`
def wrapper(
*args: Iterable[Any], **kwargs: Dict[str, Any]
) -> Callable[..., Any]:
try:
return to_wrap(*args, **kwargs)
except old_exceptions as err:
try:
raise old_to_new_exceptions[type(err)] from err
except KeyError:
raise TypeError(
"could not look up new exception to use for %r" % err
) from err
return wrapper
return decorator
|
python
|
def replace_exceptions(
old_to_new_exceptions: Dict[Type[BaseException], Type[BaseException]]
) -> Callable[..., Any]:
"""
Replaces old exceptions with new exceptions to be raised in their place.
"""
old_exceptions = tuple(old_to_new_exceptions.keys())
def decorator(to_wrap: Callable[..., Any]) -> Callable[..., Any]:
@functools.wraps(to_wrap)
# String type b/c pypy3 throws SegmentationFault with Iterable as arg on nested fn
# Ignore so we don't have to import `Iterable`
def wrapper(
*args: Iterable[Any], **kwargs: Dict[str, Any]
) -> Callable[..., Any]:
try:
return to_wrap(*args, **kwargs)
except old_exceptions as err:
try:
raise old_to_new_exceptions[type(err)] from err
except KeyError:
raise TypeError(
"could not look up new exception to use for %r" % err
) from err
return wrapper
return decorator
|
[
"def",
"replace_exceptions",
"(",
"old_to_new_exceptions",
":",
"Dict",
"[",
"Type",
"[",
"BaseException",
"]",
",",
"Type",
"[",
"BaseException",
"]",
"]",
")",
"->",
"Callable",
"[",
"...",
",",
"Any",
"]",
":",
"old_exceptions",
"=",
"tuple",
"(",
"old_to_new_exceptions",
".",
"keys",
"(",
")",
")",
"def",
"decorator",
"(",
"to_wrap",
":",
"Callable",
"[",
"...",
",",
"Any",
"]",
")",
"->",
"Callable",
"[",
"...",
",",
"Any",
"]",
":",
"@",
"functools",
".",
"wraps",
"(",
"to_wrap",
")",
"# String type b/c pypy3 throws SegmentationFault with Iterable as arg on nested fn",
"# Ignore so we don't have to import `Iterable`",
"def",
"wrapper",
"(",
"*",
"args",
":",
"Iterable",
"[",
"Any",
"]",
",",
"*",
"*",
"kwargs",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"Callable",
"[",
"...",
",",
"Any",
"]",
":",
"try",
":",
"return",
"to_wrap",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"old_exceptions",
"as",
"err",
":",
"try",
":",
"raise",
"old_to_new_exceptions",
"[",
"type",
"(",
"err",
")",
"]",
"from",
"err",
"except",
"KeyError",
":",
"raise",
"TypeError",
"(",
"\"could not look up new exception to use for %r\"",
"%",
"err",
")",
"from",
"err",
"return",
"wrapper",
"return",
"decorator"
] |
Replaces old exceptions with new exceptions to be raised in their place.
|
[
"Replaces",
"old",
"exceptions",
"with",
"new",
"exceptions",
"to",
"be",
"raised",
"in",
"their",
"place",
"."
] |
d9889753a8e016d2fcd64ade0e2db3844486551d
|
https://github.com/ethereum/eth-utils/blob/d9889753a8e016d2fcd64ade0e2db3844486551d/eth_utils/decorators.py#L97-L124
|
train
|
ethereum/eth-utils
|
eth_utils/abi.py
|
collapse_if_tuple
|
def collapse_if_tuple(abi):
"""Converts a tuple from a dict to a parenthesized list of its types.
>>> from eth_utils.abi import collapse_if_tuple
>>> collapse_if_tuple(
... {
... 'components': [
... {'name': 'anAddress', 'type': 'address'},
... {'name': 'anInt', 'type': 'uint256'},
... {'name': 'someBytes', 'type': 'bytes'},
... ],
... 'type': 'tuple',
... }
... )
'(address,uint256,bytes)'
"""
typ = abi["type"]
if not typ.startswith("tuple"):
return typ
delimited = ",".join(collapse_if_tuple(c) for c in abi["components"])
# Whatever comes after "tuple" is the array dims. The ABI spec states that
# this will have the form "", "[]", or "[k]".
array_dim = typ[5:]
collapsed = "({}){}".format(delimited, array_dim)
return collapsed
|
python
|
def collapse_if_tuple(abi):
"""Converts a tuple from a dict to a parenthesized list of its types.
>>> from eth_utils.abi import collapse_if_tuple
>>> collapse_if_tuple(
... {
... 'components': [
... {'name': 'anAddress', 'type': 'address'},
... {'name': 'anInt', 'type': 'uint256'},
... {'name': 'someBytes', 'type': 'bytes'},
... ],
... 'type': 'tuple',
... }
... )
'(address,uint256,bytes)'
"""
typ = abi["type"]
if not typ.startswith("tuple"):
return typ
delimited = ",".join(collapse_if_tuple(c) for c in abi["components"])
# Whatever comes after "tuple" is the array dims. The ABI spec states that
# this will have the form "", "[]", or "[k]".
array_dim = typ[5:]
collapsed = "({}){}".format(delimited, array_dim)
return collapsed
|
[
"def",
"collapse_if_tuple",
"(",
"abi",
")",
":",
"typ",
"=",
"abi",
"[",
"\"type\"",
"]",
"if",
"not",
"typ",
".",
"startswith",
"(",
"\"tuple\"",
")",
":",
"return",
"typ",
"delimited",
"=",
"\",\"",
".",
"join",
"(",
"collapse_if_tuple",
"(",
"c",
")",
"for",
"c",
"in",
"abi",
"[",
"\"components\"",
"]",
")",
"# Whatever comes after \"tuple\" is the array dims. The ABI spec states that",
"# this will have the form \"\", \"[]\", or \"[k]\".",
"array_dim",
"=",
"typ",
"[",
"5",
":",
"]",
"collapsed",
"=",
"\"({}){}\"",
".",
"format",
"(",
"delimited",
",",
"array_dim",
")",
"return",
"collapsed"
] |
Converts a tuple from a dict to a parenthesized list of its types.
>>> from eth_utils.abi import collapse_if_tuple
>>> collapse_if_tuple(
... {
... 'components': [
... {'name': 'anAddress', 'type': 'address'},
... {'name': 'anInt', 'type': 'uint256'},
... {'name': 'someBytes', 'type': 'bytes'},
... ],
... 'type': 'tuple',
... }
... )
'(address,uint256,bytes)'
|
[
"Converts",
"a",
"tuple",
"from",
"a",
"dict",
"to",
"a",
"parenthesized",
"list",
"of",
"its",
"types",
"."
] |
d9889753a8e016d2fcd64ade0e2db3844486551d
|
https://github.com/ethereum/eth-utils/blob/d9889753a8e016d2fcd64ade0e2db3844486551d/eth_utils/abi.py#L6-L32
|
train
|
ethereum/eth-utils
|
eth_utils/address.py
|
is_hex_address
|
def is_hex_address(value: Any) -> bool:
"""
Checks if the given string of text type is an address in hexadecimal encoded form.
"""
if not is_text(value):
return False
elif not is_hex(value):
return False
else:
unprefixed = remove_0x_prefix(value)
return len(unprefixed) == 40
|
python
|
def is_hex_address(value: Any) -> bool:
"""
Checks if the given string of text type is an address in hexadecimal encoded form.
"""
if not is_text(value):
return False
elif not is_hex(value):
return False
else:
unprefixed = remove_0x_prefix(value)
return len(unprefixed) == 40
|
[
"def",
"is_hex_address",
"(",
"value",
":",
"Any",
")",
"->",
"bool",
":",
"if",
"not",
"is_text",
"(",
"value",
")",
":",
"return",
"False",
"elif",
"not",
"is_hex",
"(",
"value",
")",
":",
"return",
"False",
"else",
":",
"unprefixed",
"=",
"remove_0x_prefix",
"(",
"value",
")",
"return",
"len",
"(",
"unprefixed",
")",
"==",
"40"
] |
Checks if the given string of text type is an address in hexadecimal encoded form.
|
[
"Checks",
"if",
"the",
"given",
"string",
"of",
"text",
"type",
"is",
"an",
"address",
"in",
"hexadecimal",
"encoded",
"form",
"."
] |
d9889753a8e016d2fcd64ade0e2db3844486551d
|
https://github.com/ethereum/eth-utils/blob/d9889753a8e016d2fcd64ade0e2db3844486551d/eth_utils/address.py#L10-L20
|
train
|
ethereum/eth-utils
|
eth_utils/address.py
|
is_binary_address
|
def is_binary_address(value: Any) -> bool:
"""
Checks if the given string is an address in raw bytes form.
"""
if not is_bytes(value):
return False
elif len(value) != 20:
return False
else:
return True
|
python
|
def is_binary_address(value: Any) -> bool:
"""
Checks if the given string is an address in raw bytes form.
"""
if not is_bytes(value):
return False
elif len(value) != 20:
return False
else:
return True
|
[
"def",
"is_binary_address",
"(",
"value",
":",
"Any",
")",
"->",
"bool",
":",
"if",
"not",
"is_bytes",
"(",
"value",
")",
":",
"return",
"False",
"elif",
"len",
"(",
"value",
")",
"!=",
"20",
":",
"return",
"False",
"else",
":",
"return",
"True"
] |
Checks if the given string is an address in raw bytes form.
|
[
"Checks",
"if",
"the",
"given",
"string",
"is",
"an",
"address",
"in",
"raw",
"bytes",
"form",
"."
] |
d9889753a8e016d2fcd64ade0e2db3844486551d
|
https://github.com/ethereum/eth-utils/blob/d9889753a8e016d2fcd64ade0e2db3844486551d/eth_utils/address.py#L23-L32
|
train
|
ethereum/eth-utils
|
eth_utils/address.py
|
is_address
|
def is_address(value: Any) -> bool:
"""
Checks if the given string in a supported value
is an address in any of the known formats.
"""
if is_checksum_formatted_address(value):
return is_checksum_address(value)
elif is_hex_address(value):
return True
elif is_binary_address(value):
return True
else:
return False
|
python
|
def is_address(value: Any) -> bool:
"""
Checks if the given string in a supported value
is an address in any of the known formats.
"""
if is_checksum_formatted_address(value):
return is_checksum_address(value)
elif is_hex_address(value):
return True
elif is_binary_address(value):
return True
else:
return False
|
[
"def",
"is_address",
"(",
"value",
":",
"Any",
")",
"->",
"bool",
":",
"if",
"is_checksum_formatted_address",
"(",
"value",
")",
":",
"return",
"is_checksum_address",
"(",
"value",
")",
"elif",
"is_hex_address",
"(",
"value",
")",
":",
"return",
"True",
"elif",
"is_binary_address",
"(",
"value",
")",
":",
"return",
"True",
"else",
":",
"return",
"False"
] |
Checks if the given string in a supported value
is an address in any of the known formats.
|
[
"Checks",
"if",
"the",
"given",
"string",
"in",
"a",
"supported",
"value",
"is",
"an",
"address",
"in",
"any",
"of",
"the",
"known",
"formats",
"."
] |
d9889753a8e016d2fcd64ade0e2db3844486551d
|
https://github.com/ethereum/eth-utils/blob/d9889753a8e016d2fcd64ade0e2db3844486551d/eth_utils/address.py#L35-L47
|
train
|
ethereum/eth-utils
|
eth_utils/address.py
|
to_normalized_address
|
def to_normalized_address(value: AnyStr) -> HexAddress:
"""
Converts an address to its normalized hexadecimal representation.
"""
try:
hex_address = hexstr_if_str(to_hex, value).lower()
except AttributeError:
raise TypeError(
"Value must be any string, instead got type {}".format(type(value))
)
if is_address(hex_address):
return HexAddress(hex_address)
else:
raise ValueError(
"Unknown format {}, attempted to normalize to {}".format(value, hex_address)
)
|
python
|
def to_normalized_address(value: AnyStr) -> HexAddress:
"""
Converts an address to its normalized hexadecimal representation.
"""
try:
hex_address = hexstr_if_str(to_hex, value).lower()
except AttributeError:
raise TypeError(
"Value must be any string, instead got type {}".format(type(value))
)
if is_address(hex_address):
return HexAddress(hex_address)
else:
raise ValueError(
"Unknown format {}, attempted to normalize to {}".format(value, hex_address)
)
|
[
"def",
"to_normalized_address",
"(",
"value",
":",
"AnyStr",
")",
"->",
"HexAddress",
":",
"try",
":",
"hex_address",
"=",
"hexstr_if_str",
"(",
"to_hex",
",",
"value",
")",
".",
"lower",
"(",
")",
"except",
"AttributeError",
":",
"raise",
"TypeError",
"(",
"\"Value must be any string, instead got type {}\"",
".",
"format",
"(",
"type",
"(",
"value",
")",
")",
")",
"if",
"is_address",
"(",
"hex_address",
")",
":",
"return",
"HexAddress",
"(",
"hex_address",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"Unknown format {}, attempted to normalize to {}\"",
".",
"format",
"(",
"value",
",",
"hex_address",
")",
")"
] |
Converts an address to its normalized hexadecimal representation.
|
[
"Converts",
"an",
"address",
"to",
"its",
"normalized",
"hexadecimal",
"representation",
"."
] |
d9889753a8e016d2fcd64ade0e2db3844486551d
|
https://github.com/ethereum/eth-utils/blob/d9889753a8e016d2fcd64ade0e2db3844486551d/eth_utils/address.py#L50-L65
|
train
|
ethereum/eth-utils
|
eth_utils/address.py
|
is_normalized_address
|
def is_normalized_address(value: Any) -> bool:
"""
Returns whether the provided value is an address in its normalized form.
"""
if not is_address(value):
return False
else:
return value == to_normalized_address(value)
|
python
|
def is_normalized_address(value: Any) -> bool:
"""
Returns whether the provided value is an address in its normalized form.
"""
if not is_address(value):
return False
else:
return value == to_normalized_address(value)
|
[
"def",
"is_normalized_address",
"(",
"value",
":",
"Any",
")",
"->",
"bool",
":",
"if",
"not",
"is_address",
"(",
"value",
")",
":",
"return",
"False",
"else",
":",
"return",
"value",
"==",
"to_normalized_address",
"(",
"value",
")"
] |
Returns whether the provided value is an address in its normalized form.
|
[
"Returns",
"whether",
"the",
"provided",
"value",
"is",
"an",
"address",
"in",
"its",
"normalized",
"form",
"."
] |
d9889753a8e016d2fcd64ade0e2db3844486551d
|
https://github.com/ethereum/eth-utils/blob/d9889753a8e016d2fcd64ade0e2db3844486551d/eth_utils/address.py#L68-L75
|
train
|
ethereum/eth-utils
|
eth_utils/address.py
|
is_canonical_address
|
def is_canonical_address(address: Any) -> bool:
"""
Returns `True` if the `value` is an address in its canonical form.
"""
if not is_bytes(address) or len(address) != 20:
return False
return address == to_canonical_address(address)
|
python
|
def is_canonical_address(address: Any) -> bool:
"""
Returns `True` if the `value` is an address in its canonical form.
"""
if not is_bytes(address) or len(address) != 20:
return False
return address == to_canonical_address(address)
|
[
"def",
"is_canonical_address",
"(",
"address",
":",
"Any",
")",
"->",
"bool",
":",
"if",
"not",
"is_bytes",
"(",
"address",
")",
"or",
"len",
"(",
"address",
")",
"!=",
"20",
":",
"return",
"False",
"return",
"address",
"==",
"to_canonical_address",
"(",
"address",
")"
] |
Returns `True` if the `value` is an address in its canonical form.
|
[
"Returns",
"True",
"if",
"the",
"value",
"is",
"an",
"address",
"in",
"its",
"canonical",
"form",
"."
] |
d9889753a8e016d2fcd64ade0e2db3844486551d
|
https://github.com/ethereum/eth-utils/blob/d9889753a8e016d2fcd64ade0e2db3844486551d/eth_utils/address.py#L86-L92
|
train
|
ethereum/eth-utils
|
eth_utils/address.py
|
is_same_address
|
def is_same_address(left: AnyAddress, right: AnyAddress) -> bool:
"""
Checks if both addresses are same or not.
"""
if not is_address(left) or not is_address(right):
raise ValueError("Both values must be valid addresses")
else:
return to_normalized_address(left) == to_normalized_address(right)
|
python
|
def is_same_address(left: AnyAddress, right: AnyAddress) -> bool:
"""
Checks if both addresses are same or not.
"""
if not is_address(left) or not is_address(right):
raise ValueError("Both values must be valid addresses")
else:
return to_normalized_address(left) == to_normalized_address(right)
|
[
"def",
"is_same_address",
"(",
"left",
":",
"AnyAddress",
",",
"right",
":",
"AnyAddress",
")",
"->",
"bool",
":",
"if",
"not",
"is_address",
"(",
"left",
")",
"or",
"not",
"is_address",
"(",
"right",
")",
":",
"raise",
"ValueError",
"(",
"\"Both values must be valid addresses\"",
")",
"else",
":",
"return",
"to_normalized_address",
"(",
"left",
")",
"==",
"to_normalized_address",
"(",
"right",
")"
] |
Checks if both addresses are same or not.
|
[
"Checks",
"if",
"both",
"addresses",
"are",
"same",
"or",
"not",
"."
] |
d9889753a8e016d2fcd64ade0e2db3844486551d
|
https://github.com/ethereum/eth-utils/blob/d9889753a8e016d2fcd64ade0e2db3844486551d/eth_utils/address.py#L95-L102
|
train
|
ethereum/eth-utils
|
eth_utils/address.py
|
to_checksum_address
|
def to_checksum_address(value: AnyStr) -> ChecksumAddress:
"""
Makes a checksum address given a supported format.
"""
norm_address = to_normalized_address(value)
address_hash = encode_hex(keccak(text=remove_0x_prefix(norm_address)))
checksum_address = add_0x_prefix(
"".join(
(
norm_address[i].upper()
if int(address_hash[i], 16) > 7
else norm_address[i]
)
for i in range(2, 42)
)
)
return ChecksumAddress(HexAddress(checksum_address))
|
python
|
def to_checksum_address(value: AnyStr) -> ChecksumAddress:
"""
Makes a checksum address given a supported format.
"""
norm_address = to_normalized_address(value)
address_hash = encode_hex(keccak(text=remove_0x_prefix(norm_address)))
checksum_address = add_0x_prefix(
"".join(
(
norm_address[i].upper()
if int(address_hash[i], 16) > 7
else norm_address[i]
)
for i in range(2, 42)
)
)
return ChecksumAddress(HexAddress(checksum_address))
|
[
"def",
"to_checksum_address",
"(",
"value",
":",
"AnyStr",
")",
"->",
"ChecksumAddress",
":",
"norm_address",
"=",
"to_normalized_address",
"(",
"value",
")",
"address_hash",
"=",
"encode_hex",
"(",
"keccak",
"(",
"text",
"=",
"remove_0x_prefix",
"(",
"norm_address",
")",
")",
")",
"checksum_address",
"=",
"add_0x_prefix",
"(",
"\"\"",
".",
"join",
"(",
"(",
"norm_address",
"[",
"i",
"]",
".",
"upper",
"(",
")",
"if",
"int",
"(",
"address_hash",
"[",
"i",
"]",
",",
"16",
")",
">",
"7",
"else",
"norm_address",
"[",
"i",
"]",
")",
"for",
"i",
"in",
"range",
"(",
"2",
",",
"42",
")",
")",
")",
"return",
"ChecksumAddress",
"(",
"HexAddress",
"(",
"checksum_address",
")",
")"
] |
Makes a checksum address given a supported format.
|
[
"Makes",
"a",
"checksum",
"address",
"given",
"a",
"supported",
"format",
"."
] |
d9889753a8e016d2fcd64ade0e2db3844486551d
|
https://github.com/ethereum/eth-utils/blob/d9889753a8e016d2fcd64ade0e2db3844486551d/eth_utils/address.py#L105-L122
|
train
|
Azure/msrestazure-for-python
|
msrestazure/azure_active_directory.py
|
get_msi_token
|
def get_msi_token(resource, port=50342, msi_conf=None):
"""Get MSI token if MSI_ENDPOINT is set.
IF MSI_ENDPOINT is not set, will try legacy access through 'http://localhost:{}/oauth2/token'.format(port).
If msi_conf is used, must be a dict of one key in ["client_id", "object_id", "msi_res_id"]
:param str resource: The resource where the token would be use.
:param int port: The port if not the default 50342 is used. Ignored if MSI_ENDPOINT is set.
:param dict[str,str] msi_conf: msi_conf if to request a token through a User Assigned Identity (if not specified, assume System Assigned)
"""
request_uri = os.environ.get("MSI_ENDPOINT", 'http://localhost:{}/oauth2/token'.format(port))
payload = {
'resource': resource
}
if msi_conf:
if len(msi_conf) > 1:
raise ValueError("{} are mutually exclusive".format(list(msi_conf.keys())))
payload.update(msi_conf)
try:
result = requests.post(request_uri, data=payload, headers={'Metadata': 'true'})
_LOGGER.debug("MSI: Retrieving a token from %s, with payload %s", request_uri, payload)
result.raise_for_status()
except Exception as ex: # pylint: disable=broad-except
_LOGGER.warning("MSI: Failed to retrieve a token from '%s' with an error of '%s'. This could be caused "
"by the MSI extension not yet fully provisioned.",
request_uri, ex)
raise
token_entry = result.json()
return token_entry['token_type'], token_entry['access_token'], token_entry
|
python
|
def get_msi_token(resource, port=50342, msi_conf=None):
"""Get MSI token if MSI_ENDPOINT is set.
IF MSI_ENDPOINT is not set, will try legacy access through 'http://localhost:{}/oauth2/token'.format(port).
If msi_conf is used, must be a dict of one key in ["client_id", "object_id", "msi_res_id"]
:param str resource: The resource where the token would be use.
:param int port: The port if not the default 50342 is used. Ignored if MSI_ENDPOINT is set.
:param dict[str,str] msi_conf: msi_conf if to request a token through a User Assigned Identity (if not specified, assume System Assigned)
"""
request_uri = os.environ.get("MSI_ENDPOINT", 'http://localhost:{}/oauth2/token'.format(port))
payload = {
'resource': resource
}
if msi_conf:
if len(msi_conf) > 1:
raise ValueError("{} are mutually exclusive".format(list(msi_conf.keys())))
payload.update(msi_conf)
try:
result = requests.post(request_uri, data=payload, headers={'Metadata': 'true'})
_LOGGER.debug("MSI: Retrieving a token from %s, with payload %s", request_uri, payload)
result.raise_for_status()
except Exception as ex: # pylint: disable=broad-except
_LOGGER.warning("MSI: Failed to retrieve a token from '%s' with an error of '%s'. This could be caused "
"by the MSI extension not yet fully provisioned.",
request_uri, ex)
raise
token_entry = result.json()
return token_entry['token_type'], token_entry['access_token'], token_entry
|
[
"def",
"get_msi_token",
"(",
"resource",
",",
"port",
"=",
"50342",
",",
"msi_conf",
"=",
"None",
")",
":",
"request_uri",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"\"MSI_ENDPOINT\"",
",",
"'http://localhost:{}/oauth2/token'",
".",
"format",
"(",
"port",
")",
")",
"payload",
"=",
"{",
"'resource'",
":",
"resource",
"}",
"if",
"msi_conf",
":",
"if",
"len",
"(",
"msi_conf",
")",
">",
"1",
":",
"raise",
"ValueError",
"(",
"\"{} are mutually exclusive\"",
".",
"format",
"(",
"list",
"(",
"msi_conf",
".",
"keys",
"(",
")",
")",
")",
")",
"payload",
".",
"update",
"(",
"msi_conf",
")",
"try",
":",
"result",
"=",
"requests",
".",
"post",
"(",
"request_uri",
",",
"data",
"=",
"payload",
",",
"headers",
"=",
"{",
"'Metadata'",
":",
"'true'",
"}",
")",
"_LOGGER",
".",
"debug",
"(",
"\"MSI: Retrieving a token from %s, with payload %s\"",
",",
"request_uri",
",",
"payload",
")",
"result",
".",
"raise_for_status",
"(",
")",
"except",
"Exception",
"as",
"ex",
":",
"# pylint: disable=broad-except",
"_LOGGER",
".",
"warning",
"(",
"\"MSI: Failed to retrieve a token from '%s' with an error of '%s'. This could be caused \"",
"\"by the MSI extension not yet fully provisioned.\"",
",",
"request_uri",
",",
"ex",
")",
"raise",
"token_entry",
"=",
"result",
".",
"json",
"(",
")",
"return",
"token_entry",
"[",
"'token_type'",
"]",
",",
"token_entry",
"[",
"'access_token'",
"]",
",",
"token_entry"
] |
Get MSI token if MSI_ENDPOINT is set.
IF MSI_ENDPOINT is not set, will try legacy access through 'http://localhost:{}/oauth2/token'.format(port).
If msi_conf is used, must be a dict of one key in ["client_id", "object_id", "msi_res_id"]
:param str resource: The resource where the token would be use.
:param int port: The port if not the default 50342 is used. Ignored if MSI_ENDPOINT is set.
:param dict[str,str] msi_conf: msi_conf if to request a token through a User Assigned Identity (if not specified, assume System Assigned)
|
[
"Get",
"MSI",
"token",
"if",
"MSI_ENDPOINT",
"is",
"set",
"."
] |
5f99262305692525d03ca87d2c5356b05c5aa874
|
https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/azure_active_directory.py#L462-L492
|
train
|
Azure/msrestazure-for-python
|
msrestazure/azure_active_directory.py
|
get_msi_token_webapp
|
def get_msi_token_webapp(resource):
"""Get a MSI token from inside a webapp or functions.
Env variable will look like:
- MSI_ENDPOINT = http://127.0.0.1:41741/MSI/token/
- MSI_SECRET = 69418689F1E342DD946CB82994CDA3CB
"""
try:
msi_endpoint = os.environ['MSI_ENDPOINT']
msi_secret = os.environ['MSI_SECRET']
except KeyError as err:
err_msg = "{} required env variable was not found. You might need to restart your app/function.".format(err)
_LOGGER.critical(err_msg)
raise RuntimeError(err_msg)
request_uri = '{}/?resource={}&api-version=2017-09-01'.format(msi_endpoint, resource)
headers = {
'secret': msi_secret
}
err = None
try:
result = requests.get(request_uri, headers=headers)
_LOGGER.debug("MSI: Retrieving a token from %s", request_uri)
if result.status_code != 200:
err = result.text
# Workaround since not all failures are != 200
if 'ExceptionMessage' in result.text:
err = result.text
except Exception as ex: # pylint: disable=broad-except
err = str(ex)
if err:
err_msg = "MSI: Failed to retrieve a token from '{}' with an error of '{}'.".format(
request_uri, err
)
_LOGGER.critical(err_msg)
raise RuntimeError(err_msg)
_LOGGER.debug('MSI: token retrieved')
token_entry = result.json()
return token_entry['token_type'], token_entry['access_token'], token_entry
|
python
|
def get_msi_token_webapp(resource):
"""Get a MSI token from inside a webapp or functions.
Env variable will look like:
- MSI_ENDPOINT = http://127.0.0.1:41741/MSI/token/
- MSI_SECRET = 69418689F1E342DD946CB82994CDA3CB
"""
try:
msi_endpoint = os.environ['MSI_ENDPOINT']
msi_secret = os.environ['MSI_SECRET']
except KeyError as err:
err_msg = "{} required env variable was not found. You might need to restart your app/function.".format(err)
_LOGGER.critical(err_msg)
raise RuntimeError(err_msg)
request_uri = '{}/?resource={}&api-version=2017-09-01'.format(msi_endpoint, resource)
headers = {
'secret': msi_secret
}
err = None
try:
result = requests.get(request_uri, headers=headers)
_LOGGER.debug("MSI: Retrieving a token from %s", request_uri)
if result.status_code != 200:
err = result.text
# Workaround since not all failures are != 200
if 'ExceptionMessage' in result.text:
err = result.text
except Exception as ex: # pylint: disable=broad-except
err = str(ex)
if err:
err_msg = "MSI: Failed to retrieve a token from '{}' with an error of '{}'.".format(
request_uri, err
)
_LOGGER.critical(err_msg)
raise RuntimeError(err_msg)
_LOGGER.debug('MSI: token retrieved')
token_entry = result.json()
return token_entry['token_type'], token_entry['access_token'], token_entry
|
[
"def",
"get_msi_token_webapp",
"(",
"resource",
")",
":",
"try",
":",
"msi_endpoint",
"=",
"os",
".",
"environ",
"[",
"'MSI_ENDPOINT'",
"]",
"msi_secret",
"=",
"os",
".",
"environ",
"[",
"'MSI_SECRET'",
"]",
"except",
"KeyError",
"as",
"err",
":",
"err_msg",
"=",
"\"{} required env variable was not found. You might need to restart your app/function.\"",
".",
"format",
"(",
"err",
")",
"_LOGGER",
".",
"critical",
"(",
"err_msg",
")",
"raise",
"RuntimeError",
"(",
"err_msg",
")",
"request_uri",
"=",
"'{}/?resource={}&api-version=2017-09-01'",
".",
"format",
"(",
"msi_endpoint",
",",
"resource",
")",
"headers",
"=",
"{",
"'secret'",
":",
"msi_secret",
"}",
"err",
"=",
"None",
"try",
":",
"result",
"=",
"requests",
".",
"get",
"(",
"request_uri",
",",
"headers",
"=",
"headers",
")",
"_LOGGER",
".",
"debug",
"(",
"\"MSI: Retrieving a token from %s\"",
",",
"request_uri",
")",
"if",
"result",
".",
"status_code",
"!=",
"200",
":",
"err",
"=",
"result",
".",
"text",
"# Workaround since not all failures are != 200",
"if",
"'ExceptionMessage'",
"in",
"result",
".",
"text",
":",
"err",
"=",
"result",
".",
"text",
"except",
"Exception",
"as",
"ex",
":",
"# pylint: disable=broad-except",
"err",
"=",
"str",
"(",
"ex",
")",
"if",
"err",
":",
"err_msg",
"=",
"\"MSI: Failed to retrieve a token from '{}' with an error of '{}'.\"",
".",
"format",
"(",
"request_uri",
",",
"err",
")",
"_LOGGER",
".",
"critical",
"(",
"err_msg",
")",
"raise",
"RuntimeError",
"(",
"err_msg",
")",
"_LOGGER",
".",
"debug",
"(",
"'MSI: token retrieved'",
")",
"token_entry",
"=",
"result",
".",
"json",
"(",
")",
"return",
"token_entry",
"[",
"'token_type'",
"]",
",",
"token_entry",
"[",
"'access_token'",
"]",
",",
"token_entry"
] |
Get a MSI token from inside a webapp or functions.
Env variable will look like:
- MSI_ENDPOINT = http://127.0.0.1:41741/MSI/token/
- MSI_SECRET = 69418689F1E342DD946CB82994CDA3CB
|
[
"Get",
"a",
"MSI",
"token",
"from",
"inside",
"a",
"webapp",
"or",
"functions",
"."
] |
5f99262305692525d03ca87d2c5356b05c5aa874
|
https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/azure_active_directory.py#L494-L534
|
train
|
Azure/msrestazure-for-python
|
msrestazure/azure_active_directory.py
|
AADMixin._configure
|
def _configure(self, **kwargs):
"""Configure authentication endpoint.
Optional kwargs may include:
- cloud_environment (msrestazure.azure_cloud.Cloud): A targeted cloud environment
- china (bool): Configure auth for China-based service,
default is 'False'.
- tenant (str): Alternative tenant, default is 'common'.
- resource (str): Alternative authentication resource, default
is 'https://management.core.windows.net/'.
- verify (bool): Verify secure connection, default is 'True'.
- timeout (int): Timeout of the request in seconds.
- proxies (dict): Dictionary mapping protocol or protocol and
hostname to the URL of the proxy.
- cache (adal.TokenCache): A adal.TokenCache, see ADAL configuration
for details. This parameter is not used here and directly passed to ADAL.
"""
if kwargs.get('china'):
err_msg = ("china parameter is deprecated, "
"please use "
"cloud_environment=msrestazure.azure_cloud.AZURE_CHINA_CLOUD")
warnings.warn(err_msg, DeprecationWarning)
self._cloud_environment = AZURE_CHINA_CLOUD
else:
self._cloud_environment = AZURE_PUBLIC_CLOUD
self._cloud_environment = kwargs.get('cloud_environment', self._cloud_environment)
auth_endpoint = self._cloud_environment.endpoints.active_directory
resource = self._cloud_environment.endpoints.active_directory_resource_id
self._tenant = kwargs.get('tenant', "common")
self._verify = kwargs.get('verify') # 'None' will honor ADAL_PYTHON_SSL_NO_VERIFY
self.resource = kwargs.get('resource', resource)
self._proxies = kwargs.get('proxies')
self._timeout = kwargs.get('timeout')
self._cache = kwargs.get('cache')
self.store_key = "{}_{}".format(
auth_endpoint.strip('/'), self.store_key)
self.secret = None
self._context = None
|
python
|
def _configure(self, **kwargs):
"""Configure authentication endpoint.
Optional kwargs may include:
- cloud_environment (msrestazure.azure_cloud.Cloud): A targeted cloud environment
- china (bool): Configure auth for China-based service,
default is 'False'.
- tenant (str): Alternative tenant, default is 'common'.
- resource (str): Alternative authentication resource, default
is 'https://management.core.windows.net/'.
- verify (bool): Verify secure connection, default is 'True'.
- timeout (int): Timeout of the request in seconds.
- proxies (dict): Dictionary mapping protocol or protocol and
hostname to the URL of the proxy.
- cache (adal.TokenCache): A adal.TokenCache, see ADAL configuration
for details. This parameter is not used here and directly passed to ADAL.
"""
if kwargs.get('china'):
err_msg = ("china parameter is deprecated, "
"please use "
"cloud_environment=msrestazure.azure_cloud.AZURE_CHINA_CLOUD")
warnings.warn(err_msg, DeprecationWarning)
self._cloud_environment = AZURE_CHINA_CLOUD
else:
self._cloud_environment = AZURE_PUBLIC_CLOUD
self._cloud_environment = kwargs.get('cloud_environment', self._cloud_environment)
auth_endpoint = self._cloud_environment.endpoints.active_directory
resource = self._cloud_environment.endpoints.active_directory_resource_id
self._tenant = kwargs.get('tenant', "common")
self._verify = kwargs.get('verify') # 'None' will honor ADAL_PYTHON_SSL_NO_VERIFY
self.resource = kwargs.get('resource', resource)
self._proxies = kwargs.get('proxies')
self._timeout = kwargs.get('timeout')
self._cache = kwargs.get('cache')
self.store_key = "{}_{}".format(
auth_endpoint.strip('/'), self.store_key)
self.secret = None
self._context = None
|
[
"def",
"_configure",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"kwargs",
".",
"get",
"(",
"'china'",
")",
":",
"err_msg",
"=",
"(",
"\"china parameter is deprecated, \"",
"\"please use \"",
"\"cloud_environment=msrestazure.azure_cloud.AZURE_CHINA_CLOUD\"",
")",
"warnings",
".",
"warn",
"(",
"err_msg",
",",
"DeprecationWarning",
")",
"self",
".",
"_cloud_environment",
"=",
"AZURE_CHINA_CLOUD",
"else",
":",
"self",
".",
"_cloud_environment",
"=",
"AZURE_PUBLIC_CLOUD",
"self",
".",
"_cloud_environment",
"=",
"kwargs",
".",
"get",
"(",
"'cloud_environment'",
",",
"self",
".",
"_cloud_environment",
")",
"auth_endpoint",
"=",
"self",
".",
"_cloud_environment",
".",
"endpoints",
".",
"active_directory",
"resource",
"=",
"self",
".",
"_cloud_environment",
".",
"endpoints",
".",
"active_directory_resource_id",
"self",
".",
"_tenant",
"=",
"kwargs",
".",
"get",
"(",
"'tenant'",
",",
"\"common\"",
")",
"self",
".",
"_verify",
"=",
"kwargs",
".",
"get",
"(",
"'verify'",
")",
"# 'None' will honor ADAL_PYTHON_SSL_NO_VERIFY",
"self",
".",
"resource",
"=",
"kwargs",
".",
"get",
"(",
"'resource'",
",",
"resource",
")",
"self",
".",
"_proxies",
"=",
"kwargs",
".",
"get",
"(",
"'proxies'",
")",
"self",
".",
"_timeout",
"=",
"kwargs",
".",
"get",
"(",
"'timeout'",
")",
"self",
".",
"_cache",
"=",
"kwargs",
".",
"get",
"(",
"'cache'",
")",
"self",
".",
"store_key",
"=",
"\"{}_{}\"",
".",
"format",
"(",
"auth_endpoint",
".",
"strip",
"(",
"'/'",
")",
",",
"self",
".",
"store_key",
")",
"self",
".",
"secret",
"=",
"None",
"self",
".",
"_context",
"=",
"None"
] |
Configure authentication endpoint.
Optional kwargs may include:
- cloud_environment (msrestazure.azure_cloud.Cloud): A targeted cloud environment
- china (bool): Configure auth for China-based service,
default is 'False'.
- tenant (str): Alternative tenant, default is 'common'.
- resource (str): Alternative authentication resource, default
is 'https://management.core.windows.net/'.
- verify (bool): Verify secure connection, default is 'True'.
- timeout (int): Timeout of the request in seconds.
- proxies (dict): Dictionary mapping protocol or protocol and
hostname to the URL of the proxy.
- cache (adal.TokenCache): A adal.TokenCache, see ADAL configuration
for details. This parameter is not used here and directly passed to ADAL.
|
[
"Configure",
"authentication",
"endpoint",
"."
] |
5f99262305692525d03ca87d2c5356b05c5aa874
|
https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/azure_active_directory.py#L60-L100
|
train
|
Azure/msrestazure-for-python
|
msrestazure/azure_active_directory.py
|
AADMixin._convert_token
|
def _convert_token(self, token):
"""Convert token fields from camel case.
:param dict token: An authentication token.
:rtype: dict
"""
# Beware that ADAL returns a pointer to its own dict, do
# NOT change it in place
token = token.copy()
# If it's from ADAL, expiresOn will be in ISO form.
# Bring it back to float, using expiresIn
if "expiresOn" in token and "expiresIn" in token:
token["expiresOn"] = token['expiresIn'] + time.time()
return {self._case.sub(r'\1_\2', k).lower(): v
for k, v in token.items()}
|
python
|
def _convert_token(self, token):
"""Convert token fields from camel case.
:param dict token: An authentication token.
:rtype: dict
"""
# Beware that ADAL returns a pointer to its own dict, do
# NOT change it in place
token = token.copy()
# If it's from ADAL, expiresOn will be in ISO form.
# Bring it back to float, using expiresIn
if "expiresOn" in token and "expiresIn" in token:
token["expiresOn"] = token['expiresIn'] + time.time()
return {self._case.sub(r'\1_\2', k).lower(): v
for k, v in token.items()}
|
[
"def",
"_convert_token",
"(",
"self",
",",
"token",
")",
":",
"# Beware that ADAL returns a pointer to its own dict, do",
"# NOT change it in place",
"token",
"=",
"token",
".",
"copy",
"(",
")",
"# If it's from ADAL, expiresOn will be in ISO form.",
"# Bring it back to float, using expiresIn",
"if",
"\"expiresOn\"",
"in",
"token",
"and",
"\"expiresIn\"",
"in",
"token",
":",
"token",
"[",
"\"expiresOn\"",
"]",
"=",
"token",
"[",
"'expiresIn'",
"]",
"+",
"time",
".",
"time",
"(",
")",
"return",
"{",
"self",
".",
"_case",
".",
"sub",
"(",
"r'\\1_\\2'",
",",
"k",
")",
".",
"lower",
"(",
")",
":",
"v",
"for",
"k",
",",
"v",
"in",
"token",
".",
"items",
"(",
")",
"}"
] |
Convert token fields from camel case.
:param dict token: An authentication token.
:rtype: dict
|
[
"Convert",
"token",
"fields",
"from",
"camel",
"case",
"."
] |
5f99262305692525d03ca87d2c5356b05c5aa874
|
https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/azure_active_directory.py#L159-L174
|
train
|
Azure/msrestazure-for-python
|
msrestazure/azure_active_directory.py
|
AADMixin.signed_session
|
def signed_session(self, session=None):
"""Create token-friendly Requests session, using auto-refresh.
Used internally when a request is made.
If a session object is provided, configure it directly. Otherwise,
create a new session and return it.
:param session: The session to configure for authentication
:type session: requests.Session
"""
self.set_token() # Adal does the caching.
self._parse_token()
return super(AADMixin, self).signed_session(session)
|
python
|
def signed_session(self, session=None):
"""Create token-friendly Requests session, using auto-refresh.
Used internally when a request is made.
If a session object is provided, configure it directly. Otherwise,
create a new session and return it.
:param session: The session to configure for authentication
:type session: requests.Session
"""
self.set_token() # Adal does the caching.
self._parse_token()
return super(AADMixin, self).signed_session(session)
|
[
"def",
"signed_session",
"(",
"self",
",",
"session",
"=",
"None",
")",
":",
"self",
".",
"set_token",
"(",
")",
"# Adal does the caching.",
"self",
".",
"_parse_token",
"(",
")",
"return",
"super",
"(",
"AADMixin",
",",
"self",
")",
".",
"signed_session",
"(",
"session",
")"
] |
Create token-friendly Requests session, using auto-refresh.
Used internally when a request is made.
If a session object is provided, configure it directly. Otherwise,
create a new session and return it.
:param session: The session to configure for authentication
:type session: requests.Session
|
[
"Create",
"token",
"-",
"friendly",
"Requests",
"session",
"using",
"auto",
"-",
"refresh",
".",
"Used",
"internally",
"when",
"a",
"request",
"is",
"made",
"."
] |
5f99262305692525d03ca87d2c5356b05c5aa874
|
https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/azure_active_directory.py#L189-L201
|
train
|
Azure/msrestazure-for-python
|
msrestazure/azure_active_directory.py
|
AADMixin.refresh_session
|
def refresh_session(self, session=None):
"""Return updated session if token has expired, attempts to
refresh using newly acquired token.
If a session object is provided, configure it directly. Otherwise,
create a new session and return it.
:param session: The session to configure for authentication
:type session: requests.Session
:rtype: requests.Session.
"""
if 'refresh_token' in self.token:
try:
token = self._context.acquire_token_with_refresh_token(
self.token['refresh_token'],
self.id,
self.resource,
self.secret # This is needed when using Confidential Client
)
self.token = self._convert_token(token)
except adal.AdalError as err:
raise_with_traceback(AuthenticationError, "", err)
return self.signed_session(session)
|
python
|
def refresh_session(self, session=None):
"""Return updated session if token has expired, attempts to
refresh using newly acquired token.
If a session object is provided, configure it directly. Otherwise,
create a new session and return it.
:param session: The session to configure for authentication
:type session: requests.Session
:rtype: requests.Session.
"""
if 'refresh_token' in self.token:
try:
token = self._context.acquire_token_with_refresh_token(
self.token['refresh_token'],
self.id,
self.resource,
self.secret # This is needed when using Confidential Client
)
self.token = self._convert_token(token)
except adal.AdalError as err:
raise_with_traceback(AuthenticationError, "", err)
return self.signed_session(session)
|
[
"def",
"refresh_session",
"(",
"self",
",",
"session",
"=",
"None",
")",
":",
"if",
"'refresh_token'",
"in",
"self",
".",
"token",
":",
"try",
":",
"token",
"=",
"self",
".",
"_context",
".",
"acquire_token_with_refresh_token",
"(",
"self",
".",
"token",
"[",
"'refresh_token'",
"]",
",",
"self",
".",
"id",
",",
"self",
".",
"resource",
",",
"self",
".",
"secret",
"# This is needed when using Confidential Client",
")",
"self",
".",
"token",
"=",
"self",
".",
"_convert_token",
"(",
"token",
")",
"except",
"adal",
".",
"AdalError",
"as",
"err",
":",
"raise_with_traceback",
"(",
"AuthenticationError",
",",
"\"\"",
",",
"err",
")",
"return",
"self",
".",
"signed_session",
"(",
"session",
")"
] |
Return updated session if token has expired, attempts to
refresh using newly acquired token.
If a session object is provided, configure it directly. Otherwise,
create a new session and return it.
:param session: The session to configure for authentication
:type session: requests.Session
:rtype: requests.Session.
|
[
"Return",
"updated",
"session",
"if",
"token",
"has",
"expired",
"attempts",
"to",
"refresh",
"using",
"newly",
"acquired",
"token",
"."
] |
5f99262305692525d03ca87d2c5356b05c5aa874
|
https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/azure_active_directory.py#L203-L225
|
train
|
Azure/msrestazure-for-python
|
msrestazure/azure_operation.py
|
_validate
|
def _validate(url):
"""Validate a url.
:param str url: Polling URL extracted from response header.
:raises: ValueError if URL has no scheme or host.
"""
if url is None:
return
parsed = urlparse(url)
if not parsed.scheme or not parsed.netloc:
raise ValueError("Invalid URL header")
|
python
|
def _validate(url):
"""Validate a url.
:param str url: Polling URL extracted from response header.
:raises: ValueError if URL has no scheme or host.
"""
if url is None:
return
parsed = urlparse(url)
if not parsed.scheme or not parsed.netloc:
raise ValueError("Invalid URL header")
|
[
"def",
"_validate",
"(",
"url",
")",
":",
"if",
"url",
"is",
"None",
":",
"return",
"parsed",
"=",
"urlparse",
"(",
"url",
")",
"if",
"not",
"parsed",
".",
"scheme",
"or",
"not",
"parsed",
".",
"netloc",
":",
"raise",
"ValueError",
"(",
"\"Invalid URL header\"",
")"
] |
Validate a url.
:param str url: Polling URL extracted from response header.
:raises: ValueError if URL has no scheme or host.
|
[
"Validate",
"a",
"url",
"."
] |
5f99262305692525d03ca87d2c5356b05c5aa874
|
https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/azure_operation.py#L63-L73
|
train
|
Azure/msrestazure-for-python
|
msrestazure/azure_operation.py
|
LongRunningOperation._raise_if_bad_http_status_and_method
|
def _raise_if_bad_http_status_and_method(self, response):
"""Check response status code is valid for a Put or Patch
request. Must be 200, 201, 202, or 204.
:raises: BadStatus if invalid status.
"""
code = response.status_code
if code in {200, 202} or \
(code == 201 and self.method in {'PUT', 'PATCH'}) or \
(code == 204 and self.method in {'DELETE', 'POST'}):
return
raise BadStatus(
"Invalid return status for {!r} operation".format(self.method))
|
python
|
def _raise_if_bad_http_status_and_method(self, response):
"""Check response status code is valid for a Put or Patch
request. Must be 200, 201, 202, or 204.
:raises: BadStatus if invalid status.
"""
code = response.status_code
if code in {200, 202} or \
(code == 201 and self.method in {'PUT', 'PATCH'}) or \
(code == 204 and self.method in {'DELETE', 'POST'}):
return
raise BadStatus(
"Invalid return status for {!r} operation".format(self.method))
|
[
"def",
"_raise_if_bad_http_status_and_method",
"(",
"self",
",",
"response",
")",
":",
"code",
"=",
"response",
".",
"status_code",
"if",
"code",
"in",
"{",
"200",
",",
"202",
"}",
"or",
"(",
"code",
"==",
"201",
"and",
"self",
".",
"method",
"in",
"{",
"'PUT'",
",",
"'PATCH'",
"}",
")",
"or",
"(",
"code",
"==",
"204",
"and",
"self",
".",
"method",
"in",
"{",
"'DELETE'",
",",
"'POST'",
"}",
")",
":",
"return",
"raise",
"BadStatus",
"(",
"\"Invalid return status for {!r} operation\"",
".",
"format",
"(",
"self",
".",
"method",
")",
")"
] |
Check response status code is valid for a Put or Patch
request. Must be 200, 201, 202, or 204.
:raises: BadStatus if invalid status.
|
[
"Check",
"response",
"status",
"code",
"is",
"valid",
"for",
"a",
"Put",
"or",
"Patch",
"request",
".",
"Must",
"be",
"200",
"201",
"202",
"or",
"204",
"."
] |
5f99262305692525d03ca87d2c5356b05c5aa874
|
https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/azure_operation.py#L136-L148
|
train
|
Azure/msrestazure-for-python
|
msrestazure/azure_operation.py
|
LongRunningOperation._deserialize
|
def _deserialize(self, response):
"""Attempt to deserialize resource from response.
:param requests.Response response: latest REST call response.
"""
# Hacking response with initial status_code
previous_status = response.status_code
response.status_code = self.initial_status_code
resource = self.get_outputs(response)
response.status_code = previous_status
# Hack for Storage or SQL, to workaround the bug in the Python generator
if resource is None:
previous_status = response.status_code
for status_code_to_test in [200, 201]:
try:
response.status_code = status_code_to_test
resource = self.get_outputs(response)
except ClientException:
pass
else:
return resource
finally:
response.status_code = previous_status
return resource
|
python
|
def _deserialize(self, response):
"""Attempt to deserialize resource from response.
:param requests.Response response: latest REST call response.
"""
# Hacking response with initial status_code
previous_status = response.status_code
response.status_code = self.initial_status_code
resource = self.get_outputs(response)
response.status_code = previous_status
# Hack for Storage or SQL, to workaround the bug in the Python generator
if resource is None:
previous_status = response.status_code
for status_code_to_test in [200, 201]:
try:
response.status_code = status_code_to_test
resource = self.get_outputs(response)
except ClientException:
pass
else:
return resource
finally:
response.status_code = previous_status
return resource
|
[
"def",
"_deserialize",
"(",
"self",
",",
"response",
")",
":",
"# Hacking response with initial status_code",
"previous_status",
"=",
"response",
".",
"status_code",
"response",
".",
"status_code",
"=",
"self",
".",
"initial_status_code",
"resource",
"=",
"self",
".",
"get_outputs",
"(",
"response",
")",
"response",
".",
"status_code",
"=",
"previous_status",
"# Hack for Storage or SQL, to workaround the bug in the Python generator",
"if",
"resource",
"is",
"None",
":",
"previous_status",
"=",
"response",
".",
"status_code",
"for",
"status_code_to_test",
"in",
"[",
"200",
",",
"201",
"]",
":",
"try",
":",
"response",
".",
"status_code",
"=",
"status_code_to_test",
"resource",
"=",
"self",
".",
"get_outputs",
"(",
"response",
")",
"except",
"ClientException",
":",
"pass",
"else",
":",
"return",
"resource",
"finally",
":",
"response",
".",
"status_code",
"=",
"previous_status",
"return",
"resource"
] |
Attempt to deserialize resource from response.
:param requests.Response response: latest REST call response.
|
[
"Attempt",
"to",
"deserialize",
"resource",
"from",
"response",
"."
] |
5f99262305692525d03ca87d2c5356b05c5aa874
|
https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/azure_operation.py#L166-L190
|
train
|
Azure/msrestazure-for-python
|
msrestazure/azure_operation.py
|
LongRunningOperation.get_status_from_location
|
def get_status_from_location(self, response):
"""Process the latest status update retrieved from a 'location'
header.
:param requests.Response response: latest REST call response.
:raises: BadResponse if response has no body and not status 202.
"""
self._raise_if_bad_http_status_and_method(response)
code = response.status_code
if code == 202:
self.status = "InProgress"
else:
self.status = 'Succeeded'
if self._is_empty(response):
self.resource = None
else:
self.resource = self._deserialize(response)
|
python
|
def get_status_from_location(self, response):
"""Process the latest status update retrieved from a 'location'
header.
:param requests.Response response: latest REST call response.
:raises: BadResponse if response has no body and not status 202.
"""
self._raise_if_bad_http_status_and_method(response)
code = response.status_code
if code == 202:
self.status = "InProgress"
else:
self.status = 'Succeeded'
if self._is_empty(response):
self.resource = None
else:
self.resource = self._deserialize(response)
|
[
"def",
"get_status_from_location",
"(",
"self",
",",
"response",
")",
":",
"self",
".",
"_raise_if_bad_http_status_and_method",
"(",
"response",
")",
"code",
"=",
"response",
".",
"status_code",
"if",
"code",
"==",
"202",
":",
"self",
".",
"status",
"=",
"\"InProgress\"",
"else",
":",
"self",
".",
"status",
"=",
"'Succeeded'",
"if",
"self",
".",
"_is_empty",
"(",
"response",
")",
":",
"self",
".",
"resource",
"=",
"None",
"else",
":",
"self",
".",
"resource",
"=",
"self",
".",
"_deserialize",
"(",
"response",
")"
] |
Process the latest status update retrieved from a 'location'
header.
:param requests.Response response: latest REST call response.
:raises: BadResponse if response has no body and not status 202.
|
[
"Process",
"the",
"latest",
"status",
"update",
"retrieved",
"from",
"a",
"location",
"header",
"."
] |
5f99262305692525d03ca87d2c5356b05c5aa874
|
https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/azure_operation.py#L260-L276
|
train
|
Azure/msrestazure-for-python
|
msrestazure/azure_operation.py
|
AzureOperationPoller._polling_cookie
|
def _polling_cookie(self):
"""Collect retry cookie - we only want to do this for the test server
at this point, unless we implement a proper cookie policy.
:returns: Dictionary containing a cookie header if required,
otherwise an empty dictionary.
"""
parsed_url = urlparse(self._response.request.url)
host = parsed_url.hostname.strip('.')
if host == 'localhost':
return {'cookie': self._response.headers.get('set-cookie', '')}
return {}
|
python
|
def _polling_cookie(self):
"""Collect retry cookie - we only want to do this for the test server
at this point, unless we implement a proper cookie policy.
:returns: Dictionary containing a cookie header if required,
otherwise an empty dictionary.
"""
parsed_url = urlparse(self._response.request.url)
host = parsed_url.hostname.strip('.')
if host == 'localhost':
return {'cookie': self._response.headers.get('set-cookie', '')}
return {}
|
[
"def",
"_polling_cookie",
"(",
"self",
")",
":",
"parsed_url",
"=",
"urlparse",
"(",
"self",
".",
"_response",
".",
"request",
".",
"url",
")",
"host",
"=",
"parsed_url",
".",
"hostname",
".",
"strip",
"(",
"'.'",
")",
"if",
"host",
"==",
"'localhost'",
":",
"return",
"{",
"'cookie'",
":",
"self",
".",
"_response",
".",
"headers",
".",
"get",
"(",
"'set-cookie'",
",",
"''",
")",
"}",
"return",
"{",
"}"
] |
Collect retry cookie - we only want to do this for the test server
at this point, unless we implement a proper cookie policy.
:returns: Dictionary containing a cookie header if required,
otherwise an empty dictionary.
|
[
"Collect",
"retry",
"cookie",
"-",
"we",
"only",
"want",
"to",
"do",
"this",
"for",
"the",
"test",
"server",
"at",
"this",
"point",
"unless",
"we",
"implement",
"a",
"proper",
"cookie",
"policy",
"."
] |
5f99262305692525d03ca87d2c5356b05c5aa874
|
https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/azure_operation.py#L420-L431
|
train
|
Azure/msrestazure-for-python
|
msrestazure/azure_operation.py
|
AzureOperationPoller.remove_done_callback
|
def remove_done_callback(self, func):
"""Remove a callback from the long running operation.
:param callable func: The function to be removed from the callbacks.
:raises: ValueError if the long running operation has already
completed.
"""
if self._done is None or self._done.is_set():
raise ValueError("Process is complete.")
self._callbacks = [c for c in self._callbacks if c != func]
|
python
|
def remove_done_callback(self, func):
"""Remove a callback from the long running operation.
:param callable func: The function to be removed from the callbacks.
:raises: ValueError if the long running operation has already
completed.
"""
if self._done is None or self._done.is_set():
raise ValueError("Process is complete.")
self._callbacks = [c for c in self._callbacks if c != func]
|
[
"def",
"remove_done_callback",
"(",
"self",
",",
"func",
")",
":",
"if",
"self",
".",
"_done",
"is",
"None",
"or",
"self",
".",
"_done",
".",
"is_set",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Process is complete.\"",
")",
"self",
".",
"_callbacks",
"=",
"[",
"c",
"for",
"c",
"in",
"self",
".",
"_callbacks",
"if",
"c",
"!=",
"func",
"]"
] |
Remove a callback from the long running operation.
:param callable func: The function to be removed from the callbacks.
:raises: ValueError if the long running operation has already
completed.
|
[
"Remove",
"a",
"callback",
"from",
"the",
"long",
"running",
"operation",
"."
] |
5f99262305692525d03ca87d2c5356b05c5aa874
|
https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/azure_operation.py#L532-L541
|
train
|
Azure/msrestazure-for-python
|
msrestazure/tools.py
|
register_rp_hook
|
def register_rp_hook(r, *args, **kwargs):
"""This is a requests hook to register RP automatically.
You should not use this command manually, this is added automatically
by the SDK.
See requests documentation for details of the signature of this function.
http://docs.python-requests.org/en/master/user/advanced/#event-hooks
"""
if r.status_code == 409 and 'msrest' in kwargs:
rp_name = _check_rp_not_registered_err(r)
if rp_name:
session = kwargs['msrest']['session']
url_prefix = _extract_subscription_url(r.request.url)
if not _register_rp(session, url_prefix, rp_name):
return
req = r.request
# Change the 'x-ms-client-request-id' otherwise the Azure endpoint
# just returns the same 409 payload without looking at the actual query
if 'x-ms-client-request-id' in req.headers:
req.headers['x-ms-client-request-id'] = str(uuid.uuid1())
return session.send(req)
|
python
|
def register_rp_hook(r, *args, **kwargs):
"""This is a requests hook to register RP automatically.
You should not use this command manually, this is added automatically
by the SDK.
See requests documentation for details of the signature of this function.
http://docs.python-requests.org/en/master/user/advanced/#event-hooks
"""
if r.status_code == 409 and 'msrest' in kwargs:
rp_name = _check_rp_not_registered_err(r)
if rp_name:
session = kwargs['msrest']['session']
url_prefix = _extract_subscription_url(r.request.url)
if not _register_rp(session, url_prefix, rp_name):
return
req = r.request
# Change the 'x-ms-client-request-id' otherwise the Azure endpoint
# just returns the same 409 payload without looking at the actual query
if 'x-ms-client-request-id' in req.headers:
req.headers['x-ms-client-request-id'] = str(uuid.uuid1())
return session.send(req)
|
[
"def",
"register_rp_hook",
"(",
"r",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"r",
".",
"status_code",
"==",
"409",
"and",
"'msrest'",
"in",
"kwargs",
":",
"rp_name",
"=",
"_check_rp_not_registered_err",
"(",
"r",
")",
"if",
"rp_name",
":",
"session",
"=",
"kwargs",
"[",
"'msrest'",
"]",
"[",
"'session'",
"]",
"url_prefix",
"=",
"_extract_subscription_url",
"(",
"r",
".",
"request",
".",
"url",
")",
"if",
"not",
"_register_rp",
"(",
"session",
",",
"url_prefix",
",",
"rp_name",
")",
":",
"return",
"req",
"=",
"r",
".",
"request",
"# Change the 'x-ms-client-request-id' otherwise the Azure endpoint",
"# just returns the same 409 payload without looking at the actual query",
"if",
"'x-ms-client-request-id'",
"in",
"req",
".",
"headers",
":",
"req",
".",
"headers",
"[",
"'x-ms-client-request-id'",
"]",
"=",
"str",
"(",
"uuid",
".",
"uuid1",
"(",
")",
")",
"return",
"session",
".",
"send",
"(",
"req",
")"
] |
This is a requests hook to register RP automatically.
You should not use this command manually, this is added automatically
by the SDK.
See requests documentation for details of the signature of this function.
http://docs.python-requests.org/en/master/user/advanced/#event-hooks
|
[
"This",
"is",
"a",
"requests",
"hook",
"to",
"register",
"RP",
"automatically",
"."
] |
5f99262305692525d03ca87d2c5356b05c5aa874
|
https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/tools.py#L43-L64
|
train
|
Azure/msrestazure-for-python
|
msrestazure/tools.py
|
_register_rp
|
def _register_rp(session, url_prefix, rp_name):
"""Synchronously register the RP is paremeter.
Return False if we have a reason to believe this didn't work
"""
post_url = "{}providers/{}/register?api-version=2016-02-01".format(url_prefix, rp_name)
get_url = "{}providers/{}?api-version=2016-02-01".format(url_prefix, rp_name)
_LOGGER.warning("Resource provider '%s' used by this operation is not "
"registered. We are registering for you.", rp_name)
post_response = session.post(post_url)
if post_response.status_code != 200:
_LOGGER.warning("Registration failed. Please register manually.")
return False
while True:
time.sleep(10)
rp_info = session.get(get_url).json()
if rp_info['registrationState'] == 'Registered':
_LOGGER.warning("Registration succeeded.")
return True
|
python
|
def _register_rp(session, url_prefix, rp_name):
"""Synchronously register the RP is paremeter.
Return False if we have a reason to believe this didn't work
"""
post_url = "{}providers/{}/register?api-version=2016-02-01".format(url_prefix, rp_name)
get_url = "{}providers/{}?api-version=2016-02-01".format(url_prefix, rp_name)
_LOGGER.warning("Resource provider '%s' used by this operation is not "
"registered. We are registering for you.", rp_name)
post_response = session.post(post_url)
if post_response.status_code != 200:
_LOGGER.warning("Registration failed. Please register manually.")
return False
while True:
time.sleep(10)
rp_info = session.get(get_url).json()
if rp_info['registrationState'] == 'Registered':
_LOGGER.warning("Registration succeeded.")
return True
|
[
"def",
"_register_rp",
"(",
"session",
",",
"url_prefix",
",",
"rp_name",
")",
":",
"post_url",
"=",
"\"{}providers/{}/register?api-version=2016-02-01\"",
".",
"format",
"(",
"url_prefix",
",",
"rp_name",
")",
"get_url",
"=",
"\"{}providers/{}?api-version=2016-02-01\"",
".",
"format",
"(",
"url_prefix",
",",
"rp_name",
")",
"_LOGGER",
".",
"warning",
"(",
"\"Resource provider '%s' used by this operation is not \"",
"\"registered. We are registering for you.\"",
",",
"rp_name",
")",
"post_response",
"=",
"session",
".",
"post",
"(",
"post_url",
")",
"if",
"post_response",
".",
"status_code",
"!=",
"200",
":",
"_LOGGER",
".",
"warning",
"(",
"\"Registration failed. Please register manually.\"",
")",
"return",
"False",
"while",
"True",
":",
"time",
".",
"sleep",
"(",
"10",
")",
"rp_info",
"=",
"session",
".",
"get",
"(",
"get_url",
")",
".",
"json",
"(",
")",
"if",
"rp_info",
"[",
"'registrationState'",
"]",
"==",
"'Registered'",
":",
"_LOGGER",
".",
"warning",
"(",
"\"Registration succeeded.\"",
")",
"return",
"True"
] |
Synchronously register the RP is paremeter.
Return False if we have a reason to believe this didn't work
|
[
"Synchronously",
"register",
"the",
"RP",
"is",
"paremeter",
".",
"Return",
"False",
"if",
"we",
"have",
"a",
"reason",
"to",
"believe",
"this",
"didn",
"t",
"work"
] |
5f99262305692525d03ca87d2c5356b05c5aa874
|
https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/tools.py#L85-L104
|
train
|
Azure/msrestazure-for-python
|
msrestazure/tools.py
|
parse_resource_id
|
def parse_resource_id(rid):
"""Parses a resource_id into its various parts.
Returns a dictionary with a single key-value pair, 'name': rid, if invalid resource id.
:param rid: The resource id being parsed
:type rid: str
:returns: A dictionary with with following key/value pairs (if found):
- subscription: Subscription id
- resource_group: Name of resource group
- namespace: Namespace for the resource provider (i.e. Microsoft.Compute)
- type: Type of the root resource (i.e. virtualMachines)
- name: Name of the root resource
- child_namespace_{level}: Namespace for the child resoure of that level
- child_type_{level}: Type of the child resource of that level
- child_name_{level}: Name of the child resource of that level
- last_child_num: Level of the last child
- resource_parent: Computed parent in the following pattern: providers/{namespace}\
/{parent}/{type}/{name}
- resource_namespace: Same as namespace. Note that this may be different than the \
target resource's namespace.
- resource_type: Type of the target resource (not the parent)
- resource_name: Name of the target resource (not the parent)
:rtype: dict[str,str]
"""
if not rid:
return {}
match = _ARMID_RE.match(rid)
if match:
result = match.groupdict()
children = _CHILDREN_RE.finditer(result['children'] or '')
count = None
for count, child in enumerate(children):
result.update({
key + '_%d' % (count + 1): group for key, group in child.groupdict().items()})
result['last_child_num'] = count + 1 if isinstance(count, int) else None
result = _populate_alternate_kwargs(result)
else:
result = dict(name=rid)
return {key: value for key, value in result.items() if value is not None}
|
python
|
def parse_resource_id(rid):
"""Parses a resource_id into its various parts.
Returns a dictionary with a single key-value pair, 'name': rid, if invalid resource id.
:param rid: The resource id being parsed
:type rid: str
:returns: A dictionary with with following key/value pairs (if found):
- subscription: Subscription id
- resource_group: Name of resource group
- namespace: Namespace for the resource provider (i.e. Microsoft.Compute)
- type: Type of the root resource (i.e. virtualMachines)
- name: Name of the root resource
- child_namespace_{level}: Namespace for the child resoure of that level
- child_type_{level}: Type of the child resource of that level
- child_name_{level}: Name of the child resource of that level
- last_child_num: Level of the last child
- resource_parent: Computed parent in the following pattern: providers/{namespace}\
/{parent}/{type}/{name}
- resource_namespace: Same as namespace. Note that this may be different than the \
target resource's namespace.
- resource_type: Type of the target resource (not the parent)
- resource_name: Name of the target resource (not the parent)
:rtype: dict[str,str]
"""
if not rid:
return {}
match = _ARMID_RE.match(rid)
if match:
result = match.groupdict()
children = _CHILDREN_RE.finditer(result['children'] or '')
count = None
for count, child in enumerate(children):
result.update({
key + '_%d' % (count + 1): group for key, group in child.groupdict().items()})
result['last_child_num'] = count + 1 if isinstance(count, int) else None
result = _populate_alternate_kwargs(result)
else:
result = dict(name=rid)
return {key: value for key, value in result.items() if value is not None}
|
[
"def",
"parse_resource_id",
"(",
"rid",
")",
":",
"if",
"not",
"rid",
":",
"return",
"{",
"}",
"match",
"=",
"_ARMID_RE",
".",
"match",
"(",
"rid",
")",
"if",
"match",
":",
"result",
"=",
"match",
".",
"groupdict",
"(",
")",
"children",
"=",
"_CHILDREN_RE",
".",
"finditer",
"(",
"result",
"[",
"'children'",
"]",
"or",
"''",
")",
"count",
"=",
"None",
"for",
"count",
",",
"child",
"in",
"enumerate",
"(",
"children",
")",
":",
"result",
".",
"update",
"(",
"{",
"key",
"+",
"'_%d'",
"%",
"(",
"count",
"+",
"1",
")",
":",
"group",
"for",
"key",
",",
"group",
"in",
"child",
".",
"groupdict",
"(",
")",
".",
"items",
"(",
")",
"}",
")",
"result",
"[",
"'last_child_num'",
"]",
"=",
"count",
"+",
"1",
"if",
"isinstance",
"(",
"count",
",",
"int",
")",
"else",
"None",
"result",
"=",
"_populate_alternate_kwargs",
"(",
"result",
")",
"else",
":",
"result",
"=",
"dict",
"(",
"name",
"=",
"rid",
")",
"return",
"{",
"key",
":",
"value",
"for",
"key",
",",
"value",
"in",
"result",
".",
"items",
"(",
")",
"if",
"value",
"is",
"not",
"None",
"}"
] |
Parses a resource_id into its various parts.
Returns a dictionary with a single key-value pair, 'name': rid, if invalid resource id.
:param rid: The resource id being parsed
:type rid: str
:returns: A dictionary with with following key/value pairs (if found):
- subscription: Subscription id
- resource_group: Name of resource group
- namespace: Namespace for the resource provider (i.e. Microsoft.Compute)
- type: Type of the root resource (i.e. virtualMachines)
- name: Name of the root resource
- child_namespace_{level}: Namespace for the child resoure of that level
- child_type_{level}: Type of the child resource of that level
- child_name_{level}: Name of the child resource of that level
- last_child_num: Level of the last child
- resource_parent: Computed parent in the following pattern: providers/{namespace}\
/{parent}/{type}/{name}
- resource_namespace: Same as namespace. Note that this may be different than the \
target resource's namespace.
- resource_type: Type of the target resource (not the parent)
- resource_name: Name of the target resource (not the parent)
:rtype: dict[str,str]
|
[
"Parses",
"a",
"resource_id",
"into",
"its",
"various",
"parts",
"."
] |
5f99262305692525d03ca87d2c5356b05c5aa874
|
https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/tools.py#L106-L147
|
train
|
Azure/msrestazure-for-python
|
msrestazure/tools.py
|
_populate_alternate_kwargs
|
def _populate_alternate_kwargs(kwargs):
""" Translates the parsed arguments into a format used by generic ARM commands
such as the resource and lock commands.
"""
resource_namespace = kwargs['namespace']
resource_type = kwargs.get('child_type_{}'.format(kwargs['last_child_num'])) or kwargs['type']
resource_name = kwargs.get('child_name_{}'.format(kwargs['last_child_num'])) or kwargs['name']
_get_parents_from_parts(kwargs)
kwargs['resource_namespace'] = resource_namespace
kwargs['resource_type'] = resource_type
kwargs['resource_name'] = resource_name
return kwargs
|
python
|
def _populate_alternate_kwargs(kwargs):
""" Translates the parsed arguments into a format used by generic ARM commands
such as the resource and lock commands.
"""
resource_namespace = kwargs['namespace']
resource_type = kwargs.get('child_type_{}'.format(kwargs['last_child_num'])) or kwargs['type']
resource_name = kwargs.get('child_name_{}'.format(kwargs['last_child_num'])) or kwargs['name']
_get_parents_from_parts(kwargs)
kwargs['resource_namespace'] = resource_namespace
kwargs['resource_type'] = resource_type
kwargs['resource_name'] = resource_name
return kwargs
|
[
"def",
"_populate_alternate_kwargs",
"(",
"kwargs",
")",
":",
"resource_namespace",
"=",
"kwargs",
"[",
"'namespace'",
"]",
"resource_type",
"=",
"kwargs",
".",
"get",
"(",
"'child_type_{}'",
".",
"format",
"(",
"kwargs",
"[",
"'last_child_num'",
"]",
")",
")",
"or",
"kwargs",
"[",
"'type'",
"]",
"resource_name",
"=",
"kwargs",
".",
"get",
"(",
"'child_name_{}'",
".",
"format",
"(",
"kwargs",
"[",
"'last_child_num'",
"]",
")",
")",
"or",
"kwargs",
"[",
"'name'",
"]",
"_get_parents_from_parts",
"(",
"kwargs",
")",
"kwargs",
"[",
"'resource_namespace'",
"]",
"=",
"resource_namespace",
"kwargs",
"[",
"'resource_type'",
"]",
"=",
"resource_type",
"kwargs",
"[",
"'resource_name'",
"]",
"=",
"resource_name",
"return",
"kwargs"
] |
Translates the parsed arguments into a format used by generic ARM commands
such as the resource and lock commands.
|
[
"Translates",
"the",
"parsed",
"arguments",
"into",
"a",
"format",
"used",
"by",
"generic",
"ARM",
"commands",
"such",
"as",
"the",
"resource",
"and",
"lock",
"commands",
"."
] |
5f99262305692525d03ca87d2c5356b05c5aa874
|
https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/tools.py#L149-L162
|
train
|
Azure/msrestazure-for-python
|
msrestazure/tools.py
|
_get_parents_from_parts
|
def _get_parents_from_parts(kwargs):
""" Get the parents given all the children parameters.
"""
parent_builder = []
if kwargs['last_child_num'] is not None:
parent_builder.append('{type}/{name}/'.format(**kwargs))
for index in range(1, kwargs['last_child_num']):
child_namespace = kwargs.get('child_namespace_{}'.format(index))
if child_namespace is not None:
parent_builder.append('providers/{}/'.format(child_namespace))
kwargs['child_parent_{}'.format(index)] = ''.join(parent_builder)
parent_builder.append(
'{{child_type_{0}}}/{{child_name_{0}}}/'
.format(index).format(**kwargs))
child_namespace = kwargs.get('child_namespace_{}'.format(kwargs['last_child_num']))
if child_namespace is not None:
parent_builder.append('providers/{}/'.format(child_namespace))
kwargs['child_parent_{}'.format(kwargs['last_child_num'])] = ''.join(parent_builder)
kwargs['resource_parent'] = ''.join(parent_builder) if kwargs['name'] else None
return kwargs
|
python
|
def _get_parents_from_parts(kwargs):
""" Get the parents given all the children parameters.
"""
parent_builder = []
if kwargs['last_child_num'] is not None:
parent_builder.append('{type}/{name}/'.format(**kwargs))
for index in range(1, kwargs['last_child_num']):
child_namespace = kwargs.get('child_namespace_{}'.format(index))
if child_namespace is not None:
parent_builder.append('providers/{}/'.format(child_namespace))
kwargs['child_parent_{}'.format(index)] = ''.join(parent_builder)
parent_builder.append(
'{{child_type_{0}}}/{{child_name_{0}}}/'
.format(index).format(**kwargs))
child_namespace = kwargs.get('child_namespace_{}'.format(kwargs['last_child_num']))
if child_namespace is not None:
parent_builder.append('providers/{}/'.format(child_namespace))
kwargs['child_parent_{}'.format(kwargs['last_child_num'])] = ''.join(parent_builder)
kwargs['resource_parent'] = ''.join(parent_builder) if kwargs['name'] else None
return kwargs
|
[
"def",
"_get_parents_from_parts",
"(",
"kwargs",
")",
":",
"parent_builder",
"=",
"[",
"]",
"if",
"kwargs",
"[",
"'last_child_num'",
"]",
"is",
"not",
"None",
":",
"parent_builder",
".",
"append",
"(",
"'{type}/{name}/'",
".",
"format",
"(",
"*",
"*",
"kwargs",
")",
")",
"for",
"index",
"in",
"range",
"(",
"1",
",",
"kwargs",
"[",
"'last_child_num'",
"]",
")",
":",
"child_namespace",
"=",
"kwargs",
".",
"get",
"(",
"'child_namespace_{}'",
".",
"format",
"(",
"index",
")",
")",
"if",
"child_namespace",
"is",
"not",
"None",
":",
"parent_builder",
".",
"append",
"(",
"'providers/{}/'",
".",
"format",
"(",
"child_namespace",
")",
")",
"kwargs",
"[",
"'child_parent_{}'",
".",
"format",
"(",
"index",
")",
"]",
"=",
"''",
".",
"join",
"(",
"parent_builder",
")",
"parent_builder",
".",
"append",
"(",
"'{{child_type_{0}}}/{{child_name_{0}}}/'",
".",
"format",
"(",
"index",
")",
".",
"format",
"(",
"*",
"*",
"kwargs",
")",
")",
"child_namespace",
"=",
"kwargs",
".",
"get",
"(",
"'child_namespace_{}'",
".",
"format",
"(",
"kwargs",
"[",
"'last_child_num'",
"]",
")",
")",
"if",
"child_namespace",
"is",
"not",
"None",
":",
"parent_builder",
".",
"append",
"(",
"'providers/{}/'",
".",
"format",
"(",
"child_namespace",
")",
")",
"kwargs",
"[",
"'child_parent_{}'",
".",
"format",
"(",
"kwargs",
"[",
"'last_child_num'",
"]",
")",
"]",
"=",
"''",
".",
"join",
"(",
"parent_builder",
")",
"kwargs",
"[",
"'resource_parent'",
"]",
"=",
"''",
".",
"join",
"(",
"parent_builder",
")",
"if",
"kwargs",
"[",
"'name'",
"]",
"else",
"None",
"return",
"kwargs"
] |
Get the parents given all the children parameters.
|
[
"Get",
"the",
"parents",
"given",
"all",
"the",
"children",
"parameters",
"."
] |
5f99262305692525d03ca87d2c5356b05c5aa874
|
https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/tools.py#L164-L183
|
train
|
Azure/msrestazure-for-python
|
msrestazure/tools.py
|
resource_id
|
def resource_id(**kwargs):
"""Create a valid resource id string from the given parts.
This method builds the resource id from the left until the next required id parameter
to be appended is not found. It then returns the built up id.
:param dict kwargs: The keyword arguments that will make up the id.
The method accepts the following keyword arguments:
- subscription (required): Subscription id
- resource_group: Name of resource group
- namespace: Namespace for the resource provider (i.e. Microsoft.Compute)
- type: Type of the resource (i.e. virtualMachines)
- name: Name of the resource (or parent if child_name is also \
specified)
- child_namespace_{level}: Namespace for the child resoure of that level (optional)
- child_type_{level}: Type of the child resource of that level
- child_name_{level}: Name of the child resource of that level
:returns: A resource id built from the given arguments.
:rtype: str
"""
kwargs = {k: v for k, v in kwargs.items() if v is not None}
rid_builder = ['/subscriptions/{subscription}'.format(**kwargs)]
try:
try:
rid_builder.append('resourceGroups/{resource_group}'.format(**kwargs))
except KeyError:
pass
rid_builder.append('providers/{namespace}'.format(**kwargs))
rid_builder.append('{type}/{name}'.format(**kwargs))
count = 1
while True:
try:
rid_builder.append('providers/{{child_namespace_{}}}'
.format(count).format(**kwargs))
except KeyError:
pass
rid_builder.append('{{child_type_{0}}}/{{child_name_{0}}}'
.format(count).format(**kwargs))
count += 1
except KeyError:
pass
return '/'.join(rid_builder)
|
python
|
def resource_id(**kwargs):
"""Create a valid resource id string from the given parts.
This method builds the resource id from the left until the next required id parameter
to be appended is not found. It then returns the built up id.
:param dict kwargs: The keyword arguments that will make up the id.
The method accepts the following keyword arguments:
- subscription (required): Subscription id
- resource_group: Name of resource group
- namespace: Namespace for the resource provider (i.e. Microsoft.Compute)
- type: Type of the resource (i.e. virtualMachines)
- name: Name of the resource (or parent if child_name is also \
specified)
- child_namespace_{level}: Namespace for the child resoure of that level (optional)
- child_type_{level}: Type of the child resource of that level
- child_name_{level}: Name of the child resource of that level
:returns: A resource id built from the given arguments.
:rtype: str
"""
kwargs = {k: v for k, v in kwargs.items() if v is not None}
rid_builder = ['/subscriptions/{subscription}'.format(**kwargs)]
try:
try:
rid_builder.append('resourceGroups/{resource_group}'.format(**kwargs))
except KeyError:
pass
rid_builder.append('providers/{namespace}'.format(**kwargs))
rid_builder.append('{type}/{name}'.format(**kwargs))
count = 1
while True:
try:
rid_builder.append('providers/{{child_namespace_{}}}'
.format(count).format(**kwargs))
except KeyError:
pass
rid_builder.append('{{child_type_{0}}}/{{child_name_{0}}}'
.format(count).format(**kwargs))
count += 1
except KeyError:
pass
return '/'.join(rid_builder)
|
[
"def",
"resource_id",
"(",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"=",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items",
"(",
")",
"if",
"v",
"is",
"not",
"None",
"}",
"rid_builder",
"=",
"[",
"'/subscriptions/{subscription}'",
".",
"format",
"(",
"*",
"*",
"kwargs",
")",
"]",
"try",
":",
"try",
":",
"rid_builder",
".",
"append",
"(",
"'resourceGroups/{resource_group}'",
".",
"format",
"(",
"*",
"*",
"kwargs",
")",
")",
"except",
"KeyError",
":",
"pass",
"rid_builder",
".",
"append",
"(",
"'providers/{namespace}'",
".",
"format",
"(",
"*",
"*",
"kwargs",
")",
")",
"rid_builder",
".",
"append",
"(",
"'{type}/{name}'",
".",
"format",
"(",
"*",
"*",
"kwargs",
")",
")",
"count",
"=",
"1",
"while",
"True",
":",
"try",
":",
"rid_builder",
".",
"append",
"(",
"'providers/{{child_namespace_{}}}'",
".",
"format",
"(",
"count",
")",
".",
"format",
"(",
"*",
"*",
"kwargs",
")",
")",
"except",
"KeyError",
":",
"pass",
"rid_builder",
".",
"append",
"(",
"'{{child_type_{0}}}/{{child_name_{0}}}'",
".",
"format",
"(",
"count",
")",
".",
"format",
"(",
"*",
"*",
"kwargs",
")",
")",
"count",
"+=",
"1",
"except",
"KeyError",
":",
"pass",
"return",
"'/'",
".",
"join",
"(",
"rid_builder",
")"
] |
Create a valid resource id string from the given parts.
This method builds the resource id from the left until the next required id parameter
to be appended is not found. It then returns the built up id.
:param dict kwargs: The keyword arguments that will make up the id.
The method accepts the following keyword arguments:
- subscription (required): Subscription id
- resource_group: Name of resource group
- namespace: Namespace for the resource provider (i.e. Microsoft.Compute)
- type: Type of the resource (i.e. virtualMachines)
- name: Name of the resource (or parent if child_name is also \
specified)
- child_namespace_{level}: Namespace for the child resoure of that level (optional)
- child_type_{level}: Type of the child resource of that level
- child_name_{level}: Name of the child resource of that level
:returns: A resource id built from the given arguments.
:rtype: str
|
[
"Create",
"a",
"valid",
"resource",
"id",
"string",
"from",
"the",
"given",
"parts",
"."
] |
5f99262305692525d03ca87d2c5356b05c5aa874
|
https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/tools.py#L185-L228
|
train
|
Azure/msrestazure-for-python
|
msrestazure/tools.py
|
is_valid_resource_id
|
def is_valid_resource_id(rid, exception_type=None):
"""Validates the given resource id.
:param rid: The resource id being validated.
:type rid: str
:param exception_type: Raises this Exception if invalid.
:type exception_type: :class:`Exception`
:returns: A boolean describing whether the id is valid.
:rtype: bool
"""
is_valid = False
try:
is_valid = rid and resource_id(**parse_resource_id(rid)).lower() == rid.lower()
except KeyError:
pass
if not is_valid and exception_type:
raise exception_type()
return is_valid
|
python
|
def is_valid_resource_id(rid, exception_type=None):
"""Validates the given resource id.
:param rid: The resource id being validated.
:type rid: str
:param exception_type: Raises this Exception if invalid.
:type exception_type: :class:`Exception`
:returns: A boolean describing whether the id is valid.
:rtype: bool
"""
is_valid = False
try:
is_valid = rid and resource_id(**parse_resource_id(rid)).lower() == rid.lower()
except KeyError:
pass
if not is_valid and exception_type:
raise exception_type()
return is_valid
|
[
"def",
"is_valid_resource_id",
"(",
"rid",
",",
"exception_type",
"=",
"None",
")",
":",
"is_valid",
"=",
"False",
"try",
":",
"is_valid",
"=",
"rid",
"and",
"resource_id",
"(",
"*",
"*",
"parse_resource_id",
"(",
"rid",
")",
")",
".",
"lower",
"(",
")",
"==",
"rid",
".",
"lower",
"(",
")",
"except",
"KeyError",
":",
"pass",
"if",
"not",
"is_valid",
"and",
"exception_type",
":",
"raise",
"exception_type",
"(",
")",
"return",
"is_valid"
] |
Validates the given resource id.
:param rid: The resource id being validated.
:type rid: str
:param exception_type: Raises this Exception if invalid.
:type exception_type: :class:`Exception`
:returns: A boolean describing whether the id is valid.
:rtype: bool
|
[
"Validates",
"the",
"given",
"resource",
"id",
"."
] |
5f99262305692525d03ca87d2c5356b05c5aa874
|
https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/tools.py#L230-L247
|
train
|
Azure/msrestazure-for-python
|
msrestazure/tools.py
|
is_valid_resource_name
|
def is_valid_resource_name(rname, exception_type=None):
"""Validates the given resource name to ARM guidelines, individual services may be more restrictive.
:param rname: The resource name being validated.
:type rname: str
:param exception_type: Raises this Exception if invalid.
:type exception_type: :class:`Exception`
:returns: A boolean describing whether the name is valid.
:rtype: bool
"""
match = _ARMNAME_RE.match(rname)
if match:
return True
if exception_type:
raise exception_type()
return False
|
python
|
def is_valid_resource_name(rname, exception_type=None):
"""Validates the given resource name to ARM guidelines, individual services may be more restrictive.
:param rname: The resource name being validated.
:type rname: str
:param exception_type: Raises this Exception if invalid.
:type exception_type: :class:`Exception`
:returns: A boolean describing whether the name is valid.
:rtype: bool
"""
match = _ARMNAME_RE.match(rname)
if match:
return True
if exception_type:
raise exception_type()
return False
|
[
"def",
"is_valid_resource_name",
"(",
"rname",
",",
"exception_type",
"=",
"None",
")",
":",
"match",
"=",
"_ARMNAME_RE",
".",
"match",
"(",
"rname",
")",
"if",
"match",
":",
"return",
"True",
"if",
"exception_type",
":",
"raise",
"exception_type",
"(",
")",
"return",
"False"
] |
Validates the given resource name to ARM guidelines, individual services may be more restrictive.
:param rname: The resource name being validated.
:type rname: str
:param exception_type: Raises this Exception if invalid.
:type exception_type: :class:`Exception`
:returns: A boolean describing whether the name is valid.
:rtype: bool
|
[
"Validates",
"the",
"given",
"resource",
"name",
"to",
"ARM",
"guidelines",
"individual",
"services",
"may",
"be",
"more",
"restrictive",
"."
] |
5f99262305692525d03ca87d2c5356b05c5aa874
|
https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/tools.py#L250-L267
|
train
|
Azure/msrestazure-for-python
|
msrestazure/polling/async_arm_polling.py
|
AsyncARMPolling._delay
|
async def _delay(self):
"""Check for a 'retry-after' header to set timeout,
otherwise use configured timeout.
"""
if self._response is None:
await asyncio.sleep(0)
if self._response.headers.get('retry-after'):
await asyncio.sleep(int(self._response.headers['retry-after']))
else:
await asyncio.sleep(self._timeout)
|
python
|
async def _delay(self):
"""Check for a 'retry-after' header to set timeout,
otherwise use configured timeout.
"""
if self._response is None:
await asyncio.sleep(0)
if self._response.headers.get('retry-after'):
await asyncio.sleep(int(self._response.headers['retry-after']))
else:
await asyncio.sleep(self._timeout)
|
[
"async",
"def",
"_delay",
"(",
"self",
")",
":",
"if",
"self",
".",
"_response",
"is",
"None",
":",
"await",
"asyncio",
".",
"sleep",
"(",
"0",
")",
"if",
"self",
".",
"_response",
".",
"headers",
".",
"get",
"(",
"'retry-after'",
")",
":",
"await",
"asyncio",
".",
"sleep",
"(",
"int",
"(",
"self",
".",
"_response",
".",
"headers",
"[",
"'retry-after'",
"]",
")",
")",
"else",
":",
"await",
"asyncio",
".",
"sleep",
"(",
"self",
".",
"_timeout",
")"
] |
Check for a 'retry-after' header to set timeout,
otherwise use configured timeout.
|
[
"Check",
"for",
"a",
"retry",
"-",
"after",
"header",
"to",
"set",
"timeout",
"otherwise",
"use",
"configured",
"timeout",
"."
] |
5f99262305692525d03ca87d2c5356b05c5aa874
|
https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/polling/async_arm_polling.py#L83-L92
|
train
|
Azure/msrestazure-for-python
|
msrestazure/polling/async_arm_polling.py
|
AsyncARMPolling.update_status
|
async def update_status(self):
"""Update the current status of the LRO.
"""
if self._operation.async_url:
self._response = await self.request_status(self._operation.async_url)
self._operation.set_async_url_if_present(self._response)
self._operation.get_status_from_async(self._response)
elif self._operation.location_url:
self._response = await self.request_status(self._operation.location_url)
self._operation.set_async_url_if_present(self._response)
self._operation.get_status_from_location(self._response)
elif self._operation.method == "PUT":
initial_url = self._operation.initial_response.request.url
self._response = await self.request_status(initial_url)
self._operation.set_async_url_if_present(self._response)
self._operation.get_status_from_resource(self._response)
else:
raise BadResponse("Unable to find status link for polling.")
|
python
|
async def update_status(self):
"""Update the current status of the LRO.
"""
if self._operation.async_url:
self._response = await self.request_status(self._operation.async_url)
self._operation.set_async_url_if_present(self._response)
self._operation.get_status_from_async(self._response)
elif self._operation.location_url:
self._response = await self.request_status(self._operation.location_url)
self._operation.set_async_url_if_present(self._response)
self._operation.get_status_from_location(self._response)
elif self._operation.method == "PUT":
initial_url = self._operation.initial_response.request.url
self._response = await self.request_status(initial_url)
self._operation.set_async_url_if_present(self._response)
self._operation.get_status_from_resource(self._response)
else:
raise BadResponse("Unable to find status link for polling.")
|
[
"async",
"def",
"update_status",
"(",
"self",
")",
":",
"if",
"self",
".",
"_operation",
".",
"async_url",
":",
"self",
".",
"_response",
"=",
"await",
"self",
".",
"request_status",
"(",
"self",
".",
"_operation",
".",
"async_url",
")",
"self",
".",
"_operation",
".",
"set_async_url_if_present",
"(",
"self",
".",
"_response",
")",
"self",
".",
"_operation",
".",
"get_status_from_async",
"(",
"self",
".",
"_response",
")",
"elif",
"self",
".",
"_operation",
".",
"location_url",
":",
"self",
".",
"_response",
"=",
"await",
"self",
".",
"request_status",
"(",
"self",
".",
"_operation",
".",
"location_url",
")",
"self",
".",
"_operation",
".",
"set_async_url_if_present",
"(",
"self",
".",
"_response",
")",
"self",
".",
"_operation",
".",
"get_status_from_location",
"(",
"self",
".",
"_response",
")",
"elif",
"self",
".",
"_operation",
".",
"method",
"==",
"\"PUT\"",
":",
"initial_url",
"=",
"self",
".",
"_operation",
".",
"initial_response",
".",
"request",
".",
"url",
"self",
".",
"_response",
"=",
"await",
"self",
".",
"request_status",
"(",
"initial_url",
")",
"self",
".",
"_operation",
".",
"set_async_url_if_present",
"(",
"self",
".",
"_response",
")",
"self",
".",
"_operation",
".",
"get_status_from_resource",
"(",
"self",
".",
"_response",
")",
"else",
":",
"raise",
"BadResponse",
"(",
"\"Unable to find status link for polling.\"",
")"
] |
Update the current status of the LRO.
|
[
"Update",
"the",
"current",
"status",
"of",
"the",
"LRO",
"."
] |
5f99262305692525d03ca87d2c5356b05c5aa874
|
https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/polling/async_arm_polling.py#L94-L111
|
train
|
Azure/msrestazure-for-python
|
msrestazure/polling/async_arm_polling.py
|
AsyncARMPolling.request_status
|
async def request_status(self, status_link):
"""Do a simple GET to this status link.
This method re-inject 'x-ms-client-request-id'.
:rtype: requests.Response
"""
# ARM requires to re-inject 'x-ms-client-request-id' while polling
header_parameters = {
'x-ms-client-request-id': self._operation.initial_response.request.headers['x-ms-client-request-id']
}
request = self._client.get(status_link, headers=header_parameters)
return await self._client.async_send(request, stream=False, **self._operation_config)
|
python
|
async def request_status(self, status_link):
"""Do a simple GET to this status link.
This method re-inject 'x-ms-client-request-id'.
:rtype: requests.Response
"""
# ARM requires to re-inject 'x-ms-client-request-id' while polling
header_parameters = {
'x-ms-client-request-id': self._operation.initial_response.request.headers['x-ms-client-request-id']
}
request = self._client.get(status_link, headers=header_parameters)
return await self._client.async_send(request, stream=False, **self._operation_config)
|
[
"async",
"def",
"request_status",
"(",
"self",
",",
"status_link",
")",
":",
"# ARM requires to re-inject 'x-ms-client-request-id' while polling",
"header_parameters",
"=",
"{",
"'x-ms-client-request-id'",
":",
"self",
".",
"_operation",
".",
"initial_response",
".",
"request",
".",
"headers",
"[",
"'x-ms-client-request-id'",
"]",
"}",
"request",
"=",
"self",
".",
"_client",
".",
"get",
"(",
"status_link",
",",
"headers",
"=",
"header_parameters",
")",
"return",
"await",
"self",
".",
"_client",
".",
"async_send",
"(",
"request",
",",
"stream",
"=",
"False",
",",
"*",
"*",
"self",
".",
"_operation_config",
")"
] |
Do a simple GET to this status link.
This method re-inject 'x-ms-client-request-id'.
:rtype: requests.Response
|
[
"Do",
"a",
"simple",
"GET",
"to",
"this",
"status",
"link",
"."
] |
5f99262305692525d03ca87d2c5356b05c5aa874
|
https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/polling/async_arm_polling.py#L113-L125
|
train
|
Azure/msrestazure-for-python
|
msrestazure/azure_exceptions.py
|
CloudErrorData.message
|
def message(self, value):
"""Attempt to deconstruct error message to retrieve further
error data.
"""
try:
import ast
value = ast.literal_eval(value)
except (SyntaxError, TypeError, ValueError):
pass
try:
value = value.get('value', value)
msg_data = value.split('\n')
self._message = msg_data[0]
except AttributeError:
self._message = value
return
try:
self.request_id = msg_data[1].partition(':')[2]
time_str = msg_data[2].partition(':')
self.error_time = Deserializer.deserialize_iso(
"".join(time_str[2:]))
except (IndexError, DeserializationError):
pass
|
python
|
def message(self, value):
"""Attempt to deconstruct error message to retrieve further
error data.
"""
try:
import ast
value = ast.literal_eval(value)
except (SyntaxError, TypeError, ValueError):
pass
try:
value = value.get('value', value)
msg_data = value.split('\n')
self._message = msg_data[0]
except AttributeError:
self._message = value
return
try:
self.request_id = msg_data[1].partition(':')[2]
time_str = msg_data[2].partition(':')
self.error_time = Deserializer.deserialize_iso(
"".join(time_str[2:]))
except (IndexError, DeserializationError):
pass
|
[
"def",
"message",
"(",
"self",
",",
"value",
")",
":",
"try",
":",
"import",
"ast",
"value",
"=",
"ast",
".",
"literal_eval",
"(",
"value",
")",
"except",
"(",
"SyntaxError",
",",
"TypeError",
",",
"ValueError",
")",
":",
"pass",
"try",
":",
"value",
"=",
"value",
".",
"get",
"(",
"'value'",
",",
"value",
")",
"msg_data",
"=",
"value",
".",
"split",
"(",
"'\\n'",
")",
"self",
".",
"_message",
"=",
"msg_data",
"[",
"0",
"]",
"except",
"AttributeError",
":",
"self",
".",
"_message",
"=",
"value",
"return",
"try",
":",
"self",
".",
"request_id",
"=",
"msg_data",
"[",
"1",
"]",
".",
"partition",
"(",
"':'",
")",
"[",
"2",
"]",
"time_str",
"=",
"msg_data",
"[",
"2",
"]",
".",
"partition",
"(",
"':'",
")",
"self",
".",
"error_time",
"=",
"Deserializer",
".",
"deserialize_iso",
"(",
"\"\"",
".",
"join",
"(",
"time_str",
"[",
"2",
":",
"]",
")",
")",
"except",
"(",
"IndexError",
",",
"DeserializationError",
")",
":",
"pass"
] |
Attempt to deconstruct error message to retrieve further
error data.
|
[
"Attempt",
"to",
"deconstruct",
"error",
"message",
"to",
"retrieve",
"further",
"error",
"data",
"."
] |
5f99262305692525d03ca87d2c5356b05c5aa874
|
https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/azure_exceptions.py#L119-L141
|
train
|
Azure/msrestazure-for-python
|
msrestazure/azure_cloud.py
|
get_cloud_from_metadata_endpoint
|
def get_cloud_from_metadata_endpoint(arm_endpoint, name=None, session=None):
"""Get a Cloud object from an ARM endpoint.
.. versionadded:: 0.4.11
:Example:
.. code:: python
get_cloud_from_metadata_endpoint(https://management.azure.com/, "Public Azure")
:param str arm_endpoint: The ARM management endpoint
:param str name: An optional name for the Cloud object. Otherwise it's the ARM endpoint
:params requests.Session session: A requests session object if you need to configure proxy, cert, etc.
:rtype Cloud:
:returns: a Cloud object
:raises: MetadataEndpointError if unable to build the Cloud object
"""
cloud = Cloud(name or arm_endpoint)
cloud.endpoints.management = arm_endpoint
cloud.endpoints.resource_manager = arm_endpoint
_populate_from_metadata_endpoint(cloud, arm_endpoint, session)
return cloud
|
python
|
def get_cloud_from_metadata_endpoint(arm_endpoint, name=None, session=None):
"""Get a Cloud object from an ARM endpoint.
.. versionadded:: 0.4.11
:Example:
.. code:: python
get_cloud_from_metadata_endpoint(https://management.azure.com/, "Public Azure")
:param str arm_endpoint: The ARM management endpoint
:param str name: An optional name for the Cloud object. Otherwise it's the ARM endpoint
:params requests.Session session: A requests session object if you need to configure proxy, cert, etc.
:rtype Cloud:
:returns: a Cloud object
:raises: MetadataEndpointError if unable to build the Cloud object
"""
cloud = Cloud(name or arm_endpoint)
cloud.endpoints.management = arm_endpoint
cloud.endpoints.resource_manager = arm_endpoint
_populate_from_metadata_endpoint(cloud, arm_endpoint, session)
return cloud
|
[
"def",
"get_cloud_from_metadata_endpoint",
"(",
"arm_endpoint",
",",
"name",
"=",
"None",
",",
"session",
"=",
"None",
")",
":",
"cloud",
"=",
"Cloud",
"(",
"name",
"or",
"arm_endpoint",
")",
"cloud",
".",
"endpoints",
".",
"management",
"=",
"arm_endpoint",
"cloud",
".",
"endpoints",
".",
"resource_manager",
"=",
"arm_endpoint",
"_populate_from_metadata_endpoint",
"(",
"cloud",
",",
"arm_endpoint",
",",
"session",
")",
"return",
"cloud"
] |
Get a Cloud object from an ARM endpoint.
.. versionadded:: 0.4.11
:Example:
.. code:: python
get_cloud_from_metadata_endpoint(https://management.azure.com/, "Public Azure")
:param str arm_endpoint: The ARM management endpoint
:param str name: An optional name for the Cloud object. Otherwise it's the ARM endpoint
:params requests.Session session: A requests session object if you need to configure proxy, cert, etc.
:rtype Cloud:
:returns: a Cloud object
:raises: MetadataEndpointError if unable to build the Cloud object
|
[
"Get",
"a",
"Cloud",
"object",
"from",
"an",
"ARM",
"endpoint",
"."
] |
5f99262305692525d03ca87d2c5356b05c5aa874
|
https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/azure_cloud.py#L229-L251
|
train
|
Azure/msrestazure-for-python
|
msrestazure/polling/arm_polling.py
|
LongRunningOperation._as_json
|
def _as_json(self, response):
"""Assuming this is not empty, return the content as JSON.
Result/exceptions is not determined if you call this method without testing _is_empty.
:raises: DeserializationError if response body contains invalid json data.
"""
# Assume ClientResponse has "body", and otherwise it's a requests.Response
content = response.text() if hasattr(response, "body") else response.text
try:
return json.loads(content)
except ValueError:
raise DeserializationError(
"Error occurred in deserializing the response body.")
|
python
|
def _as_json(self, response):
"""Assuming this is not empty, return the content as JSON.
Result/exceptions is not determined if you call this method without testing _is_empty.
:raises: DeserializationError if response body contains invalid json data.
"""
# Assume ClientResponse has "body", and otherwise it's a requests.Response
content = response.text() if hasattr(response, "body") else response.text
try:
return json.loads(content)
except ValueError:
raise DeserializationError(
"Error occurred in deserializing the response body.")
|
[
"def",
"_as_json",
"(",
"self",
",",
"response",
")",
":",
"# Assume ClientResponse has \"body\", and otherwise it's a requests.Response",
"content",
"=",
"response",
".",
"text",
"(",
")",
"if",
"hasattr",
"(",
"response",
",",
"\"body\"",
")",
"else",
"response",
".",
"text",
"try",
":",
"return",
"json",
".",
"loads",
"(",
"content",
")",
"except",
"ValueError",
":",
"raise",
"DeserializationError",
"(",
"\"Error occurred in deserializing the response body.\"",
")"
] |
Assuming this is not empty, return the content as JSON.
Result/exceptions is not determined if you call this method without testing _is_empty.
:raises: DeserializationError if response body contains invalid json data.
|
[
"Assuming",
"this",
"is",
"not",
"empty",
"return",
"the",
"content",
"as",
"JSON",
"."
] |
5f99262305692525d03ca87d2c5356b05c5aa874
|
https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/polling/arm_polling.py#L158-L171
|
train
|
Azure/msrestazure-for-python
|
msrestazure/polling/arm_polling.py
|
LongRunningOperation.should_do_final_get
|
def should_do_final_get(self):
"""Check whether the polling should end doing a final GET.
:param requests.Response response: latest REST call response.
:rtype: bool
"""
return ((self.async_url or not self.resource) and self.method in {'PUT', 'PATCH'}) \
or (self.lro_options['final-state-via'] == _LOCATION_FINAL_STATE and self.location_url and self.async_url and self.method == 'POST')
|
python
|
def should_do_final_get(self):
"""Check whether the polling should end doing a final GET.
:param requests.Response response: latest REST call response.
:rtype: bool
"""
return ((self.async_url or not self.resource) and self.method in {'PUT', 'PATCH'}) \
or (self.lro_options['final-state-via'] == _LOCATION_FINAL_STATE and self.location_url and self.async_url and self.method == 'POST')
|
[
"def",
"should_do_final_get",
"(",
"self",
")",
":",
"return",
"(",
"(",
"self",
".",
"async_url",
"or",
"not",
"self",
".",
"resource",
")",
"and",
"self",
".",
"method",
"in",
"{",
"'PUT'",
",",
"'PATCH'",
"}",
")",
"or",
"(",
"self",
".",
"lro_options",
"[",
"'final-state-via'",
"]",
"==",
"_LOCATION_FINAL_STATE",
"and",
"self",
".",
"location_url",
"and",
"self",
".",
"async_url",
"and",
"self",
".",
"method",
"==",
"'POST'",
")"
] |
Check whether the polling should end doing a final GET.
:param requests.Response response: latest REST call response.
:rtype: bool
|
[
"Check",
"whether",
"the",
"polling",
"should",
"end",
"doing",
"a",
"final",
"GET",
"."
] |
5f99262305692525d03ca87d2c5356b05c5aa874
|
https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/polling/arm_polling.py#L203-L210
|
train
|
Azure/msrestazure-for-python
|
msrestazure/polling/arm_polling.py
|
LongRunningOperation.set_initial_status
|
def set_initial_status(self, response):
"""Process first response after initiating long running
operation and set self.status attribute.
:param requests.Response response: initial REST call response.
"""
self._raise_if_bad_http_status_and_method(response)
if self._is_empty(response):
self.resource = None
else:
try:
self.resource = self._deserialize(response)
except DeserializationError:
self.resource = None
self.set_async_url_if_present(response)
if response.status_code in {200, 201, 202, 204}:
if self.async_url or self.location_url or response.status_code == 202:
self.status = 'InProgress'
elif response.status_code == 201:
status = self._get_provisioning_state(response)
self.status = status or 'InProgress'
elif response.status_code == 200:
status = self._get_provisioning_state(response)
self.status = status or 'Succeeded'
elif response.status_code == 204:
self.status = 'Succeeded'
self.resource = None
else:
raise OperationFailed("Invalid status found")
return
raise OperationFailed("Operation failed or cancelled")
|
python
|
def set_initial_status(self, response):
"""Process first response after initiating long running
operation and set self.status attribute.
:param requests.Response response: initial REST call response.
"""
self._raise_if_bad_http_status_and_method(response)
if self._is_empty(response):
self.resource = None
else:
try:
self.resource = self._deserialize(response)
except DeserializationError:
self.resource = None
self.set_async_url_if_present(response)
if response.status_code in {200, 201, 202, 204}:
if self.async_url or self.location_url or response.status_code == 202:
self.status = 'InProgress'
elif response.status_code == 201:
status = self._get_provisioning_state(response)
self.status = status or 'InProgress'
elif response.status_code == 200:
status = self._get_provisioning_state(response)
self.status = status or 'Succeeded'
elif response.status_code == 204:
self.status = 'Succeeded'
self.resource = None
else:
raise OperationFailed("Invalid status found")
return
raise OperationFailed("Operation failed or cancelled")
|
[
"def",
"set_initial_status",
"(",
"self",
",",
"response",
")",
":",
"self",
".",
"_raise_if_bad_http_status_and_method",
"(",
"response",
")",
"if",
"self",
".",
"_is_empty",
"(",
"response",
")",
":",
"self",
".",
"resource",
"=",
"None",
"else",
":",
"try",
":",
"self",
".",
"resource",
"=",
"self",
".",
"_deserialize",
"(",
"response",
")",
"except",
"DeserializationError",
":",
"self",
".",
"resource",
"=",
"None",
"self",
".",
"set_async_url_if_present",
"(",
"response",
")",
"if",
"response",
".",
"status_code",
"in",
"{",
"200",
",",
"201",
",",
"202",
",",
"204",
"}",
":",
"if",
"self",
".",
"async_url",
"or",
"self",
".",
"location_url",
"or",
"response",
".",
"status_code",
"==",
"202",
":",
"self",
".",
"status",
"=",
"'InProgress'",
"elif",
"response",
".",
"status_code",
"==",
"201",
":",
"status",
"=",
"self",
".",
"_get_provisioning_state",
"(",
"response",
")",
"self",
".",
"status",
"=",
"status",
"or",
"'InProgress'",
"elif",
"response",
".",
"status_code",
"==",
"200",
":",
"status",
"=",
"self",
".",
"_get_provisioning_state",
"(",
"response",
")",
"self",
".",
"status",
"=",
"status",
"or",
"'Succeeded'",
"elif",
"response",
".",
"status_code",
"==",
"204",
":",
"self",
".",
"status",
"=",
"'Succeeded'",
"self",
".",
"resource",
"=",
"None",
"else",
":",
"raise",
"OperationFailed",
"(",
"\"Invalid status found\"",
")",
"return",
"raise",
"OperationFailed",
"(",
"\"Operation failed or cancelled\"",
")"
] |
Process first response after initiating long running
operation and set self.status attribute.
:param requests.Response response: initial REST call response.
|
[
"Process",
"first",
"response",
"after",
"initiating",
"long",
"running",
"operation",
"and",
"set",
"self",
".",
"status",
"attribute",
"."
] |
5f99262305692525d03ca87d2c5356b05c5aa874
|
https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/polling/arm_polling.py#L212-L245
|
train
|
Azure/msrestazure-for-python
|
msrestazure/polling/arm_polling.py
|
LongRunningOperation.parse_resource
|
def parse_resource(self, response):
"""Assuming this response is a resource, use the deserialization callback to parse it.
If body is empty, assuming no resource to return.
"""
self._raise_if_bad_http_status_and_method(response)
if not self._is_empty(response):
self.resource = self._deserialize(response)
else:
self.resource = None
|
python
|
def parse_resource(self, response):
"""Assuming this response is a resource, use the deserialization callback to parse it.
If body is empty, assuming no resource to return.
"""
self._raise_if_bad_http_status_and_method(response)
if not self._is_empty(response):
self.resource = self._deserialize(response)
else:
self.resource = None
|
[
"def",
"parse_resource",
"(",
"self",
",",
"response",
")",
":",
"self",
".",
"_raise_if_bad_http_status_and_method",
"(",
"response",
")",
"if",
"not",
"self",
".",
"_is_empty",
"(",
"response",
")",
":",
"self",
".",
"resource",
"=",
"self",
".",
"_deserialize",
"(",
"response",
")",
"else",
":",
"self",
".",
"resource",
"=",
"None"
] |
Assuming this response is a resource, use the deserialization callback to parse it.
If body is empty, assuming no resource to return.
|
[
"Assuming",
"this",
"response",
"is",
"a",
"resource",
"use",
"the",
"deserialization",
"callback",
"to",
"parse",
"it",
".",
"If",
"body",
"is",
"empty",
"assuming",
"no",
"resource",
"to",
"return",
"."
] |
5f99262305692525d03ca87d2c5356b05c5aa874
|
https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/polling/arm_polling.py#L282-L290
|
train
|
Azure/msrestazure-for-python
|
msrestazure/polling/arm_polling.py
|
LongRunningOperation.get_status_from_async
|
def get_status_from_async(self, response):
"""Process the latest status update retrieved from a
'azure-asyncoperation' header.
:param requests.Response response: latest REST call response.
:raises: BadResponse if response has no body, or body does not
contain status.
"""
self._raise_if_bad_http_status_and_method(response)
if self._is_empty(response):
raise BadResponse('The response from long running operation '
'does not contain a body.')
self.status = self._get_async_status(response)
if not self.status:
raise BadResponse("No status found in body")
# Status can contains information, see ARM spec:
# https://github.com/Azure/azure-resource-manager-rpc/blob/master/v1.0/Addendum.md#operation-resource-format
# "properties": {
# /\* The resource provider can choose the values here, but it should only be
# returned on a successful operation (status being "Succeeded"). \*/
#},
# So try to parse it
try:
self.resource = self._deserialize(response)
except Exception:
self.resource = None
|
python
|
def get_status_from_async(self, response):
"""Process the latest status update retrieved from a
'azure-asyncoperation' header.
:param requests.Response response: latest REST call response.
:raises: BadResponse if response has no body, or body does not
contain status.
"""
self._raise_if_bad_http_status_and_method(response)
if self._is_empty(response):
raise BadResponse('The response from long running operation '
'does not contain a body.')
self.status = self._get_async_status(response)
if not self.status:
raise BadResponse("No status found in body")
# Status can contains information, see ARM spec:
# https://github.com/Azure/azure-resource-manager-rpc/blob/master/v1.0/Addendum.md#operation-resource-format
# "properties": {
# /\* The resource provider can choose the values here, but it should only be
# returned on a successful operation (status being "Succeeded"). \*/
#},
# So try to parse it
try:
self.resource = self._deserialize(response)
except Exception:
self.resource = None
|
[
"def",
"get_status_from_async",
"(",
"self",
",",
"response",
")",
":",
"self",
".",
"_raise_if_bad_http_status_and_method",
"(",
"response",
")",
"if",
"self",
".",
"_is_empty",
"(",
"response",
")",
":",
"raise",
"BadResponse",
"(",
"'The response from long running operation '",
"'does not contain a body.'",
")",
"self",
".",
"status",
"=",
"self",
".",
"_get_async_status",
"(",
"response",
")",
"if",
"not",
"self",
".",
"status",
":",
"raise",
"BadResponse",
"(",
"\"No status found in body\"",
")",
"# Status can contains information, see ARM spec:",
"# https://github.com/Azure/azure-resource-manager-rpc/blob/master/v1.0/Addendum.md#operation-resource-format",
"# \"properties\": {",
"# /\\* The resource provider can choose the values here, but it should only be",
"# returned on a successful operation (status being \"Succeeded\"). \\*/",
"#},",
"# So try to parse it",
"try",
":",
"self",
".",
"resource",
"=",
"self",
".",
"_deserialize",
"(",
"response",
")",
"except",
"Exception",
":",
"self",
".",
"resource",
"=",
"None"
] |
Process the latest status update retrieved from a
'azure-asyncoperation' header.
:param requests.Response response: latest REST call response.
:raises: BadResponse if response has no body, or body does not
contain status.
|
[
"Process",
"the",
"latest",
"status",
"update",
"retrieved",
"from",
"a",
"azure",
"-",
"asyncoperation",
"header",
"."
] |
5f99262305692525d03ca87d2c5356b05c5aa874
|
https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/polling/arm_polling.py#L292-L319
|
train
|
Azure/msrestazure-for-python
|
msrestazure/polling/arm_polling.py
|
ARMPolling.initialize
|
def initialize(self, client, initial_response, deserialization_callback):
"""Set the initial status of this LRO.
:param initial_response: The initial response of the poller
:raises: CloudError if initial status is incorrect LRO state
"""
self._client = client
self._response = initial_response
self._operation = LongRunningOperation(initial_response, deserialization_callback, self._lro_options)
try:
self._operation.set_initial_status(initial_response)
except BadStatus:
self._operation.status = 'Failed'
raise CloudError(initial_response)
except BadResponse as err:
self._operation.status = 'Failed'
raise CloudError(initial_response, str(err))
except OperationFailed:
raise CloudError(initial_response)
|
python
|
def initialize(self, client, initial_response, deserialization_callback):
"""Set the initial status of this LRO.
:param initial_response: The initial response of the poller
:raises: CloudError if initial status is incorrect LRO state
"""
self._client = client
self._response = initial_response
self._operation = LongRunningOperation(initial_response, deserialization_callback, self._lro_options)
try:
self._operation.set_initial_status(initial_response)
except BadStatus:
self._operation.status = 'Failed'
raise CloudError(initial_response)
except BadResponse as err:
self._operation.status = 'Failed'
raise CloudError(initial_response, str(err))
except OperationFailed:
raise CloudError(initial_response)
|
[
"def",
"initialize",
"(",
"self",
",",
"client",
",",
"initial_response",
",",
"deserialization_callback",
")",
":",
"self",
".",
"_client",
"=",
"client",
"self",
".",
"_response",
"=",
"initial_response",
"self",
".",
"_operation",
"=",
"LongRunningOperation",
"(",
"initial_response",
",",
"deserialization_callback",
",",
"self",
".",
"_lro_options",
")",
"try",
":",
"self",
".",
"_operation",
".",
"set_initial_status",
"(",
"initial_response",
")",
"except",
"BadStatus",
":",
"self",
".",
"_operation",
".",
"status",
"=",
"'Failed'",
"raise",
"CloudError",
"(",
"initial_response",
")",
"except",
"BadResponse",
"as",
"err",
":",
"self",
".",
"_operation",
".",
"status",
"=",
"'Failed'",
"raise",
"CloudError",
"(",
"initial_response",
",",
"str",
"(",
"err",
")",
")",
"except",
"OperationFailed",
":",
"raise",
"CloudError",
"(",
"initial_response",
")"
] |
Set the initial status of this LRO.
:param initial_response: The initial response of the poller
:raises: CloudError if initial status is incorrect LRO state
|
[
"Set",
"the",
"initial",
"status",
"of",
"this",
"LRO",
"."
] |
5f99262305692525d03ca87d2c5356b05c5aa874
|
https://github.com/Azure/msrestazure-for-python/blob/5f99262305692525d03ca87d2c5356b05c5aa874/msrestazure/polling/arm_polling.py#L368-L386
|
train
|
diux-dev/ncluster
|
benchmarks/pytorch_two_machines.py
|
worker
|
def worker():
""" Initialize the distributed environment. """
import torch
import torch.distributed as dist
from torch.multiprocessing import Process
import numpy as np
print("Initializing distributed pytorch")
os.environ['MASTER_ADDR'] = str(args.master_addr)
os.environ['MASTER_PORT'] = str(args.master_port)
# Use TCP backend. Gloo needs nightly, where it currently fails with
# dist.init_process_group('gloo', rank=args.rank,
# AttributeError: module 'torch.distributed' has no attribute 'init_process_group'
dist.init_process_group('tcp', rank=args.rank,
world_size=args.size)
tensor = torch.ones(args.size_mb*250*1000)*(args.rank+1)
time_list = []
outfile = 'out' if args.rank == 0 else '/dev/null'
log = util.FileLogger(outfile)
for i in range(args.iters):
# print('before: rank ', args.rank, ' has data ', tensor[0])
start_time = time.perf_counter()
if args.rank == 0:
dist.send(tensor=tensor, dst=1)
else:
dist.recv(tensor=tensor, src=0)
elapsed_time_ms = (time.perf_counter() - start_time)*1000
time_list.append(elapsed_time_ms)
# print('after: rank ', args.rank, ' has data ', tensor[0])
rate = args.size_mb/(elapsed_time_ms/1000)
log('%03d/%d added %d MBs in %.1f ms: %.2f MB/second' % (i, args.iters, args.size_mb, elapsed_time_ms, rate))
min = np.min(time_list)
median = np.median(time_list)
log(f"min: {min:8.2f}, median: {median:8.2f}, mean: {np.mean(time_list):8.2f}")
|
python
|
def worker():
""" Initialize the distributed environment. """
import torch
import torch.distributed as dist
from torch.multiprocessing import Process
import numpy as np
print("Initializing distributed pytorch")
os.environ['MASTER_ADDR'] = str(args.master_addr)
os.environ['MASTER_PORT'] = str(args.master_port)
# Use TCP backend. Gloo needs nightly, where it currently fails with
# dist.init_process_group('gloo', rank=args.rank,
# AttributeError: module 'torch.distributed' has no attribute 'init_process_group'
dist.init_process_group('tcp', rank=args.rank,
world_size=args.size)
tensor = torch.ones(args.size_mb*250*1000)*(args.rank+1)
time_list = []
outfile = 'out' if args.rank == 0 else '/dev/null'
log = util.FileLogger(outfile)
for i in range(args.iters):
# print('before: rank ', args.rank, ' has data ', tensor[0])
start_time = time.perf_counter()
if args.rank == 0:
dist.send(tensor=tensor, dst=1)
else:
dist.recv(tensor=tensor, src=0)
elapsed_time_ms = (time.perf_counter() - start_time)*1000
time_list.append(elapsed_time_ms)
# print('after: rank ', args.rank, ' has data ', tensor[0])
rate = args.size_mb/(elapsed_time_ms/1000)
log('%03d/%d added %d MBs in %.1f ms: %.2f MB/second' % (i, args.iters, args.size_mb, elapsed_time_ms, rate))
min = np.min(time_list)
median = np.median(time_list)
log(f"min: {min:8.2f}, median: {median:8.2f}, mean: {np.mean(time_list):8.2f}")
|
[
"def",
"worker",
"(",
")",
":",
"import",
"torch",
"import",
"torch",
".",
"distributed",
"as",
"dist",
"from",
"torch",
".",
"multiprocessing",
"import",
"Process",
"import",
"numpy",
"as",
"np",
"print",
"(",
"\"Initializing distributed pytorch\"",
")",
"os",
".",
"environ",
"[",
"'MASTER_ADDR'",
"]",
"=",
"str",
"(",
"args",
".",
"master_addr",
")",
"os",
".",
"environ",
"[",
"'MASTER_PORT'",
"]",
"=",
"str",
"(",
"args",
".",
"master_port",
")",
"# Use TCP backend. Gloo needs nightly, where it currently fails with",
"# dist.init_process_group('gloo', rank=args.rank,",
"# AttributeError: module 'torch.distributed' has no attribute 'init_process_group'",
"dist",
".",
"init_process_group",
"(",
"'tcp'",
",",
"rank",
"=",
"args",
".",
"rank",
",",
"world_size",
"=",
"args",
".",
"size",
")",
"tensor",
"=",
"torch",
".",
"ones",
"(",
"args",
".",
"size_mb",
"*",
"250",
"*",
"1000",
")",
"*",
"(",
"args",
".",
"rank",
"+",
"1",
")",
"time_list",
"=",
"[",
"]",
"outfile",
"=",
"'out'",
"if",
"args",
".",
"rank",
"==",
"0",
"else",
"'/dev/null'",
"log",
"=",
"util",
".",
"FileLogger",
"(",
"outfile",
")",
"for",
"i",
"in",
"range",
"(",
"args",
".",
"iters",
")",
":",
"# print('before: rank ', args.rank, ' has data ', tensor[0])",
"start_time",
"=",
"time",
".",
"perf_counter",
"(",
")",
"if",
"args",
".",
"rank",
"==",
"0",
":",
"dist",
".",
"send",
"(",
"tensor",
"=",
"tensor",
",",
"dst",
"=",
"1",
")",
"else",
":",
"dist",
".",
"recv",
"(",
"tensor",
"=",
"tensor",
",",
"src",
"=",
"0",
")",
"elapsed_time_ms",
"=",
"(",
"time",
".",
"perf_counter",
"(",
")",
"-",
"start_time",
")",
"*",
"1000",
"time_list",
".",
"append",
"(",
"elapsed_time_ms",
")",
"# print('after: rank ', args.rank, ' has data ', tensor[0])",
"rate",
"=",
"args",
".",
"size_mb",
"/",
"(",
"elapsed_time_ms",
"/",
"1000",
")",
"log",
"(",
"'%03d/%d added %d MBs in %.1f ms: %.2f MB/second'",
"%",
"(",
"i",
",",
"args",
".",
"iters",
",",
"args",
".",
"size_mb",
",",
"elapsed_time_ms",
",",
"rate",
")",
")",
"min",
"=",
"np",
".",
"min",
"(",
"time_list",
")",
"median",
"=",
"np",
".",
"median",
"(",
"time_list",
")",
"log",
"(",
"f\"min: {min:8.2f}, median: {median:8.2f}, mean: {np.mean(time_list):8.2f}\"",
")"
] |
Initialize the distributed environment.
|
[
"Initialize",
"the",
"distributed",
"environment",
"."
] |
2fd359621896717197b479c7174d06d80df1529b
|
https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/benchmarks/pytorch_two_machines.py#L61-L100
|
train
|
diux-dev/ncluster
|
ncluster/ncluster.py
|
make_job
|
def make_job(name: str = '',
run_name: str = '',
num_tasks: int = 0,
install_script: str = '',
**kwargs
) -> backend.Job:
"""
Create a job using current backend. Blocks until all tasks are up and initialized.
Args:
name: name of the job
run_name: name of the run (auto-assigned if empty)
num_tasks: number of tasks
install_script: bash-runnable script
**kwargs:
Returns:
backend.Job
"""
return _backend.make_job(name=name, run_name=run_name, num_tasks=num_tasks,
install_script=install_script, **kwargs)
|
python
|
def make_job(name: str = '',
run_name: str = '',
num_tasks: int = 0,
install_script: str = '',
**kwargs
) -> backend.Job:
"""
Create a job using current backend. Blocks until all tasks are up and initialized.
Args:
name: name of the job
run_name: name of the run (auto-assigned if empty)
num_tasks: number of tasks
install_script: bash-runnable script
**kwargs:
Returns:
backend.Job
"""
return _backend.make_job(name=name, run_name=run_name, num_tasks=num_tasks,
install_script=install_script, **kwargs)
|
[
"def",
"make_job",
"(",
"name",
":",
"str",
"=",
"''",
",",
"run_name",
":",
"str",
"=",
"''",
",",
"num_tasks",
":",
"int",
"=",
"0",
",",
"install_script",
":",
"str",
"=",
"''",
",",
"*",
"*",
"kwargs",
")",
"->",
"backend",
".",
"Job",
":",
"return",
"_backend",
".",
"make_job",
"(",
"name",
"=",
"name",
",",
"run_name",
"=",
"run_name",
",",
"num_tasks",
"=",
"num_tasks",
",",
"install_script",
"=",
"install_script",
",",
"*",
"*",
"kwargs",
")"
] |
Create a job using current backend. Blocks until all tasks are up and initialized.
Args:
name: name of the job
run_name: name of the run (auto-assigned if empty)
num_tasks: number of tasks
install_script: bash-runnable script
**kwargs:
Returns:
backend.Job
|
[
"Create",
"a",
"job",
"using",
"current",
"backend",
".",
"Blocks",
"until",
"all",
"tasks",
"are",
"up",
"and",
"initialized",
"."
] |
2fd359621896717197b479c7174d06d80df1529b
|
https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/ncluster.py#L86-L106
|
train
|
diux-dev/ncluster
|
ncluster/local_backend.py
|
make_task
|
def make_task(name='',
run_name='',
**kwargs) -> Task:
"""Create task, also create dummy run if not specified."""
ncluster_globals.task_launched = True
name = ncluster_globals.auto_assign_task_name_if_needed(name)
# tmux can't use . for session names
tmux_session = name.replace('.', '=')
tmux_window_id = 0
util.log(f'killing session {tmux_session}')
if not util.is_set("NCLUSTER_NOKILL_TMUX"):
os.system(f'tmux kill-session -t {tmux_session}')
os.system(f'tmux new-session -s {tmux_session} -n {tmux_window_id} -d')
task = Task(name,
tmux_session=tmux_session, # propagate optional args
run_name=run_name,
**kwargs)
ncluster_globals.register_task(task, run_name)
return task
|
python
|
def make_task(name='',
run_name='',
**kwargs) -> Task:
"""Create task, also create dummy run if not specified."""
ncluster_globals.task_launched = True
name = ncluster_globals.auto_assign_task_name_if_needed(name)
# tmux can't use . for session names
tmux_session = name.replace('.', '=')
tmux_window_id = 0
util.log(f'killing session {tmux_session}')
if not util.is_set("NCLUSTER_NOKILL_TMUX"):
os.system(f'tmux kill-session -t {tmux_session}')
os.system(f'tmux new-session -s {tmux_session} -n {tmux_window_id} -d')
task = Task(name,
tmux_session=tmux_session, # propagate optional args
run_name=run_name,
**kwargs)
ncluster_globals.register_task(task, run_name)
return task
|
[
"def",
"make_task",
"(",
"name",
"=",
"''",
",",
"run_name",
"=",
"''",
",",
"*",
"*",
"kwargs",
")",
"->",
"Task",
":",
"ncluster_globals",
".",
"task_launched",
"=",
"True",
"name",
"=",
"ncluster_globals",
".",
"auto_assign_task_name_if_needed",
"(",
"name",
")",
"# tmux can't use . for session names",
"tmux_session",
"=",
"name",
".",
"replace",
"(",
"'.'",
",",
"'='",
")",
"tmux_window_id",
"=",
"0",
"util",
".",
"log",
"(",
"f'killing session {tmux_session}'",
")",
"if",
"not",
"util",
".",
"is_set",
"(",
"\"NCLUSTER_NOKILL_TMUX\"",
")",
":",
"os",
".",
"system",
"(",
"f'tmux kill-session -t {tmux_session}'",
")",
"os",
".",
"system",
"(",
"f'tmux new-session -s {tmux_session} -n {tmux_window_id} -d'",
")",
"task",
"=",
"Task",
"(",
"name",
",",
"tmux_session",
"=",
"tmux_session",
",",
"# propagate optional args",
"run_name",
"=",
"run_name",
",",
"*",
"*",
"kwargs",
")",
"ncluster_globals",
".",
"register_task",
"(",
"task",
",",
"run_name",
")",
"return",
"task"
] |
Create task, also create dummy run if not specified.
|
[
"Create",
"task",
"also",
"create",
"dummy",
"run",
"if",
"not",
"specified",
"."
] |
2fd359621896717197b479c7174d06d80df1529b
|
https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/local_backend.py#L447-L469
|
train
|
diux-dev/ncluster
|
ncluster/local_backend.py
|
Task._run_raw
|
def _run_raw(self, cmd, ignore_errors=False):
"""Runs command directly, skipping tmux interface"""
# TODO: capture stdout/stderr for feature parity with aws_backend
result = os.system(cmd)
if result != 0:
if ignore_errors:
self.log(f"command ({cmd}) failed.")
assert False, "_run_raw failed"
|
python
|
def _run_raw(self, cmd, ignore_errors=False):
"""Runs command directly, skipping tmux interface"""
# TODO: capture stdout/stderr for feature parity with aws_backend
result = os.system(cmd)
if result != 0:
if ignore_errors:
self.log(f"command ({cmd}) failed.")
assert False, "_run_raw failed"
|
[
"def",
"_run_raw",
"(",
"self",
",",
"cmd",
",",
"ignore_errors",
"=",
"False",
")",
":",
"# TODO: capture stdout/stderr for feature parity with aws_backend",
"result",
"=",
"os",
".",
"system",
"(",
"cmd",
")",
"if",
"result",
"!=",
"0",
":",
"if",
"ignore_errors",
":",
"self",
".",
"log",
"(",
"f\"command ({cmd}) failed.\"",
")",
"assert",
"False",
",",
"\"_run_raw failed\""
] |
Runs command directly, skipping tmux interface
|
[
"Runs",
"command",
"directly",
"skipping",
"tmux",
"interface"
] |
2fd359621896717197b479c7174d06d80df1529b
|
https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/local_backend.py#L270-L277
|
train
|
diux-dev/ncluster
|
ncluster/local_backend.py
|
Task.upload
|
def upload(self, local_fn, remote_fn=None, dont_overwrite=False):
"""Uploads file to remote instance. If location not specified, dumps it
into default directory. Creates missing directories in path name."""
# support wildcard through glob
if '*' in local_fn:
for local_subfn in glob.glob(local_fn):
self.upload(local_subfn)
return
if remote_fn is None:
remote_fn = os.path.basename(local_fn)
if dont_overwrite and self.exists(remote_fn):
self.log("Remote file %s exists, skipping" % (remote_fn,))
return
if not remote_fn.startswith('/'):
remote_fn = self.taskdir + '/' + remote_fn
remote_fn = remote_fn.replace('~', self.homedir)
self.log('uploading ' + local_fn + ' to ' + remote_fn)
local_fn = os.path.abspath(local_fn)
self._run_raw("cp -R %s %s" % (local_fn, remote_fn))
|
python
|
def upload(self, local_fn, remote_fn=None, dont_overwrite=False):
"""Uploads file to remote instance. If location not specified, dumps it
into default directory. Creates missing directories in path name."""
# support wildcard through glob
if '*' in local_fn:
for local_subfn in glob.glob(local_fn):
self.upload(local_subfn)
return
if remote_fn is None:
remote_fn = os.path.basename(local_fn)
if dont_overwrite and self.exists(remote_fn):
self.log("Remote file %s exists, skipping" % (remote_fn,))
return
if not remote_fn.startswith('/'):
remote_fn = self.taskdir + '/' + remote_fn
remote_fn = remote_fn.replace('~', self.homedir)
self.log('uploading ' + local_fn + ' to ' + remote_fn)
local_fn = os.path.abspath(local_fn)
self._run_raw("cp -R %s %s" % (local_fn, remote_fn))
|
[
"def",
"upload",
"(",
"self",
",",
"local_fn",
",",
"remote_fn",
"=",
"None",
",",
"dont_overwrite",
"=",
"False",
")",
":",
"# support wildcard through glob",
"if",
"'*'",
"in",
"local_fn",
":",
"for",
"local_subfn",
"in",
"glob",
".",
"glob",
"(",
"local_fn",
")",
":",
"self",
".",
"upload",
"(",
"local_subfn",
")",
"return",
"if",
"remote_fn",
"is",
"None",
":",
"remote_fn",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"local_fn",
")",
"if",
"dont_overwrite",
"and",
"self",
".",
"exists",
"(",
"remote_fn",
")",
":",
"self",
".",
"log",
"(",
"\"Remote file %s exists, skipping\"",
"%",
"(",
"remote_fn",
",",
")",
")",
"return",
"if",
"not",
"remote_fn",
".",
"startswith",
"(",
"'/'",
")",
":",
"remote_fn",
"=",
"self",
".",
"taskdir",
"+",
"'/'",
"+",
"remote_fn",
"remote_fn",
"=",
"remote_fn",
".",
"replace",
"(",
"'~'",
",",
"self",
".",
"homedir",
")",
"self",
".",
"log",
"(",
"'uploading '",
"+",
"local_fn",
"+",
"' to '",
"+",
"remote_fn",
")",
"local_fn",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"local_fn",
")",
"self",
".",
"_run_raw",
"(",
"\"cp -R %s %s\"",
"%",
"(",
"local_fn",
",",
"remote_fn",
")",
")"
] |
Uploads file to remote instance. If location not specified, dumps it
into default directory. Creates missing directories in path name.
|
[
"Uploads",
"file",
"to",
"remote",
"instance",
".",
"If",
"location",
"not",
"specified",
"dumps",
"it",
"into",
"default",
"directory",
".",
"Creates",
"missing",
"directories",
"in",
"path",
"name",
"."
] |
2fd359621896717197b479c7174d06d80df1529b
|
https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/local_backend.py#L279-L303
|
train
|
diux-dev/ncluster
|
ncluster/local_backend.py
|
Task.logdir
|
def logdir(self):
"""Returns logging directory, creating one if necessary. See "Logdir" section of design doc on naming convention."""
run_name = ncluster_globals.get_run_for_task(self)
logdir = ncluster_globals.get_logdir(run_name)
if logdir:
return logdir
# create logdir. Only single task in a group creates the logdir
if ncluster_globals.is_chief(self, run_name):
chief = self
else:
chief = ncluster_globals.get_chief(run_name)
chief.setup_logdir()
return ncluster_globals.get_logdir(run_name)
|
python
|
def logdir(self):
"""Returns logging directory, creating one if necessary. See "Logdir" section of design doc on naming convention."""
run_name = ncluster_globals.get_run_for_task(self)
logdir = ncluster_globals.get_logdir(run_name)
if logdir:
return logdir
# create logdir. Only single task in a group creates the logdir
if ncluster_globals.is_chief(self, run_name):
chief = self
else:
chief = ncluster_globals.get_chief(run_name)
chief.setup_logdir()
return ncluster_globals.get_logdir(run_name)
|
[
"def",
"logdir",
"(",
"self",
")",
":",
"run_name",
"=",
"ncluster_globals",
".",
"get_run_for_task",
"(",
"self",
")",
"logdir",
"=",
"ncluster_globals",
".",
"get_logdir",
"(",
"run_name",
")",
"if",
"logdir",
":",
"return",
"logdir",
"# create logdir. Only single task in a group creates the logdir",
"if",
"ncluster_globals",
".",
"is_chief",
"(",
"self",
",",
"run_name",
")",
":",
"chief",
"=",
"self",
"else",
":",
"chief",
"=",
"ncluster_globals",
".",
"get_chief",
"(",
"run_name",
")",
"chief",
".",
"setup_logdir",
"(",
")",
"return",
"ncluster_globals",
".",
"get_logdir",
"(",
"run_name",
")"
] |
Returns logging directory, creating one if necessary. See "Logdir" section of design doc on naming convention.
|
[
"Returns",
"logging",
"directory",
"creating",
"one",
"if",
"necessary",
".",
"See",
"Logdir",
"section",
"of",
"design",
"doc",
"on",
"naming",
"convention",
"."
] |
2fd359621896717197b479c7174d06d80df1529b
|
https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/local_backend.py#L351-L366
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.