r"""
    Get the weather data for the given geometry and create an oemof
    weather object.
17731
def get_weather(conn, geometry, year):
    
    """
    rename_dc = {
        'ASWDIFD_S': 'dhi',
        'ASWDIR_S': 'dirhi',
        'PS': 'pressure',
        'T_2M': 'temp_air',
        'WSS_10M': 'v_wind',
        'Z0': 'z0'}

    if geometry.geom_type in ['Polygon', 'MultiPolygon']:
        # Create MultiWeather
        # If polygon covers only one data set switch to SingleWeather
        sql_part = """
            SELECT sp.gid, ST_AsText(point.geom), ST_AsText(sp.geom)
            FROM coastdat.cosmoclmgrid AS sp
            JOIN coastdat.spatial AS point ON (sp.gid=point.gid)
            WHERE st_intersects(ST_GeomFromText('{wkt}',4326), sp.geom)
            """.format(wkt=geometry.wkt)
        df = fetch_raw_data(sql_weather_string(year, sql_part), conn, geometry)
        obj = create_multi_weather(df, rename_dc)
    elif geometry.geom_type == 'Point':
        # Create SingleWeather
        sql_part = """
            SELECT sp.gid, ST_AsText(point.geom), ST_AsText(sp.geom)
            FROM coastdat.cosmoclmgrid AS sp
            JOIN coastdat.spatial AS point ON (sp.gid=point.gid)
            WHERE st_contains(sp.geom, ST_GeomFromText('{wkt}',4326))
            """.format(wkt=geometry.wkt)
        df = fetch_raw_data(sql_weather_string(year, sql_part), conn, geometry)
        obj = create_single_weather(df, rename_dc)
    else:
        logging.error('Unknown geometry type: {0}'.format(geometry.geom_type))
        obj = None
    return obj
1250045
function(obj) {
        var feature, geometry, attributes, bbox;
        attributes = (obj.properties) ? obj.properties : {};
        bbox = (obj.geometry && obj.geometry.bbox) || obj.bbox;
        try {
            geometry = this.parseGeometry(obj.geometry);
        } catch(err) {
            // deal with bad geometries
            throw err;
        }
        feature = new OpenLayers.Feature.Vector(geometry, attributes);
        if(bbox) {
            feature.bounds = OpenLayers.Bounds.fromArray(bbox);
        }
        if(obj.id) {
            feature.fid = obj.id;
        }
        return feature;
    }
730783
def _make_wcsgeom_from_config(config):
        """"""

        binning = config['binning']
        binsz = binning['binsz']
        coordsys = binning.get('coordsys', 'GAL')
        roiwidth = binning['roiwidth']
        proj = binning.get('proj', 'AIT')
        ra = config['selection']['ra']
        dec = config['selection']['dec']
        npix = int(np.round(roiwidth / binsz))
        skydir = SkyCoord(ra * u.deg, dec * u.deg)

        wcsgeom = WcsGeom.create(npix=npix, binsz=binsz,
                                 proj=proj, coordsys=coordsys,
                                 skydir=skydir)
        return wcsgeom
710840
def project_geometry(geometry, source, target):
    """"""

    project = partial(
        pyproj.transform,
        source,
        target
    )

    return transform(project, geometry)
