Two percent high design temperature for a location.

    Degrees in Celcius

    Args:
        station_code (str): Weather Station Code

    Returns:
        float degrees Celcius
552123
def twopercent(station_code):
    
    # (DB=>MWB) 2%, MaxDB=
    temp = None
    try:
        fin = open('%s/%s' % (env.WEATHER_DATA_PATH,
                              _basename(station_code, 'ddy')))
        for line in fin:
            value = re.search("""2%, MaxDB=(\\d+\\.\\d*)""", line)
            if value:
                temp = float(value.groups()[0])
    except IOError:
        pass

    if not temp:
        # (DB=>MWB) 2%, MaxDB=
        try:
            fin = open('%s/%s' % (env.WEATHER_DATA_PATH,
                                  _basename(station_code, 'stat')))
            flag = 0
            tdata = []
            for line in fin:
                if line.find('2%') is not -1:
                    flag = 3
                if flag > 0:
                    tdata.append(line.split('\t'))
                    flag -= 1
            temp = float(tdata[2][5].strip())
        except IOError:
            pass
    if temp:
        return temp
    else:
        raise Exception("Error: 2% High Temperature not found")
645912
def extra_args_parser(parser=None, skip_args=None, **kwargs):
        
        if skip_args is None:
            skip_args = []
        parser, actions = MCMCMetadataIO.extra_args_parser(
            parser=parser, skip_args=skip_args, **kwargs)
        if 'temps' not in skip_args:
            act = parser.add_argument(
                "--temps", nargs="+", default=0, action=ParseTempsArg,
                help="Get the given temperatures. May provide either a "
                     "sequence of integers specifying the temperatures to "
                     "plot, or 'all' for all temperatures. Default is to only "
                     "plot the coldest (= 0) temperature chain.")
            actions.append(act)
        return parser, actions
559573
def current_bed_temp(self):
        """"""
        try:
            bedtemps = self.intervals[0]['timeseries']['tempBedC']
            num_temps = len(bedtemps)

            if num_temps == 0:
                return None

            bedtemp = bedtemps[num_temps-1][1]
        except KeyError:
            bedtemp = None
        return bedtemp
1147828
def _compensate_humidity(self, adc_h):
        
        var_h = self._temp_fine - 76800.0
        if var_h == 0:
            return 0

        var_h = ((adc_h - (self._calibration_h[3] * 64.0 +
                           self._calibration_h[4] / 16384.0 * var_h))
                 * (self._calibration_h[1] / 65536.0
                    * (1.0 + self._calibration_h[5] / 67108864.0 * var_h
                       * (1.0 + self._calibration_h[2] / 67108864.0 * var_h))))
        var_h *= 1.0 - self._calibration_h[0] * var_h / 524288.0

        if var_h > 100.0:
            var_h = 100.0
        elif var_h < 0.0:
            var_h = 0.0

        return var_h
