Queries AWC for the METAR of a given station

        Args:
            icao: station ID as a four letters-digits ICAO code

        Returns: AWC result for the station
963958
def query_icao(icao: str):
        
        params = {
            'dataSource': 'metars',
            'requestType': 'retrieve',
            'format': 'csv',
            'hoursBeforeNow': 24,
        }
        AWC._validate_icao(icao)
        params['stationString'] = icao
        try:
            return AWC._query(params)
        except RequestsConnectionError:
            raise AWCRequestFailed('failed to obtain requested data from AWC')
1202189
def _list_variables(self, station_codes):
        
        # sample output from obs retrieval:
        #
        # DD9452D0
        #     HP(SRBM5)
        #         2013-07-22 19:30 45.97
        #     HT(SRBM5)
        #         2013-07-22 19:30 44.29
        #     PC(SRBM5)
        #         2013-07-22 19:30 36.19
        #
        rvar = re.compile(r"\n\s([A-Z]{2}[A-Z0-9]{0,1})\(\w+\)")

        variables = set()
        resp = requests.post(
            self.obs_retrieval_url,
            data={
                "state": "nil",
                "hsa": "nil",
                "of": "3",
                "extraids": " ".join(station_codes),
                "sinceday": -1,
            },
        )
        resp.raise_for_status()

        list(map(variables.add, rvar.findall(resp.text)))
        return variables
777749
def metar(wxdata: MetarData, units: Units) -> MetarTrans:
    
    translations = shared(wxdata, units)
    translations['wind'] = wind(wxdata.wind_direction, wxdata.wind_speed,
                                wxdata.wind_gust, wxdata.wind_variable_direction,
                                units.wind_speed)
    translations['temperature'] = temperature(wxdata.temperature, units.temperature)
    translations['dewpoint'] = temperature(wxdata.dewpoint, units.temperature)
    translations['remarks'] = remarks.translate(wxdata.remarks)  # type: ignore
    return MetarTrans(**translations)
963798
def channel_name_to_id(self, channel_name, force_lookup=False):
        
        if force_lookup or not self.channel_name_id_map:
            channels = self.channels_list()['channels']
            self.channel_name_id_map = {channel['name']: channel['id'] for channel in channels}
        channel = channel_name.startswith('#') and channel_name[1:] or channel_name
        return self.channel_name_id_map.get(channel)
968038
def get_wifi_wmm_param(data):
    
    answers = dict()
    aci_tbl = ('BE', 'BK', 'VI', 'VO')
    if data[0] & 0x80:
        answers['u-APSD'] = True
    data = data[2:]

    for i in range(4):
        key = aci_tbl[(data[0] >> 5) & 3]
        value = dict()
        if data[0] & 0x10:
            value['acm'] = True
        value['CW'] = ((1 << (data[1] & 0xf)) - 1, (1 << (data[1] >> 4)) - 1)
        value['AIFSN'] = data[0] & 0xf
        if data[2] | data[3]:
            value['TXOP'] = (data[2] + (data[3] << 8)) * 32
        answers[key] = value
        data = data[4:]

    return {'Parameter version 1': answers}
748218
def ImportStations(self, station_file, adv_file):
    ""
    for id, name, x, y, uic_code in  \
    ReadCSV(station_file, ['ORT_NR', 'ORT_NAME',
                'ORT_POS_X', 'ORT_POS_Y', 'ORT_NR_NATIONAL']):
      station = Station()
      station.id = id
      station.position = self.coord_converter(float(x), float(y))
      station.uic_code = ''
      if uic_code and len(uic_code) == 7 and uic_code[:2] == '85':
        station.uic_code = uic_code
      station.name, station.city = self.DemangleName(name)
      station.country = 'CH'
      station.url = 'http://fahrplan.zvv.ch/?to.0=' + \
                    urllib.quote(name.encode('iso-8859-1'))
      station.advertised_lines = set()
      self.stations[id] = station
    for station_id, line_id in ReadCSV(adv_file, ['ORT_NR', 'LI_NR']):
      if station_id in self.stations:
        # Line ids in this file have leading zeroes, remove.
        self.stations[station_id].advertised_lines.add(line_id.lstrip("0"))
      else:
        print("Warning, advertised lines file references " \
              "unknown station, id " + station_id)
184333
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
172210
def get_radio_by_name(self, radio_name: str) -> 'RadioPresets':
        
        if self.has_radio_presets:
            for k in FlyingUnit.RadioPresets.radio_enum[self.unit_type].keys():
                if radio_name == FlyingUnit.RadioPresets.radio_enum[self.unit_type][k]['radio_name']:
                    return FlyingUnit.RadioPresets(self, k)
            raise TypeError('{} for aircraft: {}'.format(radio_name, self.unit_type))
        else:
            raise TypeError('unit #{}: {}'.format(self.unit_id, self.unit_name))