535449
def _get_all_forecast_from_api(api_result: dict) -> OrderedDict:
    """"""
    # Total time in hours since last forecast
    total_hours_last_forecast = 1.0

    # Last forecast time
    last_time = None

    # Need the ordered dict to get
    # the days in order in next stage
    forecasts_ordered = OrderedDict()

    # Get the parameters
    for forecast in api_result['timeSeries']:

        valid_time = datetime.strptime(
            forecast['validTime'], "%Y-%m-%dT%H:%M:%SZ")
        for param in forecast['parameters']:
            if param['name'] == 't':
                temperature = float(param['values'][0])  # Celcisus
            elif param['name'] == 'r':
                humidity = int(param['values'][0])  # Percent
            elif param['name'] == 'msl':
                pressure = int(param['values'][0])  # hPa
            elif param['name'] == 'tstm':
                thunder = int(param['values'][0])  # Percent
            elif param['name'] == 'tcc_mean':
                octa = int(param['values'][0])  # Cloudiness in octas
                if 0 <= octa <= 8:  # Between 0 -> 8
                    cloudiness = round(100*octa/8)  # Convert octas to percent
                else:
                    cloudiness = 100  # If not determined use 100%
            elif param['name'] == 'Wsymb2':
                symbol = int(param['values'][0])  # category
            elif param['name'] == 'pcat':
                precipitation = int(param['values'][0])  # percipitation
            elif param['name'] == 'pmean':
                mean_precipitation = float(
                    param['values'][0])  # mean_percipitation
            elif param['name'] == 'ws':
                wind_speed = float(param['values'][0])  # wind speed
            elif param['name'] == 'wd':
                wind_direction = int(param['values'][0])  # wind direction
            elif param['name'] == 'vis':
                horizontal_visibility = float(param['values'][0])  # Visibility
            elif param['name'] == 'gust':
                wind_gust = float(param['values'][0])  # wind gust speed

        roundedTemp = int(round(temperature))

        if last_time is not None:
            total_hours_last_forecast = (valid_time - last_time).seconds/60/60

        # Total precipitation, have to calculate with the nr of
        # hours since last forecast to get correct total value
        tp = round(mean_precipitation*total_hours_last_forecast, 2)

        forecast = \
            SmhiForecast(roundedTemp, roundedTemp, roundedTemp,
                         humidity, pressure, thunder, cloudiness,
                         precipitation, wind_direction, wind_speed,
                         horizontal_visibility, wind_gust,
                         round(mean_precipitation, 1), tp, symbol,
                         valid_time)

        if valid_time.day not in forecasts_ordered:
            # add a new list
            forecasts_ordered[valid_time.day] = []

        forecasts_ordered[valid_time.day].append(forecast)

        last_time = valid_time

    return forecasts_ordered
700963
def fromGeoJson(struct, attributes=None):
    ""
    if isinstance(struct, basestring):
        struct = json.loads(struct)
    type_map = {
        'Point': Point,
        'MultiLineString': Polyline,
        'LineString': Polyline,
        'Polygon': Polygon,
        'MultiPolygon': Polygon,
        'MultiPoint': Multipoint,
        'Box': Envelope
    }
    if struct['type'] == "Feature":
        return fromGeoJson(struct, struct.get('properties', None))
    elif struct['type'] == "FeatureCollection":
        sr = None
        if 'crs' in struct:
            sr = SpatialReference(struct['crs']['properties']['code'])
            members = map(fromGeoJson, struct['members'])
            for member in members:
                member.spatialReference = sr
            return members
        else:
            return map(fromGeoJson, struct['members'])
    elif struct['type'] in type_map and hasattr(type_map[struct['type']], 
                                              'fromGeoJson'):
        instances = type_map[struct['type']].fromGeoJson(struct)
        i = []
        assert instances is not None, "GeoJson conversion returned a Null geom"
        for instance in instances:
            if 'properties' in struct:
                instance.attributes = struct['properties'].copy()
                if '@esri.sr' in instance.attributes:
                    instance.spatialReference = SpatialReference.fromJson(
                                               instance.attributes['@esri.sr'])
                    del instance.attributes['@esri.sr']
            if attributes:
                if not hasattr(instance, 'attributes'):
                    instance.attributes = {}
                for k, v in attributes.iteritems():
                    instance.attributes[k] = v
            i.append(instance)
        if i:
            if len(i) > 1:
                return i
            return i[0]
    raise ValueError("Unconvertible to geometry")
601037
def items(cls):
        
        return [
            cls.PRECIPITATION,
            cls.WIND,
            cls.TEMPERATURE,
            cls.PRESSURE
        ]
305002
function(obj) {
        if (obj == null) {
            return null;
        }
        var geometry, collection = false;
        if(obj.type == "GeometryCollection") {
            if(!(OpenLayers.Util.isArray(obj.geometries))) {
                throw "GeometryCollection must have geometries array: " + obj;
            }
            var numGeom = obj.geometries.length;
            var components = new Array(numGeom);
            for(var i=0; i<numGeom; ++i) {
                components[i] = this.parseGeometry.apply(
                    this, [obj.geometries[i]]
                );
            }
            geometry = new OpenLayers.Geometry.Collection(components);
            collection = true;
        } else {
            if(!(OpenLayers.Util.isArray(obj.coordinates))) {
                throw "Geometry must have coordinates array: " + obj;
            }
            if(!this.parseCoords[obj.type.toLowerCase()]) {
                throw "Unsupported geometry type: " + obj.type;
            }
            try {
                geometry = this.parseCoords[obj.type.toLowerCase()].apply(
                    this, [obj.coordinates]
                );
            } catch(err) {
                // deal with bad coordinates
                throw err;
            }
        }
        // We don't reproject collections because the children are reprojected
        // for us when they are created.
        if (this.internalProjection && this.externalProjection && !collection) {
            geometry.transform(this.externalProjection, 
                               this.internalProjection); 
        }                       
        return geometry;
    }
