idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
40,500
def _GetEnableOsLoginValue ( self , metadata_dict ) : instance_data , project_data = self . _GetInstanceAndProjectAttributes ( metadata_dict ) instance_value = instance_data . get ( 'enable-oslogin' ) project_value = project_data . get ( 'enable-oslogin' ) value = instance_value or project_value or '' return value . lower ( ) == 'true'
Get the value of the enable - oslogin metadata key .
40,501
def HandleAccounts ( self , result ) : self . logger . debug ( 'Checking for changes to user accounts.' ) configured_users = self . utils . GetConfiguredUsers ( ) enable_oslogin = self . _GetEnableOsLoginValue ( result ) enable_two_factor = self . _GetEnableTwoFactorValue ( result ) if enable_oslogin : desired_users = { } self . oslogin . UpdateOsLogin ( True , two_factor_desired = enable_two_factor ) else : desired_users = self . _GetAccountsData ( result ) self . oslogin . UpdateOsLogin ( False ) remove_users = sorted ( set ( configured_users ) - set ( desired_users . keys ( ) ) ) self . _UpdateUsers ( desired_users ) self . _RemoveUsers ( remove_users ) self . utils . SetConfiguredUsers ( desired_users . keys ( ) )
Called when there are changes to the contents of the metadata server .
40,502
def _SetSELinuxContext ( path ) : restorecon = '/sbin/restorecon' if os . path . isfile ( restorecon ) and os . access ( restorecon , os . X_OK ) : subprocess . call ( [ restorecon , path ] )
Set the appropriate SELinux context if SELinux tools are installed .
40,503
def SetPermissions ( path , mode = None , uid = None , gid = None , mkdir = False ) : if mkdir and not os . path . exists ( path ) : os . mkdir ( path , mode or 0o777 ) elif mode : os . chmod ( path , mode ) if uid and gid : os . chown ( path , uid , gid ) _SetSELinuxContext ( path )
Set the permissions and ownership of a path .
40,504
def Lock ( fd , path , blocking ) : operation = fcntl . LOCK_EX if blocking else fcntl . LOCK_EX | fcntl . LOCK_NB try : fcntl . flock ( fd , operation ) except IOError as e : if e . errno == errno . EWOULDBLOCK : raise IOError ( 'Exception locking %s. File already locked.' % path ) else : raise IOError ( 'Exception locking %s. %s.' % ( path , str ( e ) ) )
Lock the provided file descriptor .
40,505
def Unlock ( fd , path ) : try : fcntl . flock ( fd , fcntl . LOCK_UN | fcntl . LOCK_NB ) except IOError as e : if e . errno == errno . EWOULDBLOCK : raise IOError ( 'Exception unlocking %s. Locked by another process.' % path ) else : raise IOError ( 'Exception unlocking %s. %s.' % ( path , str ( e ) ) )
Release the lock on the file .
40,506
def LockFile ( path , blocking = False ) : fd = os . open ( path , os . O_CREAT ) try : Lock ( fd , path , blocking ) yield finally : try : Unlock ( fd , path ) finally : os . close ( fd )
Interface to flock - based file locking to prevent concurrent executions .
40,507
def RetryOnUnavailable ( func ) : @ functools . wraps ( func ) def Wrapper ( * args , ** kwargs ) : while True : try : response = func ( * args , ** kwargs ) except ( httpclient . HTTPException , socket . error , urlerror . URLError ) as e : time . sleep ( 5 ) if ( isinstance ( e , urlerror . HTTPError ) and e . getcode ( ) == httpclient . SERVICE_UNAVAILABLE ) : continue elif isinstance ( e , socket . timeout ) : continue raise else : if response . getcode ( ) == httpclient . OK : return response else : raise StatusException ( response ) return Wrapper
Function decorator to retry on a service unavailable exception .
40,508
def _GetMetadataRequest ( self , metadata_url , params = None , timeout = None ) : headers = { 'Metadata-Flavor' : 'Google' } params = urlparse . urlencode ( params or { } ) url = '%s?%s' % ( metadata_url , params ) request = urlrequest . Request ( url , headers = headers ) request_opener = urlrequest . build_opener ( urlrequest . ProxyHandler ( { } ) ) timeout = timeout or self . timeout return request_opener . open ( request , timeout = timeout * 1.1 )
Performs a GET request with the metadata headers .
40,509
def _UpdateEtag ( self , response ) : etag = response . headers . get ( 'etag' , self . etag ) etag_updated = self . etag != etag self . etag = etag return etag_updated
Update the etag from an API response .
40,510
def _GetMetadataUpdate ( self , metadata_key = '' , recursive = True , wait = True , timeout = None ) : metadata_key = os . path . join ( metadata_key , '' ) if recursive else metadata_key metadata_url = os . path . join ( METADATA_SERVER , metadata_key ) params = { 'alt' : 'json' , 'last_etag' : self . etag , 'recursive' : recursive , 'timeout_sec' : timeout or self . timeout , 'wait_for_change' : wait , } while True : response = self . _GetMetadataRequest ( metadata_url , params = params , timeout = timeout ) etag_updated = self . _UpdateEtag ( response ) if wait and not etag_updated and not timeout : continue else : break return json . loads ( response . read ( ) . decode ( 'utf-8' ) )
Request the contents of metadata server and deserialize the response .
40,511
def _HandleMetadataUpdate ( self , metadata_key = '' , recursive = True , wait = True , timeout = None , retry = True ) : exception = None while True : try : return self . _GetMetadataUpdate ( metadata_key = metadata_key , recursive = recursive , wait = wait , timeout = timeout ) except ( httpclient . HTTPException , socket . error , urlerror . URLError ) as e : if not isinstance ( e , type ( exception ) ) : exception = e self . logger . error ( 'GET request error retrieving metadata. %s.' , e ) if retry : continue else : break
Wait for a successful metadata response .
40,512
def WatchMetadata ( self , handler , metadata_key = '' , recursive = True , timeout = None ) : while True : response = self . _HandleMetadataUpdate ( metadata_key = metadata_key , recursive = recursive , wait = True , timeout = timeout ) try : handler ( response ) except Exception as e : self . logger . exception ( 'Exception calling the response handler. %s.' , e )
Watch for changes to the contents of the metadata server .
40,513
def GetMetadata ( self , metadata_key = '' , recursive = True , timeout = None , retry = True ) : return self . _HandleMetadataUpdate ( metadata_key = metadata_key , recursive = recursive , wait = False , timeout = timeout , retry = retry )
Retrieve the contents of metadata server for a metadata key .
40,514
def _LogForwardedIpChanges ( self , configured , desired , to_add , to_remove , interface ) : if not to_add and not to_remove : return self . logger . info ( 'Changing %s IPs from %s to %s by adding %s and removing %s.' , interface , configured or None , desired or None , to_add or None , to_remove or None )
Log the planned IP address changes .
40,515
def _AddForwardedIps ( self , forwarded_ips , interface ) : for address in forwarded_ips : self . ip_forwarding_utils . AddForwardedIp ( address , interface )
Configure the forwarded IP address on the network interface .
40,516
def _RemoveForwardedIps ( self , forwarded_ips , interface ) : for address in forwarded_ips : self . ip_forwarding_utils . RemoveForwardedIp ( address , interface )
Remove the forwarded IP addresses from the network interface .
40,517
def HandleForwardedIps ( self , interface , forwarded_ips , interface_ip = None ) : desired = self . ip_forwarding_utils . ParseForwardedIps ( forwarded_ips ) configured = self . ip_forwarding_utils . GetForwardedIps ( interface , interface_ip ) to_add = sorted ( set ( desired ) - set ( configured ) ) to_remove = sorted ( set ( configured ) - set ( desired ) ) self . _LogForwardedIpChanges ( configured , desired , to_add , to_remove , interface ) self . _AddForwardedIps ( to_add , interface ) self . _RemoveForwardedIps ( to_remove , interface )
Handle changes to the forwarded IPs on a network interface .
40,518
def _WriteIfcfg ( self , interfaces , logger ) : for interface in interfaces : interface_config = os . path . join ( self . network_path , 'ifcfg-%s' % interface ) interface_content = [ '# Added by Google.' , 'STARTMODE=hotplug' , 'BOOTPROTO=dhcp' , 'DHCLIENT_SET_DEFAULT_ROUTE=yes' , 'DHCLIENT_ROUTE_PRIORITY=10%s00' % interface , '' , ] with open ( interface_config , 'w' ) as interface_file : interface_file . write ( '\n' . join ( interface_content ) ) logger . info ( 'Created ifcfg file for interface %s.' , interface )
Write ifcfg files for multi - NIC support .
40,519
def _Ifup ( self , interfaces , logger ) : ifup = [ '/usr/sbin/wicked' , 'ifup' , '--timeout' , '1' ] try : subprocess . check_call ( ifup + interfaces ) except subprocess . CalledProcessError : logger . warning ( 'Could not activate interfaces %s.' , interfaces )
Activate network interfaces .
40,520
def HandleNetworkInterfaces ( self , result ) : network_interfaces = self . _ExtractInterfaceMetadata ( result ) if self . network_setup_enabled : self . network_setup . EnableNetworkInterfaces ( [ interface . name for interface in network_interfaces [ 1 : ] ] ) for interface in network_interfaces : if self . ip_forwarding_enabled : self . ip_forwarding . HandleForwardedIps ( interface . name , interface . forwarded_ips , interface . ip )
Called when network interface metadata changes .
40,521
def _ExtractInterfaceMetadata ( self , metadata ) : interfaces = [ ] for network_interface in metadata : mac_address = network_interface . get ( 'mac' ) interface = self . network_utils . GetNetworkInterface ( mac_address ) ip_addresses = [ ] if interface : ip_addresses . extend ( network_interface . get ( 'forwardedIps' , [ ] ) ) if self . ip_aliases : ip_addresses . extend ( network_interface . get ( 'ipAliases' , [ ] ) ) if self . target_instance_ips : ip_addresses . extend ( network_interface . get ( 'targetInstanceIps' , [ ] ) ) interfaces . append ( NetworkDaemon . NetworkInterface ( interface , ip_addresses , network_interface . get ( 'ip' , [ ] ) ) ) else : message = 'Network interface not found for MAC address: %s.' self . logger . warning ( message , mac_address ) return interfaces
Extracts network interface metadata .
40,522
def _build_url ( self , query_params ) : url = '' count = 0 while count < len ( self . _url_path ) : url += '/{}' . format ( self . _url_path [ count ] ) count += 1 if self . append_slash : url += '/' if query_params : url_values = urlencode ( sorted ( query_params . items ( ) ) , True ) url = '{}?{}' . format ( url , url_values ) if self . _version : url = self . _build_versioned_url ( url ) else : url = '{}{}' . format ( self . host , url ) return url
Build the final URL to be passed to urllib
40,523
def _build_client ( self , name = None ) : url_path = self . _url_path + [ name ] if name else self . _url_path return Client ( host = self . host , version = self . _version , request_headers = self . request_headers , url_path = url_path , append_slash = self . append_slash , timeout = self . timeout )
Make a new Client object
40,524
def _make_request ( self , opener , request , timeout = None ) : timeout = timeout or self . timeout try : return opener . open ( request , timeout = timeout ) except HTTPError as err : exc = handle_error ( err ) exc . __cause__ = None raise exc
Make the API call and return the response . This is separated into it s own function so we can mock it easily for testing .
40,525
def category ( msg ) : if common . typecode ( msg ) < 1 or common . typecode ( msg ) > 4 : raise RuntimeError ( "%s: Not a identification message" % msg ) msgbin = common . hex2bin ( msg ) return common . bin2int ( msgbin [ 5 : 8 ] )
Aircraft category number
40,526
def airborne_position ( msg0 , msg1 , t0 , t1 ) : mb0 = common . hex2bin ( msg0 ) [ 32 : ] mb1 = common . hex2bin ( msg1 ) [ 32 : ] cprlat_even = common . bin2int ( mb0 [ 22 : 39 ] ) / 131072.0 cprlon_even = common . bin2int ( mb0 [ 39 : 56 ] ) / 131072.0 cprlat_odd = common . bin2int ( mb1 [ 22 : 39 ] ) / 131072.0 cprlon_odd = common . bin2int ( mb1 [ 39 : 56 ] ) / 131072.0 air_d_lat_even = 360.0 / 60 air_d_lat_odd = 360.0 / 59 j = common . floor ( 59 * cprlat_even - 60 * cprlat_odd + 0.5 ) lat_even = float ( air_d_lat_even * ( j % 60 + cprlat_even ) ) lat_odd = float ( air_d_lat_odd * ( j % 59 + cprlat_odd ) ) if lat_even >= 270 : lat_even = lat_even - 360 if lat_odd >= 270 : lat_odd = lat_odd - 360 if common . cprNL ( lat_even ) != common . cprNL ( lat_odd ) : return None if ( t0 > t1 ) : lat = lat_even nl = common . cprNL ( lat ) ni = max ( common . cprNL ( lat ) - 0 , 1 ) m = common . floor ( cprlon_even * ( nl - 1 ) - cprlon_odd * nl + 0.5 ) lon = ( 360.0 / ni ) * ( m % ni + cprlon_even ) else : lat = lat_odd nl = common . cprNL ( lat ) ni = max ( common . cprNL ( lat ) - 1 , 1 ) m = common . floor ( cprlon_even * ( nl - 1 ) - cprlon_odd * nl + 0.5 ) lon = ( 360.0 / ni ) * ( m % ni + cprlon_odd ) if lon > 180 : lon = lon - 360 return round ( lat , 5 ) , round ( lon , 5 )
Decode airborn position from a pair of even and odd position message
40,527
def airborne_position_with_ref ( msg , lat_ref , lon_ref ) : mb = common . hex2bin ( msg ) [ 32 : ] cprlat = common . bin2int ( mb [ 22 : 39 ] ) / 131072.0 cprlon = common . bin2int ( mb [ 39 : 56 ] ) / 131072.0 i = int ( mb [ 21 ] ) d_lat = 360.0 / 59 if i else 360.0 / 60 j = common . floor ( lat_ref / d_lat ) + common . floor ( 0.5 + ( ( lat_ref % d_lat ) / d_lat ) - cprlat ) lat = d_lat * ( j + cprlat ) ni = common . cprNL ( lat ) - i if ni > 0 : d_lon = 360.0 / ni else : d_lon = 360.0 m = common . floor ( lon_ref / d_lon ) + common . floor ( 0.5 + ( ( lon_ref % d_lon ) / d_lon ) - cprlon ) lon = d_lon * ( m + cprlon ) return round ( lat , 5 ) , round ( lon , 5 )
Decode airborne position with only one message knowing reference nearby location such as previously calculated location ground station or airport location etc . The reference position shall be with in 180NM of the true position .
40,528
def hex2bin ( hexstr ) : num_of_bits = len ( hexstr ) * 4 binstr = bin ( int ( hexstr , 16 ) ) [ 2 : ] . zfill ( int ( num_of_bits ) ) return binstr
Convert a hexdecimal string to binary string with zero fillings .
40,529
def icao ( msg ) : DF = df ( msg ) if DF in ( 11 , 17 , 18 ) : addr = msg [ 2 : 8 ] elif DF in ( 0 , 4 , 5 , 16 , 20 , 21 ) : c0 = bin2int ( crc ( msg , encode = True ) ) c1 = hex2int ( msg [ - 6 : ] ) addr = '%06X' % ( c0 ^ c1 ) else : addr = None return addr
Calculate the ICAO address from an Mode - S message with DF4 DF5 DF20 DF21
40,530
def gray2int ( graystr ) : num = bin2int ( graystr ) num ^= ( num >> 8 ) num ^= ( num >> 4 ) num ^= ( num >> 2 ) num ^= ( num >> 1 ) return num
Convert greycode to binary
40,531
def allzeros ( msg ) : d = hex2bin ( data ( msg ) ) if bin2int ( d ) > 0 : return False else : return True
check if the data bits are all zeros
40,532
def wrongstatus ( data , sb , msb , lsb ) : status = int ( data [ sb - 1 ] ) value = bin2int ( data [ msb - 1 : lsb ] ) if not status : if value != 0 : return True return False
Check if the status bit and field bits are consistency . This Function is used for checking BDS code versions .
40,533
def version ( msg ) : tc = typecode ( msg ) if tc != 31 : raise RuntimeError ( "%s: Not a status operation message, expecting TC = 31" % msg ) msgbin = common . hex2bin ( msg ) version = common . bin2int ( msgbin [ 72 : 75 ] ) return version
ADS - B Version
40,534
def nic_v1 ( msg , NICs ) : if typecode ( msg ) < 5 or typecode ( msg ) > 22 : raise RuntimeError ( "%s: Not a surface position message (5<TC<8), \ airborne position message (8<TC<19), \ or airborne position with GNSS height (20<TC<22)" % msg ) tc = typecode ( msg ) NIC = uncertainty . TC_NICv1_lookup [ tc ] if isinstance ( NIC , dict ) : NIC = NIC [ NICs ] try : Rc = uncertainty . NICv1 [ NIC ] [ NICs ] [ 'Rc' ] VPL = uncertainty . NICv1 [ NIC ] [ NICs ] [ 'VPL' ] except KeyError : Rc , VPL = uncertainty . NA , uncertainty . NA return Rc , VPL
Calculate NIC navigation integrity category for ADS - B version 1
40,535
def nic_v2 ( msg , NICa , NICbc ) : if typecode ( msg ) < 5 or typecode ( msg ) > 22 : raise RuntimeError ( "%s: Not a surface position message (5<TC<8), \ airborne position message (8<TC<19), \ or airborne position with GNSS height (20<TC<22)" % msg ) tc = typecode ( msg ) NIC = uncertainty . TC_NICv2_lookup [ tc ] if 20 <= tc <= 22 : NICs = 0 else : NICs = NICa * 2 + NICbc try : if isinstance ( NIC , dict ) : NIC = NIC [ NICs ] Rc = uncertainty . NICv2 [ NIC ] [ NICs ] [ 'Rc' ] except KeyError : Rc = uncertainty . NA return Rc
Calculate NIC navigation integrity category for ADS - B version 2
40,536
def nic_s ( msg ) : tc = typecode ( msg ) if tc != 31 : raise RuntimeError ( "%s: Not a status operation message, expecting TC = 31" % msg ) msgbin = common . hex2bin ( msg ) nic_s = int ( msgbin [ 75 ] ) return nic_s
Obtain NIC supplement bit TC = 31 message
40,537
def nic_b ( msg ) : tc = typecode ( msg ) if tc < 9 or tc > 18 : raise RuntimeError ( "%s: Not a airborne position message, expecting 8<TC<19" % msg ) msgbin = common . hex2bin ( msg ) nic_b = int ( msgbin [ 39 ] ) return nic_b
Obtain NICb navigation integrity category supplement - b
40,538
def nac_p ( msg ) : tc = typecode ( msg ) if tc not in [ 29 , 31 ] : raise RuntimeError ( "%s: Not a target state and status message, \ or operation status message, expecting TC = 29 or 31" % msg ) msgbin = common . hex2bin ( msg ) if tc == 29 : NACp = common . bin2int ( msgbin [ 71 : 75 ] ) elif tc == 31 : NACp = common . bin2int ( msgbin [ 76 : 80 ] ) try : EPU = uncertainty . NACp [ NACp ] [ 'EPU' ] VEPU = uncertainty . NACp [ NACp ] [ 'VEPU' ] except KeyError : EPU , VEPU = uncertainty . NA , uncertainty . NA return EPU , VEPU
Calculate NACp Navigation Accuracy Category - Position
40,539
def nac_v ( msg ) : tc = typecode ( msg ) if tc != 19 : raise RuntimeError ( "%s: Not an airborne velocity message, expecting TC = 19" % msg ) msgbin = common . hex2bin ( msg ) NACv = common . bin2int ( msgbin [ 42 : 45 ] ) try : HFOMr = uncertainty . NACv [ NACv ] [ 'HFOMr' ] VFOMr = uncertainty . NACv [ NACv ] [ 'VFOMr' ] except KeyError : HFOMr , VFOMr = uncertainty . NA , uncertainty . NA return HFOMr , VFOMr
Calculate NACv Navigation Accuracy Category - Velocity
40,540
def sil ( msg , version ) : tc = typecode ( msg ) if tc not in [ 29 , 31 ] : raise RuntimeError ( "%s: Not a target state and status messag, \ or operation status message, expecting TC = 29 or 31" % msg ) msgbin = common . hex2bin ( msg ) if tc == 29 : SIL = common . bin2int ( msgbin [ 76 : 78 ] ) elif tc == 31 : SIL = common . bin2int ( msgbin [ 82 : 84 ] ) try : PE_RCu = uncertainty . SIL [ SIL ] [ 'PE_RCu' ] PE_VPL = uncertainty . SIL [ SIL ] [ 'PE_VPL' ] except KeyError : PE_RCu , PE_VPL = uncertainty . NA , uncertainty . NA base = 'unknown' if version == 2 : if tc == 29 : SIL_SUP = common . bin2int ( msgbin [ 39 ] ) elif tc == 31 : SIL_SUP = common . bin2int ( msgbin [ 86 ] ) if SIL_SUP == 0 : base = "hour" elif SIL_SUP == 1 : base = "sample" return PE_RCu , PE_VPL , base
Calculate SIL Surveillance Integrity Level
40,541
def roll50 ( msg ) : d = hex2bin ( data ( msg ) ) if d [ 0 ] == '0' : return None sign = int ( d [ 1 ] ) value = bin2int ( d [ 2 : 11 ] ) if sign : value = value - 512 angle = value * 45.0 / 256.0 return round ( angle , 1 )
Roll angle BDS 5 0 message
40,542
def trk50 ( msg ) : d = hex2bin ( data ( msg ) ) if d [ 11 ] == '0' : return None sign = int ( d [ 12 ] ) value = bin2int ( d [ 13 : 23 ] ) if sign : value = value - 1024 trk = value * 90.0 / 512.0 if trk < 0 : trk = 360 + trk return round ( trk , 3 )
True track angle BDS 5 0 message
40,543
def gs50 ( msg ) : d = hex2bin ( data ( msg ) ) if d [ 23 ] == '0' : return None spd = bin2int ( d [ 24 : 34 ] ) * 2 return spd
Ground speed BDS 5 0 message
40,544
def tas50 ( msg ) : d = hex2bin ( data ( msg ) ) if d [ 45 ] == '0' : return None tas = bin2int ( d [ 46 : 56 ] ) * 2 return tas
Aircraft true airspeed BDS 5 0 message
40,545
def ias53 ( msg ) : d = hex2bin ( data ( msg ) ) if d [ 12 ] == '0' : return None ias = bin2int ( d [ 13 : 23 ] ) return ias
Indicated airspeed DBS 5 3 message
40,546
def mach53 ( msg ) : d = hex2bin ( data ( msg ) ) if d [ 23 ] == '0' : return None mach = bin2int ( d [ 24 : 33 ] ) * 0.008 return round ( mach , 3 )
MACH number DBS 5 3 message
40,547
def tas53 ( msg ) : d = hex2bin ( data ( msg ) ) if d [ 33 ] == '0' : return None tas = bin2int ( d [ 34 : 46 ] ) * 0.5 return round ( tas , 1 )
Aircraft true airspeed BDS 5 3 message
40,548
def read_skysense_buffer ( self ) : SS_MSGLENGTH = 24 SS_STARTCHAR = 0x24 if len ( self . buffer ) <= SS_MSGLENGTH : return None messages = [ ] while len ( self . buffer ) > SS_MSGLENGTH : i = 0 if self . buffer [ i ] == SS_STARTCHAR and self . buffer [ i + SS_MSGLENGTH ] == SS_STARTCHAR : i += 1 if ( self . buffer [ i ] >> 7 ) : payload = self . buffer [ i : i + 14 ] else : payload = self . buffer [ i : i + 7 ] msg = '' . join ( '%02X' % j for j in payload ) i += 14 tsbin = self . buffer [ i : i + 6 ] sec = ( ( tsbin [ 0 ] & 0x7f ) << 10 ) | ( tsbin [ 1 ] << 2 ) | ( tsbin [ 2 ] >> 6 ) nano = ( ( tsbin [ 2 ] & 0x3f ) << 24 ) | ( tsbin [ 3 ] << 16 ) | ( tsbin [ 4 ] << 8 ) | tsbin [ 5 ] ts = sec + nano * 1.0e-9 i += 6 i += 3 self . buffer = self . buffer [ SS_MSGLENGTH : ] messages . append ( [ msg , ts ] ) else : self . buffer = self . buffer [ 1 : ] return messages
Skysense stream format .
40,549
def is10 ( msg ) : if allzeros ( msg ) : return False d = hex2bin ( data ( msg ) ) if d [ 0 : 8 ] != '00010000' : return False if bin2int ( d [ 9 : 14 ] ) != 0 : return False if d [ 14 ] == '1' and bin2int ( d [ 16 : 23 ] ) < 5 : return False if d [ 14 ] == '0' and bin2int ( d [ 16 : 23 ] ) > 4 : return False return True
Check if a message is likely to be BDS code 1 0
40,550
def is17 ( msg ) : if allzeros ( msg ) : return False d = hex2bin ( data ( msg ) ) if bin2int ( d [ 28 : 56 ] ) != 0 : return False caps = cap17 ( msg ) if 'BDS20' not in caps : return False return True
Check if a message is likely to be BDS code 1 7
40,551
def cap17 ( msg ) : allbds = [ '05' , '06' , '07' , '08' , '09' , '0A' , '20' , '21' , '40' , '41' , '42' , '43' , '44' , '45' , '48' , '50' , '51' , '52' , '53' , '54' , '55' , '56' , '5F' , '60' , 'NA' , 'NA' , 'E1' , 'E2' ] d = hex2bin ( data ( msg ) ) idx = [ i for i , v in enumerate ( d [ : 28 ] ) if v == '1' ] capacity = [ 'BDS' + allbds [ i ] for i in idx if allbds [ i ] is not 'NA' ] return capacity
Extract capacities from BDS 1 7 message
40,552
def get_aircraft ( self ) : acs = self . acs icaos = list ( acs . keys ( ) ) for icao in icaos : if acs [ icao ] [ 'lat' ] is None : acs . pop ( icao ) return acs
all aircraft that are stored in memeory
40,553
def altitude_diff ( msg ) : tc = common . typecode ( msg ) if tc != 19 : raise RuntimeError ( "%s: Not a airborne velocity message, expecting TC=19" % msg ) msgbin = common . hex2bin ( msg ) sign = - 1 if int ( msgbin [ 80 ] ) else 1 value = common . bin2int ( msgbin [ 81 : 88 ] ) if value == 0 or value == 127 : return None else : return sign * ( value - 1 ) * 25
Decode the differece between GNSS and barometric altitude
40,554
def is50or60 ( msg , spd_ref , trk_ref , alt_ref ) : def vxy ( v , angle ) : vx = v * np . sin ( np . radians ( angle ) ) vy = v * np . cos ( np . radians ( angle ) ) return vx , vy if not ( bds50 . is50 ( msg ) and bds60 . is60 ( msg ) ) : return None h50 = bds50 . trk50 ( msg ) v50 = bds50 . gs50 ( msg ) if h50 is None or v50 is None : return 'BDS50,BDS60' h60 = bds60 . hdg60 ( msg ) m60 = bds60 . mach60 ( msg ) i60 = bds60 . ias60 ( msg ) if h60 is None or ( m60 is None and i60 is None ) : return 'BDS50,BDS60' m60 = np . nan if m60 is None else m60 i60 = np . nan if i60 is None else i60 XY5 = vxy ( v50 * aero . kts , h50 ) XY6m = vxy ( aero . mach2tas ( m60 , alt_ref * aero . ft ) , h60 ) XY6i = vxy ( aero . cas2tas ( i60 * aero . kts , alt_ref * aero . ft ) , h60 ) allbds = [ 'BDS50' , 'BDS60' , 'BDS60' ] X = np . array ( [ XY5 , XY6m , XY6i ] ) Mu = np . array ( vxy ( spd_ref * aero . kts , trk_ref ) ) try : dist = np . linalg . norm ( X - Mu , axis = 1 ) BDS = allbds [ np . nanargmin ( dist ) ] except ValueError : return 'BDS50,BDS60' return BDS
Use reference ground speed and trk to determine BDS50 and DBS60 .
40,555
def infer ( msg , mrar = False ) : df = common . df ( msg ) if common . allzeros ( msg ) : return 'EMPTY' if df == 17 : tc = common . typecode ( msg ) if 1 <= tc <= 4 : return 'BDS08' if 5 <= tc <= 8 : return 'BDS06' if 9 <= tc <= 18 : return 'BDS05' if tc == 19 : return 'BDS09' if 20 <= tc <= 22 : return 'BDS05' if tc == 28 : return 'BDS61' if tc == 29 : return 'BDS62' if tc == 31 : return 'BDS65' IS10 = bds10 . is10 ( msg ) IS17 = bds17 . is17 ( msg ) IS20 = bds20 . is20 ( msg ) IS30 = bds30 . is30 ( msg ) IS40 = bds40 . is40 ( msg ) IS50 = bds50 . is50 ( msg ) IS60 = bds60 . is60 ( msg ) IS44 = bds44 . is44 ( msg ) IS45 = bds45 . is45 ( msg ) if mrar : allbds = np . array ( [ "BDS10" , "BDS17" , "BDS20" , "BDS30" , "BDS40" , "BDS44" , "BDS45" , "BDS50" , "BDS60" ] ) mask = [ IS10 , IS17 , IS20 , IS30 , IS40 , IS44 , IS45 , IS50 , IS60 ] else : allbds = np . array ( [ "BDS10" , "BDS17" , "BDS20" , "BDS30" , "BDS40" , "BDS50" , "BDS60" ] ) mask = [ IS10 , IS17 , IS20 , IS30 , IS40 , IS50 , IS60 ] bds = ',' . join ( sorted ( allbds [ mask ] ) ) if len ( bds ) == 0 : return None else : return bds
Estimate the most likely BDS code of an message .
40,556
def is40 ( msg ) : if allzeros ( msg ) : return False d = hex2bin ( data ( msg ) ) if wrongstatus ( d , 1 , 2 , 13 ) : return False if wrongstatus ( d , 14 , 15 , 26 ) : return False if wrongstatus ( d , 27 , 28 , 39 ) : return False if wrongstatus ( d , 48 , 49 , 51 ) : return False if wrongstatus ( d , 54 , 55 , 56 ) : return False if bin2int ( d [ 39 : 47 ] ) != 0 : return False if bin2int ( d [ 51 : 53 ] ) != 0 : return False return True
Check if a message is likely to be BDS code 4 0
40,557
def alt40fms ( msg ) : d = hex2bin ( data ( msg ) ) if d [ 13 ] == '0' : return None alt = bin2int ( d [ 14 : 26 ] ) * 16 return alt
Selected altitude FMS
40,558
def p40baro ( msg ) : d = hex2bin ( data ( msg ) ) if d [ 26 ] == '0' : return None p = bin2int ( d [ 27 : 39 ] ) * 0.1 + 800 return p
Barometric pressure setting
40,559
def is44 ( msg ) : if allzeros ( msg ) : return False d = hex2bin ( data ( msg ) ) if wrongstatus ( d , 5 , 6 , 23 ) : return False if wrongstatus ( d , 35 , 36 , 46 ) : return False if wrongstatus ( d , 47 , 48 , 49 ) : return False if wrongstatus ( d , 50 , 51 , 56 ) : return False if bin2int ( d [ 0 : 4 ] ) > 4 : return False vw = wind44 ( msg ) if vw is not None and vw [ 0 ] > 250 : return False temp , temp2 = temp44 ( msg ) if min ( temp , temp2 ) > 60 or max ( temp , temp2 ) < - 80 : return False return True
Check if a message is likely to be BDS code 4 4 .
40,560
def wind44 ( msg ) : d = hex2bin ( data ( msg ) ) status = int ( d [ 4 ] ) if not status : return None speed = bin2int ( d [ 5 : 14 ] ) direction = bin2int ( d [ 14 : 23 ] ) * 180.0 / 256.0 return round ( speed , 0 ) , round ( direction , 1 )
Wind speed and direction .
40,561
def p44 ( msg ) : d = hex2bin ( data ( msg ) ) if d [ 34 ] == '0' : return None p = bin2int ( d [ 35 : 46 ] ) return p
Static pressure .
40,562
def is60 ( msg ) : if allzeros ( msg ) : return False d = hex2bin ( data ( msg ) ) if wrongstatus ( d , 1 , 2 , 12 ) : return False if wrongstatus ( d , 13 , 14 , 23 ) : return False if wrongstatus ( d , 24 , 25 , 34 ) : return False if wrongstatus ( d , 35 , 36 , 45 ) : return False if wrongstatus ( d , 46 , 47 , 56 ) : return False ias = ias60 ( msg ) if ias is not None and ias > 500 : return False mach = mach60 ( msg ) if mach is not None and mach > 1 : return False vr_baro = vr60baro ( msg ) if vr_baro is not None and abs ( vr_baro ) > 6000 : return False vr_ins = vr60ins ( msg ) if vr_ins is not None and abs ( vr_ins ) > 6000 : return False return True
Check if a message is likely to be BDS code 6 0
40,563
def hdg60 ( msg ) : d = hex2bin ( data ( msg ) ) if d [ 0 ] == '0' : return None sign = int ( d [ 1 ] ) value = bin2int ( d [ 2 : 12 ] ) if sign : value = value - 1024 hdg = value * 90 / 512.0 if hdg < 0 : hdg = 360 + hdg return round ( hdg , 3 )
Megnetic heading of aircraft
40,564
def mach60 ( msg ) : d = hex2bin ( data ( msg ) ) if d [ 23 ] == '0' : return None mach = bin2int ( d [ 24 : 34 ] ) * 2.048 / 512.0 return round ( mach , 3 )
Aircraft MACH number
40,565
def vr60baro ( msg ) : d = hex2bin ( data ( msg ) ) if d [ 34 ] == '0' : return None sign = int ( d [ 35 ] ) value = bin2int ( d [ 36 : 45 ] ) if value == 0 or value == 511 : return 0 value = value - 512 if sign else value roc = value * 32 return roc
Vertical rate from barometric measurement this value may be very noisy .
40,566
def is45 ( msg ) : if allzeros ( msg ) : return False d = hex2bin ( data ( msg ) ) if wrongstatus ( d , 1 , 2 , 3 ) : return False if wrongstatus ( d , 4 , 5 , 6 ) : return False if wrongstatus ( d , 7 , 8 , 9 ) : return False if wrongstatus ( d , 10 , 11 , 12 ) : return False if wrongstatus ( d , 13 , 14 , 15 ) : return False if wrongstatus ( d , 16 , 17 , 26 ) : return False if wrongstatus ( d , 27 , 28 , 38 ) : return False if wrongstatus ( d , 39 , 40 , 51 ) : return False if bin2int ( d [ 51 : 56 ] ) != 0 : return False temp = temp45 ( msg ) if temp : if temp > 60 or temp < - 80 : return False return True
Check if a message is likely to be BDS code 4 5 .
40,567
def ws45 ( msg ) : d = hex2bin ( data ( msg ) ) if d [ 3 ] == '0' : return None ws = bin2int ( d [ 4 : 6 ] ) return ws
Wind shear .
40,568
def wv45 ( msg ) : d = hex2bin ( data ( msg ) ) if d [ 12 ] == '0' : return None ws = bin2int ( d [ 13 : 15 ] ) return ws
Wake vortex .
40,569
def p45 ( msg ) : d = hex2bin ( data ( msg ) ) if d [ 26 ] == '0' : return None p = bin2int ( d [ 27 : 38 ] ) return p
Average static pressure .
40,570
def rh45 ( msg ) : d = hex2bin ( data ( msg ) ) if d [ 38 ] == '0' : return None rh = bin2int ( d [ 39 : 51 ] ) * 16 return rh
Radio height .
40,571
def vsound ( H ) : T = temperature ( H ) a = np . sqrt ( gamma * R * T ) return a
Speed of sound
40,572
def distance ( lat1 , lon1 , lat2 , lon2 , H = 0 ) : phi1 = np . radians ( 90.0 - lat1 ) phi2 = np . radians ( 90.0 - lat2 ) theta1 = np . radians ( lon1 ) theta2 = np . radians ( lon2 ) cos = np . sin ( phi1 ) * np . sin ( phi2 ) * np . cos ( theta1 - theta2 ) + np . cos ( phi1 ) * np . cos ( phi2 ) cos = np . where ( cos > 1 , 1 , cos ) arc = np . arccos ( cos ) dist = arc * ( r_earth + H ) return dist
Compute spherical distance from spherical coordinates .
40,573
def tas2mach ( Vtas , H ) : a = vsound ( H ) Mach = Vtas / a return Mach
True Airspeed to Mach number
40,574
def mach2tas ( Mach , H ) : a = vsound ( H ) Vtas = Mach * a return Vtas
Mach number to True Airspeed
40,575
def tas2eas ( Vtas , H ) : rho = density ( H ) Veas = Vtas * np . sqrt ( rho / rho0 ) return Veas
True Airspeed to Equivalent Airspeed
40,576
def cas2tas ( Vcas , H ) : p , rho , T = atmos ( H ) qdyn = p0 * ( ( 1. + rho0 * Vcas * Vcas / ( 7. * p0 ) ) ** 3.5 - 1. ) Vtas = np . sqrt ( 7. * p / rho * ( ( 1. + qdyn / p ) ** ( 2. / 7. ) - 1. ) ) return Vtas
Calibrated Airspeed to True Airspeed
40,577
def mach2cas ( Mach , H ) : Vtas = mach2tas ( Mach , H ) Vcas = tas2cas ( Vtas , H ) return Vcas
Mach number to Calibrated Airspeed
40,578
def cas2mach ( Vcas , H ) : Vtas = cas2tas ( Vcas , H ) Mach = tas2mach ( Vtas , H ) return Mach
Calibrated Airspeed to Mach number
40,579
def markdown_search_user ( request ) : data = { } username = request . GET . get ( 'username' ) if username is not None and username != '' and ' ' not in username : users = User . objects . filter ( Q ( username__icontains = username ) ) . filter ( is_active = True ) if users . exists ( ) : data . update ( { 'status' : 200 , 'data' : [ { 'username' : u . username } for u in users ] } ) return HttpResponse ( json . dumps ( data , cls = LazyEncoder ) , content_type = 'application/json' ) data . update ( { 'status' : 204 , 'error' : _ ( 'No users registered as `%(username)s` ' 'or user is unactived.' ) % { 'username' : username } } ) else : data . update ( { 'status' : 204 , 'error' : _ ( 'Validation Failed for field `username`' ) } ) return HttpResponse ( json . dumps ( data , cls = LazyEncoder ) , content_type = 'application/json' )
Json usernames of the users registered & actived .
40,580
def handleMatch ( self , m ) : username = self . unescape ( m . group ( 2 ) ) if MARTOR_ENABLE_CONFIGS [ 'mention' ] == 'true' : if username in [ u . username for u in User . objects . exclude ( is_active = False ) ] : url = '{0}{1}/' . format ( MARTOR_MARKDOWN_BASE_MENTION_URL , username ) el = markdown . util . etree . Element ( 'a' ) el . set ( 'href' , url ) el . set ( 'class' , 'direct-mention-link' ) el . text = markdown . util . AtomicString ( '@' + username ) return el
Makesure username is registered and actived .
40,581
def markdownify ( markdown_content ) : try : return markdown . markdown ( markdown_content , safe_mode = MARTOR_MARKDOWN_SAFE_MODE , extensions = MARTOR_MARKDOWN_EXTENSIONS , extension_configs = MARTOR_MARKDOWN_EXTENSION_CONFIGS ) except Exception : raise VersionNotCompatible ( "The markdown isn't compatible, please reinstall " "your python markdown into Markdown>=3.0" )
Render the markdown content to HTML .
40,582
def get_entry_url ( entry , blog_page , root_page ) : if root_page == blog_page : return reverse ( 'entry_page_serve' , kwargs = { 'year' : entry . date . strftime ( '%Y' ) , 'month' : entry . date . strftime ( '%m' ) , 'day' : entry . date . strftime ( '%d' ) , 'slug' : entry . slug } ) else : blog_path = strip_prefix_and_ending_slash ( blog_page . specific . last_url_part ) return reverse ( 'entry_page_serve_slug' , kwargs = { 'blog_path' : blog_path , 'year' : entry . date . strftime ( '%Y' ) , 'month' : entry . date . strftime ( '%m' ) , 'day' : entry . date . strftime ( '%d' ) , 'slug' : entry . slug } )
Get the entry url given and entry page a blog page instances . It will use an url or another depending if blog_page is the root page .
40,583
def get_feeds_url ( blog_page , root_page ) : if root_page == blog_page : return reverse ( 'blog_page_feed' ) else : blog_path = strip_prefix_and_ending_slash ( blog_page . specific . last_url_part ) return reverse ( 'blog_page_feed_slug' , kwargs = { 'blog_path' : blog_path } )
Get the feeds urls a blog page instance . It will use an url or another depending if blog_page is the root page .
40,584
def install_dependencies ( dependencies , verbose = False ) : if not dependencies : return stdout = stderr = None if verbose else subprocess . DEVNULL with tempfile . TemporaryDirectory ( ) as req_dir : req_file = Path ( req_dir ) / "requirements.txt" with open ( req_file , "w" ) as f : for dependency in dependencies : f . write ( f"{dependency}\n" ) pip = [ "python3" , "-m" , "pip" , "install" , "-r" , req_file ] if sys . base_prefix == sys . prefix and not hasattr ( sys , "real_prefix" ) : pip . append ( "--user" ) try : subprocess . check_call ( pip , stdout = stdout , stderr = stderr ) except subprocess . CalledProcessError : raise Error ( _ ( "failed to install dependencies" ) ) importlib . reload ( site )
Install all packages in dependency list via pip .
40,585
def install_translations ( config ) : if not config : return from . import _translation checks_translation = gettext . translation ( domain = config [ "domain" ] , localedir = internal . check_dir / config [ "localedir" ] , fallback = True ) _translation . add_fallback ( checks_translation )
Add check translations according to config as a fallback to existing translations
40,586
def hash ( file ) : exists ( file ) log ( _ ( "hashing {}..." ) . format ( file ) ) with open ( file , "rb" ) as f : sha256 = hashlib . sha256 ( ) for block in iter ( lambda : f . read ( 65536 ) , b"" ) : sha256 . update ( block ) return sha256 . hexdigest ( )
Hashes file using SHA - 256 .
40,587
def exists ( * paths ) : for path in paths : log ( _ ( "checking that {} exists..." ) . format ( path ) ) if not os . path . exists ( path ) : raise Failure ( _ ( "{} not found" ) . format ( path ) )
Assert that all given paths exist .
40,588
def import_checks ( path ) : dir = internal . check_dir / path file = internal . load_config ( dir ) [ "checks" ] mod = internal . import_file ( dir . name , ( dir / file ) . resolve ( ) ) sys . modules [ dir . name ] = mod return mod
Import checks module given relative path .
40,589
def _raw ( s ) : if isinstance ( s , list ) : s = "\n" . join ( _raw ( item ) for item in s ) if s == EOF : return "EOF" s = repr ( s ) s = s [ 1 : - 1 ] if len ( s ) > 15 : s = s [ : 15 ] + "..." return s
Get raw representation of s truncating if too long .
40,590
def _copy ( src , dst ) : try : shutil . copy ( src , dst ) except IsADirectoryError : if os . path . isdir ( dst ) : dst = os . path . join ( dst , os . path . basename ( src ) ) shutil . copytree ( src , dst )
Copy src to dst copying recursively if src is a directory .
40,591
def stdin ( self , line , prompt = True , timeout = 3 ) : if line == EOF : log ( "sending EOF..." ) else : log ( _ ( "sending input {}..." ) . format ( line ) ) if prompt : try : self . process . expect ( ".+" , timeout = timeout ) except ( TIMEOUT , EOF ) : raise Failure ( _ ( "expected prompt for input, found none" ) ) except UnicodeDecodeError : raise Failure ( _ ( "output not valid ASCII text" ) ) try : if line == EOF : self . process . sendeof ( ) else : self . process . sendline ( line ) except OSError : pass return self
Send line to stdin optionally expect a prompt .
40,592
def reject ( self , timeout = 1 ) : log ( _ ( "checking that input was rejected..." ) ) try : self . _wait ( timeout ) except Failure as e : if not isinstance ( e . __cause__ , TIMEOUT ) : raise else : raise Failure ( _ ( "expected program to reject input, but it did not" ) ) return self
Check that the process survives for timeout . Useful for checking whether program is waiting on input .
40,593
def import_file ( name , path ) : spec = importlib . util . spec_from_file_location ( name , path ) mod = importlib . util . module_from_spec ( spec ) spec . loader . exec_module ( mod ) return mod
Import a file given a raw file path .
40,594
def compile ( * files , exe_name = None , cc = CC , ** cflags ) : if not files : raise RuntimeError ( _ ( "compile requires at least one file" ) ) if exe_name is None and files [ 0 ] . endswith ( ".c" ) : exe_name = Path ( files [ 0 ] ) . stem files = " " . join ( files ) flags = CFLAGS . copy ( ) flags . update ( cflags ) flags = " " . join ( ( f"-{flag}" + ( f"={value}" if value is not True else "" ) ) . replace ( "_" , "-" ) for flag , value in flags . items ( ) if value ) out_flag = f" -o {exe_name} " if exe_name is not None else " " run ( f"{cc} {files}{out_flag}{flags}" ) . exit ( 0 )
Compile C source files .
40,595
def valgrind ( command , env = { } ) : xml_file = tempfile . NamedTemporaryFile ( ) internal . register . after_check ( lambda : _check_valgrind ( xml_file ) ) return run ( f"valgrind --show-leak-kinds=all --xml=yes --xml-file={xml_file.name} -- {command}" , env = env )
Run a command with valgrind .
40,596
def _check_valgrind ( xml_file ) : log ( _ ( "checking for valgrind errors..." ) ) xml = ET . ElementTree ( file = xml_file ) reported = set ( ) for error in xml . iterfind ( "error" ) : kind = error . find ( "kind" ) . text what = error . find ( "xwhat/text" if kind . startswith ( "Leak_" ) else "what" ) . text msg = [ "\t" , what ] for frame in error . iterfind ( "stack/frame" ) : obj = frame . find ( "obj" ) if obj is not None and internal . run_dir in Path ( obj . text ) . parents : file , line = frame . find ( "file" ) , frame . find ( "line" ) if file is not None and line is not None : msg . append ( f": ({_('file')}: {file.text}, {_('line')}: {line.text})" ) break msg = "" . join ( msg ) if msg not in reported : log ( msg ) reported . add ( msg ) if reported : raise Failure ( _ ( "valgrind tests failed; rerun with --log for more information." ) )
Log and report any errors encountered by valgrind .
40,597
def _timeout ( seconds ) : def _handle_timeout ( * args ) : raise Timeout ( seconds ) signal . signal ( signal . SIGALRM , _handle_timeout ) signal . alarm ( seconds ) try : yield finally : signal . alarm ( 0 ) signal . signal ( signal . SIGALRM , signal . SIG_DFL )
Context manager that runs code block until timeout is reached .
40,598
def run ( self , files , working_area ) : results = { name : None for name in self . check_names } checks_root = working_area . parent with futures . ProcessPoolExecutor ( ) as executor : not_done = set ( executor . submit ( run_check ( name , self . checks_spec , checks_root ) ) for name , _ in self . child_map [ None ] ) not_passed = [ ] while not_done : done , not_done = futures . wait ( not_done , return_when = futures . FIRST_COMPLETED ) for future in done : result , state = future . result ( ) results [ result . name ] = result if result . passed : for child_name , _ in self . child_map [ result . name ] : not_done . add ( executor . submit ( run_check ( child_name , self . checks_spec , checks_root , state ) ) ) else : not_passed . append ( result . name ) for name in not_passed : self . _skip_children ( name , results ) return results . values ( )
Run checks concurrently . Returns a list of CheckResults ordered by declaration order of the checks in the imported module
40,599
def append_code ( original , codefile ) : with open ( codefile ) as code , open ( original , "a" ) as o : o . write ( "\n" ) o . writelines ( code )
Append the contents of one file to another .