/*
Each record contains a field with a custom code - Use a custom lookup to find an associated GeoJSON geometry
542626
function (record, index) {
		var code = this.options.codeField ? L.Util.getFieldValue(record, this.options.codeField) : index;

		this._lookupIndex = this._lookupIndex || L.GeometryUtils.indexFeatureCollection(this.options.locationLookup, this.options.locationIndexField || this.options.codeField);

		var geoJSON = this._lookupIndex[code];
		var location = null;

		if (!geoJSON && code.indexOf('0') === 0) {
			geoJSON = this._lookupIndex[code.substring(1)];
		}

		if (geoJSON) {
			var me = this;
			var recordToLayer = function (location, record) {
				return me.recordToLayer(location, record);
			};

			location = L.GeometryUtils.getGeoJSONLocation(geoJSON, record, this.options.locationTextField, recordToLayer);
		}

		return location;
	}
910719
function(record, extraNames) {
      var fieldNames = record.getFields().map(function (field) {
        return field.getName();
      });

      if (extraNames) {
        fieldNames = fieldNames.concat(extraNames);
      }
      return fieldNames;
    }
1038294
function getPrototype(model) {
  if (model.__recordPrototype) return model.__recordPrototype;

  const mrProto = Object.assign({}, proto);// eslint-disable-line no-use-before-define
  const extraProperties = {};
  Object.keys(model.def.fields).forEach((fieldName) => {
    extraProperties[fieldName] = {
      enumerable: true,
      get() {
        const value = getf.call(this, fieldName);
        return value;
      },
      set(value) {
        return setf.call(this, fieldName, value);
      },
    };
  });
  Object.defineProperties(mrProto, extraProperties);
  model.__recordPrototype = mrProto;
  return mrProto;
}
238078
def _parse_json(self, doc, exactly_one):
        
        if doc.get('error'):
            raise GeocoderServiceError(doc['error']['message'])

        try:
            places = doc['response']['GeoObjectCollection']['featureMember']
        except KeyError:
            raise GeocoderParseError('Failed to parse server response')

        def parse_code(place):
            """
            Parse each record.
            """
            try:
                place = place['GeoObject']
            except KeyError:
                raise GeocoderParseError('Failed to parse server response')

            longitude, latitude = [
                float(_) for _ in place['Point']['pos'].split(' ')
            ]

            name_elements = ['name', 'description']
            location = ', '.join([place[k] for k in name_elements if place.get(k)])

            return Location(location, (latitude, longitude), place)

        if exactly_one:
            try:
                return parse_code(places[0])
            except IndexError:
                return None
        else:
            return [parse_code(place) for place in places]
327149
function (record, index) {
		var getLocation = function (latitudeField, longitudeField) {
			var latitude = L.Util.getFieldValue(record, latitudeField);
			var longitude = L.Util.getFieldValue(record, longitudeField);
			var location = null;

			if (latitude && longitude) {
				var latlng = new L.LatLng(latitude, longitude);
				location = {
					location: latlng,
					text: [latlng.lat.toFixed(3),latlng.lng.toFixed(3)].join(', '),
					center: latlng
				};
			}

			return location;
		};

		var location = getLocation(this.options.latitudeField, this.options.longitudeField);

		if (!location && this.options.fallbackLocationFields) {
			var fallbackIndex = 0;
			var fallbackLocationFields;
			while (!location && fallbackIndex < this.options.fallbackLocationFields.length) {
				fallbackLocationFields = this.options.fallbackLocationFields[fallbackIndex];
				location = getLocation(fallbackLocationFields.latitudeField, fallbackLocationFields.longitudeField);
				fallbackIndex++;
			}
		}

		return location;
	}
620369
private static Field recordIdFieldIn(Class klass) {
        for (Field field : klass.getDeclaredFields()) {
            if (field.isAnnotationPresent(RecordId.class)) {
                return field;
            }
        }
        Class superclass = klass.getSuperclass();
        if (superclass != null) {
            return recordIdFieldIn(superclass);
        }
        throw new RecordIdNotFoundException(klass);
    }
1227470
def geojson(self, feature_id):
        """"""
        if self._geojson.get('id', feature_id) == feature_id:
            return self._geojson
        else:
            geo = self._geojson.copy()
            geo['id'] = feature_id
            return geo
1301030
function( json, params, callback ){
    if ( params.geometry ){
      this.geometryFilter( json, params, callback );
    } else if ( params.where ){
      this.whereFilter( json, params, callback );
    } else {
      //probably better to parse all params upfront and confirm valid types
      if ( params.returnCountOnly === 'true' || params.returnCountOnly ){
        
        callback( null, { count: json.features.length });

      } else if ( params.returnIdsOnly === 'true' || params.returnIdsOnly){
        this.getIds( json, params.idField, params, function( err, ids ){
          callback( err, ids );
        });

      } else {

        if (params.orderByFields && params.orderByFields !== ''){
          var fld = params.orderByFields.split(' ');
          var order = params.orderByFields;
          if (fld[fld.length-1] == 'DESC'){
            order = '-' + params.orderByFields;
          }
          json.features = this.orderBy(json.features, params.orderByFields, order);
        }

        if ( ( params.returnGeometry === false || params.returnGeometry == 'false') && (!params.outFields || params.outFields != '*')){
          json.features.forEach(function(f){
            delete f.geometry;
          });
        } else if ( params.outSR && ( params.outSR == '102100' ) ){
          if ( json.spatialReference ){
            json.spatialReference.wkid = params.outSR;
            var coords;
            // project each geometry to merator
            json.features.forEach( function( f ){
              if ( f.geometry.x && f.geometry.y ) {
                coords = new terraformer.Point( [f.geometry.x, f.geometry.y] ).toMercator().coordinates;
                f.geometry.x = coords[0];
                f.geometry.y = coords[1];
              } else if ( f.geometry.rings ){
                f.geometry.rings = new terraformer.Polygon( f.geometry.rings ).toMercator().coordinates;
              } else if ( f.geometry.paths ) {
                f.geometry.paths = new terraformer.LineString( f.geometry.paths ).toMercator().coordinates;
              }
              f.geometry.spatialReference.wkid = params.outSR;
            });
          }
        }

        // checkout for outfields
        if ( params.outFields && params.outFields != '*' ){
          var features = [],
            props,
            outFields = params.outFields.split( ',' );

          json.features.forEach( function( f ){
            props = _.pick(f.attributes || f.properties, outFields);

            var newFeature = { geometry: f.geometry};
            if ( f.properties ) {
              newFeature.properties = props;
            } else {
              newFeature.attributes = props;
            }
            features.push( newFeature );
          });
          json.features = features;
        }

        // before we send back json, process outStats
        if ( params.outStatistics ){
          this.outStatistics( json, params, callback );
        } else {
          callback( null, json );
        }


      }

    }

  }
83640
def _parse_json(self, doc, exactly_one):
        
        places = doc.get('geonames', [])
        self._raise_for_error(doc)
        if not len(places):
            return None

        def parse_code(place):
            """
            Parse each record.
            """
            latitude = place.get('lat', None)
            longitude = place.get('lng', None)
            if latitude and longitude:
                latitude = float(latitude)
                longitude = float(longitude)
            else:
                return None

            placename = place.get('name')
            state = place.get('adminName1', None)
            country = place.get('countryName', None)

            location = ', '.join(
                [x for x in [placename, state, country] if x]
            )

            return Location(location, (latitude, longitude), place)

        if exactly_one:
            return parse_code(places[0])
        else:
            return [parse_code(place) for place in places]
307241
function getFormDataSources(formJSON) {
    var dataSources;
    var pages = formJSON.pages || [];
    dataSources = _.map(pages, function(page) {
      var fields = page.fields || [];

      fields = _.map(fields, function(field) {
        //If the field is defined as a Data Source field, and it has a data source, then return that data source.
        if (field.dataSourceType === models.FORM_CONSTANTS.DATA_SOURCE_TYPE_DATA_SOURCE && field.dataSource) {
          return field.dataSource;
        } else {
          return undefined;
        }
      });

      //Removing any undefined values
      return _.compact(fields);
    });

    //Remove all nested arrays
    dataSources = _.flatten(dataSources);

    logger.debug("Got Form Data Sources", dataSources);

    //Only Want One Of Each Data Source
    return _.uniq(dataSources);
  }
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)
318928
private Geometry parseGeometry(JsonParser jp, String geometryType) throws IOException, SQLException {        
        if (geometryType.equalsIgnoreCase(GeoJsonField.POINT)) {
            return parsePoint(jp);
        } else if (geometryType.equalsIgnoreCase(GeoJsonField.MULTIPOINT)) {
            return parseMultiPoint(jp);
        } else if (geometryType.equalsIgnoreCase(GeoJsonField.LINESTRING)) {
            return parseLinestring(jp);
        } else if (geometryType.equalsIgnoreCase(GeoJsonField.MULTILINESTRING)) {
            return parseMultiLinestring(jp);
        } else if (geometryType.equalsIgnoreCase(GeoJsonField.POLYGON)) {
            return parsePolygon(jp);
        } else if (geometryType.equalsIgnoreCase(GeoJsonField.MULTIPOLYGON)) {
            return parseMultiPolygon(jp);
        } else if (geometryType.equalsIgnoreCase(GeoJsonField.GEOMETRYCOLLECTION)) {
            return parseGeometryCollection(jp);
        } else {
            throw new SQLException("Unsupported geometry : " + geometryType);
        }
    }
1130218
def from_geojson(geojson, srid=4326):
        
        type_ = geojson["type"].lower()
        if type_ == "geometrycollection":
            geometries = []
            for geometry in geojson["geometries"]:
                geometries.append(Geometry.from_geojson(geometry, srid=None))
            return GeometryCollection(geometries, srid)
        elif type_ == "point":
            return Point(geojson["coordinates"], srid=srid)
        elif type_ == "linestring":
            return LineString(geojson["coordinates"], srid=srid)
        elif type_ == "polygon":
            return Polygon(geojson["coordinates"], srid=srid)
        elif type_ == "multipoint":
            geometries = _MultiGeometry._multi_from_geojson(geojson, Point)
            return MultiPoint(geometries, srid=srid)
        elif type_ == "multilinestring":
            geometries = _MultiGeometry._multi_from_geojson(geojson, LineString)
            return MultiLineString(geometries, srid=srid)
        elif type_ == "multipolygon":
            geometries = _MultiGeometry._multi_from_geojson(geojson, Polygon)
            return MultiPolygon(geometries, srid=srid)
522227
public static Geometry geomFromGeoJSON(String geojson) throws IOException, SQLException {
        if (geojson == null) {
            return null;
        }
        if (jsFactory == null) {
            jsFactory = new JsonFactory();
            jsFactory.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
            jsFactory.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
            jsFactory.configure(JsonParser.Feature.ALLOW_NON_NUMERIC_NUMBERS, true);
            reader = new GJGeometryReader(new GeometryFactory());
        }
        JsonParser jp = jsFactory.createParser(geojson);
        return reader.parseGeometry(jp);
    }
1254096
function( key, geojson, layerId, callback ){
    var self = this;
    var info = {},
      count = 0;
      error = null;

      info.name = geojson.name ;
      info.updated_at = geojson.updated_at;
      info.expires_at = geojson.expires_at;
      info.retrieved_at = geojson.retrieved_at;
      info.status = geojson.status;
      info.format = geojson.format;
      info.sha = geojson.sha;
      info.info = geojson.info;

      var table = key+':'+layerId;

      self._createTable( table, self._buildSchemaFromFeature(), function(err){

        // insert each feature
        if ( geojson.length ){
          geojson = geojson[0];
        }
        geojson.features.forEach(function(feature, i){
          self._run(self._insertFeature(table, feature, i), function(err){
          });
        });

        // TODO Why not use an update query here?
        self._run( 'delete from "'+self.infoTable+'" where id=\''+table+':info\'', function(err){
          self._run( 'insert into "'+self.infoTable+'" values (\''+table+':info\',\''+JSON.stringify(info).replace(/'/g,'')+'\')', function(err){
            callback(err, true);
          });
        });
      });

  }
803201
function (identifier) {
            var self = this;

            // Search for Lookup records associated with the identifier (id, macAddress, ipAddress).
            return waterline.lookups.findByTerm(identifier).then(function (documents) {
                // Identify a record with a node id.
                var lookup = _.find(documents, function (item) {
                    return item.node !== undefined;
                });
                // If we find a record with a node id then we can lookup the node with it,
                // otherwise we can try to lookup with the identifier directly.
                if (lookup) {
                    return self.findOne({ id: lookup.node });
                } else {
                    return self.findOne({ id: identifier })
                    .then(function(rec) {
                        if(!rec) {
                            return self.findOne({identifiers: identifier});
                        }
                        return rec;
                    });
                }
            });
        }
1337723
function toGeoJSON(json, options = Options) {
  const short = options.short || Options.short
  const collection = helpers.featureCollection([])
  json.results.map(result => {
    // Get Geometries
    const point = parsePoint(result)
    const bbox = parseBBox(result)

    // Calculate Confidence score
    const location_type = result.geometry.location_type
    let confidence = confidenceScore(bbox)
    if (location_type === 'ROOFTOP') { confidence = 10 }

    // GeoJSON Point properties
    const properties = {
      confidence,
      location_type,
      formatted_address: result.formatted_address,
      place_id: result.place_id,
      types: result.types,
    }

    // Google Specific Properties
    const components = parseAddressComponents(result.address_components, short)
    Object.keys(components).forEach(key => properties[key] = components[key])

    // Store Point to GeoJSON feature collection
    if (point) {
      point.bbox = bbox
      point.properties = properties
      collection.features.push(point)
    }
  })
  return collection
}