1199768
def check_weather(self):
        '''
        
        '''
        if self.station_id is None:
            # Failed to get the nearest station ID when first launched, so
            # retry it.
            self.get_station_id()

        self.data['update_error'] = ''
        try:
            query_url = STATION_QUERY_URL % (self.api_key,
                                             'conditions',
                                             self.station_id)
            try:
                response = self.api_request(query_url)['current_observation']
                self.forecast_url = response.pop('ob_url', None)
            except KeyError:
                self.logger.error('No weather data found for %s', self.station_id)
                self.data['update_error'] = self.update_error
                return

            if self.forecast:
                query_url = STATION_QUERY_URL % (self.api_key,
                                                 'forecast',
                                                 self.station_id)
                try:
                    forecast = self.api_request(query_url)['forecast']
                    forecast = forecast['simpleforecast']['forecastday'][0]
                except (KeyError, IndexError, TypeError):
                    self.logger.error(
                        'No forecast data found for %s', self.station_id)
                    # This is a non-fatal error, so don't return but do set the
                    # error flag.
                    self.data['update_error'] = self.update_error

                unit = 'celsius' if self.units == 'metric' else 'fahrenheit'
                low_temp = forecast.get('low', {}).get(unit, '')
                high_temp = forecast.get('high', {}).get(unit, '')
            else:
                low_temp = high_temp = ''

            if self.units == 'metric':
                temp_unit = 'c'
                speed_unit = 'kph'
                distance_unit = 'km'
                pressure_unit = 'mb'
            else:
                temp_unit = 'f'
                speed_unit = 'mph'
                distance_unit = 'mi'
                pressure_unit = 'in'

            def _find(key, data=None, default=''):
                if data is None:
                    data = response
                return str(data.get(key, default))

            try:
                observation_epoch = _find('observation_epoch') or _find('local_epoch')
                observation_time = datetime.fromtimestamp(int(observation_epoch))
            except (TypeError, ValueError):
                log.debug(
                    'Observation time \'%s\' is not a UNIX timestamp',
                    observation_epoch
                )
                observation_time = datetime.fromtimestamp(0)

            self.data['city'] = _find('city', response['observation_location'])
            self.data['condition'] = _find('weather')
            self.data['observation_time'] = observation_time
            self.data['current_temp'] = _find('temp_' + temp_unit).split('.')[0]
            self.data['low_temp'] = low_temp
            self.data['high_temp'] = high_temp
            self.data['temp_unit'] = '°' + temp_unit.upper()
            self.data['feelslike'] = _find('feelslike_' + temp_unit)
            self.data['dewpoint'] = _find('dewpoint_' + temp_unit)
            self.data['wind_speed'] = _find('wind_' + speed_unit)
            self.data['wind_unit'] = speed_unit
            self.data['wind_direction'] = _find('wind_dir')
            self.data['wind_gust'] = _find('wind_gust_' + speed_unit)
            self.data['pressure'] = _find('pressure_' + pressure_unit)
            self.data['pressure_unit'] = pressure_unit
            self.data['pressure_trend'] = _find('pressure_trend')
            self.data['visibility'] = _find('visibility_' + distance_unit)
            self.data['visibility_unit'] = distance_unit
            self.data['humidity'] = _find('relative_humidity').rstrip('%')
            self.data['uv_index'] = _find('UV')
        except Exception:
            # Don't let an uncaught exception kill the update thread
            self.logger.error(
                'Uncaught error occurred while checking weather. '
                'Exception follows:', exc_info=True
            )
            self.data['update_error'] = self.update_error
655066
def temperature(self):
        
        if not self.awake:
            raise Exception("MPU6050 is in sleep mode, use wakeup()")

        raw = self.i2c_read_register(0x41, 2)
        raw = struct.unpack('>h', raw)[0]
        return round((raw / 340) + 36.53, 2)
10100
def decode_temperature(packet, channel=1):
    """"""
    val = str(packet.get(QSDATA, ''))
    if len(val) == 12 and val.startswith('34') and channel == 1:
        temperature = int(val[-4:], 16)
        return round(float((-46.85 + (175.72 * (temperature / pow(2, 16))))))
    return None
735544
def temperature(self):
        
        ut = self.get_raw_temp()
        x1 = ((ut - self.cal['AC6']) * self.cal['AC5']) >> 15
        x2 = (self.cal['MC'] << 11) // (x1 + self.cal['MD'])
        b5 = x1 + x2
        return ((b5 + 8) >> 4) / 10
640549
def set_target_temp(self, temperature):
        
        if 35 < temperature < 5:
            logging.info("Refusing to set temp outside of allowed range")
            return False
        else:
            self._hm_send_address(self.address, 18, temperature, 1)
            return True
1107973
def temperatures(self, force_refresh=False):
        """"""
        self._populate_full_data(force_refresh)
        for device in self.full_data['devices']:
            set_point = 0
            status = ""
            if 'heatSetpoint' in device['thermostat']['changeableValues']:
                set_point = float(
                    device['thermostat']['changeableValues']["heatSetpoint"]["value"])
                status = device['thermostat']['changeableValues']["heatSetpoint"]["status"]
            else:
                status = device['thermostat']['changeableValues']['status']
            yield {'thermostat': device['thermostatModelType'],
                   'id': device['deviceID'],
                   'name': device['name'],
                   'temp': float(device['thermostat']['indoorTemperature']),
                   'setpoint': set_point,
                   'status': status,
                   'mode': device['thermostat']['changeableValues']['mode']}
833451
def EAS2TAS(ARSP,GPS,BARO,ground_temp=25):
    ''''''
    tempK = ground_temp + 273.15 - 0.0065 * GPS.Alt
    return sqrt(1.225 / (BARO.Press / (287.26 * tempK)))