586275
function ParseInternationalNumber(number) {
    var ret;

    // Parse and strip the country code.
    var countryCode = ParseCountryCode(number);
    if (!countryCode)
      return null;
    number = number.substr(countryCode.length);

    // Lookup the meta data for the region (or regions) and if the rest of
    // the number parses for that region, return the parsed number.
    var entry = dataBase[countryCode];
    if (Array.isArray(entry)) {
      for (var n = 0; n < entry.length; ++n) {
        if (typeof entry[n] == "string")
          entry[n] = ParseMetaData(countryCode, entry[n]);
        if (n > 0)
          entry[n].formats = entry[0].formats;
        ret = ParseNationalNumber(number, entry[n])
        if (ret)
          return ret;
      }
      return null;
    }
    if (typeof entry == "string")
      entry = dataBase[countryCode] = ParseMetaData(countryCode, entry);
    return ParseNationalNumber(number, entry);
  }
818591
def avro_name(url):  # type: (AnyStr) -> AnyStr
    
    frg = urllib.parse.urldefrag(url)[1]
    if frg != '':
        if '/' in frg:
            return frg[frg.rindex('/') + 1:]
        return frg
    return url
433167
def get_altimeter(wxdata: [str], units: Units, version: str = 'NA') -> ([str], Number):  # type: ignore  # noqa
    
    if not wxdata:
        return wxdata, None
    altimeter = ''
    target = wxdata[-1]
    if version == 'NA':
        # Version target
        if target[0] == 'A':
            altimeter = wxdata.pop()[1:]
        # Other version but prefer normal if available
        elif target[0] == 'Q':
            if wxdata[-2][0] == 'A':
                wxdata.pop()
                altimeter = wxdata.pop()[1:]
            else:
                units.altimeter = 'hPa'
                altimeter = wxdata.pop()[1:].lstrip('.')
        # Else grab the digits
        elif len(target) == 4 and target.isdigit():
            altimeter = wxdata.pop()
    elif version == 'IN':
        # Version target
        if target[0] == 'Q':
            altimeter = wxdata.pop()[1:].lstrip('.')
            if '/' in altimeter:
                altimeter = altimeter[:altimeter.find('/')]
        # Other version but prefer normal if available
        elif target[0] == 'A':
            if wxdata[-2][0] == 'Q':
                wxdata.pop()
                altimeter = wxdata.pop()[1:]
            else:
                units.altimeter = 'inHg'
                altimeter = wxdata.pop()[1:]
    # Some stations report both, but we only need one
    if wxdata and (wxdata[-1][0] == 'A' or wxdata[-1][0] == 'Q'):
        wxdata.pop()
    # convert to Number
    if not altimeter:
        return wxdata, None
    if units.altimeter == 'inHg':
        value = altimeter[:2] + '.' + altimeter[2:]
    else:
        value = altimeter
    return wxdata, make_number(value, altimeter)
1065788
def get_station_temperature_datetime(self, station_id):
        
        request = requests.get(
            "{}/station/{}/parameters/temperature/datetime".format(
                self.base_url, station_id))
        if request.status_code != 200:
            return None
        return datetime.strptime(request.json(), "%Y-%m-%dT%H:%M:%S")
799300
def _find_ip4_broadcast_addresses():
    
    yield "255.255.255.255"
    for interface in netifaces.interfaces():
        ifaddresses = netifaces.ifaddresses(interface)
        for family in ifaddresses:
            if family == netifaces.AF_INET:
                address_info = ifaddresses[family]
                for info in address_info:
                    if "broadcast" in info:
                        yield info['broadcast']
1019638
def get_station_id(self):
        '''
        
        '''
        extra_opts = '/pws:0' if not self.use_pws else ''
        api_url = GEOLOOKUP_URL % (self.api_key,
                                   extra_opts,
                                   self.location_code)
        response = self.api_request(api_url)
        station_type = 'pws' if self.use_pws else 'airport'
        try:
            stations = response['location']['nearby_weather_stations']
            nearest = stations[station_type]['station'][0]
        except (KeyError, IndexError):
            raise Exception(
                'No locations matched location_code %s' % self.location_code)

        self.logger.error('nearest = %s', nearest)
        if self.use_pws:
            nearest_pws = nearest.get('id', '')
            if not nearest_pws:
                raise Exception('No id entry for nearest PWS')
            self.station_id = 'pws:%s' % nearest_pws
        else:
            nearest_airport = nearest.get('icao', '')
            if not nearest_airport:
                raise Exception('No icao entry for nearest airport')
            self.station_id = 'icao:%s' % nearest_airport
665462
def raw(self, format=None, **kwargs):
        
        station_codes = self._apply_features_filter(self._get_station_codes())
        metadata = self._get_metadata(station_codes, **kwargs)
        raw_data = self._get_raw_data(station_codes, **kwargs)

        return (metadata, raw_data)
358234
def eere_station(station_code):
    
    with open(env.SRC_PATH + '/eere_meta.csv') as eere_meta:
        stations = csv.DictReader(eere_meta)
        for station in stations:
            if station['station_code'] == station_code:
                return station
    raise KeyError('station not found')
774144
def read_meta(self, **kwargs):
        '''
        
        '''
        # TODO Try to rewrite the code to be more logical
        # The reason the equivalent statement is not in the read_data method
        # above is because self.readdata_kwargs are passed
        # as **kwargs to the read_data function.
        if 'channel_naming' in self.readdata_kwargs:
            kwargs['channel_naming'] = self.readdata_kwargs['channel_naming']
        meta = parse_fcs(self.datafile,
                         reformat_meta=True,
                         meta_data_only=True, **kwargs)
        return meta