idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
50,800 | def _load_resources ( self ) : for t in self . doc . find ( 'Root.Table' ) : for c in t . find ( 'Table.Column' ) : if c . get_value ( 'datatype' ) == 'geometry' : c [ 'transform' ] = '^empty_str' c [ 'datatype' ] = 'text' return super ( ) . _load_resources ( ) | Remove the geography from the files since it isn t particularly useful in Excel |
50,801 | def make_bucket_policy_statements ( bucket ) : import yaml from os . path import dirname , join , abspath import copy import metatab with open ( join ( dirname ( abspath ( metatab . __file__ ) ) , 'support' , 'policy_parts.yaml' ) ) as f : parts = yaml . load ( f ) statements = { } cl = copy . deepcopy ( parts [ 'list' ] ) cl [ 'Resource' ] = arn_prefix + bucket statements [ 'list' ] = cl cl = copy . deepcopy ( parts [ 'bucket' ] ) cl [ 'Resource' ] = arn_prefix + bucket statements [ 'bucket' ] = cl for sd in TOP_LEVEL_DIRS : cl = copy . deepcopy ( parts [ 'read' ] ) cl [ 'Resource' ] = arn_prefix + bucket + '/' + sd + '/*' cl [ 'Sid' ] = cl [ 'Sid' ] . title ( ) + sd . title ( ) statements [ cl [ 'Sid' ] ] = cl cl = copy . deepcopy ( parts [ 'write' ] ) cl [ 'Resource' ] = arn_prefix + bucket + '/' + sd + '/*' cl [ 'Sid' ] = cl [ 'Sid' ] . title ( ) + sd . title ( ) statements [ cl [ 'Sid' ] ] = cl cl = copy . deepcopy ( parts [ 'listb' ] ) cl [ 'Resource' ] = arn_prefix + bucket cl [ 'Sid' ] = cl [ 'Sid' ] . title ( ) + sd . title ( ) cl [ 'Condition' ] [ 'StringLike' ] [ 's3:prefix' ] = [ sd + '/*' ] statements [ cl [ 'Sid' ] ] = cl return statements | Return the statemtns in a bucket policy as a dict of dicts |
50,802 | def bucket_dict_to_policy ( args , bucket_name , d ) : import json iam = get_resource ( args , 'iam' ) statements = make_bucket_policy_statements ( bucket_name ) user_stats = set ( ) for ( user , prefix ) , mode in d . items ( ) : user_stats . add ( ( user , 'list' ) ) user_stats . add ( ( user , 'bucket' ) ) if mode == 'R' : user_stats . add ( ( user , 'Read' + prefix . title ( ) ) ) user_stats . add ( ( user , 'List' + prefix . title ( ) ) ) elif mode == 'W' : user_stats . add ( ( user , 'List' + prefix . title ( ) ) ) user_stats . add ( ( user , 'Read' + prefix . title ( ) ) ) user_stats . add ( ( user , 'Write' + prefix . title ( ) ) ) users_arns = { } for user_name , section in user_stats : section = statements [ section ] if user_name not in users_arns : user = iam . User ( user_name ) users_arns [ user . name ] = user else : user = users_arns [ user_name ] section [ 'Principal' ] [ 'AWS' ] . append ( user . arn ) for sid in list ( statements . keys ( ) ) : if not statements [ sid ] [ 'Principal' ] [ 'AWS' ] : del statements [ sid ] return json . dumps ( dict ( Version = "2012-10-17" , Statement = list ( statements . values ( ) ) ) , indent = 4 ) | Create a bucket policy document from a permissions dict . |
50,803 | def bucket_policy_to_dict ( policy ) : import json if not isinstance ( policy , dict ) : policy = json . loads ( policy ) statements = { s [ 'Sid' ] : s for s in policy [ 'Statement' ] } d = { } for rw in ( 'Read' , 'Write' ) : for prefix in TOP_LEVEL_DIRS : sid = rw . title ( ) + prefix . title ( ) if sid in statements : if isinstance ( statements [ sid ] [ 'Principal' ] [ 'AWS' ] , list ) : for principal in statements [ sid ] [ 'Principal' ] [ 'AWS' ] : user_name = principal . split ( '/' ) . pop ( ) d [ ( user_name , prefix ) ] = rw [ 0 ] else : user_name = statements [ sid ] [ 'Principal' ] [ 'AWS' ] . split ( '/' ) . pop ( ) d [ ( user_name , prefix ) ] = rw [ 0 ] return d | Produce a dictionary of read write permissions for an existing bucket policy document |
50,804 | def get_iam_account ( l , args , user_name ) : iam = get_resource ( args , 'iam' ) user = iam . User ( user_name ) user . load ( ) return l . find_or_new_account ( user . arn ) | Return the local Account for a user name by fetching User and looking up the arn . |
50,805 | def getSVD ( data , k , getComponents = False , getS = False , normalization = 'mean' ) : if normalization == 'nanmean' : data2 = data . tordd ( ) . sortByKey ( ) . values ( ) . map ( lambda x : _convert_to_vector ( x . flatten ( ) - np . nanmean ( x ) ) ) elif normalization == 'mean' : data2 = data . tordd ( ) . sortByKey ( ) . values ( ) . map ( lambda x : _convert_to_vector ( x . flatten ( ) - x . mean ( ) ) ) elif normalization is 'zscore' : data2 = data . tordd ( ) . sortByKey ( ) . values ( ) . map ( lambda x : _convert_to_vector ( zscore ( x . flatten ( ) ) ) ) elif normalization is None : data2 = data . tordd ( ) . sortByKey ( ) . values ( ) . map ( lambda x : _convert_to_vector ( x . flatten ( ) ) ) else : raise ValueError ( 'Normalization should be one of: mean, nanmean, zscore, None. Got: %s' % normalization ) mat = RowMatrix ( data2 ) mat . rows . cache ( ) mat . rows . count ( ) svd = compute_svd ( row_matrix = mat , k = k , compute_u = False ) if getComponents : components = svd . call ( "V" ) . toArray ( ) components = components . transpose ( 1 , 0 ) . reshape ( ( k , ) + data . shape [ 1 : ] ) else : components = None projection = np . array ( RowMatrix_new ( data2 ) . multiply ( svd . call ( "V" ) ) . rows . collect ( ) ) if getS : s = svd . call ( "s" ) . toArray ( ) else : s = None return projection , components , s | Wrapper for computeSVD that will normalize and handle a Thunder Images object |
50,806 | def human_duration ( duration_seconds : float ) -> str : if duration_seconds < 0.001 : return '0 ms' if duration_seconds < 1 : return '{} ms' . format ( int ( duration_seconds * 1000 ) ) return '{} s' . format ( int ( duration_seconds ) ) | Convert a duration in seconds into a human friendly string . |
50,807 | def call_with_retry ( func : Callable , exceptions , max_retries : int , logger : Logger , * args , ** kwargs ) : attempt = 0 while True : try : return func ( * args , ** kwargs ) except exceptions as e : attempt += 1 if attempt >= max_retries : raise delay = exponential_backoff ( attempt , cap = 60 ) logger . warning ( '%s: retrying in %s' , e , delay ) time . sleep ( delay . total_seconds ( ) ) | Call a function and retry it on failure . |
50,808 | def exponential_backoff ( attempt : int , cap : int = 1200 ) -> timedelta : base = 3 temp = min ( base * 2 ** attempt , cap ) return timedelta ( seconds = temp / 2 + random . randint ( 0 , temp / 2 ) ) | Calculate a delay to retry using an exponential backoff algorithm . |
50,809 | def float_to_fp ( signed , n_bits , n_frac ) : if signed : max_v = ( 1 << ( n_bits - 1 ) ) - 1 min_v = - max_v - 1 else : min_v = 0 max_v = ( 1 << n_bits ) - 1 scale = 2.0 ** n_frac def bitsk ( value ) : int_val = int ( scale * value ) return max ( ( min ( max_v , int_val ) , min_v ) ) return bitsk | Return a function to convert a floating point value to a fixed point value . |
50,810 | def get_metadata_path ( name ) : return pkg_resources . resource_filename ( 'voobly' , os . path . join ( METADATA_PATH , '{}.json' . format ( name ) ) ) | Get reference metadata file path . |
50,811 | def _make_request ( session , url , argument = None , params = None , raw = False ) : if not params : params = { } params [ 'key' ] = session . auth . key try : if argument : request_url = '{}{}{}{}' . format ( session . auth . base_url , VOOBLY_API_URL , url , argument ) else : request_url = '{}{}' . format ( VOOBLY_API_URL , url ) resp = session . get ( request_url , params = params ) except RequestException : raise VooblyError ( 'failed to connect' ) if resp . text == 'bad-key' : raise VooblyError ( 'bad api key' ) elif resp . text == 'too-busy' : raise VooblyError ( 'service too busy' ) elif not resp . text : raise VooblyError ( 'no data returned' ) if raw : return resp . text try : return tablib . Dataset ( ) . load ( resp . text ) . dict except UnsupportedFormat : raise VooblyError ( 'unexpected error {}' . format ( resp . text ) ) | Make a request to API endpoint . |
50,812 | def make_scrape_request ( session , url , mode = 'get' , data = None ) : try : html = session . request ( mode , url , data = data ) except RequestException : raise VooblyError ( 'failed to connect' ) if SCRAPE_FETCH_ERROR in html . text : raise VooblyError ( 'not logged in' ) if html . status_code != 200 or SCRAPE_PAGE_NOT_FOUND in html . text : raise VooblyError ( 'page not found' ) return bs4 . BeautifulSoup ( html . text , features = 'lxml' ) | Make a request to URL . |
50,813 | def get_ladder ( session , ladder_id , user_id = None , user_ids = None , start = 0 , limit = LADDER_RESULT_LIMIT ) : params = { 'start' : start , 'limit' : limit } if isinstance ( ladder_id , str ) : ladder_id = lookup_ladder_id ( ladder_id ) if limit > LADDER_RESULT_LIMIT : raise VooblyError ( 'limited to 40 rows' ) if user_ids : params [ 'uidlist' ] = ',' . join ( [ str ( uid ) for uid in user_ids ] ) elif user_id : params [ 'uid' ] = user_id resp = _make_request ( session , LADDER_URL , ladder_id , params ) if user_id : if not resp : raise VooblyError ( 'user not ranked' ) return resp [ 0 ] return resp | Get ladder . |
50,814 | def get_lobbies ( session , game_id ) : if isinstance ( game_id , str ) : game_id = lookup_game_id ( game_id ) lobbies = _make_request ( session , LOBBY_URL , game_id ) for lobby in lobbies : if len ( lobby [ 'ladders' ] ) > 0 : lobby [ 'ladders' ] = lobby [ 'ladders' ] [ : - 1 ] . split ( '|' ) return lobbies | Get lobbies for a game . |
50,815 | def get_user ( session , user_id ) : try : user_id = int ( user_id ) except ValueError : user_id = find_user ( session , user_id ) resp = _make_request ( session , USER_URL , user_id ) if not resp : raise VooblyError ( 'user id not found' ) return resp [ 0 ] | Get user . |
50,816 | def find_user ( session , username ) : resp = _make_request ( session , FIND_USER_URL , username ) if not resp : raise VooblyError ( 'user not found' ) try : return int ( resp [ 0 ] [ 'uid' ] ) except ValueError : raise VooblyError ( 'user not found' ) | Find user by name - returns user ID . |
50,817 | def find_users ( session , * usernames ) : user_string = ',' . join ( usernames ) return _make_request ( session , FIND_USERS_URL , user_string ) | Find multiple users by name . |
50,818 | def user ( session , uid , ladder_ids = None ) : data = get_user ( session , uid ) resp = dict ( data ) if not ladder_ids : return resp resp [ 'ladders' ] = { } for ladder_id in ladder_ids : if isinstance ( ladder_id , str ) : ladder_id = lookup_ladder_id ( ladder_id ) try : ladder_data = dict ( get_ladder ( session , ladder_id , user_id = uid ) ) resp [ 'ladders' ] [ ladder_id ] = ladder_data except VooblyError : pass return resp | Get all possible user info by name . |
50,819 | def ladders ( session , game_id ) : if isinstance ( game_id , str ) : game_id = lookup_game_id ( game_id ) lobbies = get_lobbies ( session , game_id ) ladder_ids = set ( ) for lobby in lobbies : ladder_ids |= set ( lobby [ 'ladders' ] ) return list ( ladder_ids ) | Get a list of ladder IDs . |
50,820 | def get_clan_matches ( session , subdomain , clan_id , from_timestamp = None , limit = None ) : return get_recent_matches ( session , 'https://{}.voobly.com/{}/{}/0' . format ( subdomain , TEAM_MATCHES_URL , clan_id ) , from_timestamp , limit ) | Get recent matches by clan . |
50,821 | def get_user_matches ( session , user_id , from_timestamp = None , limit = None ) : return get_recent_matches ( session , '{}{}/{}/Matches/games/matches/user/{}/0' . format ( session . auth . base_url , PROFILE_URL , user_id , user_id ) , from_timestamp , limit ) | Get recent matches by user . |
50,822 | def get_recent_matches ( session , init_url , from_timestamp , limit ) : if not from_timestamp : from_timestamp = datetime . datetime . now ( ) - datetime . timedelta ( days = 1 ) matches = [ ] page_id = 0 done = False while not done and page_id < MAX_MATCH_PAGE_ID : url = '{}/{}' . format ( init_url , page_id ) parsed = make_scrape_request ( session , url ) for row in parsed . find ( 'table' ) . find_all ( 'tr' ) [ 1 : ] : cols = row . find_all ( 'td' ) played_at = dateparser . parse ( cols [ 2 ] . text ) match_id = int ( cols [ 5 ] . find ( 'a' ) . text [ 1 : ] ) has_rec = cols [ 6 ] . find ( 'a' ) . find ( 'img' ) if played_at < from_timestamp or ( limit and len ( matches ) == limit ) : done = True break if not has_rec : continue matches . append ( { 'timestamp' : played_at , 'match_id' : match_id } ) if not matches : break page_id += 1 return matches | Get recently played user matches . |
50,823 | def get_ladder_matches ( session , ladder_id , from_timestamp = None , limit = LADDER_MATCH_LIMIT ) : if not from_timestamp : from_timestamp = datetime . datetime . now ( ) - datetime . timedelta ( days = 1 ) matches = [ ] page_id = 0 done = False i = 0 while not done and page_id < MAX_LADDER_PAGE_ID : url = '{}{}/{}/{}' . format ( session . auth . base_url , LADDER_MATCHES_URL , lookup_ladder_id ( ladder_id ) , page_id ) parsed = make_scrape_request ( session , url ) for row in parsed . find ( text = 'Recent Matches' ) . find_next ( 'table' ) . find_all ( 'tr' ) [ 1 : ] : cols = row . find_all ( 'td' ) played_at = dateparser . parse ( cols [ 0 ] . text ) match_id = int ( cols [ 1 ] . find ( 'a' ) . text [ 1 : ] ) has_rec = cols [ 4 ] . find ( 'a' ) . find ( 'img' ) if not has_rec : continue if played_at < from_timestamp or i >= limit : done = True break matches . append ( { 'timestamp' : played_at , 'match_id' : match_id } ) i += 1 page_id += 1 return matches | Get recently played ladder matches . |
50,824 | def get_match ( session , match_id ) : url = '{}{}/{}' . format ( session . auth . base_url , MATCH_URL , match_id ) parsed = make_scrape_request ( session , url ) game = parsed . find ( 'h3' ) . text if game != GAME_AOC : raise ValueError ( 'not an aoc match' ) date_played = parsed . find ( text = MATCH_DATE_PLAYED ) . find_next ( 'td' ) . text players = [ ] colors = { } player_count = int ( parsed . find ( 'td' , text = 'Players:' ) . find_next ( 'td' ) . text ) for div in parsed . find_all ( 'div' , style = True ) : if not div [ 'style' ] . startswith ( 'background-color:' ) : continue if len ( players ) == player_count : break username_elem = div . find_next ( 'a' , href = re . compile ( PROFILE_PATH ) ) username = username_elem . text color = div [ 'style' ] . split ( ':' ) [ 1 ] . split ( ';' ) [ 0 ] . strip ( ) colors [ username ] = color rec = None for dl_elem in parsed . find_all ( 'a' , href = re . compile ( '^/files/view' ) ) : rec_name = dl_elem . find ( 'b' , text = re . compile ( username + '$' ) ) if rec_name : rec = rec_name . parent user = parsed . find ( 'a' , text = username ) if not user : continue user_id = int ( user [ 'href' ] . split ( '/' ) [ - 1 ] ) children = list ( user . find_next ( 'span' ) . children ) rate_after = None rate_before = None if str ( children [ 0 ] ) . strip ( ) == MATCH_NEW_RATE : rate_after = int ( children [ 1 ] . text ) rate_before = rate_after - int ( children [ 3 ] . text ) elif str ( children [ 4 ] ) . strip ( ) == MATCH_NEW_RATE : rate_after = int ( children [ 5 ] . text ) rate_before = rate_after - int ( children [ 3 ] . text ) players . append ( { 'url' : rec [ 'href' ] if rec else None , 'id' : user_id , 'username' : username , 'color_id' : COLOR_MAPPING . get ( colors [ username ] ) , 'rate_before' : rate_before , 'rate_after' : rate_after } ) return { 'timestamp' : dateparser . parse ( date_played ) , 'players' : players } | Get match metadata . |
50,825 | def download_rec ( session , rec_url , target_path ) : try : resp = session . get ( session . auth . base_url + rec_url ) except RequestException : raise VooblyError ( 'failed to connect for download' ) try : downloaded = zipfile . ZipFile ( io . BytesIO ( resp . content ) ) downloaded . extractall ( target_path ) except zipfile . BadZipFile : raise VooblyError ( 'invalid zip file' ) return downloaded . namelist ( ) [ 0 ] | Download and extract a recorded game . |
50,826 | def login ( session ) : if not session . auth . username or not session . auth . password : raise VooblyError ( 'must supply username and password' ) _LOGGER . info ( "logging in (no valid cookie found)" ) session . cookies . clear ( ) try : session . get ( session . auth . base_url + LOGIN_PAGE ) resp = session . post ( session . auth . base_url + LOGIN_URL , data = { 'username' : session . auth . username , 'password' : session . auth . password } ) except RequestException : raise VooblyError ( 'failed to connect for login' ) if resp . status_code != 200 : raise VooblyError ( 'failed to login' ) _save_cookies ( session . cookies , session . auth . cookie_path ) | Login to Voobly . |
50,827 | def get_session ( key = None , username = None , password = None , cache = True , cache_expiry = datetime . timedelta ( days = 7 ) , cookie_path = COOKIE_PATH , backend = 'memory' , version = VERSION_GLOBAL ) : class VooblyAuth ( AuthBase ) : def __init__ ( self , key , username , password , cookie_path , version ) : self . key = key self . username = username self . password = password self . cookie_path = cookie_path self . base_url = BASE_URLS [ version ] def __call__ ( self , r ) : return r if version not in BASE_URLS : raise ValueError ( 'unsupported voobly version' ) session = requests . session ( ) if cache : session = requests_cache . core . CachedSession ( expire_after = cache_expiry , backend = backend ) session . auth = VooblyAuth ( key , username , password , cookie_path , version ) if os . path . exists ( cookie_path ) : _LOGGER . info ( "cookie found at: %s" , cookie_path ) session . cookies = _load_cookies ( cookie_path ) return session | Get Voobly API session . |
50,828 | def main ( ) : neutron_config . register_agent_state_opts_helper ( CONF ) common_config . init ( sys . argv [ 1 : ] ) neutron_config . setup_logging ( ) hyperv_agent = HyperVNeutronAgent ( ) LOG . info ( "Agent initialized successfully, now running... " ) hyperv_agent . daemon_loop ( ) | The entry point for the Hyper - V Neutron Agent . |
50,829 | def _setup_qos_extension ( self ) : if not CONF . AGENT . enable_qos_extension : return self . _qos_ext = qos_extension . QosAgentExtension ( ) self . _qos_ext . consume_api ( self ) self . _qos_ext . initialize ( self . _connection , 'hyperv' ) | Setup the QOS extension if it is required . |
50,830 | def run_cell_magic ( self , magic_name , line , cell ) : if magic_name == 'bash' : self . shebang ( "bash" , cell ) elif magic_name == 'metatab' : self . mm . metatab ( line , cell ) | Run a limited number of magics from scripts without IPython |
50,831 | def var_expand ( self , cmd , depth = 0 , formatter = DollarFormatter ( ) ) : ns = self . user_ns . copy ( ) try : frame = sys . _getframe ( depth + 1 ) except ValueError : pass else : ns . update ( frame . f_locals ) try : cmd = formatter . vformat ( cmd , args = [ ] , kwargs = ns ) except Exception : pass return cmd | Expand python variables in a string . |
50,832 | def shebang ( self , line , cell ) : argv = arg_split ( line , posix = not sys . platform . startswith ( 'win' ) ) args , cmd = self . shebang . parser . parse_known_args ( argv ) try : p = Popen ( cmd , stdout = PIPE , stderr = PIPE , stdin = PIPE ) except OSError as e : if e . errno == errno . ENOENT : print ( "Couldn't find program: %r" % cmd [ 0 ] ) return else : raise if not cell . endswith ( '\n' ) : cell += '\n' cell = cell . encode ( 'utf8' , 'replace' ) if args . bg : self . bg_processes . append ( p ) self . _gc_bg_processes ( ) if args . out : self . shell . user_ns [ args . out ] = p . stdout if args . err : self . shell . user_ns [ args . err ] = p . stderr self . job_manager . new ( self . _run_script , p , cell , daemon = True ) if args . proc : self . shell . user_ns [ args . proc ] = p return try : out , err = p . communicate ( cell ) except KeyboardInterrupt : try : p . send_signal ( signal . SIGINT ) time . sleep ( 0.1 ) if p . poll ( ) is not None : print ( "Process is interrupted." ) return p . terminate ( ) time . sleep ( 0.1 ) if p . poll ( ) is not None : print ( "Process is terminated." ) return p . kill ( ) print ( "Process is killed." ) except OSError : pass except Exception as e : print ( "Error while terminating subprocess (pid=%i): %s" % ( p . pid , e ) ) return out = py3compat . bytes_to_str ( out ) err = py3compat . bytes_to_str ( err ) if args . out : self . shell . user_ns [ args . out ] = out else : sys . stdout . write ( out ) sys . stdout . flush ( ) if args . err : self . shell . user_ns [ args . err ] = err else : sys . stderr . write ( err ) sys . stderr . flush ( ) | Run a cell via a shell command |
50,833 | def _get_vertices_neighbours ( nets ) : zero_fn = ( lambda : 0 ) vertices_neighbours = defaultdict ( lambda : defaultdict ( zero_fn ) ) for net in nets : if net . weight != 0 : for sink in net . sinks : vertices_neighbours [ net . source ] [ sink ] += net . weight vertices_neighbours [ sink ] [ net . source ] += net . weight return vertices_neighbours | Generate a listing of each vertex s immedate neighbours in an undirected interpretation of a graph . |
50,834 | def _dfs ( vertex , vertices_neighbours ) : visited = set ( ) to_visit = deque ( [ vertex ] ) while to_visit : vertex = to_visit . pop ( ) if vertex not in visited : yield vertex visited . add ( vertex ) to_visit . extend ( vertices_neighbours [ vertex ] ) | Generate all the vertices connected to the supplied vertex in depth - first - search order . |
50,835 | def _get_connected_subgraphs ( vertices , vertices_neighbours ) : remaining_vertices = set ( vertices ) subgraphs = [ ] while remaining_vertices : subgraph = set ( _dfs ( remaining_vertices . pop ( ) , vertices_neighbours ) ) remaining_vertices . difference_update ( subgraph ) subgraphs . append ( subgraph ) return subgraphs | Break a graph containing unconnected subgraphs into a list of connected subgraphs . |
50,836 | def _cuthill_mckee ( vertices , vertices_neighbours ) : vertices_degrees = { v : sum ( itervalues ( vertices_neighbours [ v ] ) ) for v in vertices } peripheral_vertex = min ( vertices , key = ( lambda v : vertices_degrees [ v ] ) ) visited = set ( [ peripheral_vertex ] ) cm_order = [ peripheral_vertex ] previous_layer = set ( [ peripheral_vertex ] ) while len ( cm_order ) < len ( vertices ) : adjacent = set ( ) for vertex in previous_layer : adjacent . update ( vertices_neighbours [ vertex ] ) adjacent . difference_update ( visited ) visited . update ( adjacent ) cm_order . extend ( sorted ( adjacent , key = ( lambda v : vertices_degrees [ v ] ) ) ) previous_layer = adjacent return cm_order | Yield the Cuthill - McKee order for a connected undirected graph . |
50,837 | def rcm_vertex_order ( vertices_resources , nets ) : vertices_neighbours = _get_vertices_neighbours ( nets ) for subgraph_vertices in _get_connected_subgraphs ( vertices_resources , vertices_neighbours ) : cm_order = _cuthill_mckee ( subgraph_vertices , vertices_neighbours ) for vertex in reversed ( cm_order ) : yield vertex | A generator which iterates over the vertices in Reverse - Cuthill - McKee order . |
50,838 | def rcm_chip_order ( machine ) : vertices = list ( machine ) nets = [ ] for ( x , y ) in vertices : neighbours = [ ] for link in Links : if ( x , y , link ) in machine : dx , dy = link . to_vector ( ) neighbour = ( ( x + dx ) % machine . width , ( y + dy ) % machine . height ) if neighbour in machine : neighbours . append ( neighbour ) nets . append ( Net ( ( x , y ) , neighbours ) ) return rcm_vertex_order ( vertices , nets ) | A generator which iterates over a set of chips in a machine in Reverse - Cuthill - McKee order . |
50,839 | def register_datadog ( tracer = None , namespace : Optional [ str ] = None , service : str = 'spinach' ) : if tracer is None : from ddtrace import tracer @ signals . job_started . connect_via ( namespace ) def job_started ( namespace , job , ** kwargs ) : tracer . trace ( 'spinach.task' , service = service , span_type = 'worker' , resource = job . task_name ) @ signals . job_finished . connect_via ( namespace ) def job_finished ( namespace , job , ** kwargs ) : root_span = tracer . current_root_span ( ) for attr in job . __slots__ : root_span . set_tag ( attr , getattr ( job , attr ) ) root_span . finish ( ) @ signals . job_failed . connect_via ( namespace ) def job_failed ( namespace , job , ** kwargs ) : root_span = tracer . current_root_span ( ) root_span . set_traceback ( ) @ signals . job_schedule_retry . connect_via ( namespace ) def job_schedule_retry ( namespace , job , ** kwargs ) : root_span = tracer . current_root_span ( ) root_span . set_traceback ( ) | Register the Datadog integration . |
50,840 | def copy_reference ( resource , doc , env , * args , ** kwargs ) : yield from doc . reference ( resource . name ) | A row - generating function that yields from a reference . This permits an upstream package to be copied and modified by this package while being formally referenced as a dependency |
50,841 | def copy_reference_group ( resource , doc , env , * args , ** kwargs ) : all_headers = [ ] for ref in doc . references ( ) : if ref . get_value ( 'Group' ) == resource . get_value ( 'Group' ) : for row in ref . iterrowproxy ( ) : all_headers . append ( list ( row . keys ( ) ) ) break headers = [ ] for e in zip ( * all_headers ) : for c in set ( e ) : if c not in headers : headers . append ( c ) if resource . get_value ( 'RefArgs' ) : ref_args = [ e . strip ( ) for e in resource . get_value ( 'RefArgs' ) . strip ( ) . split ( ',' ) ] else : ref_args = [ ] yield ref_args + headers for ref in doc . references ( ) : if ref . get_value ( 'Group' ) == resource . get_value ( 'Group' ) : ref_args_values = [ ref . get_value ( e ) for e in ref_args ] for row in ref . iterdict : yield ref_args_values + [ row . get ( c ) for c in headers ] | A Row generating function that copies all of the references that have the same Group argument as this reference |
50,842 | def is_older_than_metadata ( self ) : try : path = self . doc_file . path except AttributeError : path = self . doc_file source_ref = self . _doc . ref . path try : age_diff = getmtime ( source_ref ) - getmtime ( path ) return age_diff > 0 except ( FileNotFoundError , OSError ) : return False | Return True if the package save file is older than the metadata . If it is it should be rebuilt . Returns False if the time of either can t be determined |
50,843 | def _load_resource ( self , source_r , abs_path = False ) : from itertools import islice from metapack . exc import MetapackError from os . path import splitext r = self . datafile ( source_r . name ) if self . reuse_resources : self . prt ( "Re-using data for '{}' " . format ( r . name ) ) else : self . prt ( "Loading data for '{}' " . format ( r . name ) ) if not r . name : raise MetapackError ( f"Resource/reference term has no name: {str(r)}" ) if r . term_is ( 'root.sql' ) : new_r = self . doc [ 'Resources' ] . new_term ( 'Root.Datafile' , '' ) new_r . name = r . name self . doc . remove_term ( r ) r = new_r r . url = 'data/' + r . name + '.csv' path = join ( self . package_path . path , r . url ) makedirs ( dirname ( path ) , exist_ok = True ) if not self . reuse_resources or not exists ( path ) : if self . reuse_resources : self . prt ( "Resource {} doesn't exist, rebuilding" . format ( path ) ) if exists ( path ) : remove ( path ) gen = islice ( source_r , 1 , None ) headers = source_r . headers self . write_csv ( path , headers , gen ) for k , v in source_r . post_iter_meta . items ( ) : r [ k ] = v try : if source_r . errors : for col_name , errors in source_r . errors . items ( ) : self . warn ( "ERRORS for column '{}' " . format ( col_name ) ) for e in islice ( errors , 5 ) : self . warn ( ' {}' . format ( e ) ) if len ( errors ) > 5 : self . warn ( "... and {} more " . format ( len ( errors ) - 5 ) ) except AttributeError : pass if source_r . errors : self . err ( "Resource processing generated conversion errors" ) ref = self . _write_doc ( ) p = FileSystemPackageBuilder ( ref , self . package_root ) p . _clean_doc ( ) ref = p . _write_doc ( ) | The CSV package has no resources so we just need to resolve the URLs to them . Usually the CSV package is built from a file system ackage on a publically acessible server . |
50,844 | def _load_documentation ( self , term , contents , file_name ) : try : title = term [ 'title' ] . value except KeyError : self . warn ( "Documentation has no title, skipping: '{}' " . format ( term . value ) ) return if term . term_is ( 'Root.Readme' ) : package_sub_dir = 'docs' else : try : eu = term . expanded_url parsed_url = term . parsed_url except AttributeError : parsed_url = eu = parse_app_url ( term . value ) if eu . proto == 'file' and not parsed_url . path_is_absolute : package_sub_dir = parsed_url . fspath . parent else : package_sub_dir = 'docs' path = join ( self . package_path . path , package_sub_dir , file_name ) self . prt ( "Loading documentation for '{}', '{}' to '{}' " . format ( title , file_name , path ) ) makedirs ( dirname ( path ) , exist_ok = True ) if exists ( path ) : remove ( path ) with open ( path , 'wb' ) as f : f . write ( contents ) | Load a single documentation entry |
50,845 | def _getPayload ( self , record ) : try : d = record . __dict__ pid = d . pop ( 'process' , 'nopid' ) tid = d . pop ( 'thread' , 'notid' ) payload = { k : v for ( k , v ) in d . items ( ) if k in TOP_KEYS } payload [ 'meta' ] = { k : v for ( k , v ) in d . items ( ) if k in META_KEYS } payload [ 'details' ] = { k : simple_json ( v ) for ( k , v ) in d . items ( ) if k not in self . detail_ignore_set } payload [ 'log' ] = payload . pop ( 'name' , 'n/a' ) payload [ 'level' ] = payload . pop ( 'levelname' , 'n/a' ) payload [ 'meta' ] [ 'line' ] = payload [ 'meta' ] . pop ( 'lineno' , 'n/a' ) payload [ 'message' ] = record . getMessage ( ) tb = self . _getTraceback ( record ) if tb : payload [ 'traceback' ] = tb except Exception as e : payload = { 'level' : 'ERROR' , 'message' : 'could not format' , 'exception' : repr ( e ) , } payload [ 'pid' ] = 'p-{}' . format ( pid ) payload [ 'tid' ] = 't-{}' . format ( tid ) return payload | The data that will be sent to the RESTful API |
50,846 | def _getEndpoint ( self , add_tags = None ) : return 'https://logs-01.loggly.com/bulk/{0}/tag/{1}/' . format ( self . custom_token , self . _implodeTags ( add_tags = add_tags ) ) | Override Build Loggly s RESTful API endpoint |
50,847 | def _getPayload ( self , record ) : payload = super ( LogglyHandler , self ) . _getPayload ( record ) payload [ 'tags' ] = self . _implodeTags ( ) return payload | The data that will be sent to loggly . |
50,848 | def nonver_name ( self ) : nv = self . as_version ( None ) if not nv : import re nv = re . sub ( r'-[^-]+$' , '' , self . name ) return nv | Return the non versioned name |
50,849 | def set_wrappable_term ( self , v , term ) : import textwrap for t in self [ 'Root' ] . find ( term ) : self . remove_term ( t ) for l in textwrap . wrap ( v , 80 ) : self [ 'Root' ] . new_term ( term , l ) | Set the Root . Description possibly splitting long descriptions across multiple terms . |
50,850 | def get_lib_module_dict ( self ) : from importlib import import_module if not self . ref : return { } u = parse_app_url ( self . ref ) if u . scheme == 'file' : if not self . set_sys_path ( ) : return { } for module_name in self . lib_dir_names : try : m = import_module ( module_name ) return { k : v for k , v in m . __dict__ . items ( ) if not k . startswith ( '__' ) } except ModuleNotFoundError as e : if not module_name in str ( e ) : raise continue else : return { } | Load the lib directory as a python module so it can be used to provide functions for rowpipe transforms . This only works filesystem packages |
50,851 | def _repr_html_ ( self , ** kwargs ) : from jinja2 import Template from markdown import markdown as convert_markdown extensions = [ 'markdown.extensions.extra' , 'markdown.extensions.admonition' ] return convert_markdown ( self . markdown , extensions ) | Produce HTML for Jupyter Notebook |
50,852 | def write_csv ( self , path = None ) : self . sort_sections ( [ 'Root' , 'Contacts' , 'Documentation' , 'References' , 'Resources' , 'Citations' , 'Schema' ] ) if self . description : self . description = self . description if self . abstract : self . description = self . abstract t = self [ 'Root' ] . get_or_new_term ( 'Root.Modified' ) t . value = datetime_now ( ) self . sort_by_term ( ) return super ( ) . write_csv ( str ( path ) ) | Write CSV file . Sorts the sections before calling the superclass write_csv |
50,853 | def dimensions_wizard ( ) : option = yield MultipleChoice ( "What type of SpiNNaker system to you have?" , [ "A single four-chip 'SpiNN-3' board" , "A single forty-eight-chip 'SpiNN-5' board" , "Multiple forty-eight-chip 'SpiNN-5' boards" , "Other" ] , None ) assert 0 <= option < 4 if option == 0 : raise Success ( { "dimensions" : ( 2 , 2 ) } ) elif option == 1 : raise Success ( { "dimensions" : ( 8 , 8 ) } ) elif option == 2 : num_boards = yield Text ( "How many 'SpiNN-5' boards are in the system?" ) try : w , h = standard_system_dimensions ( int ( num_boards ) ) except ValueError : raise Failure ( "'{}' is not a valid number of boards." . format ( num_boards ) ) raise Success ( { "dimensions" : ( w , h ) } ) else : dimensions = yield Text ( "What are the dimensions of the network in chips (e.g. 24x12)?" ) match = re . match ( r"\s*(\d+)\s*[xX]\s*(\d+)\s*" , dimensions ) if not match : raise Failure ( "'{}' is not a valid system size." . format ( dimensions ) ) else : w = int ( match . group ( 1 ) ) h = int ( match . group ( 2 ) ) raise Success ( { "dimensions" : ( w , h ) } ) | A wizard which attempts to determine the dimensions of a SpiNNaker system . |
50,854 | def ip_address_wizard ( ) : option = yield MultipleChoice ( "Would you like to auto-detect the SpiNNaker system's IP address?" , [ "Auto-detect" , "Manually Enter IP address or hostname" ] , 0 ) assert 0 <= option < 2 if option == 0 : yield Prompt ( "Make sure the SpiNNaker system is switched on and is not booted." ) yield Info ( "Discovering attached SpiNNaker systems..." ) ip_address = listen ( ) if ip_address is None : raise Failure ( "Did not discover a locally connected SpiNNaker system." ) elif option == 1 : ip_address = yield Text ( "What is the IP address or hostname of the SpiNNaker system?" ) if ip_address == "" : raise Failure ( "No IP address or hostname entered" ) raise Success ( { "ip_address" : ip_address } ) | A wizard which attempts to determine the IP of a SpiNNaker system . |
50,855 | def cat ( * wizards ) : data = { } for wizard in wizards : try : response = None while True : response = yield wizard . send ( response ) except Success as s : data . update ( s . data ) raise Success ( data ) | A higher - order wizard which is the concatenation of a number of other wizards . |
50,856 | def cli_wrapper ( generator ) : first = True response = None while True : if not first : print ( ) first = False try : message = generator . send ( response ) if isinstance ( message , MultipleChoice ) : print ( message . question ) for num , choice in enumerate ( message . options ) : print ( " {}: {}" . format ( num , choice ) ) option = input ( "Select an option 0-{}{}: " . format ( len ( message . options ) - 1 , " (default: {})" . format ( message . default ) if message . default is not None else "" ) ) if option == "" and message . default is not None : option = message . default try : response = int ( option ) except ValueError : response = - 1 if not ( 0 <= response < len ( message . options ) ) : print ( "ERROR: {} is not a valid option." . format ( option ) ) return None elif isinstance ( message , Text ) : print ( message . question ) response = input ( "> " ) elif isinstance ( message , Prompt ) : print ( message . message ) input ( "<Press enter to continue>" ) response = None elif isinstance ( message , Info ) : print ( message . message ) response = None except Failure as f : print ( "ERROR: {}" . format ( str ( f ) ) ) return None except Success as s : return s . data | Given a wizard implements an interactive command - line human - friendly interface for it . |
50,857 | def _net_cost ( net , placements , has_wrap_around_links , machine ) : if has_wrap_around_links : x , y = placements [ net . source ] num_vertices = len ( net . sinks ) + 1 xs = [ x ] * num_vertices ys = [ y ] * num_vertices i = 1 for v in net . sinks : x , y = placements [ v ] xs [ i ] = x ys [ i ] = y i += 1 xs . sort ( ) ys . sort ( ) x_max_delta = 0 last_x = xs [ - 1 ] - machine . width for x in xs : delta = x - last_x last_x = x if delta > x_max_delta : x_max_delta = delta y_max_delta = 0 last_y = ys [ - 1 ] - machine . height for y in ys : delta = y - last_y last_y = y if delta > y_max_delta : y_max_delta = delta return ( ( ( machine . width - x_max_delta ) + ( machine . height - y_max_delta ) ) * net . weight * math . sqrt ( len ( net . sinks ) + 1 ) ) else : x1 , y1 = x2 , y2 = placements [ net . source ] for vertex in net . sinks : x , y = placements [ vertex ] x1 = x if x < x1 else x1 y1 = y if y < y1 else y1 x2 = x if x > x2 else x2 y2 = y if y > y2 else y2 return ( ( ( x2 - x1 ) + ( y2 - y1 ) ) * float ( net . weight ) * math . sqrt ( len ( net . sinks ) + 1 ) ) | Get the cost of a given net . |
50,858 | def _vertex_net_cost ( vertex , v2n , placements , has_wrap_around_links , machine ) : total_cost = 0.0 for net in v2n [ vertex ] : total_cost += _net_cost ( net , placements , has_wrap_around_links , machine ) return total_cost | Get the total cost of the nets connected to the given vertex . |
50,859 | def _get_candidate_swap ( resources , location , l2v , vertices_resources , fixed_vertices , machine ) : chip_resources = machine [ location ] vertices = l2v [ location ] to_move = [ ] i = 0 while overallocated ( subtract_resources ( chip_resources , resources ) ) : if i >= len ( vertices ) : return None elif vertices [ i ] in fixed_vertices : i += 1 continue else : vertex = vertices [ i ] chip_resources = add_resources ( chip_resources , vertices_resources [ vertex ] ) to_move . append ( vertex ) i += 1 return to_move | Given a chip location select a set of vertices which would have to be moved elsewhere to accommodate the arrival of the specified set of resources . |
50,860 | def _swap ( vas , vas_location , vbs , vbs_location , l2v , vertices_resources , placements , machine ) : vas_location2v = l2v [ vas_location ] vbs_location2v = l2v [ vbs_location ] vas_resources = machine [ vas_location ] vbs_resources = machine [ vbs_location ] for va in vas : placements [ va ] = vbs_location vas_location2v . remove ( va ) vbs_location2v . append ( va ) resources = vertices_resources [ va ] vas_resources = add_resources ( vas_resources , resources ) vbs_resources = subtract_resources ( vbs_resources , resources ) for vb in vbs : placements [ vb ] = vas_location vbs_location2v . remove ( vb ) vas_location2v . append ( vb ) resources = vertices_resources [ vb ] vas_resources = subtract_resources ( vas_resources , resources ) vbs_resources = add_resources ( vbs_resources , resources ) machine [ vas_location ] = vas_resources machine [ vbs_location ] = vbs_resources | Swap the positions of two sets of vertices . |
50,861 | def _load_script ( self , filename : str ) -> Script : with open ( path . join ( here , 'redis_scripts' , filename ) , mode = 'rb' ) as f : script_data = f . read ( ) rv = self . _r . register_script ( script_data ) if script_data . startswith ( b'-- idempotency protected script' ) : self . _idempotency_protected_scripts . append ( rv ) return rv | Load a Lua script . |
50,862 | def main ( ) : neutron_config . register_agent_state_opts_helper ( CONF ) common_config . init ( sys . argv [ 1 : ] ) neutron_config . setup_logging ( ) hnv_agent = HNVAgent ( ) LOG . info ( "Agent initialized successfully, now running... " ) hnv_agent . daemon_loop ( ) | The entry point for the HNV Agent . |
50,863 | def send_scp ( self , buffer_size , x , y , p , cmd , arg1 = 0 , arg2 = 0 , arg3 = 0 , data = b'' , expected_args = 3 , timeout = 0.0 ) : class Callback ( object ) : def __init__ ( self ) : self . packet = None def __call__ ( self , packet ) : self . packet = SCPPacket . from_bytestring ( packet , n_args = expected_args ) callback = Callback ( ) packets = [ scpcall ( x , y , p , cmd , arg1 , arg2 , arg3 , data , callback , timeout ) ] self . send_scp_burst ( buffer_size , 1 , packets ) assert callback . packet is not None return callback . packet | Transmit a packet to the SpiNNaker machine and block until an acknowledgement is received . |
50,864 | def get_specification ( version : str ) -> Mapping [ str , Any ] : spec_dir = config [ "bel" ] [ "lang" ] [ "specifications" ] spec_dict = { } bel_versions = get_bel_versions ( ) if version not in bel_versions : log . error ( "Cannot get unknown version BEL specification" ) return { "error" : "unknown version of BEL" } version_underscored = version . replace ( "." , "_" ) json_fn = f"{spec_dir}/bel_v{version_underscored}.json" with open ( json_fn , "r" ) as f : spec_dict = json . load ( f ) return spec_dict | Get BEL Specification |
50,865 | def get_bel_versions ( ) -> List [ str ] : spec_dir = config [ "bel" ] [ "lang" ] [ "specifications" ] fn = f"{spec_dir}/versions.json" with open ( fn , "r" ) as f : versions = json . load ( f ) return versions | Get BEL Language versions supported |
50,866 | def update_specifications ( force : bool = False ) : spec_dir = config [ "bel" ] [ "lang" ] [ "specifications" ] if not os . path . isdir ( spec_dir ) : os . mkdir ( spec_dir ) log . info ( f"Updating BEL Specifications - stored in {spec_dir}" ) if config [ "bel" ] [ "lang" ] [ "specification_github_repo" ] : github_belspec_files ( spec_dir , force = force ) files = glob . glob ( f"{spec_dir}/*.yml" ) for fn in files : new_fn = fn . replace ( "yml" , "yaml" ) os . rename ( fn , new_fn ) files = glob . glob ( f"{spec_dir}/*.yaml" ) versions = { } for fn in files : filename = os . path . basename ( fn ) check_version = filename . replace ( "bel_v" , "" ) . replace ( ".yaml" , "" ) . replace ( "_" , "." ) json_fn = fn . replace ( ".yaml" , ".json" ) version = belspec_yaml2json ( fn , json_fn ) if version != check_version : log . error ( f"Version mis-match for {fn} - fn version: {check_version} version: {version}" ) versions [ version ] = filename with open ( f"{spec_dir}/versions.json" , "w" ) as f : json . dump ( list ( set ( versions ) ) , f , indent = 4 ) create_ebnf_parser ( files ) | Update BEL specifications |
50,867 | def github_belspec_files ( spec_dir , force : bool = False ) : if not force : dtnow = datetime . datetime . utcnow ( ) delta = datetime . timedelta ( 1 ) yesterday = dtnow - delta for fn in glob . glob ( f"{spec_dir}/bel*yaml" ) : if datetime . datetime . fromtimestamp ( os . path . getmtime ( fn ) ) > yesterday : log . info ( "Skipping BEL Specification update - specs less than 1 day old" ) return repo_url = "https://api.github.com/repos/belbio/bel_specifications/contents/specifications" params = { } github_access_token = os . getenv ( "GITHUB_ACCESS_TOKEN" , "" ) if github_access_token : params = { "access_token" : github_access_token } r = requests . get ( repo_url , params = params ) if r . status_code == 200 : results = r . json ( ) for f in results : url = f [ "download_url" ] fn = os . path . basename ( url ) if "yaml" not in fn and "yml" in fn : fn = fn . replace ( "yml" , "yaml" ) r = requests . get ( url , params = params , allow_redirects = True ) if r . status_code == 200 : open ( f"{spec_dir}/{fn}" , "wb" ) . write ( r . content ) else : sys . exit ( f"Could not get BEL Spec file {url} from Github -- Status: {r.status_code} Msg: {r.content}" ) else : sys . exit ( f"Could not get BEL Spec directory listing from Github -- Status: {r.status_code} Msg: {r.content}" ) | Get belspec files from Github repo |
50,868 | def belspec_yaml2json ( yaml_fn : str , json_fn : str ) -> str : try : spec_dict = yaml . load ( open ( yaml_fn , "r" ) . read ( ) , Loader = yaml . SafeLoader ) spec_dict [ "admin" ] = { } spec_dict [ "admin" ] [ "version_underscored" ] = spec_dict [ "version" ] . replace ( "." , "_" ) spec_dict [ "admin" ] [ "parser_fn" ] = yaml_fn . replace ( ".yaml" , "_parser.py" ) add_relations ( spec_dict ) add_functions ( spec_dict ) add_namespaces ( spec_dict ) enhance_function_signatures ( spec_dict ) add_function_signature_help ( spec_dict ) with open ( json_fn , "w" ) as f : json . dump ( spec_dict , f ) except Exception as e : log . error ( "Warning: BEL Specification {yaml_fn} could not be read. Cannot proceed." . format ( yaml_fn ) ) sys . exit ( ) return spec_dict [ "version" ] | Enhance BEL specification and save as JSON file |
50,869 | def add_relations ( spec_dict : Mapping [ str , Any ] ) -> Mapping [ str , Any ] : spec_dict [ "relations" ] [ "list" ] = [ ] spec_dict [ "relations" ] [ "list_short" ] = [ ] spec_dict [ "relations" ] [ "list_long" ] = [ ] spec_dict [ "relations" ] [ "to_short" ] = { } spec_dict [ "relations" ] [ "to_long" ] = { } for relation_name in spec_dict [ "relations" ] [ "info" ] : abbreviated_name = spec_dict [ "relations" ] [ "info" ] [ relation_name ] [ "abbreviation" ] spec_dict [ "relations" ] [ "list" ] . extend ( ( relation_name , abbreviated_name ) ) spec_dict [ "relations" ] [ "list_long" ] . append ( relation_name ) spec_dict [ "relations" ] [ "list_short" ] . append ( abbreviated_name ) spec_dict [ "relations" ] [ "to_short" ] [ relation_name ] = abbreviated_name spec_dict [ "relations" ] [ "to_short" ] [ abbreviated_name ] = abbreviated_name spec_dict [ "relations" ] [ "to_long" ] [ abbreviated_name ] = relation_name spec_dict [ "relations" ] [ "to_long" ] [ relation_name ] = relation_name return spec_dict | Add relation keys to spec_dict |
50,870 | def add_functions ( spec_dict : Mapping [ str , Any ] ) -> Mapping [ str , Any ] : spec_dict [ "functions" ] [ "list" ] = [ ] spec_dict [ "functions" ] [ "list_long" ] = [ ] spec_dict [ "functions" ] [ "list_short" ] = [ ] spec_dict [ "functions" ] [ "primary" ] = { } spec_dict [ "functions" ] [ "primary" ] [ "list_long" ] = [ ] spec_dict [ "functions" ] [ "primary" ] [ "list_short" ] = [ ] spec_dict [ "functions" ] [ "modifier" ] = { } spec_dict [ "functions" ] [ "modifier" ] [ "list_long" ] = [ ] spec_dict [ "functions" ] [ "modifier" ] [ "list_short" ] = [ ] spec_dict [ "functions" ] [ "to_short" ] = { } spec_dict [ "functions" ] [ "to_long" ] = { } for func_name in spec_dict [ "functions" ] [ "info" ] : abbreviated_name = spec_dict [ "functions" ] [ "info" ] [ func_name ] [ "abbreviation" ] spec_dict [ "functions" ] [ "list" ] . extend ( ( func_name , abbreviated_name ) ) spec_dict [ "functions" ] [ "list_long" ] . append ( func_name ) spec_dict [ "functions" ] [ "list_short" ] . append ( abbreviated_name ) if spec_dict [ "functions" ] [ "info" ] [ func_name ] [ "type" ] == "primary" : spec_dict [ "functions" ] [ "primary" ] [ "list_long" ] . append ( func_name ) spec_dict [ "functions" ] [ "primary" ] [ "list_short" ] . append ( abbreviated_name ) else : spec_dict [ "functions" ] [ "modifier" ] [ "list_long" ] . append ( func_name ) spec_dict [ "functions" ] [ "modifier" ] [ "list_short" ] . append ( abbreviated_name ) spec_dict [ "functions" ] [ "to_short" ] [ abbreviated_name ] = abbreviated_name spec_dict [ "functions" ] [ "to_short" ] [ func_name ] = abbreviated_name spec_dict [ "functions" ] [ "to_long" ] [ abbreviated_name ] = func_name spec_dict [ "functions" ] [ "to_long" ] [ func_name ] = func_name return spec_dict | Add function keys to spec_dict |
50,871 | def enhance_function_signatures ( spec_dict : Mapping [ str , Any ] ) -> Mapping [ str , Any ] : for func in spec_dict [ "functions" ] [ "signatures" ] : for i , sig in enumerate ( spec_dict [ "functions" ] [ "signatures" ] [ func ] [ "signatures" ] ) : args = sig [ "arguments" ] req_args = [ ] pos_args = [ ] opt_args = [ ] mult_args = [ ] for arg in args : if arg . get ( "multiple" , False ) : if arg [ "type" ] in [ "Function" , "Modifier" ] : mult_args . extend ( arg . get ( "values" , [ ] ) ) elif arg [ "type" ] in [ "StrArgNSArg" , "NSArg" , "StrArg" ] : mult_args . append ( arg [ "type" ] ) elif arg . get ( "optional" , False ) and arg . get ( "position" , False ) : if arg [ "type" ] in [ "Function" , "Modifier" ] : pos_args . append ( arg . get ( "values" , [ ] ) ) elif arg [ "type" ] in [ "StrArgNSArg" , "NSArg" , "StrArg" ] : pos_args . append ( arg [ "type" ] ) elif arg . get ( "optional" , False ) : if arg [ "type" ] in [ "Function" , "Modifier" ] : opt_args . extend ( arg . get ( "values" , [ ] ) ) elif arg [ "type" ] in [ "StrArgNSArg" , "NSArg" , "StrArg" ] : opt_args . append ( arg [ "type" ] ) else : if arg [ "type" ] in [ "Function" , "Modifier" ] : req_args . append ( arg . get ( "values" , [ ] ) ) elif arg [ "type" ] in [ "StrArgNSArg" , "NSArg" , "StrArg" ] : req_args . append ( arg [ "type" ] ) spec_dict [ "functions" ] [ "signatures" ] [ func ] [ "signatures" ] [ i ] [ "req_args" ] = copy . deepcopy ( req_args ) spec_dict [ "functions" ] [ "signatures" ] [ func ] [ "signatures" ] [ i ] [ "pos_args" ] = copy . deepcopy ( pos_args ) spec_dict [ "functions" ] [ "signatures" ] [ func ] [ "signatures" ] [ i ] [ "opt_args" ] = copy . deepcopy ( opt_args ) spec_dict [ "functions" ] [ "signatures" ] [ func ] [ "signatures" ] [ i ] [ "mult_args" ] = copy . deepcopy ( mult_args ) return spec_dict | Enhance function signatures |
50,872 | def create_ebnf_parser ( files ) : flag = False for belspec_fn in files : if config [ "bel" ] [ "lang" ] [ "specification_github_repo" ] : tmpl_fn = get_ebnf_template ( ) ebnf_fn = belspec_fn . replace ( ".yaml" , ".ebnf" ) if not os . path . exists ( ebnf_fn ) or os . path . getmtime ( belspec_fn ) > os . path . getmtime ( ebnf_fn ) : with open ( belspec_fn , "r" ) as f : belspec = yaml . load ( f , Loader = yaml . SafeLoader ) tmpl_dir = os . path . dirname ( tmpl_fn ) tmpl_basename = os . path . basename ( tmpl_fn ) bel_major_version = belspec [ "version" ] . split ( "." ) [ 0 ] env = jinja2 . Environment ( loader = jinja2 . FileSystemLoader ( tmpl_dir ) ) template = env . get_template ( tmpl_basename ) relations_list = [ ( relation , belspec [ "relations" ] [ "info" ] [ relation ] [ "abbreviation" ] ) for relation in belspec [ "relations" ] [ "info" ] ] relations_list = sorted ( list ( itertools . chain ( * relations_list ) ) , key = len , reverse = True ) functions_list = [ ( function , belspec [ "functions" ] [ "info" ] [ function ] [ "abbreviation" ] ) for function in belspec [ "functions" ] [ "info" ] if belspec [ "functions" ] [ "info" ] [ function ] [ "type" ] == "primary" ] functions_list = sorted ( list ( itertools . chain ( * functions_list ) ) , key = len , reverse = True ) modifiers_list = [ ( function , belspec [ "functions" ] [ "info" ] [ function ] [ "abbreviation" ] ) for function in belspec [ "functions" ] [ "info" ] if belspec [ "functions" ] [ "info" ] [ function ] [ "type" ] == "modifier" ] modifiers_list = sorted ( list ( itertools . chain ( * modifiers_list ) ) , key = len , reverse = True ) created_time = datetime . datetime . now ( ) . strftime ( "%B %d, %Y - %I:%M:%S%p" ) ebnf = template . render ( functions = functions_list , m_functions = modifiers_list , relations = relations_list , bel_version = belspec [ "version" ] , bel_major_version = bel_major_version , created_time = created_time , ) with open ( ebnf_fn , "w" ) as f : f . write ( ebnf ) parser_fn = ebnf_fn . replace ( ".ebnf" , "_parser.py" ) parser = tatsu . to_python_sourcecode ( ebnf , filename = parser_fn ) flag = True with open ( parser_fn , "wt" ) as f : f . write ( parser ) if flag : importlib . invalidate_caches ( ) | Create EBNF files and EBNF - based parsers |
50,873 | def get_function_help ( function : str , bel_spec : BELSpec ) : function_long = bel_spec [ "functions" ] [ "to_long" ] . get ( function ) function_help = [ ] if function_long : for signature in bel_spec [ "functions" ] [ "signatures" ] [ function_long ] [ "signatures" ] : function_help . append ( { "function_summary" : signature [ "argument_summary" ] , "argument_help" : signature [ "argument_help_listing" ] , "description" : bel_spec [ "functions" ] [ "info" ] [ function_long ] [ "description" ] , } ) return function_help | Get function_help given function name |
50,874 | def in_span ( loc : int , span : Span ) -> bool : if loc >= span [ 0 ] and loc <= span [ 1 ] : return True else : return False | Checks if loc is inside span |
50,875 | def relation_completions ( completion_text : str , bel_spec : BELSpec , bel_fmt : str , size : int ) -> list : if bel_fmt == "short" : relation_list = bel_spec [ "relations" ] [ "list_short" ] else : relation_list = bel_spec [ "relations" ] [ "list_long" ] matches = [ ] for r in relation_list : if re . match ( completion_text , r ) : matches . append ( r ) replace_list = [ ] for match in matches : highlight = match . replace ( completion_text , f"<em>{completion_text}</em>" ) replace_list . append ( { "replacement" : match , "label" : match , "highlight" : highlight , "type" : "Relation" , } ) return replace_list [ : size ] | Filter BEL relations by prefix |
50,876 | def function_completions ( completion_text : str , bel_spec : BELSpec , function_list : list , bel_fmt : str , size : int , ) -> list : if isinstance ( function_list , list ) : if bel_fmt in [ "short" , "medium" ] : function_list = [ bel_spec [ "functions" ] [ "to_short" ] [ fn ] for fn in function_list ] else : function_list = [ bel_spec [ "functions" ] [ "to_long" ] [ fn ] for fn in function_list ] elif bel_fmt in [ "short" , "medium" ] : function_list = bel_spec [ "functions" ] [ "primary" ] [ "list_short" ] else : function_list = bel_spec [ "functions" ] [ "primary" ] [ "list_long" ] matches = [ ] for f in function_list : escaped_completion_text = completion_text . replace ( r"(" , r"\(" ) . replace ( r")" , r"\)" ) log . debug ( f"Completion match: {escaped_completion_text} F: {f}" ) if re . match ( escaped_completion_text , f ) : matches . append ( f ) replace_list = [ ] for match in matches : if completion_text : highlight = match . replace ( completion_text , f"<em>{completion_text}</em>" ) else : highlight = completion_text replace_list . append ( { "replacement" : match , "label" : f"{match}()" , "highlight" : highlight , "type" : "Function" , } ) return replace_list [ : size ] | Filter BEL functions by prefix |
50,877 | def add_completions ( replace_list : list , belstr : str , replace_span : Span , completion_text : str ) -> List [ Mapping [ str , Any ] ] : completions = [ ] for r in replace_list : if len ( belstr ) > 0 : belstr_end = len ( belstr ) - 1 else : belstr_end = 0 log . debug ( f'Replace list {r} Replace_span {replace_span} BELstr: {belstr} Len: {belstr_end} Test1 {r["type"] == "Function"} Test2 {replace_span[1] + 1 == len(belstr)}' ) if ( r [ "type" ] == "Function" and replace_span [ 0 ] > 0 and belstr [ replace_span [ 0 ] - 1 ] == "," ) : log . debug ( "prior char is a comma" ) replacement = ( belstr [ 0 : replace_span [ 0 ] ] + " " + f"{r['replacement']}()" + belstr [ replace_span [ 1 ] + 1 : ] ) cursor_loc = len ( belstr [ 0 : replace_span [ 0 ] ] + " " + f"{r['replacement']}()" ) elif replace_span [ 0 ] > 0 and belstr [ replace_span [ 0 ] - 1 ] == "," : log . debug ( "prior char is a comma" ) replacement = ( belstr [ 0 : replace_span [ 0 ] ] + " " + r [ "replacement" ] + belstr [ replace_span [ 1 ] + 1 : ] ) cursor_loc = len ( belstr [ 0 : replace_span [ 0 ] ] + " " + r [ "replacement" ] ) elif r [ "type" ] == "Function" and replace_span [ 1 ] >= belstr_end : replacement = belstr [ 0 : replace_span [ 0 ] ] + f"{r['replacement']}()" cursor_loc = len ( replacement ) - 1 log . debug ( f"Replacement: {replacement}" ) else : replacement = ( belstr [ 0 : replace_span [ 0 ] ] + r [ "replacement" ] + belstr [ replace_span [ 1 ] + 1 : ] ) cursor_loc = len ( belstr [ 0 : replace_span [ 0 ] ] + r [ "replacement" ] ) completions . append ( { "replacement" : replacement , "cursor_loc" : cursor_loc , "highlight" : r [ "highlight" ] , "label" : r [ "label" ] , } ) return completions | Create completions to return given replacement list |
50,878 | def get_completions ( belstr : str , cursor_loc : int , bel_spec : BELSpec , bel_comp : str , bel_fmt : str , species_id : str , size : int , ) : ast , errors = pparse . get_ast_dict ( belstr ) spans = pparse . collect_spans ( ast ) completion_text = "" completions = [ ] function_help = [ ] log . debug ( f"Cursor location BELstr: {belstr} Cursor idx: {cursor_loc}" ) cursor_results = cursor ( belstr , ast , cursor_loc ) log . debug ( f"Cursor results: {cursor_results}" ) if not cursor_results : log . debug ( "Cursor results is empty" ) return ( completion_text , completions , function_help , spans ) completion_text = cursor_results . get ( "completion_text" , "" ) replace_span = cursor_results [ "replace_span" ] namespace = cursor_results . get ( "namespace" , None ) if "parent_function" in cursor_results : parent_function = cursor_results [ "parent_function" ] function_help = bel_specification . get_function_help ( cursor_results [ "parent_function" ] , bel_spec ) args = cursor_results . get ( "args" , [ ] ) arg_idx = cursor_results . get ( "arg_idx" ) replace_list = arg_completions ( completion_text , parent_function , args , arg_idx , bel_spec , bel_fmt , species_id , namespace , size , ) elif cursor_results [ "type" ] == "Function" : function_list = None replace_list = function_completions ( completion_text , bel_spec , function_list , bel_fmt , size ) elif cursor_results [ "type" ] == "Relation" : replace_list = relation_completions ( completion_text , bel_spec , bel_fmt , size ) completions . extend ( add_completions ( replace_list , belstr , replace_span , completion_text ) ) return completion_text , completions , function_help , spans | Get BEL Assertion completions |
50,879 | def parse_functions ( bels : list , char_locs : CharLocs , parsed : Parsed , errors : Errors ) -> Tuple [ Parsed , Errors ] : parens = char_locs [ "parens" ] if not parens : bels_len = len ( bels ) - 1 span = ( 0 , bels_len ) parsed [ span ] = { "name" : "" . join ( bels ) , "type" : "Function" , "span" : span , "name_span" : ( span ) , "function_level" : "top" , } return parsed , errors for sp in sorted ( parens ) : ep , function_level = parens [ sp ] if bels [ sp - 1 ] == " " : continue for i in range ( sp - 1 , 0 , - 1 ) : if bels [ i ] in [ " " , "," , "(" ] : if i < sp - 1 : if ep == - 1 : span = ( i + 1 , len ( bels ) - 1 ) else : span = ( i + 1 , ep ) parsed [ span ] = { "name" : "" . join ( bels [ i + 1 : sp ] ) , "type" : "Function" , "span" : span , "name_span" : ( i + 1 , sp - 1 ) , "parens_span" : ( sp , ep ) , "function_level" : function_level , } break else : if ep == - 1 : span = ( 0 , len ( bels ) - 1 ) else : span = ( 0 , ep ) parsed [ span ] = { "name" : "" . join ( bels [ 0 : sp ] ) , "type" : "Function" , "span" : span , "name_span" : ( 0 , sp - 1 ) , "parens_span" : ( sp , ep ) , "function_level" : function_level , } return parsed , errors | Parse functions from BEL using paren comma quote character locations |
50,880 | def parse_args ( bels : list , char_locs : CharLocs , parsed : Parsed , errors : Errors ) -> Tuple [ Parsed , Errors ] : commas = char_locs [ "commas" ] for span in parsed : if parsed [ span ] [ "type" ] != "Function" or "parens_span" not in parsed [ span ] : continue sp , ep = parsed [ span ] [ "parens_span" ] if ep == - 1 : args_end = len ( bels ) - 1 else : args_end = ep - 1 args = [ ] arg_start = sp + 1 each_arg_end_list = sorted ( [ end - 1 for end in commas . get ( sp , [ ] ) ] + [ args_end ] ) for arg_end in each_arg_end_list : while arg_start < args_end and bels [ arg_start ] == " " : arg_start += 1 trimmed_arg_end = arg_end while trimmed_arg_end > arg_start and bels [ trimmed_arg_end ] == " " : trimmed_arg_end -= 1 if trimmed_arg_end < arg_start : trimmed_arg_end = arg_start arg = "" . join ( bels [ arg_start : trimmed_arg_end + 1 ] ) args . append ( { "arg" : arg , "span" : ( arg_start , trimmed_arg_end ) } ) arg_start = arg_end + 2 parsed [ span ] [ "args" ] = args return parsed , errors | Parse arguments from functions |
50,881 | def arg_types ( parsed : Parsed , errors : Errors ) -> Tuple [ Parsed , Errors ] : func_pattern = re . compile ( r"\s*[a-zA-Z]+\(" ) nsarg_pattern = re . compile ( r"^\s*([A-Z]+):(.*?)\s*$" ) for span in parsed : if parsed [ span ] [ "type" ] != "Function" or "parens_span" not in parsed [ span ] : continue for i , arg in enumerate ( parsed [ span ] [ "args" ] ) : nsarg_matches = nsarg_pattern . match ( arg [ "arg" ] ) if func_pattern . match ( arg [ "arg" ] ) : parsed [ span ] [ "args" ] [ i ] . update ( { "type" : "Function" } ) elif nsarg_matches : ( start , end ) = arg [ "span" ] ns = nsarg_matches . group ( 1 ) ns_val = nsarg_matches . group ( 2 ) ns_span = nsarg_matches . span ( 1 ) ns_span = ( ns_span [ 0 ] + start , ns_span [ 1 ] + start - 1 ) ns_val_span = nsarg_matches . span ( 2 ) ns_val_span = ( ns_val_span [ 0 ] + start , ns_val_span [ 1 ] + start - 1 ) parsed [ span ] [ "args" ] [ i ] . update ( { "type" : "NSArg" , "ns" : ns , "ns_span" : ns_span , "ns_val" : ns_val , "ns_val_span" : ns_val_span , } ) else : parsed [ span ] [ "args" ] [ i ] . update ( { "type" : "StrArg" } ) return parsed , errors | Add argument types to parsed function data structure |
50,882 | def parse_relations ( belstr : str , char_locs : CharLocs , parsed : Parsed , errors : Errors ) -> Tuple [ Parsed , Errors ] : quotes = char_locs [ "quotes" ] quoted_range = set ( [ i for start , end in quotes . items ( ) for i in range ( start , end ) ] ) for match in relations_pattern_middle . finditer ( belstr ) : ( start , end ) = match . span ( 1 ) end = end - 1 if start != end : test_range = set ( range ( start , end ) ) else : test_range = set ( start ) if test_range . intersection ( quoted_range ) : continue span_key = ( start , end ) parsed [ span_key ] = { "type" : "Relation" , "name" : match . group ( 1 ) , "span" : ( start , end ) , } for match in relations_pattern_end . finditer ( belstr ) : ( start , end ) = match . span ( 1 ) log . debug ( f"Relation-end {match}" ) end = end - 1 if start != end : test_range = set ( range ( start , end ) ) else : test_range = set ( start ) if test_range . intersection ( quoted_range ) : continue span_key = ( start , end ) parsed [ span_key ] = { "type" : "Relation" , "name" : match . group ( 1 ) , "span" : ( start , end ) , } return parsed , errors | Parse relations from BEL string |
50,883 | def parse_nested ( bels : list , char_locs : CharLocs , parsed : Parsed , errors : Errors ) -> Tuple [ Parsed , Errors ] : for sp in char_locs [ "nested_parens" ] : ep , level = char_locs [ "nested_parens" ] [ sp ] if ep == - 1 : ep = len ( bels ) + 1 parsed [ ( sp , ep ) ] = { "type" : "Nested" , "span" : ( sp , ep ) } return parsed , errors | Parse nested BEL object |
50,884 | def dump_json ( d : dict ) -> None : import json k = d . keys ( ) v = d . values ( ) k1 = [ str ( i ) for i in k ] return json . dumps ( dict ( zip ( * [ k1 , v ] ) ) , indent = 4 ) | Dump json when using tuples for dictionary keys |
50,885 | def collect_spans ( ast : AST ) -> List [ Tuple [ str , Tuple [ int , int ] ] ] : spans = [ ] if ast . get ( "subject" , False ) : spans . extend ( collect_spans ( ast [ "subject" ] ) ) if ast . get ( "object" , False ) : spans . extend ( collect_spans ( ast [ "object" ] ) ) if ast . get ( "nested" , False ) : spans . extend ( collect_spans ( ast [ "nested" ] ) ) if ast . get ( "function" , False ) : log . debug ( f"Processing function" ) spans . append ( ( "Function" , ast [ "function" ] [ "name_span" ] ) ) log . debug ( f"Spans: {spans}" ) if ast . get ( "args" , False ) : for idx , arg in enumerate ( ast [ "args" ] ) : log . debug ( f"Arg {arg}" ) if arg . get ( "function" , False ) : log . debug ( f"Recursing on arg function" ) results = collect_spans ( arg ) log . debug ( f"Results {results}" ) spans . extend ( results ) elif arg . get ( "nsarg" , False ) : log . debug ( f"Processing NSArg Arg {arg}" ) spans . append ( ( "NSArg" , arg [ "span" ] ) ) spans . append ( ( "NSPrefix" , arg [ "nsarg" ] [ "ns_span" ] ) ) spans . append ( ( "NSVal" , arg [ "nsarg" ] [ "ns_val_span" ] ) ) elif arg [ "type" ] == "StrArg" : spans . append ( ( "StrArg" , arg [ "span" ] ) ) log . debug ( f"Spans: {spans}" ) return spans | Collect flattened list of spans of BEL syntax types |
50,886 | def print_spans ( spans , max_idx : int ) -> None : bel_spans = [ " " ] * ( max_idx + 3 ) for val , span in spans : if val in [ "Nested" , "NSArg" ] : continue for i in range ( span [ 0 ] , span [ 1 ] + 1 ) : bel_spans [ i ] = val [ 0 ] bel_spans = [ " " ] * ( max_idx + 3 ) for val , span in spans : if val not in [ "Nested" ] : continue for i in range ( span [ 0 ] , span [ 1 ] + 1 ) : bel_spans [ i ] = val [ 0 ] | Quick test to show how character spans match original BEL String |
50,887 | def parsed_function_to_ast ( parsed : Parsed , parsed_key ) : sub = parsed [ parsed_key ] subtree = { "type" : "Function" , "span" : sub [ "span" ] , "function" : { "name" : sub [ "name" ] , "name_span" : sub [ "name_span" ] , "parens_span" : sub . get ( "parens_span" , [ ] ) , } , } args = [ ] for arg in parsed [ parsed_key ] . get ( "args" , [ ] ) : if arg [ "type" ] == "Function" : args . append ( parsed_function_to_ast ( parsed , arg [ "span" ] ) ) elif arg [ "type" ] == "NSArg" : args . append ( { "arg" : arg [ "arg" ] , "type" : arg [ "type" ] , "span" : arg [ "span" ] , "nsarg" : { "ns" : arg [ "ns" ] , "ns_val" : arg [ "ns_val" ] , "ns_span" : arg [ "ns_span" ] , "ns_val_span" : arg [ "ns_val_span" ] , } , } ) elif arg [ "type" ] == "StrArg" : args . append ( { "arg" : arg [ "arg" ] , "type" : arg [ "type" ] , "span" : arg [ "span" ] } ) subtree [ "args" ] = copy . deepcopy ( args ) return subtree | Create AST for top - level functions |
50,888 | def parsed_top_level_errors ( parsed , errors , component_type : str = "" ) -> Errors : fn_cnt = 0 rel_cnt = 0 nested_cnt = 0 for key in parsed : if parsed [ key ] [ "type" ] == "Function" : fn_cnt += 1 if parsed [ key ] [ "type" ] == "Relation" : rel_cnt += 1 if parsed [ key ] [ "type" ] == "Nested" : nested_cnt += 1 if not component_type : if nested_cnt > 1 : errors . append ( ( "Error" , "Too many nested objects - can only have one per BEL Assertion" , ) ) if nested_cnt : if rel_cnt > 2 : errors . append ( ( "Error" , "Too many relations - can only have two in a nested BEL Assertion" , ) ) elif fn_cnt > 4 : errors . append ( ( "Error" , "Too many BEL subject and object candidates" ) ) else : if rel_cnt > 1 : errors . append ( ( "Error" , "Too many relations - can only have one in a BEL Assertion" , ) ) elif fn_cnt > 2 : errors . append ( ( "Error" , "Too many BEL subject and object candidates" ) ) elif component_type == "subject" : if rel_cnt > 0 : errors . append ( ( "Error" , "Too many relations - cannot have any in a BEL Subject" ) ) elif fn_cnt > 1 : errors . append ( ( "Error" , "Too many BEL subject candidates - can only have one" ) ) elif component_type == "object" : if nested_cnt : if rel_cnt > 1 : errors . append ( ( "Error" , "Too many relations - can only have one in a nested BEL object" , ) ) elif fn_cnt > 2 : errors . append ( ( "Error" , "Too many BEL subject and object candidates in a nested BEL object" , ) ) else : if rel_cnt > 0 : errors . append ( ( "Error" , "Too many relations - cannot have any in a BEL Subject" ) ) elif fn_cnt > 1 : errors . append ( ( "Error" , "Too many BEL subject candidates - can only have one" ) ) return errors | Check full parse for errors |
50,889 | def parsed_to_ast ( parsed : Parsed , errors : Errors , component_type : str = "" ) : ast = { } sorted_keys = sorted ( parsed . keys ( ) ) for key in sorted_keys : if parsed [ key ] [ "type" ] == "Nested" : nested_component_stack = [ "subject" , "object" ] if component_type : component_stack = [ component_type ] else : component_stack = [ "subject" , "object" ] for key in sorted_keys : if parsed [ key ] [ "type" ] == "Function" and parsed [ key ] [ "function_level" ] == "top" : ast [ component_stack . pop ( 0 ) ] = parsed_function_to_ast ( parsed , key ) elif parsed [ key ] [ "type" ] == "Relation" and "relation" not in ast : ast [ "relation" ] = { "name" : parsed [ key ] [ "name" ] , "type" : "Relation" , "span" : key , } elif parsed [ key ] [ "type" ] == "Nested" : ast [ "nested" ] = { } for nested_key in sorted_keys : if nested_key <= key : continue if ( parsed [ nested_key ] [ "type" ] == "Function" and parsed [ nested_key ] [ "function_level" ] == "top" ) : ast [ "nested" ] [ nested_component_stack . pop ( 0 ) ] = parsed_function_to_ast ( parsed , nested_key ) elif ( parsed [ nested_key ] [ "type" ] == "Relation" and "relation" not in ast [ "nested" ] ) : ast [ "nested" ] [ "relation" ] = { "name" : parsed [ nested_key ] [ "name" ] , "type" : "Relation" , "span" : parsed [ nested_key ] [ "span" ] , } return ast , errors return ast , errors | Convert parsed data struct to AST dictionary |
50,890 | def get_ast_dict ( belstr , component_type : str = "" ) : errors = [ ] parsed = { } bels = list ( belstr ) char_locs , errors = parse_chars ( bels , errors ) parsed , errors = parse_functions ( belstr , char_locs , parsed , errors ) parsed , errors = parse_args ( bels , char_locs , parsed , errors ) parsed , errors = arg_types ( parsed , errors ) parsed , errors = parse_relations ( belstr , char_locs , parsed , errors ) parsed , errors = parse_nested ( bels , char_locs , parsed , errors ) errors = parsed_top_level_errors ( parsed , errors ) ast , errors = parsed_to_ast ( parsed , errors , component_type = component_type ) return ast , errors | Convert BEL string to AST dictionary |
50,891 | def get_ast_obj ( belstr , bel_version , component_type : str = "" ) : ast_dict , errors = get_ast_dict ( belstr , component_type ) spec = bel_specification . get_specification ( bel_version ) subj = ast_dict [ "subject" ] subj_ast = add_ast_fn ( subj , spec ) relation = None obj = None if "relation" in ast_dict : relation = ast_dict [ "relation" ] [ "name" ] if "object" in ast_dict : obj = ast_dict [ "object" ] obj_ast = add_ast_fn ( obj , spec ) return BELAst ( subj_ast , relation , obj_ast , spec ) elif "nested" in ast_dict : nested_subj = ast_dict [ "nested" ] [ "subject" ] nested_subj_ast = add_ast_fn ( nested_subj , spec ) nested_relation = ast_dict [ "nested" ] [ "relation" ] [ "name" ] nested_obj = ast_dict [ "nested" ] [ "object" ] nested_obj_ast = add_ast_fn ( nested_obj , spec ) return BELAst ( subj_ast , relation , BELAst ( nested_subj_ast , nested_relation , nested_obj_ast , spec ) , spec , ) return BELAst ( subj_ast , None , None , spec ) | Convert AST partialparse dict to BELAst |
50,892 | def add_ast_fn ( d , spec , parent_function = None ) : if d [ "type" ] == "Function" : ast_fn = Function ( d [ "function" ] [ "name" ] , spec , parent_function = parent_function ) for arg in d [ "args" ] : if arg [ "type" ] == "Function" : ast_fn . add_argument ( add_ast_fn ( arg , spec , parent_function = ast_fn ) ) elif arg [ "type" ] == "NSArg" : ast_fn . add_argument ( NSArg ( arg [ "nsarg" ] [ "ns" ] , arg [ "nsarg" ] [ "ns_val" ] , ast_fn ) ) elif arg [ "type" ] == "StrArg" : ast_fn . add_argument ( StrArg ( arg [ "arg" ] , ast_fn ) ) return ast_fn | Convert dict AST to object AST Function |
50,893 | def convert_namespaces_str ( bel_str : str , api_url : str = None , namespace_targets : Mapping [ str , List [ str ] ] = None , canonicalize : bool = False , decanonicalize : bool = False , ) -> str : matches = re . findall ( r'([A-Z]+:"(?:\\.|[^"\\])*"|[A-Z]+:(?:[^\),\s]+))' , bel_str ) for nsarg in matches : if "DEFAULT:" in nsarg : continue updated_nsarg = convert_nsarg ( nsarg , api_url = api_url , namespace_targets = namespace_targets , canonicalize = canonicalize , decanonicalize = decanonicalize , ) if updated_nsarg != nsarg : bel_str = bel_str . replace ( nsarg , updated_nsarg ) return bel_str | Convert namespace in string |
50,894 | def convert_namespaces_ast ( ast , api_url : str = None , namespace_targets : Mapping [ str , List [ str ] ] = None , canonicalize : bool = False , decanonicalize : bool = False , ) : if isinstance ( ast , NSArg ) : given_term_id = "{}:{}" . format ( ast . namespace , ast . value ) if ( canonicalize and not ast . canonical ) or ( decanonicalize and not ast . decanonical ) : normalized_term = convert_nsarg ( given_term_id , api_url = api_url , namespace_targets = namespace_targets , canonicalize = canonicalize , decanonicalize = decanonicalize , ) if canonicalize : ast . canonical = normalized_term elif decanonicalize : ast . decanonical = normalized_term if canonicalize : ns , value = ast . canonical . split ( ":" ) ast . change_nsvalue ( ns , value ) elif decanonicalize : ns , value = ast . canonical . split ( ":" ) ast . change_nsvalue ( ns , value ) if hasattr ( ast , "args" ) : for arg in ast . args : convert_namespaces_ast ( arg , api_url = api_url , namespace_targets = namespace_targets , canonicalize = canonicalize , decanonicalize = decanonicalize , ) return ast | Recursively convert namespaces of BEL Entities in BEL AST using API endpoint |
50,895 | def orthologize ( ast , bo , species_id : str ) : if not species_id : bo . validation_messages . append ( ( "WARNING" , "No species id was provided for orthologization" ) ) return ast if isinstance ( ast , NSArg ) : if ast . orthologs : if ast . orthologs . get ( species_id , None ) : orthologized_nsarg_val = ast . orthologs [ species_id ] [ "decanonical" ] ns , value = orthologized_nsarg_val . split ( ":" ) ast . change_nsvalue ( ns , value ) ast . canonical = ast . orthologs [ species_id ] [ "canonical" ] ast . decanonical = ast . orthologs [ species_id ] [ "decanonical" ] ast . orthologized = True bo . ast . species . add ( ( species_id , ast . orthologs [ species_id ] [ "species_label" ] ) ) else : bo . ast . species . add ( ( ast . species_id , ast . species_label ) ) bo . validation_messages . append ( ( "WARNING" , f"No ortholog found for {ast.namespace}:{ast.value}" ) ) elif ast . species_id : bo . ast . species . add ( ( ast . species_id , ast . species_label ) ) if hasattr ( ast , "args" ) : for arg in ast . args : orthologize ( arg , bo , species_id ) return ast | Recursively orthologize BEL Entities in BEL AST using API endpoint |
50,896 | def populate_ast_nsarg_orthologs ( ast , species ) : ortholog_namespace = "EG" if isinstance ( ast , NSArg ) : if re . match ( ortholog_namespace , ast . canonical ) : orthologs = bel . terms . orthologs . get_orthologs ( ast . canonical , list ( species . keys ( ) ) ) for species_id in species : if species_id in orthologs : orthologs [ species_id ] [ "species_label" ] = species [ species_id ] ast . orthologs = copy . deepcopy ( orthologs ) if hasattr ( ast , "args" ) : for arg in ast . args : populate_ast_nsarg_orthologs ( arg , species ) return ast | Recursively collect NSArg orthologs for BEL AST |
50,897 | def preprocess_bel_stmt ( stmt : str ) -> str : stmt = stmt . strip ( ) stmt = re . sub ( r",+" , "," , stmt ) stmt = re . sub ( r"," , ", " , stmt ) stmt = re . sub ( r" +" , " " , stmt ) return stmt | Clean up basic formatting of BEL statement |
50,898 | def _dump_spec ( spec ) : with open ( "spec.yaml" , "w" ) as f : yaml . dump ( spec , f , Dumper = MyDumper , default_flow_style = False ) | Dump bel specification dictionary using YAML |
50,899 | def process_rule ( edges : Edges , ast : Function , rule : Mapping [ str , Any ] , spec : BELSpec ) : ast_type = ast . __class__ . __name__ trigger_functions = rule . get ( "trigger_function" , [ ] ) trigger_types = rule . get ( "trigger_type" , [ ] ) rule_subject = rule . get ( "subject" ) rule_relation = rule . get ( "relation" ) rule_object = rule . get ( "object" ) log . debug ( f"Running {rule_relation} Type: {ast_type}" ) if isinstance ( ast , Function ) : function_name = ast . name args = ast . args parent_function = ast . parent_function if function_name in trigger_functions : if rule_subject == "trigger_value" : subject = ast if rule_object == "args" : for arg in args : log . debug ( f"1: {subject} {arg}" ) edge_ast = BELAst ( subject , rule_relation , arg , spec ) edges . append ( edge_ast ) elif rule_object == "parent_function" and parent_function : log . debug ( f"2: {subject} {parent_function}" ) edge_ast = BELAst ( subject , rule_relation , parent_function , spec ) edges . append ( edge_ast ) elif ast_type in trigger_types : if rule_subject == "trigger_value" : subject = ast if rule_object == "args" : for arg in args : log . debug ( f"3: {subject} {arg}" ) edge_ast = BELAst ( subject , rule_relation , arg , spec ) edges . append ( edge_ast ) elif rule_object == "parent_function" and parent_function : log . debug ( f"4: {subject} {parent_function}" ) edge_ast = BELAst ( subject , rule_relation , parent_function , spec ) edges . append ( edge_ast ) if isinstance ( ast , NSArg ) : term = "{}:{}" . format ( ast . namespace , ast . value ) parent_function = ast . parent_function if ast_type in trigger_types : if rule_subject == "trigger_value" : subject = term if rule_object == "args" : for arg in args : log . debug ( f"5: {subject} {arg}" ) edge_ast = BELAst ( subject , rule_relation , arg , spec ) edges . append ( edge_ast ) elif rule_object == "parent_function" and parent_function : log . debug ( f"6: {subject} {parent_function}" ) edge_ast = BELAst ( subject , rule_relation , parent_function , spec ) edges . append ( edge_ast ) if hasattr ( ast , "args" ) : for arg in ast . args : process_rule ( edges , arg , rule , spec ) | Process computed edge rule |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.