237021
def check_weather(self):
        '''
        
        '''

        if self.units not in ('imperial', 'metric'):
            raise Exception("units must be one of (imperial, metric)!")

        if self.location_code is None:
            self.logger.error(
                'A location_code is required to check Weather.com. See the '
                'documentation for more information.'
            )
            self.data['update_error'] = self.update_error
            return
        self.data['update_error'] = ''
        try:

            self.parser.get_weather_data(self.forecast_url)
            if self.parser.weather_data is None:
                self.logger.error(
                    'Failed to read weather data from page. Run module with '
                    'debug logging to get more information.'
                )
                self.data['update_error'] = self.update_error
                return

            try:
                observed = self.parser.weather_data['Observation']
                # Observation data stored under a sub-key containing the
                # lat/long coordinates. For example:
                #
                # geocode:41.77,-88.35:language:en-US:units:e
                #
                # Since this is the only key under "Observation", we can just
                # use next(iter(observed)) to get it.
                observed = observed[next(iter(observed))]['data']['vt1observation']
            except KeyError:
                self.logger.error(
                    'Failed to retrieve current conditions from API response. '
                    'Run module with debug logging to get more information.'
                )
                self.data['update_error'] = self.update_error
                return

            try:
                forecast = self.parser.weather_data['DailyForecast']
                # Same as above, use next(iter(forecast)) to drill down to the
                # correct nested dict level.
                forecast = forecast[next(iter(forecast))]
                forecast = forecast['data']['vt1dailyForecast'][0]
            except (IndexError, KeyError):
                self.logger.error(
                    'Failed to retrieve forecast data from API response. '
                    'Run module with debug logging to get more information.'
                )
                self.data['update_error'] = self.update_error
                return

            try:
                self.city_name = self.parser.weather_data['Location']
                # Again, same technique as above used to get down to the
                # correct nested dict level.
                self.city_name = self.city_name[next(iter(self.city_name))]
                self.city_name = self.city_name['data']['prsntNm']
            except KeyError:
                self.logger.warning(
                    'Failed to get city name from API response, falling back '
                    'to location code \'%s\'', self.location_code
                )
                self.city_name = self.location_code

            # Cut off the timezone from the end of the string (it's after the last
            # space, hence the use of rpartition). International timezones (or ones
            # outside the system locale) don't seem to be handled well by
            # datetime.datetime.strptime().
            try:
                observation_time_str = str(observed.get('observationTime', ''))
                observation_time = datetime.strptime(observation_time_str,
                                                     '%Y-%d-%yT%H:%M:%S%z')
            except (ValueError, AttributeError):
                observation_time = datetime.fromtimestamp(0)

            try:
                pressure_trend_str = observed.get('barometerTrend', '').lower()
            except AttributeError:
                pressure_trend_str = ''

            if pressure_trend_str == 'rising':
                pressure_trend = '+'
            elif pressure_trend_str == 'falling':
                pressure_trend = '-'
            else:
                pressure_trend = ''

            try:
                high_temp = forecast.get('day', {}).get('temperature', '')
            except (AttributeError, IndexError):
                high_temp = ''
            else:
                if high_temp is None:
                    # In the mid-afternoon, the high temp disappears from the
                    # forecast, so just set high_temp to an empty string.
                    high_temp = ''

            try:
                low_temp = forecast.get('night', {}).get('temperature', '')
            except (AttributeError, IndexError):
                low_temp = ''

            if self.units == 'imperial':
                temp_unit = '°F'
                wind_unit = 'mph'
                pressure_unit = 'in'
                visibility_unit = 'mi'
            else:
                temp_unit = '°C'
                wind_unit = 'kph'
                pressure_unit = 'mb'
                visibility_unit = 'km'

            self.data['city'] = self.city_name
            self.data['condition'] = str(observed.get('phrase', ''))
            self.data['observation_time'] = observation_time
            self.data['current_temp'] = str(observed.get('temperature', ''))
            self.data['low_temp'] = str(low_temp)
            self.data['high_temp'] = str(high_temp)
            self.data['temp_unit'] = temp_unit
            self.data['feelslike'] = str(observed.get('feelsLike', ''))
            self.data['dewpoint'] = str(observed.get('dewPoint', ''))
            self.data['wind_speed'] = str(observed.get('windSpeed', ''))
            self.data['wind_unit'] = wind_unit
            self.data['wind_direction'] = str(observed.get('windDirCompass', ''))
            # Gust can be None, using "or" to ensure empty string in this case
            self.data['wind_gust'] = str(observed.get('gust', '') or '')
            self.data['pressure'] = str(observed.get('altimeter', ''))
            self.data['pressure_unit'] = pressure_unit
            self.data['pressure_trend'] = pressure_trend
            self.data['visibility'] = str(observed.get('visibility', ''))
            self.data['visibility_unit'] = visibility_unit
            self.data['humidity'] = str(observed.get('humidity', ''))
            self.data['uv_index'] = str(observed.get('uvIndex', ''))
        except Exception:
            # Don't let an uncaught exception kill the update thread
            self.logger.error(
                'Uncaught error occurred while checking weather. '
                'Exception follows:', exc_info=True
            )
            self.data['update_error'] = self.update_error
