idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
19,200 | def visualize_diagram ( bpmn_diagram ) : g = bpmn_diagram . diagram_graph pos = bpmn_diagram . get_nodes_positions ( ) nx . draw_networkx_nodes ( g , pos , node_shape = 's' , node_color = 'white' , nodelist = bpmn_diagram . get_nodes_id_list_by_type ( consts . Consts . task ) ) nx . draw_networkx_nodes ( g , pos , node_shape = 's' , node_color = 'white' , nodelist = bpmn_diagram . get_nodes_id_list_by_type ( consts . Consts . subprocess ) ) nx . draw_networkx_nodes ( g , pos , node_shape = 'd' , node_color = 'white' , nodelist = bpmn_diagram . get_nodes_id_list_by_type ( consts . Consts . complex_gateway ) ) nx . draw_networkx_nodes ( g , pos , node_shape = 'o' , node_color = 'white' , nodelist = bpmn_diagram . get_nodes_id_list_by_type ( consts . Consts . event_based_gateway ) ) nx . draw_networkx_nodes ( g , pos , node_shape = 'd' , node_color = 'white' , nodelist = bpmn_diagram . get_nodes_id_list_by_type ( consts . Consts . inclusive_gateway ) ) nx . draw_networkx_nodes ( g , pos , node_shape = 'd' , node_color = 'white' , nodelist = bpmn_diagram . get_nodes_id_list_by_type ( consts . Consts . exclusive_gateway ) ) nx . draw_networkx_nodes ( g , pos , node_shape = 'd' , node_color = 'white' , nodelist = bpmn_diagram . get_nodes_id_list_by_type ( consts . Consts . parallel_gateway ) ) nx . draw_networkx_nodes ( g , pos , node_shape = 'o' , node_color = 'white' , nodelist = bpmn_diagram . get_nodes_id_list_by_type ( consts . Consts . start_event ) ) nx . draw_networkx_nodes ( g , pos , node_shape = 'o' , node_color = 'white' , nodelist = bpmn_diagram . get_nodes_id_list_by_type ( consts . Consts . intermediate_catch_event ) ) nx . draw_networkx_nodes ( g , pos , node_shape = 'o' , node_color = 'white' , nodelist = bpmn_diagram . get_nodes_id_list_by_type ( consts . Consts . end_event ) ) nx . draw_networkx_nodes ( g , pos , node_shape = 'o' , node_color = 'white' , nodelist = bpmn_diagram . get_nodes_id_list_by_type ( consts . Consts . intermediate_throw_event ) ) node_labels = { } for node in g . nodes ( data = True ) : node_labels [ node [ 0 ] ] = node [ 1 ] . get ( consts . Consts . node_name ) nx . draw_networkx_labels ( g , pos , node_labels ) nx . draw_networkx_edges ( g , pos ) edge_labels = { } for edge in g . edges ( data = True ) : edge_labels [ ( edge [ 0 ] , edge [ 1 ] ) ] = edge [ 2 ] . get ( consts . Consts . name ) nx . draw_networkx_edge_labels ( g , pos , edge_labels ) plt . show ( ) | Shows a simple visualization of diagram |
19,201 | def bpmn_diagram_to_png ( bpmn_diagram , file_name ) : g = bpmn_diagram . diagram_graph graph = pydotplus . Dot ( ) for node in g . nodes ( data = True ) : if node [ 1 ] . get ( consts . Consts . type ) == consts . Consts . task : n = pydotplus . Node ( name = node [ 0 ] , shape = "box" , style = "rounded" , label = node [ 1 ] . get ( consts . Consts . node_name ) ) elif node [ 1 ] . get ( consts . Consts . type ) == consts . Consts . exclusive_gateway : n = pydotplus . Node ( name = node [ 0 ] , shape = "diamond" , label = node [ 1 ] . get ( consts . Consts . node_name ) ) else : n = pydotplus . Node ( name = node [ 0 ] , label = node [ 1 ] . get ( consts . Consts . node_name ) ) graph . add_node ( n ) for edge in g . edges ( data = True ) : e = pydotplus . Edge ( src = edge [ 0 ] , dst = edge [ 1 ] , label = edge [ 2 ] . get ( consts . Consts . name ) ) graph . add_edge ( e ) graph . write ( file_name + ".png" , format = 'png' ) | Create a png picture for given diagram |
19,202 | def get_node_by_id ( self , node_id ) : tmp_nodes = self . diagram_graph . nodes ( data = True ) for node in tmp_nodes : if node [ 0 ] == node_id : return node | Gets a node with requested ID . Returns a tuple where first value is node ID second - a dictionary of all node attributes . |
19,203 | def get_nodes_id_list_by_type ( self , node_type ) : tmp_nodes = self . diagram_graph . nodes ( data = True ) id_list = [ ] for node in tmp_nodes : if node [ 1 ] [ consts . Consts . type ] == node_type : id_list . append ( node [ 0 ] ) return id_list | Get a list of node s id by requested type . Returns a list of ids |
19,204 | def add_process_to_diagram ( self , process_name = "" , process_is_closed = False , process_is_executable = False , process_type = "None" ) : plane_id = BpmnDiagramGraph . id_prefix + str ( uuid . uuid4 ( ) ) process_id = BpmnDiagramGraph . id_prefix + str ( uuid . uuid4 ( ) ) self . process_elements [ process_id ] = { consts . Consts . name : process_name , consts . Consts . is_closed : "true" if process_is_closed else "false" , consts . Consts . is_executable : "true" if process_is_executable else "false" , consts . Consts . process_type : process_type } self . plane_attributes [ consts . Consts . id ] = plane_id self . plane_attributes [ consts . Consts . bpmn_element ] = process_id return process_id | Adds a new process to diagram and corresponding participant process diagram and plane |
19,205 | def add_flow_node_to_diagram ( self , process_id , node_type , name , node_id = None ) : if node_id is None : node_id = BpmnDiagramGraph . id_prefix + str ( uuid . uuid4 ( ) ) self . diagram_graph . add_node ( node_id ) self . diagram_graph . node [ node_id ] [ consts . Consts . id ] = node_id self . diagram_graph . node [ node_id ] [ consts . Consts . type ] = node_type self . diagram_graph . node [ node_id ] [ consts . Consts . node_name ] = name self . diagram_graph . node [ node_id ] [ consts . Consts . incoming_flow ] = [ ] self . diagram_graph . node [ node_id ] [ consts . Consts . outgoing_flow ] = [ ] self . diagram_graph . node [ node_id ] [ consts . Consts . process ] = process_id self . diagram_graph . node [ node_id ] [ consts . Consts . width ] = "100" self . diagram_graph . node [ node_id ] [ consts . Consts . height ] = "100" self . diagram_graph . node [ node_id ] [ consts . Consts . x ] = "100" self . diagram_graph . node [ node_id ] [ consts . Consts . y ] = "100" return node_id , self . diagram_graph . node [ node_id ] | Helper function that adds a new Flow Node to diagram . It is used to add a new node of specified type . Adds a basic information inherited from Flow Node type . |
19,206 | def add_start_event_to_diagram ( self , process_id , start_event_name = "" , start_event_definition = None , parallel_multiple = False , is_interrupting = True , node_id = None ) : start_event_id , start_event = self . add_flow_node_to_diagram ( process_id , consts . Consts . start_event , start_event_name , node_id ) self . diagram_graph . node [ start_event_id ] [ consts . Consts . parallel_multiple ] = "true" if parallel_multiple else "false" self . diagram_graph . node [ start_event_id ] [ consts . Consts . is_interrupting ] = "true" if is_interrupting else "false" start_event_definitions = { "message" : "messageEventDefinition" , "timer" : "timerEventDefinition" , "conditional" : "conditionalEventDefinition" , "signal" : "signalEventDefinition" , "escalation" : "escalationEventDefinition" } event_def_list = [ ] if start_event_definition == "message" : event_def_list . append ( BpmnDiagramGraph . add_event_definition_element ( "message" , start_event_definitions ) ) elif start_event_definition == "timer" : event_def_list . append ( BpmnDiagramGraph . add_event_definition_element ( "timer" , start_event_definitions ) ) elif start_event_definition == "conditional" : event_def_list . append ( BpmnDiagramGraph . add_event_definition_element ( "conditional" , start_event_definitions ) ) elif start_event_definition == "signal" : event_def_list . append ( BpmnDiagramGraph . add_event_definition_element ( "signal" , start_event_definitions ) ) elif start_event_definition == "escalation" : event_def_list . append ( BpmnDiagramGraph . add_event_definition_element ( "escalation" , start_event_definitions ) ) self . diagram_graph . node [ start_event_id ] [ consts . Consts . event_definitions ] = event_def_list return start_event_id , start_event | Adds a StartEvent element to BPMN diagram . |
19,207 | def add_inclusive_gateway_to_diagram ( self , process_id , gateway_name = "" , gateway_direction = "Unspecified" , default = None , node_id = None ) : inclusive_gateway_id , inclusive_gateway = self . add_gateway_to_diagram ( process_id , consts . Consts . inclusive_gateway , gateway_name = gateway_name , gateway_direction = gateway_direction , node_id = node_id ) self . diagram_graph . node [ inclusive_gateway_id ] [ consts . Consts . default ] = default return inclusive_gateway_id , inclusive_gateway | Adds an inclusiveGateway element to BPMN diagram . |
19,208 | def add_parallel_gateway_to_diagram ( self , process_id , gateway_name = "" , gateway_direction = "Unspecified" , node_id = None ) : parallel_gateway_id , parallel_gateway = self . add_gateway_to_diagram ( process_id , consts . Consts . parallel_gateway , gateway_name = gateway_name , gateway_direction = gateway_direction , node_id = node_id ) return parallel_gateway_id , parallel_gateway | Adds an parallelGateway element to BPMN diagram . |
19,209 | def get_nodes_positions ( self ) : nodes = self . get_nodes ( ) output = { } for node in nodes : output [ node [ 0 ] ] = ( float ( node [ 1 ] [ consts . Consts . x ] ) , float ( node [ 1 ] [ consts . Consts . y ] ) ) return output | Getter method for nodes positions . |
19,210 | def create_tree ( path , depth = DEPTH ) : os . mkdir ( path ) for i in range ( NUM_FILES ) : filename = os . path . join ( path , 'file{0:03}.txt' . format ( i ) ) with open ( filename , 'wb' ) as f : f . write ( b'foo' ) if depth <= 1 : return for i in range ( NUM_DIRS ) : dirname = os . path . join ( path , 'dir{0:03}' . format ( i ) ) create_tree ( dirname , depth - 1 ) | Create a directory tree at path with given depth and NUM_DIRS and NUM_FILES at each level . |
19,211 | def get_tree_size ( path ) : size = 0 try : for entry in scandir . scandir ( path ) : if entry . is_symlink ( ) : pass elif entry . is_dir ( ) : size += get_tree_size ( os . path . join ( path , entry . name ) ) else : size += entry . stat ( ) . st_size except OSError : pass return size | Return total size of all files in directory tree at path . |
19,212 | def unfold ( tensor , mode ) : return np . moveaxis ( tensor , mode , 0 ) . reshape ( ( tensor . shape [ mode ] , - 1 ) ) | Returns the mode - mode unfolding of tensor . |
19,213 | def khatri_rao ( matrices ) : n_columns = matrices [ 0 ] . shape [ 1 ] n_factors = len ( matrices ) start = ord ( 'a' ) common_dim = 'z' target = '' . join ( chr ( start + i ) for i in range ( n_factors ) ) source = ',' . join ( i + common_dim for i in target ) operation = source + '->' + target + common_dim return np . einsum ( operation , * matrices ) . reshape ( ( - 1 , n_columns ) ) | Khatri - Rao product of a list of matrices . |
19,214 | def soft_cluster_factor ( factor ) : f = np . copy ( factor ) cluster_ids = np . argmax ( np . abs ( f ) , axis = 1 ) scores = f [ range ( f . shape [ 0 ] ) , cluster_ids ] perm = [ ] for cluster in np . unique ( cluster_ids ) : idx = np . where ( cluster_ids == cluster ) [ 0 ] perm += list ( idx [ np . argsort ( scores [ idx ] ) ] [ : : - 1 ] ) return cluster_ids , perm | Returns soft - clustering of data based on CP decomposition results . |
19,215 | 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 . |
19,216 | def reverse_segment ( path , n1 , n2 ) : q = path . copy ( ) if n2 > n1 : q [ n1 : ( n2 + 1 ) ] = path [ n1 : ( n2 + 1 ) ] [ : : - 1 ] return q else : seg = np . hstack ( ( path [ n1 : ] , path [ : ( n2 + 1 ) ] ) ) [ : : - 1 ] brk = len ( q ) - n1 q [ n1 : ] = seg [ : brk ] q [ : ( n2 + 1 ) ] = seg [ brk : ] return q | Reverse the nodes between n1 and n2 . |
19,217 | def full ( self ) : unf = sci . dot ( self . factors [ 0 ] , khatri_rao ( self . factors [ 1 : ] ) . T ) return sci . reshape ( unf , self . shape ) | Converts KTensor to a dense ndarray . |
19,218 | def rebalance ( self ) : norms = [ sci . linalg . norm ( f , axis = 0 ) for f in self . factors ] lam = sci . multiply . reduce ( norms ) ** ( 1 / self . ndim ) self . factors = [ f * ( lam / fn ) for f , fn in zip ( self . factors , norms ) ] return self | Rescales factors across modes so that all norms match . |
19,219 | def permute ( self , idx ) : if set ( idx ) != set ( range ( self . rank ) ) : raise ValueError ( 'Invalid permutation specified.' ) self . factors = [ f [ : , idx ] for f in self . factors ] return self . factors | Permutes the columns of the factor matrices inplace |
19,220 | def kruskal_align ( U , V , permute_U = False , permute_V = False ) : unrm = [ f / np . linalg . norm ( f , axis = 0 ) for f in U . factors ] vnrm = [ f / np . linalg . norm ( f , axis = 0 ) for f in V . factors ] sim_matrices = [ np . dot ( u . T , v ) for u , v in zip ( unrm , vnrm ) ] cost = 1 - np . mean ( np . abs ( sim_matrices ) , axis = 0 ) indices = Munkres ( ) . compute ( cost . copy ( ) ) prmU , prmV = zip ( * indices ) similarity = np . mean ( 1 - cost [ prmU , prmV ] ) unmatched_U = list ( set ( range ( U . rank ) ) - set ( prmU ) ) unmatched_V = list ( set ( range ( V . rank ) ) - set ( prmV ) ) if permute_U and permute_V : idx = np . argsort ( cost [ prmU , prmV ] ) elif permute_V : idx = np . argsort ( prmU ) elif permute_U : idx = np . argsort ( prmV ) else : return similarity prmU = [ prmU [ i ] for i in idx ] prmV = [ prmV [ i ] for i in idx ] if permute_U : U . permute ( prmU ) if permute_V : V . permute ( prmV ) flips = np . sign ( [ F [ prmU , prmV ] for F in sim_matrices ] ) flips [ 0 ] *= np . prod ( flips , axis = 0 ) if permute_U : for i , f in enumerate ( flips ) : U . factors [ i ] *= f elif permute_V : for i , f in enumerate ( flips ) : V . factors [ i ] *= f return similarity | Aligns two KTensors and returns a similarity score . |
19,221 | def plot_objective ( ensemble , partition = 'train' , ax = None , jitter = 0.1 , scatter_kw = dict ( ) , line_kw = dict ( ) ) : if ax is None : ax = plt . gca ( ) if partition == 'train' : pass elif partition == 'test' : raise NotImplementedError ( 'Cross-validation is on the TODO list.' ) else : raise ValueError ( "partition must be 'train' or 'test'." ) x , obj , min_obj = [ ] , [ ] , [ ] for rank in sorted ( ensemble . results ) : o = ensemble . objectives ( rank ) obj . extend ( o ) x . extend ( np . full ( len ( o ) , rank ) ) min_obj . append ( min ( o ) ) ux = np . unique ( x ) x = np . array ( x ) + ( np . random . rand ( len ( x ) ) - 0.5 ) * jitter ax . scatter ( x , obj , ** scatter_kw ) ax . plot ( ux , min_obj , ** line_kw ) ax . set_xlabel ( 'model rank' ) ax . set_ylabel ( 'objective' ) return ax | Plots objective function as a function of model rank . |
19,222 | def plot_similarity ( ensemble , ax = None , jitter = 0.1 , scatter_kw = dict ( ) , line_kw = dict ( ) ) : if ax is None : ax = plt . gca ( ) x , sim , mean_sim = [ ] , [ ] , [ ] for rank in sorted ( ensemble . results ) : s = ensemble . similarities ( rank ) [ 1 : ] sim . extend ( s ) x . extend ( np . full ( len ( s ) , rank ) ) mean_sim . append ( np . mean ( s ) ) ux = np . unique ( x ) x = np . array ( x ) + ( np . random . rand ( len ( x ) ) - 0.5 ) * jitter ax . scatter ( x , sim , ** scatter_kw ) ax . plot ( ux , mean_sim , ** line_kw ) ax . set_xlabel ( 'model rank' ) ax . set_ylabel ( 'model similarity' ) ax . set_ylim ( [ 0 , 1.1 ] ) return ax | Plots similarity across optimization runs as a function of model rank . |
19,223 | def _broadcast_arg ( U , arg , argtype , name ) : if arg is None or isinstance ( arg , argtype ) : return [ arg for _ in range ( U . ndim ) ] elif np . iterable ( arg ) : if len ( arg ) != U . ndim : raise ValueError ( 'Parameter {} was specified as a sequence of ' 'incorrect length. The length must match the ' 'number of tensor dimensions ' '(U.ndim={})' . format ( name , U . ndim ) ) elif not all ( [ isinstance ( a , argtype ) for a in arg ] ) : raise TypeError ( 'Parameter {} specified as a sequence of ' 'incorrect type. ' 'Expected {}.' . format ( name , argtype ) ) else : return arg else : raise TypeError ( 'Parameter {} specified as a {}.' ' Expected {}.' . format ( name , type ( arg ) , argtype ) ) | Broadcasts plotting option arg to all factors . |
19,224 | 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 . |
19,225 | def _check_random_state ( random_state ) : if random_state is None or isinstance ( random_state , int ) : return sci . random . RandomState ( random_state ) elif isinstance ( random_state , sci . random . RandomState ) : return random_state else : raise TypeError ( 'Seed should be None, int or np.random.RandomState' ) | Checks and processes user input for seeding random numbers . |
19,226 | def randn_ktensor ( shape , rank , norm = None , random_state = None ) : rns = _check_random_state ( random_state ) factors = KTensor ( [ rns . standard_normal ( ( i , rank ) ) for i in shape ] ) return _rescale_tensor ( factors , norm ) | Generates a random N - way tensor with rank R where the entries are drawn from the standard normal distribution . |
19,227 | def fit ( self , X , ranks , replicates = 1 , verbose = True ) : if not isinstance ( ranks , collections . Iterable ) : ranks = ( ranks , ) for r in ranks : if r not in self . results : self . results [ r ] = [ ] if verbose : itr = trange ( replicates , desc = 'Fitting rank-{} models' . format ( r ) , leave = False ) else : itr = range ( replicates ) for i in itr : model_fit = self . _fit_method ( X , r , ** self . _fit_options ) self . results [ r ] . append ( model_fit ) if verbose : min_obj = min ( [ res . obj for res in self . results [ r ] ] ) max_obj = max ( [ res . obj for res in self . results [ r ] ] ) elapsed = sum ( [ res . total_time for res in self . results [ r ] ] ) print ( 'Rank-{} models: min obj, {:.2f}; ' 'max obj, {:.2f}; time to fit, ' '{:.1f}s' . format ( r , min_obj , max_obj , elapsed ) ) for r in ranks : idx = np . argsort ( [ result . obj for result in self . results [ r ] ] ) self . results [ r ] = [ self . results [ r ] [ i ] for i in idx ] for i in reversed ( range ( 1 , len ( ranks ) ) ) : r0 , r1 = ranks [ i - 1 ] , ranks [ i ] U = self . results [ r0 ] [ 0 ] . factors V = self . results [ r1 ] [ 0 ] . factors kruskal_align ( U , V , permute_U = True ) for r in ranks : U = self . results [ r ] [ 0 ] . factors self . results [ r ] [ 0 ] . similarity = 1.0 for res in self . results [ r ] [ 1 : ] : res . similarity = kruskal_align ( U , res . factors , permute_V = True ) | Fits CP tensor decompositions for different choices of rank . |
19,228 | 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 . |
19,229 | 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 . |
19,230 | 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 . |
19,231 | def _create_model_class ( self , model ) : cls_name = model . replace ( '.' , '_' ) if sys . version_info [ 0 ] < 3 : if isinstance ( cls_name , unicode ) : cls_name = cls_name . encode ( 'utf-8' ) attrs = { '_env' : self , '_odoo' : self . _odoo , '_name' : model , '_columns' : { } , } fields_get = self . _odoo . execute ( model , 'fields_get' ) for field_name , field_data in fields_get . items ( ) : if field_name not in FIELDS_RESERVED : Field = fields . generate_field ( field_name , field_data ) attrs [ '_columns' ] [ field_name ] = Field attrs [ field_name ] = Field if 'name' not in attrs [ '_columns' ] : field_data = { 'type' : 'text' , 'string' : 'Name' , 'readonly' : True } Field = fields . generate_field ( 'name' , field_data ) attrs [ '_columns' ] [ 'name' ] = Field attrs [ 'name' ] = Field return type ( cls_name , ( Model , ) , attrs ) | Generate the model proxy class . |
19,232 | def get_all ( rc_file = '~/.odoorpcrc' ) : conf = ConfigParser ( ) conf . read ( [ os . path . expanduser ( rc_file ) ] ) sessions = { } for name in conf . sections ( ) : sessions [ name ] = { 'type' : conf . get ( name , 'type' ) , 'host' : conf . get ( name , 'host' ) , 'protocol' : conf . get ( name , 'protocol' ) , 'port' : conf . getint ( name , 'port' ) , 'timeout' : conf . getfloat ( name , 'timeout' ) , 'user' : conf . get ( name , 'user' ) , 'passwd' : conf . get ( name , 'passwd' ) , 'database' : conf . get ( name , 'database' ) , } return sessions | Return all session configurations from the rc_file file . |
19,233 | def get ( name , rc_file = '~/.odoorpcrc' ) : conf = ConfigParser ( ) conf . read ( [ os . path . expanduser ( rc_file ) ] ) if not conf . has_section ( name ) : raise ValueError ( "'%s' session does not exist in %s" % ( name , rc_file ) ) return { 'type' : conf . get ( name , 'type' ) , 'host' : conf . get ( name , 'host' ) , 'protocol' : conf . get ( name , 'protocol' ) , 'port' : conf . getint ( name , 'port' ) , 'timeout' : conf . getfloat ( name , 'timeout' ) , 'user' : conf . get ( name , 'user' ) , 'passwd' : conf . get ( name , 'passwd' ) , 'database' : conf . get ( name , 'database' ) , } | Return the session configuration identified by name from the rc_file file . |
19,234 | def save ( name , data , rc_file = '~/.odoorpcrc' ) : conf = ConfigParser ( ) conf . read ( [ os . path . expanduser ( rc_file ) ] ) if not conf . has_section ( name ) : conf . add_section ( name ) for key in data : value = data [ key ] conf . set ( name , key , str ( value ) ) with open ( os . path . expanduser ( rc_file ) , 'w' ) as file_ : os . chmod ( os . path . expanduser ( rc_file ) , stat . S_IREAD | stat . S_IWRITE ) conf . write ( file_ ) | Save the data session configuration under the name name in the rc_file file . |
19,235 | def remove ( name , rc_file = '~/.odoorpcrc' ) : conf = ConfigParser ( ) conf . read ( [ os . path . expanduser ( rc_file ) ] ) if not conf . has_section ( name ) : raise ValueError ( "'%s' session does not exist in %s" % ( name , rc_file ) ) conf . remove_section ( name ) with open ( os . path . expanduser ( rc_file ) , 'wb' ) as file_ : conf . write ( file_ ) | Remove the session configuration identified by name from the rc_file file . |
19,236 | def get_json_log_data ( data ) : log_data = data for param in LOG_HIDDEN_JSON_PARAMS : if param in data [ 'params' ] : if log_data is data : log_data = copy . deepcopy ( data ) log_data [ 'params' ] [ param ] = "**********" return log_data | Returns a new data dictionary with hidden params for log purpose . |
19,237 | def http ( self , url , data = None , headers = None ) : return self . _connector . proxy_http ( url , data , headers ) | Low level method to execute raw HTTP queries . |
19,238 | 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 . |
19,239 | def login ( self , db , login = 'admin' , password = 'admin' ) : data = self . json ( '/web/session/authenticate' , { 'db' : db , 'login' : login , 'password' : password } ) uid = data [ 'result' ] [ 'uid' ] if uid : context = data [ 'result' ] [ 'user_context' ] self . _env = Environment ( self , db , uid , context = context ) self . _login = login self . _password = password else : raise error . RPCError ( "Wrong login ID or password" ) | Log in as the given user with the password passwd on the database db . |
19,240 | 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 ( ) args_to_send = [ self . env . db , self . env . uid , self . _password , model , signal , record_id ] data = self . json ( '/jsonrpc' , { 'service' : 'object' , 'method' : 'exec_workflow' , 'args' : args_to_send } ) return data . get ( 'result' ) | Execute the workflow signal on the instance having the ID record_id of model . |
19,241 | def create ( self , password , db , demo = False , lang = 'en_US' , admin_password = 'admin' ) : self . _odoo . json ( '/jsonrpc' , { 'service' : 'db' , 'method' : 'create_database' , 'args' : [ password , db , demo , lang , admin_password ] } ) | Request the server to create a new database named db which will have admin_password as administrator password and localized with the lang parameter . You have to set the flag demo to True in order to insert demonstration data . |
19,242 | 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 . |
19,243 | def timeout ( self , timeout ) : self . _proxy_json . _timeout = timeout self . _proxy_http . _timeout = timeout | Set the timeout . |
19,244 | 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 . |
19,245 | 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 ) > self . size : raise ValueError ( "Lenght of the '{0}' is limited to {1}" . format ( self . name , self . size ) ) if not value and self . required : raise ValueError ( "'{0}' field is required" . format ( self . name ) ) return value | Check the validity of a value for the field . |
19,246 | def _check_relation ( self , relation ) : selection = [ val [ 0 ] for val in self . selection ] if relation not in selection : raise ValueError ( ( "The value '{value}' supplied doesn't match with the possible" " values '{selection}' for the '{field_name}' field" ) . format ( value = relation , selection = selection , field_name = self . name , ) ) return relation | Raise a ValueError if relation is not allowed among the possible values . |
19,247 | 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 . |
19,248 | def _with_env ( self , env ) : res = self . _browse ( env , self . _ids ) return res | As the with_env class method but for recordset . |
19,249 | def _init_values ( self , context = None ) : if context is None : context = self . env . context basic_fields = [ ] for field_name in self . _columns : field = self . _columns [ field_name ] if not getattr ( field , 'relation' , False ) : basic_fields . append ( field_name ) if self . ids : rows = self . __class__ . read ( self . ids , basic_fields , context = context , load = '_classic_write' ) ids_fetched = set ( ) for row in rows : ids_fetched . add ( row [ 'id' ] ) for field_name in row : if field_name == 'id' : continue self . _values [ field_name ] [ row [ 'id' ] ] = row [ field_name ] ids_in_error = set ( self . ids ) - ids_fetched if ids_in_error : raise ValueError ( "There is no '{model}' record with IDs {ids}." . format ( model = self . _name , ids = list ( ids_in_error ) ) ) else : default_get = self . __class__ . default_get ( list ( self . _columns ) , context = context ) for field_name in self . _columns : self . _values [ field_name ] [ None ] = default_get . get ( field_name , False ) | Retrieve field values from the server . May be used to restore the original values in the purpose to cancel all changes made . |
19,250 | def from_wei ( number : int , unit : str ) -> Union [ int , decimal . Decimal ] : if unit . lower ( ) not in units : raise ValueError ( "Unknown unit. Must be one of {0}" . format ( "/" . join ( units . keys ( ) ) ) ) if number == 0 : return 0 if number < MIN_WEI or number > MAX_WEI : raise ValueError ( "value must be between 1 and 2**256 - 1" ) unit_value = units [ unit . lower ( ) ] with localcontext ( ) as ctx : ctx . prec = 999 d_number = decimal . Decimal ( value = number , context = ctx ) result_value = d_number / unit_value return result_value | Takes a number of wei and converts it to any other ether unit . |
19,251 | def to_wei ( number : int , unit : str ) -> int : if unit . lower ( ) not in units : raise ValueError ( "Unknown unit. Must be one of {0}" . format ( "/" . join ( units . keys ( ) ) ) ) if is_integer ( number ) or is_string ( number ) : d_number = decimal . Decimal ( value = number ) elif isinstance ( number , float ) : d_number = decimal . Decimal ( value = str ( number ) ) elif isinstance ( number , decimal . Decimal ) : d_number = number else : raise TypeError ( "Unsupported type. Must be one of integer, float, or string" ) s_number = str ( number ) unit_value = units [ unit . lower ( ) ] if d_number == 0 : return 0 if d_number < 1 and "." in s_number : with localcontext ( ) as ctx : multiplier = len ( s_number ) - s_number . index ( "." ) - 1 ctx . prec = multiplier d_number = decimal . Decimal ( value = number , context = ctx ) * 10 ** multiplier unit_value /= 10 ** multiplier with localcontext ( ) as ctx : ctx . prec = 999 result_value = decimal . Decimal ( value = d_number , context = ctx ) * unit_value if result_value < MIN_WEI or result_value > MAX_WEI : raise ValueError ( "Resulting wei value must be between 1 and 2**256 - 1" ) return int ( result_value ) | Takes a number of a unit and converts it to wei . |
19,252 | def validate_conversion_arguments ( to_wrap ) : @ functools . wraps ( to_wrap ) def wrapper ( * args , ** kwargs ) : _assert_one_val ( * args , ** kwargs ) if kwargs : _validate_supported_kwarg ( kwargs ) if len ( args ) == 0 and "primitive" not in kwargs : _assert_hexstr_or_text_kwarg_is_text_type ( ** kwargs ) return to_wrap ( * args , ** kwargs ) return wrapper | Validates arguments for conversion functions . - Only a single argument is present - Kwarg must be primitive hexstr or text - If it is hexstr or text that it is a text type |
19,253 | def replace_exceptions ( old_to_new_exceptions : Dict [ Type [ BaseException ] , Type [ BaseException ] ] ) -> Callable [ ... , Any ] : old_exceptions = tuple ( old_to_new_exceptions . keys ( ) ) def decorator ( to_wrap : Callable [ ... , Any ] ) -> Callable [ ... , Any ] : @ functools . wraps ( to_wrap ) def wrapper ( * args : Iterable [ Any ] , ** kwargs : Dict [ str , Any ] ) -> Callable [ ... , Any ] : try : return to_wrap ( * args , ** kwargs ) except old_exceptions as err : try : raise old_to_new_exceptions [ type ( err ) ] from err except KeyError : raise TypeError ( "could not look up new exception to use for %r" % err ) from err return wrapper return decorator | Replaces old exceptions with new exceptions to be raised in their place . |
19,254 | def collapse_if_tuple ( abi ) : typ = abi [ "type" ] if not typ . startswith ( "tuple" ) : return typ delimited = "," . join ( collapse_if_tuple ( c ) for c in abi [ "components" ] ) array_dim = typ [ 5 : ] collapsed = "({}){}" . format ( delimited , array_dim ) return collapsed | Converts a tuple from a dict to a parenthesized list of its types . |
19,255 | def is_hex_address ( value : Any ) -> bool : if not is_text ( value ) : return False elif not is_hex ( value ) : return False else : unprefixed = remove_0x_prefix ( value ) return len ( unprefixed ) == 40 | Checks if the given string of text type is an address in hexadecimal encoded form . |
19,256 | 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 . |
19,257 | def is_address ( value : Any ) -> bool : if is_checksum_formatted_address ( value ) : return is_checksum_address ( value ) elif is_hex_address ( value ) : return True elif is_binary_address ( value ) : return True else : return False | Checks if the given string in a supported value is an address in any of the known formats . |
19,258 | def to_normalized_address ( value : AnyStr ) -> HexAddress : try : hex_address = hexstr_if_str ( to_hex , value ) . lower ( ) except AttributeError : raise TypeError ( "Value must be any string, instead got type {}" . format ( type ( value ) ) ) if is_address ( hex_address ) : return HexAddress ( hex_address ) else : raise ValueError ( "Unknown format {}, attempted to normalize to {}" . format ( value , hex_address ) ) | Converts an address to its normalized hexadecimal representation . |
19,259 | 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 . |
19,260 | def is_canonical_address ( address : Any ) -> bool : if not is_bytes ( address ) or len ( address ) != 20 : return False return address == to_canonical_address ( address ) | Returns True if the value is an address in its canonical form . |
19,261 | def is_same_address ( left : AnyAddress , right : AnyAddress ) -> bool : if not is_address ( left ) or not is_address ( right ) : raise ValueError ( "Both values must be valid addresses" ) else : return to_normalized_address ( left ) == to_normalized_address ( right ) | Checks if both addresses are same or not . |
19,262 | def to_checksum_address ( value : AnyStr ) -> ChecksumAddress : norm_address = to_normalized_address ( value ) address_hash = encode_hex ( keccak ( text = remove_0x_prefix ( norm_address ) ) ) checksum_address = add_0x_prefix ( "" . join ( ( norm_address [ i ] . upper ( ) if int ( address_hash [ i ] , 16 ) > 7 else norm_address [ i ] ) for i in range ( 2 , 42 ) ) ) return ChecksumAddress ( HexAddress ( checksum_address ) ) | Makes a checksum address given a supported format . |
19,263 | def get_msi_token ( resource , port = 50342 , msi_conf = None ) : request_uri = os . environ . get ( "MSI_ENDPOINT" , 'http://localhost:{}/oauth2/token' . format ( port ) ) payload = { 'resource' : resource } if msi_conf : if len ( msi_conf ) > 1 : raise ValueError ( "{} are mutually exclusive" . format ( list ( msi_conf . keys ( ) ) ) ) payload . update ( msi_conf ) try : result = requests . post ( request_uri , data = payload , headers = { 'Metadata' : 'true' } ) _LOGGER . debug ( "MSI: Retrieving a token from %s, with payload %s" , request_uri , payload ) result . raise_for_status ( ) except Exception as ex : _LOGGER . warning ( "MSI: Failed to retrieve a token from '%s' with an error of '%s'. This could be caused " "by the MSI extension not yet fully provisioned." , request_uri , ex ) raise token_entry = result . json ( ) return token_entry [ 'token_type' ] , token_entry [ 'access_token' ] , token_entry | Get MSI token if MSI_ENDPOINT is set . |
19,264 | def get_msi_token_webapp ( resource ) : try : msi_endpoint = os . environ [ 'MSI_ENDPOINT' ] msi_secret = os . environ [ 'MSI_SECRET' ] except KeyError as err : err_msg = "{} required env variable was not found. You might need to restart your app/function." . format ( err ) _LOGGER . critical ( err_msg ) raise RuntimeError ( err_msg ) request_uri = '{}/?resource={}&api-version=2017-09-01' . format ( msi_endpoint , resource ) headers = { 'secret' : msi_secret } err = None try : result = requests . get ( request_uri , headers = headers ) _LOGGER . debug ( "MSI: Retrieving a token from %s" , request_uri ) if result . status_code != 200 : err = result . text if 'ExceptionMessage' in result . text : err = result . text except Exception as ex : err = str ( ex ) if err : err_msg = "MSI: Failed to retrieve a token from '{}' with an error of '{}'." . format ( request_uri , err ) _LOGGER . critical ( err_msg ) raise RuntimeError ( err_msg ) _LOGGER . debug ( 'MSI: token retrieved' ) token_entry = result . json ( ) return token_entry [ 'token_type' ] , token_entry [ 'access_token' ] , token_entry | Get a MSI token from inside a webapp or functions . |
19,265 | def _configure ( self , ** kwargs ) : if kwargs . get ( 'china' ) : err_msg = ( "china parameter is deprecated, " "please use " "cloud_environment=msrestazure.azure_cloud.AZURE_CHINA_CLOUD" ) warnings . warn ( err_msg , DeprecationWarning ) self . _cloud_environment = AZURE_CHINA_CLOUD else : self . _cloud_environment = AZURE_PUBLIC_CLOUD self . _cloud_environment = kwargs . get ( 'cloud_environment' , self . _cloud_environment ) auth_endpoint = self . _cloud_environment . endpoints . active_directory resource = self . _cloud_environment . endpoints . active_directory_resource_id self . _tenant = kwargs . get ( 'tenant' , "common" ) self . _verify = kwargs . get ( 'verify' ) self . resource = kwargs . get ( 'resource' , resource ) self . _proxies = kwargs . get ( 'proxies' ) self . _timeout = kwargs . get ( 'timeout' ) self . _cache = kwargs . get ( 'cache' ) self . store_key = "{}_{}" . format ( auth_endpoint . strip ( '/' ) , self . store_key ) self . secret = None self . _context = None | Configure authentication endpoint . |
19,266 | def _convert_token ( self , token ) : token = token . copy ( ) if "expiresOn" in token and "expiresIn" in token : token [ "expiresOn" ] = token [ 'expiresIn' ] + time . time ( ) return { self . _case . sub ( r'\1_\2' , k ) . lower ( ) : v for k , v in token . items ( ) } | Convert token fields from camel case . |
19,267 | 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 . |
19,268 | def refresh_session ( self , session = None ) : if 'refresh_token' in self . token : try : token = self . _context . acquire_token_with_refresh_token ( self . token [ 'refresh_token' ] , self . id , self . resource , self . secret ) self . token = self . _convert_token ( token ) except adal . AdalError as err : raise_with_traceback ( AuthenticationError , "" , err ) return self . signed_session ( session ) | Return updated session if token has expired attempts to refresh using newly acquired token . |
19,269 | def _validate ( url ) : if url is None : return parsed = urlparse ( url ) if not parsed . scheme or not parsed . netloc : raise ValueError ( "Invalid URL header" ) | Validate a url . |
19,270 | def _raise_if_bad_http_status_and_method ( self , response ) : code = response . status_code if code in { 200 , 202 } or ( code == 201 and self . method in { 'PUT' , 'PATCH' } ) or ( code == 204 and self . method in { 'DELETE' , 'POST' } ) : return raise BadStatus ( "Invalid return status for {!r} operation" . format ( self . method ) ) | Check response status code is valid for a Put or Patch request . Must be 200 201 202 or 204 . |
19,271 | def _deserialize ( self , response ) : previous_status = response . status_code response . status_code = self . initial_status_code resource = self . get_outputs ( response ) response . status_code = previous_status if resource is None : previous_status = response . status_code for status_code_to_test in [ 200 , 201 ] : try : response . status_code = status_code_to_test resource = self . get_outputs ( response ) except ClientException : pass else : return resource finally : response . status_code = previous_status return resource | Attempt to deserialize resource from response . |
19,272 | def get_status_from_location ( self , response ) : self . _raise_if_bad_http_status_and_method ( response ) code = response . status_code if code == 202 : self . status = "InProgress" else : self . status = 'Succeeded' if self . _is_empty ( response ) : self . resource = None else : self . resource = self . _deserialize ( response ) | Process the latest status update retrieved from a location header . |
19,273 | def _polling_cookie ( self ) : parsed_url = urlparse ( self . _response . request . url ) host = parsed_url . hostname . strip ( '.' ) if host == 'localhost' : return { 'cookie' : self . _response . headers . get ( 'set-cookie' , '' ) } return { } | Collect retry cookie - we only want to do this for the test server at this point unless we implement a proper cookie policy . |
19,274 | def remove_done_callback ( self , func ) : if self . _done is None or self . _done . is_set ( ) : raise ValueError ( "Process is complete." ) self . _callbacks = [ c for c in self . _callbacks if c != func ] | Remove a callback from the long running operation . |
19,275 | def register_rp_hook ( r , * args , ** kwargs ) : if r . status_code == 409 and 'msrest' in kwargs : rp_name = _check_rp_not_registered_err ( r ) if rp_name : session = kwargs [ 'msrest' ] [ 'session' ] url_prefix = _extract_subscription_url ( r . request . url ) if not _register_rp ( session , url_prefix , rp_name ) : return req = r . request if 'x-ms-client-request-id' in req . headers : req . headers [ 'x-ms-client-request-id' ] = str ( uuid . uuid1 ( ) ) return session . send ( req ) | This is a requests hook to register RP automatically . |
19,276 | def _register_rp ( session , url_prefix , rp_name ) : post_url = "{}providers/{}/register?api-version=2016-02-01" . format ( url_prefix , rp_name ) get_url = "{}providers/{}?api-version=2016-02-01" . format ( url_prefix , rp_name ) _LOGGER . warning ( "Resource provider '%s' used by this operation is not " "registered. We are registering for you." , rp_name ) post_response = session . post ( post_url ) if post_response . status_code != 200 : _LOGGER . warning ( "Registration failed. Please register manually." ) return False while True : time . sleep ( 10 ) rp_info = session . get ( get_url ) . json ( ) if rp_info [ 'registrationState' ] == 'Registered' : _LOGGER . warning ( "Registration succeeded." ) return True | Synchronously register the RP is paremeter . Return False if we have a reason to believe this didn t work |
19,277 | def parse_resource_id ( rid ) : if not rid : return { } match = _ARMID_RE . match ( rid ) if match : result = match . groupdict ( ) children = _CHILDREN_RE . finditer ( result [ 'children' ] or '' ) count = None for count , child in enumerate ( children ) : result . update ( { key + '_%d' % ( count + 1 ) : group for key , group in child . groupdict ( ) . items ( ) } ) result [ 'last_child_num' ] = count + 1 if isinstance ( count , int ) else None result = _populate_alternate_kwargs ( result ) else : result = dict ( name = rid ) return { key : value for key , value in result . items ( ) if value is not None } | Parses a resource_id into its various parts . |
19,278 | def _populate_alternate_kwargs ( kwargs ) : resource_namespace = kwargs [ 'namespace' ] resource_type = kwargs . get ( 'child_type_{}' . format ( kwargs [ 'last_child_num' ] ) ) or kwargs [ 'type' ] resource_name = kwargs . get ( 'child_name_{}' . format ( kwargs [ 'last_child_num' ] ) ) or kwargs [ 'name' ] _get_parents_from_parts ( kwargs ) kwargs [ 'resource_namespace' ] = resource_namespace kwargs [ 'resource_type' ] = resource_type kwargs [ 'resource_name' ] = resource_name return kwargs | Translates the parsed arguments into a format used by generic ARM commands such as the resource and lock commands . |
19,279 | def _get_parents_from_parts ( kwargs ) : parent_builder = [ ] if kwargs [ 'last_child_num' ] is not None : parent_builder . append ( '{type}/{name}/' . format ( ** kwargs ) ) for index in range ( 1 , kwargs [ 'last_child_num' ] ) : child_namespace = kwargs . get ( 'child_namespace_{}' . format ( index ) ) if child_namespace is not None : parent_builder . append ( 'providers/{}/' . format ( child_namespace ) ) kwargs [ 'child_parent_{}' . format ( index ) ] = '' . join ( parent_builder ) parent_builder . append ( '{{child_type_{0}}}/{{child_name_{0}}}/' . format ( index ) . format ( ** kwargs ) ) child_namespace = kwargs . get ( 'child_namespace_{}' . format ( kwargs [ 'last_child_num' ] ) ) if child_namespace is not None : parent_builder . append ( 'providers/{}/' . format ( child_namespace ) ) kwargs [ 'child_parent_{}' . format ( kwargs [ 'last_child_num' ] ) ] = '' . join ( parent_builder ) kwargs [ 'resource_parent' ] = '' . join ( parent_builder ) if kwargs [ 'name' ] else None return kwargs | Get the parents given all the children parameters . |
19,280 | def resource_id ( ** kwargs ) : kwargs = { k : v for k , v in kwargs . items ( ) if v is not None } rid_builder = [ '/subscriptions/{subscription}' . format ( ** kwargs ) ] try : try : rid_builder . append ( 'resourceGroups/{resource_group}' . format ( ** kwargs ) ) except KeyError : pass rid_builder . append ( 'providers/{namespace}' . format ( ** kwargs ) ) rid_builder . append ( '{type}/{name}' . format ( ** kwargs ) ) count = 1 while True : try : rid_builder . append ( 'providers/{{child_namespace_{}}}' . format ( count ) . format ( ** kwargs ) ) except KeyError : pass rid_builder . append ( '{{child_type_{0}}}/{{child_name_{0}}}' . format ( count ) . format ( ** kwargs ) ) count += 1 except KeyError : pass return '/' . join ( rid_builder ) | Create a valid resource id string from the given parts . |
19,281 | def is_valid_resource_id ( rid , exception_type = None ) : is_valid = False try : is_valid = rid and resource_id ( ** parse_resource_id ( rid ) ) . lower ( ) == rid . lower ( ) except KeyError : pass if not is_valid and exception_type : raise exception_type ( ) return is_valid | Validates the given resource id . |
19,282 | def is_valid_resource_name ( rname , exception_type = None ) : match = _ARMNAME_RE . match ( rname ) if match : return True if exception_type : raise exception_type ( ) return False | Validates the given resource name to ARM guidelines individual services may be more restrictive . |
19,283 | async def _delay ( self ) : if self . _response is None : await asyncio . sleep ( 0 ) if self . _response . headers . get ( 'retry-after' ) : await asyncio . sleep ( int ( self . _response . headers [ 'retry-after' ] ) ) else : await asyncio . sleep ( self . _timeout ) | Check for a retry - after header to set timeout otherwise use configured timeout . |
19,284 | async def update_status ( self ) : if self . _operation . async_url : self . _response = await self . request_status ( self . _operation . async_url ) self . _operation . set_async_url_if_present ( self . _response ) self . _operation . get_status_from_async ( self . _response ) elif self . _operation . location_url : self . _response = await self . request_status ( self . _operation . location_url ) self . _operation . set_async_url_if_present ( self . _response ) self . _operation . get_status_from_location ( self . _response ) elif self . _operation . method == "PUT" : initial_url = self . _operation . initial_response . request . url self . _response = await self . request_status ( initial_url ) self . _operation . set_async_url_if_present ( self . _response ) self . _operation . get_status_from_resource ( self . _response ) else : raise BadResponse ( "Unable to find status link for polling." ) | Update the current status of the LRO . |
19,285 | 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' ] } request = self . _client . get ( status_link , headers = header_parameters ) return await self . _client . async_send ( request , stream = False , ** self . _operation_config ) | Do a simple GET to this status link . |
19,286 | def message ( self , value ) : try : import ast value = ast . literal_eval ( value ) except ( SyntaxError , TypeError , ValueError ) : pass try : value = value . get ( 'value' , value ) msg_data = value . split ( '\n' ) self . _message = msg_data [ 0 ] except AttributeError : self . _message = value return try : self . request_id = msg_data [ 1 ] . partition ( ':' ) [ 2 ] time_str = msg_data [ 2 ] . partition ( ':' ) self . error_time = Deserializer . deserialize_iso ( "" . join ( time_str [ 2 : ] ) ) except ( IndexError , DeserializationError ) : pass | Attempt to deconstruct error message to retrieve further error data . |
19,287 | def get_cloud_from_metadata_endpoint ( arm_endpoint , name = None , session = None ) : cloud = Cloud ( name or arm_endpoint ) cloud . endpoints . management = arm_endpoint cloud . endpoints . resource_manager = arm_endpoint _populate_from_metadata_endpoint ( cloud , arm_endpoint , session ) return cloud | Get a Cloud object from an ARM endpoint . |
19,288 | def _as_json ( self , response ) : content = response . text ( ) if hasattr ( response , "body" ) else response . text try : return json . loads ( content ) except ValueError : raise DeserializationError ( "Error occurred in deserializing the response body." ) | Assuming this is not empty return the content as JSON . |
19,289 | def should_do_final_get ( self ) : return ( ( self . async_url or not self . resource ) and self . method in { 'PUT' , 'PATCH' } ) or ( self . lro_options [ 'final-state-via' ] == _LOCATION_FINAL_STATE and self . location_url and self . async_url and self . method == 'POST' ) | Check whether the polling should end doing a final GET . |
19,290 | def set_initial_status ( self , response ) : self . _raise_if_bad_http_status_and_method ( response ) if self . _is_empty ( response ) : self . resource = None else : try : self . resource = self . _deserialize ( response ) except DeserializationError : self . resource = None self . set_async_url_if_present ( response ) if response . status_code in { 200 , 201 , 202 , 204 } : if self . async_url or self . location_url or response . status_code == 202 : self . status = 'InProgress' elif response . status_code == 201 : status = self . _get_provisioning_state ( response ) self . status = status or 'InProgress' elif response . status_code == 200 : status = self . _get_provisioning_state ( response ) self . status = status or 'Succeeded' elif response . status_code == 204 : self . status = 'Succeeded' self . resource = None else : raise OperationFailed ( "Invalid status found" ) return raise OperationFailed ( "Operation failed or cancelled" ) | Process first response after initiating long running operation and set self . status attribute . |
19,291 | def parse_resource ( self , response ) : self . _raise_if_bad_http_status_and_method ( response ) if not self . _is_empty ( response ) : self . resource = self . _deserialize ( response ) else : self . resource = None | Assuming this response is a resource use the deserialization callback to parse it . If body is empty assuming no resource to return . |
19,292 | def get_status_from_async ( self , response ) : self . _raise_if_bad_http_status_and_method ( response ) if self . _is_empty ( response ) : raise BadResponse ( 'The response from long running operation ' 'does not contain a body.' ) self . status = self . _get_async_status ( response ) if not self . status : raise BadResponse ( "No status found in body" ) try : self . resource = self . _deserialize ( response ) except Exception : self . resource = None | Process the latest status update retrieved from a azure - asyncoperation header . |
19,293 | def initialize ( self , client , initial_response , deserialization_callback ) : self . _client = client self . _response = initial_response self . _operation = LongRunningOperation ( initial_response , deserialization_callback , self . _lro_options ) try : self . _operation . set_initial_status ( initial_response ) except BadStatus : self . _operation . status = 'Failed' raise CloudError ( initial_response ) except BadResponse as err : self . _operation . status = 'Failed' raise CloudError ( initial_response , str ( err ) ) except OperationFailed : raise CloudError ( initial_response ) | Set the initial status of this LRO . |
19,294 | def worker ( ) : import torch import torch . distributed as dist from torch . multiprocessing import Process import numpy as np print ( "Initializing distributed pytorch" ) os . environ [ 'MASTER_ADDR' ] = str ( args . master_addr ) os . environ [ 'MASTER_PORT' ] = str ( args . master_port ) dist . init_process_group ( 'tcp' , rank = args . rank , world_size = args . size ) tensor = torch . ones ( args . size_mb * 250 * 1000 ) * ( args . rank + 1 ) time_list = [ ] outfile = 'out' if args . rank == 0 else '/dev/null' log = util . FileLogger ( outfile ) for i in range ( args . iters ) : start_time = time . perf_counter ( ) if args . rank == 0 : dist . send ( tensor = tensor , dst = 1 ) else : dist . recv ( tensor = tensor , src = 0 ) elapsed_time_ms = ( time . perf_counter ( ) - start_time ) * 1000 time_list . append ( elapsed_time_ms ) rate = args . size_mb / ( elapsed_time_ms / 1000 ) log ( '%03d/%d added %d MBs in %.1f ms: %.2f MB/second' % ( i , args . iters , args . size_mb , elapsed_time_ms , rate ) ) min = np . min ( time_list ) median = np . median ( time_list ) log ( f"min: {min:8.2f}, median: {median:8.2f}, mean: {np.mean(time_list):8.2f}" ) | Initialize the distributed environment . |
19,295 | def make_job ( name : str = '' , run_name : str = '' , num_tasks : int = 0 , install_script : str = '' , ** kwargs ) -> backend . Job : return _backend . make_job ( name = name , run_name = run_name , num_tasks = num_tasks , install_script = install_script , ** kwargs ) | Create a job using current backend . Blocks until all tasks are up and initialized . |
19,296 | def make_task ( name = '' , run_name = '' , ** kwargs ) -> Task : ncluster_globals . task_launched = True name = ncluster_globals . auto_assign_task_name_if_needed ( name ) tmux_session = name . replace ( '.' , '=' ) tmux_window_id = 0 util . log ( f'killing session {tmux_session}' ) if not util . is_set ( "NCLUSTER_NOKILL_TMUX" ) : os . system ( f'tmux kill-session -t {tmux_session}' ) os . system ( f'tmux new-session -s {tmux_session} -n {tmux_window_id} -d' ) task = Task ( name , tmux_session = tmux_session , run_name = run_name , ** kwargs ) ncluster_globals . register_task ( task , run_name ) return task | Create task also create dummy run if not specified . |
19,297 | def _run_raw ( self , cmd , ignore_errors = False ) : result = os . system ( cmd ) if result != 0 : if ignore_errors : self . log ( f"command ({cmd}) failed." ) assert False , "_run_raw failed" | Runs command directly skipping tmux interface |
19,298 | def upload ( self , local_fn , remote_fn = None , dont_overwrite = False ) : if '*' in local_fn : for local_subfn in glob . glob ( local_fn ) : self . upload ( local_subfn ) return if remote_fn is None : remote_fn = os . path . basename ( local_fn ) if dont_overwrite and self . exists ( remote_fn ) : self . log ( "Remote file %s exists, skipping" % ( remote_fn , ) ) return if not remote_fn . startswith ( '/' ) : remote_fn = self . taskdir + '/' + remote_fn remote_fn = remote_fn . replace ( '~' , self . homedir ) self . log ( 'uploading ' + local_fn + ' to ' + remote_fn ) local_fn = os . path . abspath ( local_fn ) self . _run_raw ( "cp -R %s %s" % ( local_fn , remote_fn ) ) | Uploads file to remote instance . If location not specified dumps it into default directory . Creates missing directories in path name . |
19,299 | 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 . is_chief ( self , run_name ) : chief = self else : chief = ncluster_globals . get_chief ( run_name ) chief . setup_logdir ( ) return ncluster_globals . get_logdir ( run_name ) | Returns logging directory creating one if necessary . See Logdir section of design doc on naming convention . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.