Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def set_flow_node_ref_list(self, value): if value is None or not isinstance(value, list): raise TypeError("FlowNodeRefList new value must be a list") else: for element in value: if not isinstance(element, str):...
[ "\n Setter for 'flow_node_ref' field.\n :param value - a new value of 'flow_node_ref' field. Must be a list of String objects (ID of referenced nodes).\n " ]
Please provide a description of the function:def set_child_lane_set(self, value): if value is None: self.__child_lane_set = value elif not isinstance(value, lane_set.LaneSet): raise TypeError("ChildLaneSet must be a LaneSet") else: self.__child_lane_s...
[ "\n Setter for 'child_lane_set' field.\n :param value - a new value of 'child_lane_set' field. Must be an object of LaneSet type.\n " ]
Please provide a description of the function:def export_xml_file(self, directory, filename): bpmn_export.BpmnDiagramGraphExport.export_xml_file(directory, filename, self)
[ "\n Exports diagram inner graph to BPMN 2.0 XML file (with Diagram Interchange data).\n\n :param directory: strings representing output directory,\n :param filename: string representing output file name.\n " ]
Please provide a description of the function:def export_xml_file_no_di(self, directory, filename): bpmn_export.BpmnDiagramGraphExport.export_xml_file_no_di(directory, filename, self)
[ "\n Exports diagram inner graph to BPMN 2.0 XML file (without Diagram Interchange data).\n\n :param directory: strings representing output directory,\n :param filename: string representing output file name.\n " ]
Please provide a description of the function:def export_csv_file(self, directory, filename): bpmn_csv_export.BpmnDiagramGraphCsvExport.export_process_to_csv(self, directory, filename)
[ "\n Exports diagram inner graph to BPMN 2.0 XML file (with Diagram Interchange data).\n\n :param directory: strings representing output directory,\n :param filename: string representing output file name.\n " ]
Please provide a description of the function:def get_nodes(self, node_type=""): tmp_nodes = self.diagram_graph.nodes(True) if node_type == "": return tmp_nodes else: nodes = [] for node in tmp_nodes: if node[1][consts.Consts.type] == n...
[ "\n Gets all nodes of requested type. If no type is provided by user, all nodes in BPMN diagram graph are returned.\n Returns a dictionary, where key is an ID of node, value is a dictionary of all node attributes.\n\n :param node_type: string with valid BPMN XML tag name (e.g. 'task', 'sequence...
Please provide a description of the function:def get_nodes_list_by_process_id(self, process_id): tmp_nodes = self.diagram_graph.nodes(True) nodes = [] for node in tmp_nodes: if node[1][consts.Consts.process] == process_id: nodes.append(node) return no...
[ "\n Gets all nodes of requested type. If no type is provided by user, all nodes in BPMN diagram graph are returned.\n Returns a dictionary, where key is an ID of node, value is a dictionary of all node attributes.\n\n :param process_id: string object, representing an ID of parent process elemen...
Please provide a description of the function:def get_node_by_id(self, node_id): tmp_nodes = self.diagram_graph.nodes(data=True) for node in tmp_nodes: if node[0] == node_id: return node
[ "\n Gets a node with requested ID.\n Returns a tuple, where first value is node ID, second - a dictionary of all node attributes.\n\n :param node_id: string with ID of node.\n " ]
Please provide a description of the function:def get_nodes_id_list_by_type(self, node_type): tmp_nodes = self.diagram_graph.nodes(data=True) id_list = [] for node in tmp_nodes: if node[1][consts.Consts.type] == node_type: id_list.append(node[0]) retur...
[ "\n Get a list of node's id by requested type.\n Returns a list of ids\n\n :param node_type: string with valid BPMN XML tag name (e.g. 'task', 'sequenceFlow').\n " ]
Please provide a description of the function:def get_flow_by_id(self, flow_id): tmp_flows = self.diagram_graph.edges(data=True) for flow in tmp_flows: if flow[2][consts.Consts.id] == flow_id: return flow
[ "\n Gets an edge (flow) with requested ID.\n Returns a tuple, where first value is node ID, second - a dictionary of all node attributes.\n\n :param flow_id: string with edge ID.\n " ]
Please provide a description of the function:def get_flows_list_by_process_id(self, process_id): tmp_flows = self.diagram_graph.edges(data=True) flows = [] for flow in tmp_flows: if consts.Consts.process in flow[2] and flow[2][consts.Consts.process] == process_id: ...
[ "\n Gets an edge (flow) with requested ID.\n Returns a tuple, where first value is node ID, second - a dictionary of all node attributes.\n\n :param process_id: string object, representing an ID of parent process element.\n " ]
Please provide a description of the function:def create_new_diagram_graph(self, diagram_name=""): self.__init__() diagram_id = BpmnDiagramGraph.id_prefix + str(uuid.uuid4()) self.diagram_attributes[consts.Consts.id] = diagram_id self.diagram_attributes[consts.Consts.name] = dia...
[ "\n Initializes a new BPMN diagram and sets up a basic diagram attributes.\n Accepts a user-defined values for following attributes:\n (Diagram element)\n\n - name - default value empty string.\n\n :param diagram_name: string type. Represents a user-defined value of 'BPMNDiagram' ...
Please provide a description of the function:def add_process_to_diagram(self, process_name="", process_is_closed=False, process_is_executable=False, process_type="None"): plane_id = BpmnDiagramGraph.id_prefix + str(uuid.uuid4()) process_id = BpmnDiagramGraph.id_pr...
[ "\n Adds a new process to diagram and corresponding participant\n process, diagram and plane\n\n Accepts a user-defined values for following attributes:\n (Process element)\n - isClosed - default value false,\n - isExecutable - default value false,\n - processTyp...
Please provide a description of the function:def add_flow_node_to_diagram(self, process_id, node_type, name, node_id=None): if node_id is None: node_id = BpmnDiagramGraph.id_prefix + str(uuid.uuid4()) self.diagram_graph.add_node(node_id) self.diagram_graph.node[node_id][cons...
[ "\n Helper function that adds a new Flow Node to diagram. It is used to add a new node of specified type.\n Adds a basic information inherited from Flow Node type.\n\n :param process_id: string object. ID of parent process,\n :param node_type: string object. Represents type of BPMN node ...
Please provide a description of the function:def add_task_to_diagram(self, process_id, task_name="", node_id=None): return self.add_flow_node_to_diagram(process_id, consts.Consts.task, task_name, node_id)
[ "\n Adds a Task element to BPMN diagram.\n User-defined attributes:\n\n - name\n\n\n :param process_id: string object. ID of parent process,\n :param task_name: string object. Name of task,\n :param node_id: string object. ID of node. Default value - None.\n :return:...
Please provide a description of the function:def add_subprocess_to_diagram(self, process_id, subprocess_name, is_expanded=False, triggered_by_event=False, node_id=None): subprocess_id, subprocess = self.add_flow_node_to_diagram(process_id, consts.Consts.subprocess, sub...
[ "\n Adds a SubProcess element to BPMN diagram.\n User-defined attributes:\n\n - name\n - triggered_by_event\n\n\n :param process_id: string object. ID of parent process,\n :param subprocess_name: string object. Name of subprocess,\n :param is_expanded: boolean value ...
Please provide a description of the function:def add_start_event_to_diagram(self, process_id, start_event_name="", start_event_definition=None, parallel_multiple=False, is_interrupting=True, node_id=None): start_event_id, start_event = self.add_flow_node_to_diagram(pr...
[ "\n Adds a StartEvent element to BPMN diagram.\n\n User-defined attributes:\n\n - name\n - parallel_multiple\n - is_interrupting\n - event definition (creates a special type of start event). Supported event definitions -\n * 'message': 'messageEventDefinition', \...
Please provide a description of the function:def add_end_event_to_diagram(self, process_id, end_event_name="", end_event_definition=None, node_id=None): end_event_id, end_event = self.add_flow_node_to_diagram(process_id, consts.Consts.end_event, end_event_name, ...
[ "\n Adds an EndEvent element to BPMN diagram.\n User-defined attributes:\n\n - name\n - event definition (creates a special type of end event). Supported event definitions\n * `terminate`: 'terminateEventDefinition', \n * `signal`: 'signalEventDefinition', \n ...
Please provide a description of the function:def add_event_definition_element(event_type, event_definitions): event_def_id = BpmnDiagramGraph.id_prefix + str(uuid.uuid4()) event_def = {consts.Consts.id: event_def_id, consts.Consts.definition_type: event_definitions[event_type]} return e...
[ "\n Helper function, that creates event definition element (special type of event) from given parameters.\n\n :param event_type: string object. Short name of required event definition,\n :param event_definitions: dictionary of event definitions. Key is a short name of event definition,\n ...
Please provide a description of the function:def add_gateway_to_diagram(self, process_id, gateway_type, gateway_name="", gateway_direction="Unspecified", node_id=None): gateway_id, gateway = self.add_flow_node_to_diagram(process_id, gateway_type, gateway_name, node_id) ...
[ "\n Adds an exclusiveGateway element to BPMN diagram.\n\n :param process_id: string object. ID of parent process,\n :param gateway_type: string object. Type of gateway to be added.\n :param gateway_name: string object. Name of exclusive gateway,\n :param gateway_direction: string ...
Please provide a description of the function:def add_exclusive_gateway_to_diagram(self, process_id, gateway_name="", gateway_direction="Unspecified", default=None, node_id=None): exclusive_gateway_id, exclusive_gateway = self.add_gateway_to_diagram(process_id, ...
[ "\n Adds an exclusiveGateway element to BPMN diagram.\n\n :param process_id: string object. ID of parent process,\n :param gateway_name: string object. Name of exclusive gateway,\n :param gateway_direction: string object. Accepted values - \"Unspecified\", \"Converging\", \"Diverging\", ...
Please provide a description of the function:def add_inclusive_gateway_to_diagram(self, process_id, gateway_name="", gateway_direction="Unspecified", default=None, node_id=None): inclusive_gateway_id, inclusive_gateway = self.add_gateway_to_diagram(process_id, ...
[ "\n Adds an inclusiveGateway element to BPMN diagram.\n\n :param process_id: string object. ID of parent process,\n :param gateway_name: string object. Name of inclusive gateway,\n :param gateway_direction: string object. Accepted values - \"Unspecified\", \"Converging\", \"Diverging\", ...
Please provide a description of the function:def add_parallel_gateway_to_diagram(self, process_id, gateway_name="", gateway_direction="Unspecified", node_id=None): parallel_gateway_id, parallel_gateway = self.add_gateway_to_diagram(process_id, ...
[ "\n Adds an parallelGateway element to BPMN diagram.\n\n :param process_id: string object. ID of parent process,\n :param gateway_name: string object. Name of inclusive gateway,\n :param gateway_direction: string object. Accepted values - \"Unspecified\", \"Converging\", \"Diverging\", \...
Please provide a description of the function:def add_sequence_flow_to_diagram(self, process_id, source_ref_id, target_ref_id, sequence_flow_name=""): sequence_flow_id = BpmnDiagramGraph.id_prefix + str(uuid.uuid4()) self.sequence_flows[sequence_flow_id] = {consts.Consts.name: sequence_flow_name...
[ "\n Adds a SequenceFlow element to BPMN diagram.\n Requires that user passes a sourceRef and targetRef as parameters.\n User-defined attributes:\n\n - name\n\n :param process_id: string object. ID of parent process,\n :param source_ref_id: string object. ID of source no...
Please provide a description of the function:def get_nodes_positions(self): nodes = self.get_nodes() output = {} for node in nodes: output[node[0]] = (float(node[1][consts.Consts.x]), float(node[1][consts.Consts.y])) return output
[ "\n Getter method for nodes positions.\n\n :return: A dictionary with nodes as keys and positions as values\n " ]
Please provide a description of the function:def set_condition(self, value): if value is None or not isinstance(value, str): raise TypeError("Condition is required and must be set to a String") else: self.__condition = value
[ "\n Setter for 'condition' field.\n :param value - a new value of 'condition' field. Required field. Must be a String.\n " ]
Please provide a description of the function:def os_walk_pre_35(top, topdown=True, onerror=None, followlinks=False): islink, join, isdir = os.path.islink, os.path.join, os.path.isdir try: names = os.listdir(top) except OSError as err: if onerror is not None: onerror(err) ...
[ "Pre Python 3.5 implementation of os.walk() that doesn't use scandir." ]
Please provide a description of the function:def create_tree(path, depth=DEPTH): os.mkdir(path) for i in range(NUM_FILES): filename = os.path.join(path, 'file{0:03}.txt'.format(i)) with open(filename, 'wb') as f: f.write(b'foo') if depth <= 1: return for i in ran...
[ "Create a directory tree at path with given depth, and NUM_DIRS and\n NUM_FILES at each level.\n " ]
Please provide a description of the function:def get_tree_size(path): size = 0 try: for entry in scandir.scandir(path): if entry.is_symlink(): pass elif entry.is_dir(): size += get_tree_size(os.path.join(path, entry.name)) else: ...
[ "Return total size of all files in directory tree at path." ]
Please provide a description of the function:def unfold(tensor, mode): return np.moveaxis(tensor, mode, 0).reshape((tensor.shape[mode], -1))
[ "Returns the mode-`mode` unfolding of `tensor`.\n\n Parameters\n ----------\n tensor : ndarray\n mode : int\n\n Returns\n -------\n ndarray\n unfolded_tensor of shape ``(tensor.shape[mode], -1)``\n\n Author\n ------\n Jean Kossaifi <https://github.com/tensorly>\n " ]
Please provide a description of the function:def khatri_rao(matrices): n_columns = matrices[0].shape[1] n_factors = len(matrices) start = ord('a') common_dim = 'z' target = ''.join(chr(start + i) for i in range(n_factors)) source = ','.join(i+common_dim for i in target) operation = so...
[ "Khatri-Rao product of a list of matrices.\n\n Parameters\n ----------\n matrices : list of ndarray\n\n Returns\n -------\n khatri_rao_product: matrix of shape ``(prod(n_i), m)``\n where ``prod(n_i) = prod([m.shape[0] for m in matrices])``\n i.e. the product of the number of rows of ...
Please provide a description of the function:def soft_cluster_factor(factor): # copy factor of interest f = np.copy(factor) # cluster based on score of maximum absolute value cluster_ids = np.argmax(np.abs(f), axis=1) scores = f[range(f.shape[0]), cluster_ids] # resort within each cluste...
[ "Returns soft-clustering of data based on CP decomposition results.\n\n Parameters\n ----------\n data : ndarray, N x R matrix of nonnegative data\n Datapoints are held in rows, features are held in columns\n\n Returns\n -------\n cluster_ids : ndarray, vector of N integers in range(0, R)\n...
Please provide a description of the function:def tsp_linearize(data, niter=1000, metric='euclidean', **kwargs): # Compute pairwise distances between all datapoints N = data.shape[0] D = scipy.spatial.distance.pdist(data, metric=metric, **kwargs) # To solve the travelling salesperson problem with ...
[ "Sorts a matrix dataset to (approximately) solve the traveling\n salesperson problem. The matrix can be re-sorted so that sequential rows\n represent datapoints that are close to each other based on some\n user-defined distance metric. Uses 2-opt local search algorithm.\n\n Args\n ----\n data : nd...
Please provide a description of the function:def hclust_linearize(U): from scipy.cluster import hierarchy Z = hierarchy.ward(U) return hierarchy.leaves_list(hierarchy.optimal_leaf_ordering(Z, U))
[ "Sorts the rows of a matrix by hierarchical clustering.\n\n Parameters:\n U (ndarray) : matrix of data\n\n Returns:\n prm (ndarray) : permutation of the rows\n " ]
Please provide a description of the function:def reverse_segment(path, n1, n2): q = path.copy() if n2 > n1: q[n1:(n2+1)] = path[n1:(n2+1)][::-1] return q else: seg = np.hstack((path[n1:], path[:(n2+1)]))[::-1] brk = len(q) - n1 q[n1:] = seg[:brk] q[:(n2+1...
[ "Reverse the nodes between n1 and n2.\n " ]
Please provide a description of the function:def _solve_tsp(dist, niter): # number of nodes N = dist.shape[0] # tsp path for quick calculation of cost ii = np.arange(N) jj = np.hstack((np.arange(1, N), 0)) # for each node, cache a sorted list of all other nodes in order of # increasi...
[ "Solve travelling salesperson problem (TSP) by two-opt swapping.\n\n Params\n ------\n dist (ndarray) : distance matrix\n\n Returns\n -------\n path (ndarray) : permutation of nodes in graph (rows of dist matrix)\n " ]
Please provide a description of the function:def full(self): # Compute tensor unfolding along first mode unf = sci.dot(self.factors[0], khatri_rao(self.factors[1:]).T) # Inverse unfolding along first mode return sci.reshape(unf, self.shape)
[ "Converts KTensor to a dense ndarray." ]
Please provide a description of the function:def rebalance(self): # Compute norms along columns for each factor matrix norms = [sci.linalg.norm(f, axis=0) for f in self.factors] # Multiply norms across all modes lam = sci.multiply.reduce(norms) ** (1/self.ndim) # Upda...
[ "Rescales factors across modes so that all norms match.\n " ]
Please provide a description of the function:def permute(self, idx): # Check that input is a true permutation if set(idx) != set(range(self.rank)): raise ValueError('Invalid permutation specified.') # Update factors self.factors = [f[:, idx] for f in self.factors] ...
[ "Permutes the columns of the factor matrices inplace\n " ]
Please provide a description of the function:def kruskal_align(U, V, permute_U=False, permute_V=False): # Compute similarity matrices. unrm = [f / np.linalg.norm(f, axis=0) for f in U.factors] vnrm = [f / np.linalg.norm(f, axis=0) for f in V.factors] sim_matrices = [np.dot(u.T, v) for u, v in zip(...
[ "Aligns two KTensors and returns a similarity score.\n\n Parameters\n ----------\n U : KTensor\n First kruskal tensor to align.\n V : KTensor\n Second kruskal tensor to align.\n permute_U : bool\n If True, modifies 'U' to align the KTensors (default is False).\n permute_V : bo...
Please provide a description of the function:def plot_objective(ensemble, partition='train', ax=None, jitter=0.1, scatter_kw=dict(), line_kw=dict()): if ax is None: ax = plt.gca() if partition == 'train': pass elif partition == 'test': raise NotImplementedEr...
[ "Plots objective function as a function of model rank.\n\n Parameters\n ----------\n ensemble : Ensemble object\n holds optimization results across a range of model ranks\n partition : string, one of: {'train', 'test'}\n specifies whether to plot the objective function on the training\n ...
Please provide a description of the function:def plot_similarity(ensemble, ax=None, jitter=0.1, scatter_kw=dict(), line_kw=dict()): if ax is None: ax = plt.gca() # compile statistics for plotting x, sim, mean_sim = [], [], [] for rank in sorted(ensemble.results): ...
[ "Plots similarity across optimization runs as a function of model rank.\n\n Parameters\n ----------\n ensemble : Ensemble object\n holds optimization results across a range of model ranks\n ax : matplotlib axis (optional)\n axis to plot on (defaults to current axis object)\n jitter : fl...
Please provide a description of the function:def plot_factors(U, plots='line', fig=None, axes=None, scatter_kw=dict(), line_kw=dict(), bar_kw=dict(), **kwargs): # ~~~~~~~~~~~~~ # PARSE OPTIONS # ~~~~~~~~~~~~~ kwargs.setdefault('figsize', (8, U.rank)) # parse optional inputs ...
[ "Plots a KTensor.\n\n Note: Each keyword option is broadcast to all modes of the KTensor. For\n example, if `U` is a 3rd-order tensor (i.e. `U.ndim == 3`) then\n `plot_factors(U, plots=['line','bar','scatter'])` plots all factors for the\n first mode as a line plot, the second as a bar plot, and the thi...
Please provide a description of the function:def _broadcast_arg(U, arg, argtype, name): # if input is not iterable, broadcast it all dimensions of the tensor if arg is None or isinstance(arg, argtype): return [arg for _ in range(U.ndim)] # check if iterable input is valid elif np.iterable...
[ "Broadcasts plotting option `arg` to all factors.\n\n Args:\n U : KTensor\n arg : argument provided by the user\n argtype : expected type for arg\n name : name of the variable, used for error handling\n\n Returns:\n iterable version of arg of length U.ndim\n " ]
Please provide a description of the function:def _check_cpd_inputs(X, rank): if X.ndim < 3: raise ValueError("Array with X.ndim > 2 expected.") if rank <= 0 or not isinstance(rank, int): raise ValueError("Rank is invalid.")
[ "Checks that inputs to optimization function are appropriate.\n\n Parameters\n ----------\n X : ndarray\n Tensor used for fitting CP decomposition.\n rank : int\n Rank of low rank decomposition.\n\n Raises\n ------\n ValueError: If inputs are not suited for CP decomposition.\n ...
Please provide a description of the function:def _get_initial_ktensor(init, X, rank, random_state, scale_norm=True): normX = linalg.norm(X) if scale_norm else None if init == 'randn': # TODO - match the norm of the initialization to the norm of X. U = randn_ktensor(X.shape, rank, norm=norm...
[ "\n Parameters\n ----------\n init : str\n Specifies type of initializations ('randn', 'rand')\n X : ndarray\n Tensor that the decomposition is fit to.\n rank : int\n Rank of decomposition\n random_state : RandomState or int\n Specifies seed for random number generator\...
Please provide a description of the function:def still_optimizing(self): # Check if we need to give up on optimizing. if (self.iterations > self.max_iter) or (self.time_elapsed() > self.max_time): return False # Always optimize for at least 'min_iter' iterations. e...
[ "True unless converged or maximum iterations/time exceeded." ]
Please provide a description of the function:def _check_random_state(random_state): if random_state is None or isinstance(random_state, int): return sci.random.RandomState(random_state) elif isinstance(random_state, sci.random.RandomState): return random_state else: raise TypeEr...
[ "Checks and processes user input for seeding random numbers.\n\n Parameters\n ----------\n random_state : int, RandomState instance or None\n If int, a RandomState instance is created with this integer seed.\n If RandomState instance, random_state is returned;\n If None, a RandomState ...
Please provide a description of the function:def randn_ktensor(shape, rank, norm=None, random_state=None): # Check input. rns = _check_random_state(random_state) # Draw low-rank factor matrices with i.i.d. Gaussian elements. factors = KTensor([rns.standard_normal((i, rank)) for i in shape]) r...
[ "\n Generates a random N-way tensor with rank R, where the entries are\n drawn from the standard normal distribution.\n\n Parameters\n ----------\n shape : tuple\n shape of the tensor\n\n rank : integer\n rank of the tensor\n\n norm : float or None, optional (defaults: None)\n ...
Please provide a description of the function:def rand_ktensor(shape, rank, norm=None, random_state=None): # Check input. rns = _check_random_state(random_state) # Randomize low-rank factor matrices i.i.d. uniform random elements. factors = KTensor([rns.uniform(0.0, 1.0, size=(i, rank)) for i in s...
[ "\n Generates a random N-way tensor with rank R, where the entries are\n drawn from the standard uniform distribution in the interval [0.0,1].\n\n Parameters\n ----------\n shape : tuple\n shape of the tensor\n\n rank : integer\n rank of the tensor\n\n norm : float or None, option...
Please provide a description of the function:def mcp_als(X, rank, mask, random_state=None, init='randn', **options): # Check inputs. optim_utils._check_cpd_inputs(X, rank) # Initialize problem. U, _ = optim_utils._get_initial_ktensor(init, X, rank, random_state, scale_norm=False) result = Fit...
[ "Fits CP Decomposition with missing data using Alternating Least Squares (ALS).\n\n Parameters\n ----------\n X : (I_1, ..., I_N) array_like\n A tensor with ``X.ndim >= 3``.\n\n rank : integer\n The `rank` sets the number of components to be computed.\n\n mask : (I_1, ..., I_N) array_li...
Please provide a description of the function:def ncp_bcd(X, rank, random_state=None, init='rand', **options): # Check inputs. optim_utils._check_cpd_inputs(X, rank) # Store norm of X for computing objective function. N = X.ndim # Initialize problem. U, normX = optim_utils._get_initial_kt...
[ "\n Fits nonnegative CP Decomposition using the Block Coordinate Descent (BCD)\n Method.\n\n Parameters\n ----------\n X : (I_1, ..., I_N) array_like\n A real array with nonnegative entries and ``X.ndim >= 3``.\n\n rank : integer\n The `rank` sets the number of components to be compu...
Please provide a description of the function:def ncp_hals(X, rank, random_state=None, init='rand', **options): # Check inputs. optim_utils._check_cpd_inputs(X, rank) # Initialize problem. U, normX = optim_utils._get_initial_ktensor(init, X, rank, random_state) result = FitResult(U, 'NCP_HALS'...
[ "\n Fits nonnegtaive CP Decomposition using the Hierarcial Alternating Least\n Squares (HALS) Method.\n\n Parameters\n ----------\n X : (I_1, ..., I_N) array_like\n A real array with nonnegative entries and ``X.ndim >= 3``.\n\n rank : integer\n The `rank` sets the number of component...
Please provide a description of the function:def cp_als(X, rank, random_state=None, init='randn', **options): # Check inputs. optim_utils._check_cpd_inputs(X, rank) # Initialize problem. U, normX = optim_utils._get_initial_ktensor(init, X, rank, random_state) result = FitResult(U, 'CP_ALS', *...
[ "Fits CP Decomposition using Alternating Least Squares (ALS).\n\n Parameters\n ----------\n X : (I_1, ..., I_N) array_like\n A tensor with ``X.ndim >= 3``.\n\n rank : integer\n The `rank` sets the number of components to be computed.\n\n random_state : integer, ``RandomState``, or ``Non...
Please provide a description of the function:def fit(self, X, ranks, replicates=1, verbose=True): # Make ranks iterable if necessary. if not isinstance(ranks, collections.Iterable): ranks = (ranks,) # Iterate over model ranks, optimize multiple replicates at each rank. ...
[ "\n Fits CP tensor decompositions for different choices of rank.\n\n Parameters\n ----------\n X : array_like\n Real tensor\n ranks : int, or iterable\n iterable specifying number of components in each model\n replicates: int\n number of mod...
Please provide a description of the function: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.\n " ]
Please provide a description of the function: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.\n " ]
Please provide a description of the function: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.\n " ]
Please provide a description of the function:def commit(self): # Iterate on a new set, as we remove record during iteration from the # original one for record in set(self.dirty): values = {} for field in record._values_to_write: if record.id in re...
[ "Commit dirty records to the server. This method is automatically\n called when the `auto_commit` option is set to `True` (default).\n It can be useful to set the former option to `False` to get better\n performance by reducing the number of RPC requests generated.\n\n With `auto_commit`...
Please provide a description of the function:def ref(self, xml_id): model, id_ = self._odoo.execute( 'ir.model.data', 'xmlid_to_res_model_res_id', xml_id, True) return self[model].browse(id_)
[ "Return the record corresponding to the given `xml_id` (also called\n external ID).\n Raise an :class:`RPCError <odoorpc.error.RPCError>` if no record\n is found.\n\n .. doctest::\n\n >>> odoo.env.ref('base.lang_en')\n Recordset('res.lang', [1])\n\n :return: ...
Please provide a description of the function:def _create_model_class(self, model): cls_name = model.replace('.', '_') # Hack for Python 2 (no need to do this for Python 3) if sys.version_info[0] < 3: if isinstance(cls_name, unicode): cls_name = cls_name.encod...
[ "Generate the model proxy class.\n\n :return: a :class:`odoorpc.models.Model` class\n " ]
Please provide a description of the function:def get_all(rc_file='~/.odoorpcrc'): conf = ConfigParser() conf.read([os.path.expanduser(rc_file)]) sessions = {} for name in conf.sections(): sessions[name] = { 'type': conf.get(name, 'type'), 'host': conf.get(name, 'host...
[ "Return all session configurations from the `rc_file` file.\n\n >>> import odoorpc\n >>> from pprint import pprint as pp\n >>> pp(odoorpc.session.get_all()) # doctest: +SKIP\n {'foo': {'database': 'db_name',\n 'host': 'localhost',\n 'passwd': 'password',\n 'port':...
Please provide a description of the function:def get(name, rc_file='~/.odoorpcrc'): conf = ConfigParser() conf.read([os.path.expanduser(rc_file)]) if not conf.has_section(name): raise ValueError( "'%s' session does not exist in %s" % (name, rc_file)) return { 'type': con...
[ "Return the session configuration identified by `name`\n from the `rc_file` file.\n\n >>> import odoorpc\n >>> from pprint import pprint as pp\n >>> pp(odoorpc.session.get('foo')) # doctest: +SKIP\n {'database': 'db_name',\n 'host': 'localhost',\n 'passwd': 'password',\n 'port': 8069,\...
Please provide a description of the function:def save(name, data, rc_file='~/.odoorpcrc'): conf = ConfigParser() conf.read([os.path.expanduser(rc_file)]) if not conf.has_section(name): conf.add_section(name) for key in data: value = data[key] conf.set(name, key, str(value)) ...
[ "Save the `data` session configuration under the name `name`\n in the `rc_file` file.\n\n >>> import odoorpc\n >>> odoorpc.session.save(\n ... 'foo',\n ... {'type': 'ODOO', 'host': 'localhost', 'protocol': 'jsonrpc',\n ... 'port': 8069, 'timeout': 120, 'database': 'db_name'\n ... ...
Please provide a description of the function:def remove(name, rc_file='~/.odoorpcrc'): conf = ConfigParser() conf.read([os.path.expanduser(rc_file)]) if not conf.has_section(name): raise ValueError( "'%s' session does not exist in %s" % (name, rc_file)) conf.remove_section(name)...
[ "Remove the session configuration identified by `name`\n from the `rc_file` file.\n\n >>> import odoorpc\n >>> odoorpc.session.remove('foo') # doctest: +SKIP\n\n .. doctest::\n :hide:\n\n >>> import odoorpc\n >>> session = '%s_session' % DB\n >>> odoorpc.session.remove(se...
Please provide a description of the function:def get_encodings(hint_encoding='utf-8'): fallbacks = { 'latin1': 'latin9', 'iso-8859-1': 'iso8859-15', 'cp1252': '1252', } if hint_encoding: yield hint_encoding if hint_encoding.lower() in fallbacks: yield...
[ "Used to try different encoding.\n Function copied from Odoo 11.0 (odoo.loglevels.get_encodings).\n This piece of code is licensed under the LGPL-v3 and so it is compatible\n with the LGPL-v3 license of OdooRPC::\n\n - https://github.com/odoo/odoo/blob/11.0/LICENSE\n - https://github.com/odoo...
Please provide a description of the function:def get_json_log_data(data): log_data = data for param in LOG_HIDDEN_JSON_PARAMS: if param in data['params']: if log_data is data: log_data = copy.deepcopy(data) log_data['params'][param] = "**********" return ...
[ "Returns a new `data` dictionary with hidden params\n for log purpose.\n " ]
Please provide a description of the function:def json(self, url, params): data = self._connector.proxy_json(url, params) if data.get('error'): raise error.RPCError( data['error']['data']['message'], data['error']) return data
[ "Low level method to execute JSON queries.\n It basically performs a request and raises an\n :class:`odoorpc.error.RPCError` exception if the response contains\n an error.\n\n You have to know the names of each parameter required by the function\n called, and set them in the `para...
Please provide a description of the function:def http(self, url, data=None, headers=None): return self._connector.proxy_http(url, data, headers)
[ "Low level method to execute raw HTTP queries.\n\n .. note::\n\n For low level JSON-RPC queries, see the more convenient\n :func:`odoorpc.ODOO.json` method instead.\n\n You have to know the names of each POST parameter required by the\n URL, and set them in the `data` stri...
Please provide a description of the function: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." ]
Please provide a description of the function:def login(self, db, login='admin', password='admin'): # Get the user's ID and generate the corresponding user record data = self.json( '/web/session/authenticate', {'db': db, 'login': login, 'password': password}) uid ...
[ "Log in as the given `user` with the password `passwd` on the\n database `db`.\n\n .. doctest::\n :options: +SKIP\n\n >>> odoo.login('db_name', 'admin', 'admin')\n >>> odoo.env.user.name\n 'Administrator'\n\n *Python 2:*\n\n :raise: :class:`odo...
Please provide a description of the function:def logout(self): if not self._env: return False self.json('/web/session/destroy', {}) self._env = None self._login = None self._password = None return True
[ "Log out the user.\n\n >>> odoo.logout()\n True\n\n *Python 2:*\n\n :return: `True` if the operation succeed, `False` if no user was logged\n :raise: :class:`odoorpc.error.RPCError`\n :raise: `urllib2.URLError` (connection error)\n\n *Python 3:*\n\n :return: `...
Please provide a description of the function:def execute(self, model, method, *args): self._check_logged_user() # Execute the query args_to_send = [self.env.db, self.env.uid, self._password, model, method] args_to_send.extend(args) data = self.jso...
[ "Execute the `method` of `model`.\n `*args` parameters varies according to the `method` used.\n\n .. doctest::\n :options: +SKIP\n\n >>> odoo.execute('res.partner', 'read', [1], ['name'])\n [{'id': 1, 'name': 'YourCompany'}]\n\n .. doctest::\n :hide:\...
Please provide a description of the function:def exec_workflow(self, model, record_id, signal): if tools.v(self.version)[0] >= 11: raise DeprecationWarning( u"Workflows have been removed in Odoo >= 11.0") self._check_logged_user() # Execute the workflow query...
[ "Execute the workflow `signal` on\n the instance having the ID `record_id` of `model`.\n\n *Python 2:*\n\n :raise: :class:`odoorpc.error.RPCError`\n :raise: :class:`odoorpc.error.InternalError` (if not logged)\n :raise: `urllib2.URLError` (connection error)\n\n *Python 3:*\...
Please provide a description of the function:def save(self, name, rc_file='~/.odoorpcrc'): self._check_logged_user() data = { 'type': self.__class__.__name__, 'host': self.host, 'protocol': self.protocol, 'port': self.port, 'timeout': ...
[ "Save the current :class:`ODOO <odoorpc.ODOO>` instance (a `session`)\n inside `rc_file` (``~/.odoorpcrc`` by default). This session will be\n identified by `name`::\n\n >>> import odoorpc\n >>> odoo = odoorpc.ODOO('localhost', port=8069)\n >>> odoo.login('db_name', 'a...
Please provide a description of the function:def load(cls, name, rc_file='~/.odoorpcrc'): data = session.get(name, rc_file) if data.get('type') != cls.__name__: raise error.InternalError( "'{0}' session is not of type '{1}'".format( name, cls.__na...
[ "Return a connected :class:`ODOO` session identified by `name`:\n\n .. doctest::\n :options: +SKIP\n\n >>> import odoorpc\n >>> odoo = odoorpc.ODOO.load('foo')\n\n Such sessions are stored with the\n :func:`save <odoorpc.ODOO.save>` method.\n\n *Python 2:...
Please provide a description of the function:def list(cls, rc_file='~/.odoorpcrc'): sessions = session.get_all(rc_file) return [name for name in sessions if sessions[name].get('type') == cls.__name__]
[ "Return a list of all stored sessions available in the\n `rc_file` file:\n\n .. doctest::\n :options: +SKIP\n\n >>> import odoorpc\n >>> odoorpc.ODOO.list()\n ['foo', 'bar']\n\n Use the :func:`save <odoorpc.ODOO.save>` and\n :func:`load <odoorp...
Please provide a description of the function:def remove(cls, name, rc_file='~/.odoorpcrc'): data = session.get(name, rc_file) if data.get('type') != cls.__name__: raise error.InternalError( "'{0}' session is not of type '{1}'".format( name, cls.__...
[ "Remove the session identified by `name` from the `rc_file` file:\n\n .. doctest::\n :options: +SKIP\n\n >>> import odoorpc\n >>> odoorpc.ODOO.remove('foo')\n True\n\n *Python 2:*\n\n :raise: `ValueError` (if the session does not exist)\n :rais...
Please provide a description of the function:def dump(self, password, db, format_='zip'): args = [password, db] if v(self._odoo.version)[0] >= 9: args.append(format_) data = self._odoo.json( '/jsonrpc', {'service': 'db', 'method': 'dump',...
[ "Backup the `db` database. Returns the dump as a binary ZIP file\n containing the SQL dump file alongside the filestore directory (if any).\n\n >>> dump = odoo.db.dump('super_admin_passwd', 'prod') # doctest: +SKIP\n\n .. doctest::\n :hide:\n\n >>> dump = odoo.db.dump(SUPE...
Please provide a description of the function:def create(self, password, db, demo=False, lang='en_US', admin_password='admin'): self._odoo.json( '/jsonrpc', {'service': 'db', 'method': 'create_database', 'args': [password, db, demo, lang, admin_password]...
[ "Request the server to create a new database named `db`\n which will have `admin_password` as administrator password and\n localized with the `lang` parameter.\n You have to set the flag `demo` to `True` in order to insert\n demonstration data.\n\n >>> odoo.db.create('super_admin_...
Please provide a description of the function:def drop(self, password, db): if self._odoo._env and self._odoo._env.db == db: # Remove the existing session to avoid HTTP session error self._odoo.logout() data = self._odoo.json( '/jsonrpc', {'service...
[ "Drop the `db` database. Returns `True` if the database was removed,\n `False` otherwise (database did not exist):\n\n >>> odoo.db.drop('super_admin_passwd', 'test') # doctest: +SKIP\n True\n\n The super administrator password is required to perform this method.\n\n *Python 2:*\n\...
Please provide a description of the function:def duplicate(self, password, db, new_db): self._odoo.json( '/jsonrpc', {'service': 'db', 'method': 'duplicate_database', 'args': [password, db, new_db]})
[ "Duplicate `db' as `new_db`.\n\n >>> odoo.db.duplicate('super_admin_passwd', 'prod', 'test') # doctest: +SKIP\n\n The super administrator password is required to perform this method.\n\n *Python 2:*\n\n :raise: :class:`odoorpc.error.RPCError` (access denied / wrong database)\n :ra...
Please provide a description of the function:def restore(self, password, db, dump, copy=False): if dump.closed: raise error.InternalError("Dump file closed") b64_data = base64.standard_b64encode(dump.read()).decode() self._odoo.json( '/jsonrpc', {'ser...
[ "Restore the `dump` database into the new `db` database.\n The `dump` file object can be obtained with the\n :func:`dump <DB.dump>` method.\n If `copy` is set to `True`, the restored database will have a new UUID.\n\n >>> odoo.db.restore('super_admin_passwd', 'test', dump_file) # doctest...
Please provide a description of the function:def _get_proxies(self): proxy_json = jsonrpclib.ProxyJSON( self.host, self.port, self._timeout, ssl=self.ssl, deserialize=self.deserialize, opener=self._opener) proxy_http = jsonrpclib.ProxyHTTP( self.host, self.po...
[ "Returns the :class:`ProxyJSON <odoorpc.rpc.jsonrpclib.ProxyJSON>`\n and :class:`ProxyHTTP <odoorpc.rpc.jsonrpclib.ProxyHTTP>` instances\n corresponding to the server version used.\n " ]
Please provide a description of the function:def timeout(self, timeout): self._proxy_json._timeout = timeout self._proxy_http._timeout = timeout
[ "Set the timeout." ]
Please provide a description of the function: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." ]
Please provide a description of the function:def odoo_tuple_in(iterable): if not iterable: return False def is_odoo_tuple(elt): try: return elt[:1][0] in [1, 2, 3, 4, 5] \ or elt[:2] in [(6, 0), [6, 0], (0, 0), [0, 0]] except (TypeError, Inde...
[ "Return `True` if `iterable` contains an expected tuple like\n ``(6, 0, IDS)`` (and so on).\n\n >>> odoo_tuple_in([0, 1, 2]) # Simple list\n False\n >>> odoo_tuple_in([(6, 0, [42])]) # List of tuples\n True\n >>> odoo_tuple_in([[1, 42]]) # List of lists\n ...
Please provide a description of the function:def tuples2ids(tuples, ids): for value in tuples: if value[0] == 6 and value[2]: ids = value[2] elif value[0] == 5: ids[:] = [] elif value[0] == 4 and value[1] and value[1] not in ids: ids.append(value[1]) ...
[ "Update `ids` according to `tuples`, e.g. (3, 0, X), (4, 0, X)..." ]
Please provide a description of the function:def records2ids(iterable): def record2id(elt): if isinstance(elt, Model): return elt.id return elt return [record2id(elt) for elt in iterable]
[ "Replace records contained in `iterable` with their corresponding IDs:\n\n >>> groups = list(odoo.env.user.groups_id)\n >>> records2ids(groups)\n [1, 2, 3, 14, 17, 18, 19, 7, 8, 9, 5, 20, 21, 22, 23]\n ", "If `elt` is a record, return its ID." ]
Please provide a description of the function:def generate_field(name, data): assert 'type' in data field = TYPES_TO_FIELDS.get(data['type'], Unknown)(name, data) return field
[ "Generate a well-typed field according to the data dictionary supplied\n (obtained via the `fields_get' method of any models).\n " ]
Please provide a description of the function:def check_value(self, value): #if self.readonly: # raise error.Error( # "'{field_name}' field is readonly".format( # field_name=self.name)) if value and self.size: if not is_string(value): ...
[ "Check the validity of a value for the field." ]
Please provide a description of the function:def store(self, record, value): record._values[self.name][record.id] = value
[ "Store the value in the record." ]
Please provide a description of the function:def store(self, record, value): if record._values[self.name].get(record.id): tuples2ids(value, record._values[self.name][record.id]) else: record._values[self.name][record.id] = tuples2ids(value, [])
[ "Store the value in the record." ]
Please provide a description of the function:def _check_relation(self, relation): selection = [val[0] for val in self.selection] if relation not in selection: raise ValueError( ("The value '{value}' supplied doesn't match with the possible" " values ...
[ "Raise a `ValueError` if `relation` is not allowed among\n the possible values.\n " ]
Please provide a description of the function:def download(self, name, ids, datas=None, context=None): if context is None: context = self._odoo.env.context def check_report(name): report_model = 'ir.actions.report' if v(self._odoo.version)[0] < 11: ...
[ "Download a report from the server and return it as a remote file.\n For instance, to download the \"Quotation / Order\" report of sale orders\n identified by the IDs ``[2, 3]``:\n\n .. doctest::\n :options: +SKIP\n\n >>> report = odoo.report.download('sale.report_saleorde...
Please provide a description of the function:def list(self): report_model = 'ir.actions.report' if v(self._odoo.version)[0] < 11: report_model = 'ir.actions.report.xml' IrReport = self._odoo.env[report_model] report_ids = IrReport.search([]) reports = IrRepor...
[ "List available reports from the server by returning a dictionary\n with reports classified by data model:\n\n .. doctest::\n :options: +SKIP\n\n >>> odoo.report.list()['account.invoice']\n [{'name': u'Duplicates',\n 'report_name': u'account.account_invoic...
Please provide a description of the function:def _browse(cls, env, ids, from_record=None, iterated=None): records = cls() records._env_local = env records._ids = _normalize_ids(ids) if iterated: records._values = iterated._values records._values_to_write ...
[ "Create an instance (a recordset) corresponding to `ids` and\n attached to `env`.\n\n `from_record` parameter is used when the recordset is related to a\n parent record, and as such can take the value of a tuple\n (record, field). This is useful to update the parent record when the\n ...
Please provide a description of the function:def with_context(cls, *args, **kwargs): context = dict(args[0] if args else cls.env.context, **kwargs) return cls.with_env(cls.env(context=context))
[ "Return a model (or recordset) equivalent to the current model\n (or recordset) attached to an environment with another context.\n The context is taken from the current environment or from the\n positional arguments `args` if given, and modified by `kwargs`.\n\n Thus, the following two e...
Please provide a description of the function:def _with_context(self, *args, **kwargs): context = dict(args[0] if args else self.env.context, **kwargs) return self.with_env(self.env(context=context))
[ "As the `with_context` class method but for recordset." ]
Please provide a description of the function:def with_env(cls, env): new_cls = type(cls.__name__, cls.__bases__, dict(cls.__dict__)) new_cls._env = env return new_cls
[ "Return a model (or recordset) equivalent to the current model\n (or recordset) attached to `env`.\n " ]