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', ...
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', ...
[ "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'", ...
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): ...
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): ...
[ "def", "bpmn_diagram_to_png", "(", "bpmn_diagram", ",", "file_name", ")", ":", "g", "=", "bpmn_diagram", ".", "diagram_graph", "graph", "=", "pydotplus", ".", "Dot", "(", ")", "for", "node", "in", "g", ".", "nodes", "(", "data", "=", "True", ")", ":", ...
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...
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...
[ "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", ":", "re...
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 =...
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 =...
[ "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", "[", ...
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 f...
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 f...
[ "def", "add_process_to_diagram", "(", "self", ",", "process_name", "=", "\"\"", ",", "process_is_closed", "=", "False", ",", "process_is_executable", "=", "False", ",", "process_type", "=", "\"None\"", ")", ":", "plane_id", "=", "BpmnDiagramGraph", ".", "id_prefix...
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...
[ "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...
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...
[ "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", ".",...
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, ...
[ "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 - p...
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 - p...
[ "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': ...
[ "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, :p...
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, :p...
[ "def", "add_inclusive_gateway_to_diagram", "(", "self", ",", "process_id", ",", "gateway_name", "=", "\"\"", ",", "gateway_direction", "=", "\"Unspecified\"", ",", "default", "=", "None", ",", "node_id", "=", "None", ")", ":", "inclusive_gateway_id", ",", "inclusi...
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". Defau...
[ "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...
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...
[ "def", "add_parallel_gateway_to_diagram", "(", "self", ",", "process_id", ",", "gateway_name", "=", "\"\"", ",", "gateway_direction", "=", "\"Unspecified\"", ",", "node_id", "=", "None", ")", ":", "parallel_gateway_id", ",", "parallel_gateway", "=", "self", ".", "...
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". Defau...
[ "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]), floa...
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]), floa...
[ "def", "get_nodes_positions", "(", "self", ")", ":", "nodes", "=", "self", ".", "get_nodes", "(", ")", "output", "=", "{", "}", "for", "node", "in", "nodes", ":", "output", "[", "node", "[", "0", "]", "]", "=", "(", "float", "(", "node", "[", "1"...
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.wri...
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.wri...
[ "def", "create_tree", "(", "path", ",", "depth", "=", "DEPTH", ")", ":", "os", ".", "mkdir", "(", "path", ")", "for", "i", "in", "range", "(", "NUM_FILES", ")", ":", "filename", "=", "os", ".", "path", ".", "join", "(", "path", ",", "'file{0:03}.tx...
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)) ...
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)) ...
[ "def", "get_tree_size", "(", "path", ")", ":", "size", "=", "0", "try", ":", "for", "entry", "in", "scandir", ".", "scandir", "(", "path", ")", ":", "if", "entry", ".", "is_symlink", "(", ")", ":", "pass", "elif", "entry", ".", "is_dir", "(", ")", ...
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> ...
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> ...
[ "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 ...
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 ...
[ "def", "khatri_rao", "(", "matrices", ")", ":", "n_columns", "=", "matrices", "[", "0", "]", ".", "shape", "[", "1", "]", "n_factors", "=", "len", "(", "matrices", ")", "start", "=", "ord", "(", "'a'", ")", "common_dim", "=", "'z'", "target", "=", ...
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 matrice...
[ "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...
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...
[ "def", "soft_cluster_factor", "(", "factor", ")", ":", "f", "=", "np", ".", "copy", "(", "factor", ")", "cluster_ids", "=", "np", ".", "argmax", "(", "np", ".", "abs", "(", "f", ")", ",", "axis", "=", "1", ")", "scores", "=", "f", "[", "range", ...
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...
[ "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...
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...
[ "def", "hclust_linearize", "(", "U", ")", ":", "from", "scipy", ".", "cluster", "import", "hierarchy", "Z", "=", "hierarchy", ".", "ward", "(", "U", ")", "return", "hierarchy", ".", "leaves_list", "(", "hierarchy", ".", "optimal_leaf_ordering", "(", "Z", "...
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...
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...
[ "def", "reverse_segment", "(", "path", ",", "n1", ",", "n2", ")", ":", "q", "=", "path", ".", "copy", "(", ")", "if", "n2", ">", "n1", ":", "q", "[", "n1", ":", "(", "n2", "+", "1", ")", "]", "=", "path", "[", "n1", ":", "(", "n2", "+", ...
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", ")", ":", "unf", "=", "sci", ".", "dot", "(", "self", ".", "factors", "[", "0", "]", ",", "khatri_rao", "(", "self", ".", "factors", "[", "1", ":", "]", ")", ".", "T", ")", "return", "sci", ".", "reshape", "(", "un...
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/se...
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/se...
[ "def", "rebalance", "(", "self", ")", ":", "norms", "=", "[", "sci", ".", "linalg", ".", "norm", "(", "f", ",", "axis", "=", "0", ")", "for", "f", "in", "self", ".", "factors", "]", "lam", "=", "sci", ".", "multiply", ".", "reduce", "(", "norms...
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] fo...
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] fo...
[ "def", "permute", "(", "self", ",", "idx", ")", ":", "if", "set", "(", "idx", ")", "!=", "set", "(", "range", "(", "self", ".", "rank", ")", ")", ":", "raise", "ValueError", "(", "'Invalid permutation specified.'", ")", "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 ...
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 ...
[ "def", "kruskal_align", "(", "U", ",", "V", ",", "permute_U", "=", "False", ",", "permute_V", "=", "False", ")", ":", "unrm", "=", "[", "f", "/", "np", ".", "linalg", ".", "norm", "(", "f", ",", "axis", "=", "0", ")", "for", "f", "in", "U", "...
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 T...
[ "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 part...
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 part...
[ "def", "plot_objective", "(", "ensemble", ",", "partition", "=", "'train'", ",", "ax", "=", "None", ",", "jitter", "=", "0.1", ",", "scatter_kw", "=", "dict", "(", ")", ",", "line_kw", "=", "dict", "(", ")", ")", ":", "if", "ax", "is", "None", ":",...
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 ...
[ "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 :...
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 :...
[ "def", "plot_similarity", "(", "ensemble", ",", "ax", "=", "None", ",", "jitter", "=", "0.1", ",", "scatter_kw", "=", "dict", "(", ")", ",", "line_kw", "=", "dict", "(", ")", ")", ":", "if", "ax", "is", "None", ":", "ax", "=", "plt", ".", "gca", ...
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...
[ "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...
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...
[ "def", "_broadcast_arg", "(", "U", ",", "arg", ",", "argtype", ",", "name", ")", ":", "if", "arg", "is", "None", "or", "isinstance", "(", "arg", ",", "argtype", ")", ":", "return", "[", "arg", "for", "_", "in", "range", "(", "U", ".", "ndim", ")"...
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 ...
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 ...
[ "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", ")", ...
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 returne...
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 returne...
[ "def", "_check_random_state", "(", "random_state", ")", ":", "if", "random_state", "is", "None", "or", "isinstance", "(", "random_state", ",", "int", ")", ":", "return", "sci", ".", "random", ".", "RandomState", "(", "random_state", ")", "elif", "isinstance", ...
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 ...
[ "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 n...
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 n...
[ "def", "randn_ktensor", "(", "shape", ",", "rank", ",", "norm", "=", "None", ",", "random_state", "=", "None", ")", ":", "rns", "=", "_check_random_state", "(", "random_state", ")", "factors", "=", "KTensor", "(", "[", "rns", ".", "standard_normal", "(", ...
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 fa...
[ "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 ...
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 ...
[ "def", "fit", "(", "self", ",", "X", ",", "ranks", ",", "replicates", "=", "1", ",", "verbose", "=", "True", ")", ":", "if", "not", "isinstance", "(", "ranks", ",", "collections", ".", "Iterable", ")", ":", "ranks", "=", "(", "ranks", ",", ")", "...
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 ...
[ "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_...
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_...
[ "def", "_create_model_class", "(", "self", ",", "model", ")", ":", "cls_name", "=", "model", ".", "replace", "(", "'.'", ",", "'_'", ")", "if", "sys", ".", "version_info", "[", "0", "]", "<", "3", ":", "if", "isinstance", "(", "cls_name", ",", "unico...
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': '...
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': '...
[ "def", "get_all", "(", "rc_file", "=", "'~/.odoorpcrc'", ")", ":", "conf", "=", "ConfigParser", "(", ")", "conf", ".", "read", "(", "[", "os", ".", "path", ".", "expanduser", "(", "rc_file", ")", "]", ")", "sessions", "=", "{", "}", "for", "name", ...
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, ...
[ "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':...
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':...
[ "def", "get", "(", "name", ",", "rc_file", "=", "'~/.odoorpcrc'", ")", ":", "conf", "=", "ConfigParser", "(", ")", "conf", ".", "read", "(", "[", "os", ".", "path", ".", "expanduser", "(", "rc_file", ")", "]", ")", "if", "not", "conf", ".", "has_se...
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...
[ "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, 'timeou...
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, 'timeou...
[ "def", "save", "(", "name", ",", "data", ",", "rc_file", "=", "'~/.odoorpcrc'", ")", ":", "conf", "=", "ConfigParser", "(", ")", "conf", ".", "read", "(", "[", "os", ".", "path", ".", "expanduser", "(", "rc_file", ")", "]", ")", "if", "not", "conf"...
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': '...
[ "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 ...
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 ...
[ "def", "remove", "(", "name", ",", "rc_file", "=", "'~/.odoorpcrc'", ")", ":", "conf", "=", "ConfigParser", "(", ")", "conf", ".", "read", "(", "[", "os", ".", "path", ".", "expanduser", "(", "rc_file", ")", "]", ")", "if", "not", "conf", ".", "has...
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) :rai...
[ "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['param...
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['param...
[ "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", ".", "d...
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 ...
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 ...
[ "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. ...
[ "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
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' ...
[ "def", "login", "(", "self", ",", "db", ",", "login", "=", "'admin'", ",", "password", "=", "'admin'", ")", ":", "data", "=", "self", ".", "json", "(", "'/web/session/authenticate'", ",", "{", "'db'", ":", "db", ",", "'login'", ":", "login", ",", "'p...
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.RPCErr...
[ "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.UR...
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.UR...
[ "def", "exec_workflow", "(", "self", ",", "model", ",", "record_id", ",", "signal", ")", ":", "if", "tools", ".", "v", "(", "self", ".", "version", ")", "[", "0", "]", ">=", "11", ":", "raise", "DeprecationWarning", "(", "u\"Workflows have been removed in ...
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:* :rais...
[ "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 ord...
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 ord...
[ "def", "create", "(", "self", ",", "password", ",", "db", ",", "demo", "=", "False", ",", "lang", "=", "'en_US'", ",", "admin_password", "=", "'admin'", ")", ":", "self", ".", "_odoo", ".", "json", "(", "'/jsonrpc'", ",", "{", "'service'", ":", "'db'...
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', 'p...
[ "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", "...
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` (acc...
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` (acc...
[ "def", "duplicate", "(", "self", ",", "password", ",", "db", ",", "new_db", ")", ":", "self", ".", "_odoo", ".", "json", "(", "'/jsonrpc'", ",", "{", "'service'", ":", "'db'", ",", "'method'", ":", "'duplicate_database'", ",", "'args'", ":", "[", "pass...
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....
[ "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):...
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):...
[ "def", "check_value", "(", "self", ",", "value", ")", ":", "if", "value", "and", "self", ".", "size", ":", "if", "not", "is_string", "(", "value", ")", ":", "raise", "ValueError", "(", "\"Value supplied has to be a string\"", ")", "if", "len", "(", "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...
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...
[ "def", "_check_relation", "(", "self", ",", "relation", ")", ":", "selection", "=", "[", "val", "[", "0", "]", "for", "val", "in", "self", ".", "selection", "]", "if", "relation", "not", "in", "selection", ":", "raise", "ValueError", "(", "(", "\"The v...
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", ".", "...
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) ...
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) ...
[ "def", "_init_values", "(", "self", ",", "context", "=", "None", ")", ":", "if", "context", "is", "None", ":", "context", "=", "self", ".", "env", ".", "context", "basic_fields", "=", "[", "]", "for", "field_name", "in", "self", ".", "_columns", ":", ...
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...
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...
[ "def", "from_wei", "(", "number", ":", "int", ",", "unit", ":", "str", ")", "->", "Union", "[", "int", ",", "decimal", ".", "Decimal", "]", ":", "if", "unit", ".", "lower", "(", ")", "not", "in", "units", ":", "raise", "ValueError", "(", "\"Unknown...
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_...
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_...
[ "def", "to_wei", "(", "number", ":", "int", ",", "unit", ":", "str", ")", "->", "int", ":", "if", "unit", ".", "lower", "(", ")", "not", "in", "units", ":", "raise", "ValueError", "(", "\"Unknown unit. Must be one of {0}\"", ".", "format", "(", "\"/\"",...
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...
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...
[ "def", "validate_conversion_arguments", "(", "to_wrap", ")", ":", "@", "functools", ".", "wraps", "(", "to_wrap", ")", "def", "wrapper", "(", "*", "args", ",", "**", "kwargs", ")", ":", "_assert_one_val", "(", "*", "args", ",", "**", "kwargs", ")", "if",...
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", ...
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])...
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])...
[ "def", "replace_exceptions", "(", "old_to_new_exceptions", ":", "Dict", "[", "Type", "[", "BaseException", "]", ",", "Type", "[", "BaseException", "]", "]", ")", "->", "Callable", "[", "...", ",", "Any", "]", ":", "old_exceptions", "=", "tuple", "(", "old_...
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': '...
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': '...
[ "def", "collapse_if_tuple", "(", "abi", ")", ":", "typ", "=", "abi", "[", "\"type\"", "]", "if", "not", "typ", ".", "startswith", "(", "\"tuple\"", ")", ":", "return", "typ", "delimited", "=", "\",\"", ".", "join", "(", "collapse_if_tuple", "(", "c", "...
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'}, ......
[ "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(unpref...
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(unpref...
[ "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...
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(val...
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(val...
[ "def", "is_address", "(", "value", ":", "Any", ")", "->", "bool", ":", "if", "is_checksum_formatted_address", "(", "value", ")", ":", "return", "is_checksum_address", "(", "value", ")", "elif", "is_hex_address", "(", "value", ")", ":", "return", "True", "eli...
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 {}...
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 {}...
[ "def", "to_normalized_address", "(", "value", ":", "AnyStr", ")", "->", "HexAddress", ":", "try", ":", "hex_address", "=", "hexstr_if_str", "(", "to_hex", ",", "value", ")", ".", "lower", "(", ")", "except", "AttributeError", ":", "raise", "TypeError", "(", ...
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", "(", ...
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_addr...
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_addr...
[ "def", "is_same_address", "(", "left", ":", "AnyAddress", ",", "right", ":", "AnyAddress", ")", "->", "bool", ":", "if", "not", "is_address", "(", "left", ")", "or", "not", "is_address", "(", "right", ")", ":", "raise", "ValueError", "(", "\"Both values mu...
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( ...
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( ...
[ "def", "to_checksum_address", "(", "value", ":", "AnyStr", ")", "->", "ChecksumAddress", ":", "norm_address", "=", "to_normalized_address", "(", "value", ")", "address_hash", "=", "encode_hex", "(", "keccak", "(", "text", "=", "remove_0x_prefix", "(", "norm_addres...
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"] :para...
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"] :para...
[ "def", "get_msi_token", "(", "resource", ",", "port", "=", "50342", ",", "msi_conf", "=", "None", ")", ":", "request_uri", "=", "os", ".", "environ", ".", "get", "(", "\"MSI_ENDPOINT\"", ",", "'http://localhost:{}/oauth2/token'", ".", "format", "(", "port", ...
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. ...
[ "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_secre...
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_secre...
[ "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",...
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'. ...
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'. ...
[ "def", "_configure", "(", "self", ",", "**", "kwargs", ")", ":", "if", "kwargs", ".", "get", "(", "'china'", ")", ":", "err_msg", "=", "(", "\"china parameter is deprecated, \"", "\"please use \"", "\"cloud_environment=msrestazure.azure_cloud.AZURE_CHINA_CLOUD\"", ")", ...
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, de...
[ "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 A...
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 A...
[ "def", "_convert_token", "(", "self", ",", "token", ")", ":", "token", "=", "token", ".", "copy", "(", ")", "if", "\"expiresOn\"", "in", "token", "and", "\"expiresIn\"", "in", "token", ":", "token", "[", "\"expiresOn\"", "]", "=", "token", "[", "'expires...
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 c...
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 c...
[ "def", "signed_session", "(", "self", ",", "session", "=", "None", ")", ":", "self", ".", "set_token", "(", ")", "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: ...
[ "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 configu...
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 configu...
[ "def", "refresh_session", "(", "self", ",", "session", "=", "None", ")", ":", "if", "'refresh_token'", "in", "self", ".", "token", ":", "try", ":", "token", "=", "self", ".", "_context", ".", "acquire_token_with_refresh_token", "(", "self", ".", "token", "...
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: request...
[ "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 hea...
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 hea...
[ "def", "_validate", "(", "url", ")", ":", "if", "url", "is", "None", ":", "return", "parsed", "=", "urlparse", "(", "url", ")", "if", "not", "parsed", ".", "scheme", "or", "not", "parsed", ".", "netloc", ":", "raise", "ValueError", "(", "\"Invalid URL ...
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 =...
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 =...
[ "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", "{", ...
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_st...
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_st...
[ "def", "_deserialize", "(", "self", ",", "response", ")", ":", "previous_status", "=", "response", ".", "status_code", "response", ".", "status_code", "=", "self", ".", "initial_status_code", "resource", "=", "self", ".", "get_outputs", "(", "response", ")", "...
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_htt...
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_htt...
[ "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", "=", "\"In...
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 = urlpa...
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 = urlpa...
[ "def", "_polling_cookie", "(", "self", ")", ":", "parsed_url", "=", "urlparse", "(", "self", ".", "_response", ".", "request", ".", "url", ")", "host", "=", "parsed_url", ".", "hostname", ".", "strip", "(", "'.'", ")", "if", "host", "==", "'localhost'", ...
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._d...
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._d...
[ "def", "remove_done_callback", "(", "self", ",", "func", ")", ":", "if", "self", ".", "_done", "is", "None", "or", "self", ".", "_done", ".", "is_set", "(", ")", ":", "raise", "ValueError", "(", "\"Process is complete.\"", ")", "self", ".", "_callbacks", ...
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/u...
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/u...
[ "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", ":",...
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-0...
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-0...
[ "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\"", ...
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): ...
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): ...
[ "def", "parse_resource_id", "(", "rid", ")", ":", "if", "not", "rid", ":", "return", "{", "}", "match", "=", "_ARMID_RE", ".", "match", "(", "rid", ")", "if", "match", ":", "result", "=", "match", ".", "groupdict", "(", ")", "children", "=", "_CHILDR...
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: Subscr...
[ "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'] ...
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'] ...
[ "def", "_populate_alternate_kwargs", "(", "kwargs", ")", ":", "resource_namespace", "=", "kwargs", "[", "'namespace'", "]", "resource_type", "=", "kwargs", ".", "get", "(", "'child_type_{}'", ".", "format", "(", "kwargs", "[", "'last_child_num'", "]", ")", ")", ...
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_namespa...
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_namespa...
[ "def", "_get_parents_from_parts", "(", "kwargs", ")", ":", "parent_builder", "=", "[", "]", "if", "kwargs", "[", "'last_child_num'", "]", "is", "not", "None", ":", "parent_builder", ".", "append", "(", "'{type}/{name}/'", ".", "format", "(", "**", "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. ...
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. ...
[ "def", "resource_id", "(", "**", "kwargs", ")", ":", "kwargs", "=", "{", "k", ":", "v", "for", "k", ",", "v", "in", "kwargs", ".", "items", "(", ")", "if", "v", "is", "not", "None", "}", "rid_builder", "=", "[", "'/subscriptions/{subscription}'", "."...
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 fo...
[ "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 ...
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 ...
[ "def", "is_valid_resource_id", "(", "rid", ",", "exception_type", "=", "None", ")", ":", "is_valid", "=", "False", "try", ":", "is_valid", "=", "rid", "and", "resource_id", "(", "**", "parse_resource_id", "(", "rid", ")", ")", ".", "lower", "(", ")", "==...
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_typ...
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_typ...
[ "def", "is_valid_resource_name", "(", "rname", ",", "exception_type", "=", "None", ")", ":", "match", "=", "_ARMNAME_RE", ".", "match", "(", "rname", ")", "if", "match", ":", "return", "True", "if", "exception_type", ":", "raise", "exception_type", "(", ")",...
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 whethe...
[ "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...
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...
[ "async", "def", "_delay", "(", "self", ")", ":", "if", "self", ".", "_response", "is", "None", ":", "await", "asyncio", ".", "sleep", "(", "0", ")", "if", "self", ".", "_response", ".", "headers", ".", "get", "(", "'retry-after'", ")", ":", "await", ...
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_...
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_...
[ "async", "def", "update_status", "(", "self", ")", ":", "if", "self", ".", "_operation", ".", "async_url", ":", "self", ".", "_response", "=", "await", "self", ".", "request_status", "(", "self", ".", "_operation", ".", "async_url", ")", "self", ".", "_o...
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-...
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-...
[ "async", "def", "request_status", "(", "self", ",", "status_link", ")", ":", "header_parameters", "=", "{", "'x-ms-client-request-id'", ":", "self", ".", "_operation", ".", "initial_response", ".", "request", ".", "headers", "[", "'x-ms-client-request-id'", "]", "...
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('...
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('...
[ "def", "message", "(", "self", ",", "value", ")", ":", "try", ":", "import", "ast", "value", "=", "ast", ".", "literal_eval", "(", "value", ")", "except", "(", "SyntaxError", ",", "TypeError", ",", "ValueError", ")", ":", "pass", "try", ":", "value", ...
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 m...
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 m...
[ "def", "get_cloud_from_metadata_endpoint", "(", "arm_endpoint", ",", "name", "=", "None", ",", "session", "=", "None", ")", ":", "cloud", "=", "Cloud", "(", "name", "or", "arm_endpoint", ")", "cloud", ".", "endpoints", ".", "management", "=", "arm_endpoint", ...
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. Other...
[ "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...
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...
[ "def", "_as_json", "(", "self", ",", "response", ")", ":", "content", "=", "response", ".", "text", "(", ")", "if", "hasattr", "(", "response", ",", "\"body\"", ")", "else", "response", ".", "text", "try", ":", "return", "json", ".", "loads", "(", "c...
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....
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....
[ "def", "should_do_final_get", "(", "self", ")", ":", "return", "(", "(", "self", ".", "async_url", "or", "not", "self", ".", "resource", ")", "and", "self", ".", "method", "in", "{", "'PUT'", ",", "'PATCH'", "}", ")", "or", "(", "self", ".", "lro_opt...
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_em...
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_em...
[ "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...
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.r...
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.r...
[ "def", "parse_resource", "(", "self", ",", "response", ")", ":", "self", ".", "_raise_if_bad_http_status_and_method", "(", "response", ")", "if", "not", "self", ".", "_is_empty", "(", "response", ")", ":", "self", ".", "resource", "=", "self", ".", "_deseria...
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. ""...
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. ""...
[ "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 runnin...
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._respo...
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._respo...
[ "def", "initialize", "(", "self", ",", "client", ",", "initial_response", ",", "deserialization_callback", ")", ":", "self", ".", "_client", "=", "client", "self", ".", "_response", "=", "initial_response", "self", ".", "_operation", "=", "LongRunningOperation", ...
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.mast...
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.mast...
[ "def", "worker", "(", ")", ":", "import", "torch", "import", "torch", ".", "distributed", "as", "dist", "from", "torch", ".", "multiprocessing", "import", "Process", "import", "numpy", "as", "np", "print", "(", "\"Initializing distributed pytorch\"", ")", "os", ...
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...
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...
[ "def", "make_job", "(", "name", ":", "str", "=", "''", ",", "run_name", ":", "str", "=", "''", ",", "num_tasks", ":", "int", "=", "0", ",", "install_script", ":", "str", "=", "''", ",", "**", "kwargs", ")", "->", "backend", ".", "Job", ":", "retu...
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('...
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('...
[ "def", "make_task", "(", "name", "=", "''", ",", "run_name", "=", "''", ",", "**", "kwargs", ")", "->", "Task", ":", "ncluster_globals", ".", "task_launched", "=", "True", "name", "=", "ncluster_globals", ".", "auto_assign_task_name_if_needed", "(", "name", ...
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_ra...
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_ra...
[ "def", "_run_raw", "(", "self", ",", "cmd", ",", "ignore_errors", "=", "False", ")", ":", "result", "=", "os", ".", "system", "(", "cmd", ")", "if", "result", "!=", "0", ":", "if", "ignore_errors", ":", "self", ".", "log", "(", "f\"command ({cmd}) fail...
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)...
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)...
[ "def", "upload", "(", "self", ",", "local_fn", ",", "remote_fn", "=", "None", ",", "dont_overwrite", "=", "False", ")", ":", "if", "'*'", "in", "local_fn", ":", "for", "local_subfn", "in", "glob", ".", "glob", "(", "local_fn", ")", ":", "self", ".", ...
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...
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...
[ "def", "logdir", "(", "self", ")", ":", "run_name", "=", "ncluster_globals", ".", "get_run_for_task", "(", "self", ")", "logdir", "=", "ncluster_globals", ".", "get_logdir", "(", "run_name", ")", "if", "logdir", ":", "return", "logdir", "if", "ncluster_globals...
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