198924
def make_geo(attrs_dict, globe):
    """"""
    attr_mapping = [('satellite_height', 'perspective_point_height'),
                    ('sweep_axis', 'sweep_angle_axis')]
    kwargs = CFProjection.build_projection_kwargs(attrs_dict, attr_mapping)

    # CartoPy can't handle central latitude for Geostationary (nor should it)
    # Just remove it if it's 0.
    if not kwargs.get('central_latitude'):
        kwargs.pop('central_latitude', None)

    # If sweep_angle_axis is not present, we should look for fixed_angle_axis and adjust
    if 'sweep_axis' not in kwargs:
        kwargs['sweep_axis'] = 'x' if attrs_dict['fixed_angle_axis'] == 'y' else 'y'

    return ccrs.Geostationary(globe=globe, **kwargs)
933084
def get_live_weather(lat, lon, writer):
    """"""
    requrl = FORECAST_BASE_URL+forecast_api_token+'/'+str(lat)+','+str(lon)
    req = requests.get(requrl)
    if req.status_code == requests.codes.ok:
        weather = req.json()
        if not weather['currently']:
            click.secho("No live weather currently", fg="red", bold=True)
            return
        writer.live_weather(weather)
    else:
        click.secho("There was problem getting live weather", fg="red", bold=True)
1167930
def geojsonfeature(source, params=''):
    
    parse = re.search(r'(?P<properties>((\w+)(,\w+)*)?)(:(?P<field>(\w+)?))?(:(?P<srid>(\d+)?))?', params)
    if parse:
        parse = parse.groupdict()
    else:
        parse = {}

    geometry_field = parse.get('field') or 'geom'
    properties = parse.get('properties', '').split(',')
    srid = parse.get('srid') or GEOJSON_DEFAULT_SRID

    if source is None or isinstance(source, string_types):
        return 'null'

    if isinstance(source, (GEOSGeometry, GeometryField)):
        encoder = DjangoGeoJSONEncoder()
        if source.srid != srid:
            source.transform(srid)
        feature = {"type": "Feature", "properties": {}}
        feature['geometry'] = encoder.default(source)
        return json.dumps(feature)

    serializer = Serializer()

    if not hasattr(source, '__iter__'):
        source = [source]

    return serializer.serialize(source, properties=properties,
                                geometry_field=geometry_field, srid=srid)
1151401
def parse_json_data(content, raincontent, latitude=52.091579,
                    longitude=5.119734, timeframe=60):
    """"""
    result = {SUCCESS: False, MESSAGE: None, DATA: None}

    if timeframe < 5 or timeframe > 120:
        raise ValueError("Timeframe must be >=5 and <=120.")

    if content is not None:
        try:
            json_content = json.loads(content)
        except json.JSONDecodeError as err:
            result[MESSAGE] = "Unable to parse content as json."
            log.error("Unable to parse content as json. %s", err)
            return result

        result = __parse_ws_data(json_content, latitude, longitude)

        if result[SUCCESS] and raincontent is not None:
            data = __parse_precipfc_data(raincontent, timeframe)
            result[DATA][PRECIPITATION_FORECAST] = data

    log.debug("Extracted weather-data: %s", result[DATA])
    return result
974487
def set_geometry(self, geom):
        
        (self.thet0, self.thet, self.phi0, self.phi, self.alpha, 
            self.beta) = geom
1241350
def get_weather(self):
        
        import predix.data.weather
        weather = predix.data.weather.WeatherForecast()
        return weather