471407
def get_temperature(self):
        """"""
        try:
            request = requests.get(
                '{}/temp'.format(self.resource), timeout=self.timeout, allow_redirects=False)
            self.temperature = request.json()['compensated']
            return self.temperature
        except requests.exceptions.ConnectionError:
            raise exceptions.MyStromConnectionError()
        except ValueError:
            raise exceptions.MyStromNotVersionTwoSwitch()
682308
def get_temperature_interval(self):
        
        intervals = ({
            -20: 1, -19: 1, -18: 1, -17: 1, -16: 1, -15: 1, -14: 2,
            -13: 2, -12: 2, -11: 2, -10: 2, -9: 3, -8: 3, -7: 3, -6: 3, -5: 3,
            -4: 4, -3: 4, -2: 4, -1: 4, 0: 4, 1: 5, 2: 5, 3: 5, 4: 5, 5: 5,
            6: 6, 7: 6, 8: 6, 9: 6, 10: 6, 11: 7, 12: 7, 13: 7, 14: 7, 15: 7,
            16: 8, 17: 8, 18: 8, 19: 8, 20: 8, 21: 9, 22: 9, 23: 9, 24: 9,
            25: 9, 26: 10, 27: 10, 28: 10, 29: 10, 30: 10, 31: 10, 32: 10,
            33: 10, 34: 10, 35: 10, 36: 10, 37: 10, 38: 10, 39: 10, 40: 10})

        temperature_rounded = [ceil(i) for i in self.df['temperature_geo']]

        temperature_interval = [intervals[i] for i in temperature_rounded]

        return np.transpose(np.array(temperature_interval))
645293
def valid_daily_min_temperature(comp, units='K'):
    """

    @wraps(comp)
    def func(tasmin, *args, **kwds):
        check_valid_temperature(tasmin, units)
        check_valid(tasmin, 'cell_methods', 'time: minimum within days')
        return comp(tasmin, **kwds)

    return func
456109
def check_valid_temperature(var, units):
    """

    check_valid(var, 'standard_name', 'air_temperature')
    check_valid(var, 'units', units)
    assert_daily(var)
847378
def temp(h):
    

    # Base values and gradient in table from hand-out
    # (but corrected to avoid small discontinuities at borders of layers)
    h0 = [0.0, 11000., 20000., 32000., 47000., 51000., 71000., 86852.]

    T0 = [288.15,  # Sea level
          216.65,  # 11 km
          216.65,  # 20 km
          228.65,  # 32 km
          270.65,  # 47 km
          270.65,  # 51 km
          214.65]  # 71 km

    # a = lapse rate (temp gradient)
    # integer 0 indicates isothermic layer!
    a  = [-0.0065, # 0-11 km
            0 ,    # 11-20 km
          0.001,   # 20-32 km
          0.0028,  # 32-47 km
            0 ,    # 47-51 km
          -0.0028, # 51-71 km
          -0.002]  # 71-   km

    # Clip altitude to maximum!
    h = max(0.0,min(float(h),h0[-1]))


    # Find correct layer
    i = 0
    while h>h0[i+1] and i<len(h0)-2:
        i = i+1

    # Calculate if sothermic layer
    if a[i]==0:
        T   = T0[i]

    # Calculate for temperature gradient
    else:
        T   = T0[i] + a[i]*(h-h0[i])

    return T