835140
function buildGeom(item, params) {
    var geom = {},
        attr;

    for(var gtype in params.geom) {
      var val = params.geom[gtype];

      // Geometry parameter specified as: {Point: 'coords'}
      if(typeof val === 'string' && item.hasOwnProperty(val)) {
        if(gtype === 'GeoJSON') {
          geom = item[val];
        } else {
          geom.type = gtype;
          geom.coordinates = item[val];
        }
      }

      /* Handle things like:
      Polygon: {
        northeast: ['lat', 'lng'],
        southwest: ['lat', 'lng']
      }
      */
      else if(typeof val === 'object' && !Array.isArray(val)) {
        /*jshint loopfunc: true */
        var points = Object.keys(val).map(function(key){
          var order = val[key];
          var newItem = item[key];
          return buildGeom(newItem, {geom:{ Point: order}});
        });
        geom.type = gtype;
        /*jshint loopfunc: true */
        geom.coordinates = [].concat(points.map(function(p){
          return p.coordinates;
        }));
      }

      // Geometry parameter specified as: {Point: ['lat', 'lng', 'alt']}
      else if(Array.isArray(val) && item.hasOwnProperty(val[0]) && item.hasOwnProperty(val[1]) && item.hasOwnProperty(val[2])){
        geom.type = gtype;
        geom.coordinates = [Number(item[val[1]]), Number(item[val[0]]),  Number(item[val[2]])];
      }

      // Geometry parameter specified as: {Point: ['lat', 'lng']}
      else if(Array.isArray(val) && item.hasOwnProperty(val[0]) && item.hasOwnProperty(val[1])){
        geom.type = gtype;
        geom.coordinates = [Number(item[val[1]]), Number(item[val[0]])];
      }

      // Geometry parameter specified as: {Point: ['container.lat', 'container.lng', 'container.alt']}
      else if(Array.isArray(val) && isNested(val[0]) && isNested(val[1]) && isNested(val[2])){
        var coordinates = [];
        for (var i = 0; i < val.length; i++) {	// i.e. 0 and 1
          var paths = val[i].split('.');
          var itemClone = item;
          for (var j = 0; j < paths.length; j++) {
            if (!itemClone.hasOwnProperty(paths[j])) {
              return false;
            }
            itemClone = itemClone[paths[j]];	// Iterate deeper into the object
          }
          coordinates[i] = itemClone;
        }
        geom.type = gtype;
        geom.coordinates = [Number(coordinates[1]), Number(coordinates[0]), Number(coordinates[2])];
      }

      // Geometry parameter specified as: {Point: ['container.lat', 'container.lng']}
      else if(Array.isArray(val) && isNested(val[0]) && isNested(val[1])){
        var coordinates = [];
        for (var i = 0; i < val.length; i++) {	// i.e. 0 and 1
          var paths = val[i].split('.');
          var itemClone = item;
          for (var j = 0; j < paths.length; j++) {
            if (!itemClone.hasOwnProperty(paths[j])) {
              return false;
            }
            itemClone = itemClone[paths[j]];	// Iterate deeper into the object
          }
          coordinates[i] = itemClone;
        }
        geom.type = gtype;
        geom.coordinates = [Number(coordinates[1]), Number(coordinates[0])];
      }

      // Geometry parameter specified as: {Point: [{coordinates: [lat, lng]}]}
      else if (Array.isArray(val) && val[0].constructor.name === 'Object' && Object.keys(val[0])[0] === 'coordinates'){
        geom.type = gtype;
        geom.coordinates = [Number(item.coordinates[(val[0].coordinates).indexOf('lng')]), Number(item.coordinates[(val[0].coordinates).indexOf('lat')])];
      }
    }

    if(params.doThrows && params.doThrows.invalidGeometry && !GeoJSON.isGeometryValid(geom)){
      throw new InvalidGeometryError(item, params);
    }

    return geom;
  }
292006
def get_color_data(self, condition):
        '''
        
        '''
        if condition not in self.color_icons:
            # Check for similarly-named conditions if no exact match found
            condition_lc = condition.lower()
            if 'cloudy' in condition_lc or 'clouds' in condition_lc:
                if 'partly' in condition_lc:
                    condition = 'Partly Cloudy'
                else:
                    condition = 'Cloudy'
            elif condition_lc == 'overcast':
                condition = 'Cloudy'
            elif 'thunder' in condition_lc or 't-storm' in condition_lc:
                condition = 'Thunderstorm'
            elif 'snow' in condition_lc:
                condition = 'Snow'
            elif 'rain' in condition_lc or 'showers' in condition_lc:
                condition = 'Rainy'
            elif 'sunny' in condition_lc:
                condition = 'Sunny'
            elif 'clear' in condition_lc or 'fair' in condition_lc:
                condition = 'Fair'
            elif 'fog' in condition_lc:
                condition = 'Fog'

        return self.color_icons['default'] \
            if condition not in self.color_icons \
            else self.color_icons[condition]
946430
def get_shape(self, ds_id, ds_info):
        """"""
        var_path = ds_info['file_key']
        shape = self[var_path + '/shape']
        if ((ds_info.get('standard_name') == "longitude" or ds_info.get('standard_name') == "latitude") and
                ds_id.resolution == 10000):
            return shape[0], int(shape[1] / 2)
        return shape