/*
检查并替换输入的地理信息相关参数，使用PostGis提供的ST_GeomFromText函数
@author Pin Liu
178529
protected void checkAndReplaceInput(List<IntrospectedColumn> columns, XmlElement xe){
	  for(Element element : xe.getElements()){
	    if(element instanceof XmlElement){
	      checkAndReplaceInput(columns, (XmlElement) element);
	    }
	    if(element instanceof TextElement){
	      TextElement te = (TextElement) element;
    		checkAndReplaceInput(columns, te);
	    }
	  }
	}
1178076
private function position($pos, $oldWidth, $oldHeight, $waterWidth, $waterHeight, $isText = false, $fontSize = 14)
    {
        if ( is_array($pos) )
        {
            return [
                'x' => $pos[0],
                'y' => $pos[1]
            ];
        }

        if ($pos === self::POS_TOP_LEFT)
        {
            $posX = 0;
            $posY = ($isText) ? $waterHeight : 0;
        }
        elseif ($pos === self::POS_TOP_CENTER)
        {
            $posX = ($oldWidth - $waterWidth) / 2;
            $posY = ($isText) ? $waterHeight : 0;
        }
        elseif ($pos === self::POS_TOP_RIGHT)
        {
            $posX = $oldWidth - $waterWidth;
            $posY = ($isText) ? $waterHeight : 0;
        }
        elseif ($pos === self::POS_CENTER_LEFT)
        {
            $posX = 0;
            $posY = ($isText) ? (($oldHeight - $waterHeight) / 2) + $fontSize : ($oldHeight - $waterHeight) / 2;
        }
        elseif ($pos === self::POS_CENTER_CENTER)
        {
            $posX = ($oldWidth - $waterWidth) / 2;
            $posY = ($isText) ? (($oldHeight - $waterHeight) / 2) + $fontSize : ($oldHeight - $waterHeight) / 2;
        }
        elseif ($pos === self::POS_CENTER_RIGHT)
        {
            $posX = $oldWidth - $waterWidth;
            $posY = ($isText) ? (($oldHeight - $waterHeight) / 2) + $fontSize : ($oldHeight - $waterHeight) / 2;
        }
        elseif ($pos === self::POS_BOTTOM_LEFT)
        {
            $posX = 0;
            $posY = ($isText) ? ($oldHeight - $waterHeight) + $fontSize : $oldHeight - $waterHeight;
        }
        elseif ($pos === self::POS_BOTTOM_CENTER)
        {
            $posX = ($oldWidth - $waterWidth) / 2;
            $posY = ($isText) ? ($oldHeight - $waterHeight) + $fontSize : $oldHeight - $waterHeight;
        }
        elseif ($pos === self::POS_BOTTOM_RIGHT)
        {
            $posX = $oldWidth - $waterWidth;
            $posY = ($isText) ? ($oldHeight - $waterHeight) + $fontSize : $oldHeight - $waterHeight;
        }
        else
        {
            $posX = rand(0, ($oldWidth  - $waterWidth));
            $posY = rand(0, ($oldHeight - $waterHeight));
        }

        return [
            "x" => $posX,
            "y" => $posY
        ];
    }
812139
function findMapForContext(sContext) {
		var p, mMap;
		if ( sContext != null ) {
			// maps are defined on module IDs, reduce URN to module ID
			sContext = urnToIDAndType(sContext).id;
			p = sContext.length;
			mMap = mMaps[sContext];
			while ( p > 0 && mMap == null ) {
				p = sContext.lastIndexOf('/');
				if ( p > 0 ) { // Note: an empty segment at p = 0 (leading slash) will be ignored
					sContext = sContext.slice(0, p);
					mMap = mMaps[sContext];
				}
			}
		}
		// if none is found, fallback to '*' map
		return mMap || mMaps['*'];
	}
754628
def getAsGdalRaster(self, rasterFieldName, tableName, rasterIdFieldName, rasterId, gdalFormat, newSRID=None, **kwargs):
        

        # Check gdalFormat
        if not (gdalFormat in RasterConverter.supportedGdalRasterFormats(self._session)):
            raise ValueError('FORMAT NOT SUPPORTED: {0} format is not supported '
                             'in this PostGIS installation.'.format(gdalFormat))

        # Setup srid
        if newSRID:
            srid = ', {0}'.format(newSRID)
        else:
            srid = ''

        # Compile options
        if kwargs:
            optionsList = []
            for key, value in kwargs.iteritems():
                kwargString = "'{0}={1}'".format(key, value)
                optionsList.append(kwargString)

            optionsString = ','.join(optionsList)
            options = ', ARRAY[{0}]'.format(optionsString)
        else:
            options = ''

        # Create statement
        statement = '''
                    SELECT ST_AsGDALRaster("{0}", '{1}'{5}{6})
                    FROM "{2}" WHERE "{3}"={4};
                    '''.format(rasterFieldName, gdalFormat, tableName, rasterIdFieldName, rasterId,  options, srid)

        # Execute query
        result = self._session.execute(statement).scalar()

        return bytes(result).decode('utf-8')
983711
function(wilddogRef) {
  /********************/
  /*  PUBLIC METHODS  */
  /********************/
  /**
   * 返回创建WildGeo实例的Wilddog实例
   * @return {Wilddog} 用来创建WildGeo实例的Wilddog实例
   */
  this.ref = function() {
    return _wilddogRef;
  };

  /*
   * 往Wilddog中写入key-location数据对。当写入成功后返回一个空的promise。
   * 如果要存入的key在WildGeo中已经存在，将被覆盖重写。
   * @param {string|Object} keyOrLocations 代表被增加的位置的key或者代表要被添加的key-location数据对。
   * @param {Array.<number>|undefined} location 要被添加的经纬坐标数组。
   * @return {Promise.<>} 写入成功后执行的Promise
   */
  this.set = function(keyOrLocations, location) {
    var locations;
    if (typeof keyOrLocations === "string" && keyOrLocations.length !== 0) {
      locations = {};
      locations[keyOrLocations] = location;
    } else if (typeof keyOrLocations === "object") {
      if (typeof location !== "undefined") {
        throw new Error("The location argument should not be used if you pass an object to set().");
      }
      locations = keyOrLocations;
    } else {
      throw new Error("keyOrLocations must be a string or a mapping of key - location pairs.");
    }

    var newData = {};

    Object.keys(locations).forEach(function(key) {
      validateKey(key);

      var location = locations[key];
      if (location === null) {
        newData[key] = null;
      } else {
        validateLocation(location);

        var geohash = encodeGeohash(location);
        newData[key] = encodeWildGeoObject(location, geohash);
      }
    });

    return new RSVP.Promise(function(resolve, reject) {
      function onComplete(error) {
        if (error !== null) {
          reject("Error: Wilddog synchronization failed: " + error);
        }
        else {
          resolve();
        }
      }

      _wilddogRef.update(newData, onComplete);
    });
  };

  /**
   * 返回key对应的一个包含地理位置信息的promise
   * 如果key参数在数据库中不存在，返回空的promise
   * @param {string} key 要检索的地理位置的key值
   * @return {Promise.<Array.<number>>} 包含根据key值检索到的位置信息的promise
   */
  this.get = function(key) {
    validateKey(key);
    return new RSVP.Promise(function(resolve, reject) {
      _wilddogRef.child(key).once("value", function(dataSnapshot) {
        if (dataSnapshot.val() === null) {
          resolve(null);
        } else {
          resolve(decodeWildGeoObject(dataSnapshot.val()));
        }
      }, function (error) {
        reject("Error: Wilddog synchronization failed: " + error);
      });
    });
  };

  /**
   * 删除WildGeo中的key，删除成功后返回一个空的promise
   * 如果参数key不在WildGeo中，promise仍能成功解析。
   * @param {string} key 被删除的地理位置的key值
   * @return {Promise.<string>} 输入的key被删除后返回的promise
   */
  this.remove = function(key) {
    return this.set(key, null);
  };

  /**
   * 根据查询条件返回一个新的WildGeo实例。
   * @param {Object} queryCriteria 指定了圆心坐标和半径的查询条件
   * @return {GeoQuery} 一个新的GeoQuery对象
   */
  this.query = function(queryCriteria) {
    return new GeoQuery(_wilddogRef, queryCriteria);
  };

  /*****************/
  /*  CONSTRUCTOR  */
  /*****************/
  if (Object.prototype.toString.call(wilddogRef) !== "[object Object]") {
    throw new Error("wilddogRef must be an instance of Wilddog");
  }

  var _wilddogRef = wilddogRef;
}
1317021
function(length, points) {

                var result = {},
                    //顶点索引
                    pointIndex = null;

                for (var i = 0, j; i < length; i++) {

                    var point1 = null,
                        point2 = null;

                    //计算当前点

                    j = (i + 1) % length;

                    //保存当前处理的顶点索引
                    pointIndex = j;

                    point1 = points[i + ',' + j];

                    //计算下一个点
                    i = j;
                    j = (i + 1) % length;

                    point2 = points[i + ',' + j];

                    result[pointIndex] = {
                        points: [{
                            x: point1.x,
                            y: point1.y
                        }, {
                            x: point2.x,
                            y: point2.y
                        }],

                        center: {
                            x: (point1.x + point2.x) / 2,
                            y: (point1.y + point2.y) / 2
                        }
                    };

                    //还原i值
                    i = (pointIndex + length - 1) % length;

                }

                return result;

            }
842193
public function jsonGeoAnalysisList() {
        $wt_tree = Globals::getTree();
        $controller = new JsonController();
        $controller
            ->restrictAccess(Auth::isManager($wt_tree));
        
        // Generate an AJAX/JSON response for datatables to load a block of rows
        $search = Filter::postArray('search');
        if($search) $search = $search['value'];
        $start  = Filter::postInteger('start');
        $length = Filter::postInteger('length');
        $order  = Filter::postArray('order');
        
        foreach($order as $key => &$value) {
            switch($value['column']) {
                case 3:
                    $value['column'] = 'majgd_descr';
                    break;
                case 5;
                    $value['column'] = 'majgd_sublevel';
                    break;
                default:
                    unset($order[$key]);
            }
        }
        
        /** @var GeoAnalysisProvider $provider */
        $provider = $this->module->getProvider();
        
        $list = $provider->getFilteredGeoAnalysisList($search, $order, $start, $length);
        $recordsFiltered = count($list);
        $recordsTotal = $this->provider->getGeoAnalysisCount();
        
        $data = array();
        $place_hierarchy = $this->provider->getPlacesHierarchy();
        foreach($list as $ga) {
            /** @var GeoAnalysis $ga */
            
            $datum = array();
            $options= $ga->getOptions();
            
            $datum[0] = '
                <div class="btn-group">
                    <button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
                        <i class="fa fa-pencil"></i><span class="caret"></span>
                    </button>
                    <ul class="dropdown-menu" role="menu">
                       <li>
                            <a href="#" onclick="return set_geoanalysis_status('. $ga->getId().', '.($ga->isEnabled() ? 'false' : 'true').', \''.Filter::escapeJs($wt_tree->getName()).'\');">
                                <i class="fa fa-fw '.($ga->isEnabled() ? 'fa-times' : 'fa-check').'"></i> ' . ($ga->isEnabled() ? I18N::translate('Disable') : I18N::translate('Enable')) . '
                            </a>
                       </li>
                        <li>
                            <a href="module.php?mod='.$this->module->getName().'&mod_action=AdminConfig@edit&ga_id='.$ga->getId().'&ged='.$wt_tree->getName().'">
                                <i class="fa fa-fw fa-pencil"></i> ' . I18N::translate('Edit') . '
                            </a>
                       </li>
                       <li class="divider" />
                       <li>
                            <a href="#" onclick="return delete_geoanalysis('. $ga->getId().', \''.Filter::escapeJs($wt_tree->getName()).'\');">
                                <i class="fa fa-fw fa-trash-o"></i> ' . I18N::translate('Delete') . '
                            </a>
                       </li>
                    </ul>
                </div>';
		    $datum[1] = $ga->getId();
		    $datum[2] = $ga->isEnabled() ? 
				'<i class="fa fa-check"></i><span class="sr-only">'.I18N::translate('Enabled').'</span>' : 
				'<i class="fa fa-times"></i><span class="sr-only">'.I18N::translate('Disabled').'</span>';
		    $datum[3] = $ga->getTitle();
		    $analysis_level = $ga->getAnalysisLevel();
		    if($place_hierarchy['type'] == 'header') {
		        $datum[4] = $place_hierarchy['hierarchy'][$analysis_level - 1];
		    } else {
		        $datum[4] = $analysis_level . '(' . $place_hierarchy['hierarchy'][$analysis_level - 1] . ')';
		    }
		    $datum[5] = $ga->getAnalysisLevel();
		    $datum[6] = '<i class="fa fa-times"></i><span class="sr-only">'.I18N::translate('None').'</span>';
		    $datum[7] = '<i class="fa fa-times"></i><span class="sr-only">'.I18N::translate('None').'</span>';
		    if($ga->hasMap()) {
		        if($options->getMap()->isLoaded()) {
    		        $datum[6] = $options->getMap()->getDescription();
    		        $datum[7] = '<span data-toggle="tooltip" title="' . $options->getMap()->getTopLevelName() . '" />';
    		        $top_level = $options->getMapLevel();
    		        if($place_hierarchy['type'] == 'header') {
    		            $datum[7] .= $place_hierarchy['hierarchy'][$top_level - 1];
    		        } else {
    		            $datum[7] .= $top_level . '(' . $place_hierarchy['hierarchy'][$top_level - 1] . ')';
    		        }
    		        $datum[7] .= '</span>';
		        }
		        else {
		            $datum[6] = I18N::translate('Error when loading map.');
		        }
		    }
		    $datum[8] = $options->isUsingFlags() ? 
				'<i class="fa fa-check"></i><span class="sr-only">'.I18N::translate('Yes').'</span>' : 
				'<i class="fa fa-times"></i><span class="sr-only">'.I18N::translate('No').'</span>';
		    $datum[9] = $options->getMaxDetailsInGen() > 0 ? $options->getMaxDetailsInGen() : I18N::translate('All');
		    
		    $data[] = $datum;
        }
        
        $controller->pageHeader();
        
        $controller->encode(array(
            'draw'            => Filter::getInteger('draw'),
            'recordsTotal'    => $recordsTotal,
            'recordsFiltered' => $recordsFiltered,
            'data'            => $data
        ));
        
    }
83397
function TexInfo () {
    this.minFilter = GL_NEAREST
    this.magFilter = GL_NEAREST

    this.wrapS = GL_CLAMP_TO_EDGE
    this.wrapT = GL_CLAMP_TO_EDGE

    this.anisotropic = 1

    this.genMipmaps = false
    this.mipmapHint = GL_DONT_CARE
  }
912863
function writeMultiLineStringGeometry_(geometry) {
  if (geometry instanceof olGeomMultiLineString) {
    const ends = geometry.getEnds();
    const lineStringCount = ends.length;
    const flatCoordinates = geometry.getFlatCoordinates();
    const stride = geometry.getStride();
    let offset = 0;
    const textArray = ['L('];
    for (let i = 0; i < lineStringCount; ++i) {
      const end = ends[i];
      const text = this.encodeCoordinates_(flatCoordinates, stride, offset, end);
      if (i !== 0) {
        textArray.push('\'');
      }
      textArray.push(text);
      offset = end;
    }
    textArray.push(')');
    return textArray.join('');
  }
  return null;
}
805143
function parseData() {
    parent::parseData();

    $font = $this->getFont();

    do {
      $flags      = $font->readUInt16();
      $glyphIndex = $font->readUInt16();

      $a = 1.0;
      $b = 0.0;
      $c = 0.0;
      $d = 1.0;
      $e = 0.0;
      $f = 0.0;

      $point_compound  = null;
      $point_component = null;

      $instructions = null;

      if ($flags & self::ARG_1_AND_2_ARE_WORDS) {
        if ($flags & self::ARGS_ARE_XY_VALUES) {
          $e = $font->readInt16();
          $f = $font->readInt16();
        }
        else {
          $point_compound  = $font->readUInt16();
          $point_component = $font->readUInt16();
        }
      }
      else {
        if ($flags & self::ARGS_ARE_XY_VALUES) {
          $e = $font->readInt8();
          $f = $font->readInt8();
        }
        else {
          $point_compound  = $font->readUInt8();
          $point_component = $font->readUInt8();
        }
      }

      if ($flags & self::WE_HAVE_A_SCALE) {
        $a = $d = $font->readInt16();
      }
      elseif ($flags & self::WE_HAVE_AN_X_AND_Y_SCALE) {
        $a = $font->readInt16();
        $d = $font->readInt16();
      }
      elseif ($flags & self::WE_HAVE_A_TWO_BY_TWO) {
        $a = $font->readInt16();
        $b = $font->readInt16();
        $c = $font->readInt16();
        $d = $font->readInt16();
      }

      //if ($flags & self::WE_HAVE_INSTRUCTIONS) {
      //
      //}

      $component                  = new OutlineComponent();
      $component->flags           = $flags;
      $component->glyphIndex      = $glyphIndex;
      $component->a               = $a;
      $component->b               = $b;
      $component->c               = $c;
      $component->d               = $d;
      $component->e               = $e;
      $component->f               = $f;
      $component->point_compound  = $point_compound;
      $component->point_component = $point_component;
      $component->instructions    = $instructions;

      $this->components[] = $component;
    } while ($flags & self::MORE_COMPONENTS);
  }
1210623
function placeSlotSegs(segs) {
	var levels = buildSlotSegLevels(segs);
	var level0 = levels[0];
	var i;

	computeForwardSlotSegs(levels);

	if (level0) {

		for (i=0; i<level0.length; i++) {
			computeSlotSegPressures(level0[i]);
		}

		for (i=0; i<level0.length; i++) {
			computeSlotSegCoords(level0[i], 0, 0);
		}
	}

	return flattenSlotSegLevels(levels);
}
542684
public function toGeoJson() {
        $Context = $this->_context;


        //If is a invalid object
        if (null === $Context) {
            return $Context;
        }


        //If is not an array(query response) and  is a object
        if (!is_array($Context)) {
            //Check if is a valid entity object
            if (is_object($Context) && isset($Context->id) && isset($Context->type)) {
                $Context = [$Context];
            } else {
                return null;
            }
        }

        $geoJson = (object) ["type" => "FeatureCollection", "features" => []];

        //Build FeatureCollection
//        $countContext = count($Context);
        foreach ($Context as $Entity) { //0.0080490112304688 Seconds
//        for ($i = 0; $i < $countContext; $i++) { //0.025826215744019 Seconds
//            $Entity = $Context[$i];

            if (!(isset($Entity->id) && isset($Entity->type))) {
                continue;
            }
            
            $Feature = (object) ["type" => "Feature", "properties" => ['__metadata'=>[]], "geometry" => null];

            $entityType = null;
            $entityID = null;
            //Roll-out all properties of this feature
            foreach ($Entity as $key => $attr) {
                switch ($key) {
                    case "id":
                        $entityID = $attr;
                        $Feature->properties[$key] = $attr;
                        break;
                    case "type":
                        $entityType = $attr;
                        $Feature->properties[$key] = $attr;
                        break;
                    default:
                        switch ($attr->type) {
                            case "geo:json":
                                $Feature->geometry = $attr->value;
                                $Feature->geometry->type = ucfirst(strtolower($Feature->geometry->type)); //Normalization of geoJson geometry type name.
                                if (isset($attr->metadata) && !empty((array) $attr->metadata)) {
                                    $Feature->properties['geo_metadata'] = $attr->metadata;
                                }
                                break;
                            case "geo:point":
                                $coords = array_reverse(explode(",", $attr->value)); //Change WGS84 Lat Long to Long Lat as GeoJson specifications.

                                array_filter($coords, function($coord) {
                                    return floatval(trim($coord));
                                });

                                $Feature->geometry = (object) [
                                            "type" => "Point",
                                            "coordinates" => $coords
                                ];

                                if (isset($attr->metadata) && !empty((array) $attr->metadata)) {
                                    $Feature->properties['geo_metadata'] = $attr->metadata;
                                }
                                break;
                            case "geo:box":
                                $x = array_reverse(explode(",", $attr->value[0])); //Change WGS84 Lat Long to Long Lat as GeoJson specifications.
                                $y = array_reverse(explode(",", $attr->value[1])); //Change WGS84 Lat Long to Long Lat as GeoJson specifications.
                                //Convert boundary box to polygon using WKT  format POLYGON(x1 y1, x1 y2, x2 y2, x2 y1, x1 y1)
                                $coords = [
                                    [$x[0], $y[0]], //x1 y1
                                    [$x[0], $y[1]], //x1 y2
                                    [$x[1], $y[1]], //x2 y2
                                    [$x[0], $y[0]], //x2 y1                                      
                                    [$x[0], $y[0]] //x1 y1
                                ];

                                $Feature->geometry = (object) [
                                            "type" => "Polygon",
                                            "coordinates" => $coords
                                ];

                                if (isset($attr->metadata) && !empty((array) $attr->metadata)) {
                                    $Feature->properties['geo_metadata'] = $attr->metadata;
                                }
                                break;
                            case "geo:polygon":
                            case "geo:line":
                                //Transform Value Pairs to Polygon/Line Coords
                                $coords = array_filter($attr->value, function($rawvalue) {
                                    $coords = array_reverse(explode(",", $rawvalue)); //Change WGS84 Lat Long to Long Lat as GeoJson specifications.
                                    array_filter($coords, function($coord) {
                                        return floatval(trim($coord));
                                    });
                                    return $coords;
                                });

                                $Feature->geometry = (object) [
                                            "type" => ($attr->type == "geo:polygon") ? "Polygon" : "LineString",
                                            "coordinates" => $coords
                                ];

                                if (isset($attr->metadata) && !empty((array) $attr->metadata)) {
                                    $Feature->properties['geo_metadata'] = $attr->metadata;
                                }
                                break;
                            default:
                                $Feature->properties[$key] = $attr->value;
                                if (isset($attr->metadata) && !empty((array) $attr->metadata)) {
                                    $Feature->properties['__metadata'][$key] = $attr->metadata;
                                }

                                //Add type to metadata
                                if(isset($attr->type)){
                                    if(!isset($Feature->properties['__metadata'][$key])){
                                        $Feature->properties['__metadata'][$key] = [];
                                    }

                                    $Feature->properties['__metadata'][$key]['type'] = $attr->type;
                                }

                                break;
                        }
                        break;
                }
            }
            
            $Feature->id = "{$entityType}-{$entityID}";

            //Finally if this context have a valid geometry append to feature collection
            if ($Feature->geometry != null) {
                $Feature->properties = (object) $Feature->properties;
                array_push($geoJson->features, $Feature);
            }
        }

        return $geoJson;
    }
273939
function getSegments(glyfUnicodes, bound) {

            var prevGlyph = null;
            var result = [];
            var segment = {};

            glyfUnicodes.forEach(function (glyph) {

                if (bound === undefined || glyph.unicode <= bound) {
                    // 初始化编码头部，这里unicode和graph id 都必须连续
                    if (prevGlyph === null
                        || glyph.unicode !== prevGlyph.unicode + 1
                        || glyph.id !== prevGlyph.id + 1
                    ) {
                        if (prevGlyph !== null) {
                            segment.end = prevGlyph.unicode;
                            result.push(segment);
                            segment = {
                                start: glyph.unicode,
                                startId: glyph.id,
                                delta: encodeDelta(glyph.id - glyph.unicode)
                            };
                        }
                        else {
                            segment.start = glyph.unicode;
                            segment.startId = glyph.id;
                            segment.delta = encodeDelta(glyph.id - glyph.unicode);
                        }
                    }

                    prevGlyph = glyph;
                }
            });

            // need to finish the last segment
            if (prevGlyph !== null) {
                segment.end = prevGlyph.unicode;
                result.push(segment);
            }

            // 返回编码范围
            return result;
        }
483798
function sqSegSegDist(x0, y0, x1, y1, x2, y2, x3, y3) {
    var ux = x1 - x0;
    var uy = y1 - y0;
    var vx = x3 - x2;
    var vy = y3 - y2;
    var wx = x0 - x2;
    var wy = y0 - y2;
    var a = ux * ux + uy * uy;
    var b = ux * vx + uy * vy;
    var c = vx * vx + vy * vy;
    var d = ux * wx + uy * wy;
    var e = vx * wx + vy * wy;
    var D = a * c - b * b;

    var sc, sN, tc, tN;
    var sD = D;
    var tD = D;

    if (D === 0) {
        sN = 0;
        sD = 1;
        tN = e;
        tD = c;
    } else {
        sN = b * e - c * d;
        tN = a * e - b * d;
        if (sN < 0) {
            sN = 0;
            tN = e;
            tD = c;
        } else if (sN > sD) {
            sN = sD;
            tN = e + b;
            tD = c;
        }
    }

    if (tN < 0.0) {
        tN = 0.0;
        if (-d < 0.0) sN = 0.0;
        else if (-d > a) sN = sD;
        else {
            sN = -d;
            sD = a;
        }
    } else if (tN > tD) {
        tN = tD;
        if ((-d + b) < 0.0) sN = 0;
        else if (-d + b > a) sN = sD;
        else {
            sN = -d + b;
            sD = a;
        }
    }

    sc = sN === 0 ? 0 : sN / sD;
    tc = tN === 0 ? 0 : tN / tD;

    var cx = (1 - sc) * x0 + sc * x1;
    var cy = (1 - sc) * y0 + sc * y1;
    var cx2 = (1 - tc) * x2 + tc * x3;
    var cy2 = (1 - tc) * y2 + tc * y3;
    var dx = cx2 - cx;
    var dy = cy2 - cy;

    return dx * dx + dy * dy;
}
617454
function createGeo() {
    $cnt = count( $this->geo );
    if( 0 >= $cnt )
      return;
    $attributes = $this->_createParams( $this->geo['params'] );
    $content    = null;
    $content   .= number_format( (float) $this->geo['value']['latitude'], 6, '.', '');
    $content   .= ';';
    $content   .= number_format( (float) $this->geo['value']['longitude'], 6, '.', '');
    return $this->_createElement( 'GEO', $attributes, $content );
  }
1057879
function(context, geometry, style, featureId, type) {
        var components = geometry.components;
        var len = components.length;
        context.beginPath();
        var start = this.getLocalXY(components[0]);
        var x = start[0];
        var y = start[1];
        if (!isNaN(x) && !isNaN(y)) {
            context.moveTo(start[0], start[1]);
            for (var i=1; i<len; ++i) {
                var pt = this.getLocalXY(components[i]);
                context.lineTo(pt[0], pt[1]);
            }
            if (type === "fill") {
                context.fill();
            } else {
                context.stroke();
            }
        }
    }
871623
function (position) {
			this.writeDebug('autoGeocodeQuery',arguments);
			var _this = this,
				distance = null,
				$distanceInput = $('#' + this.settings.maxDistanceID),
				originAddress;

			// Query string parameters
			if (this.settings.querystringParams === true) {
				// Check for distance query string parameters
				if (this.getQueryString(this.settings.maxDistanceID)){
					distance = this.getQueryString(this.settings.maxDistanceID);

					if ($distanceInput.val() !== '') {
						distance = $distanceInput.val();
					}
				}
				else{
					// Get the distance if set
					if (this.settings.maxDistance === true) {
						distance = $distanceInput.val() || '';
					}
				}
			}
			else {
				// Get the distance if set
				if (this.settings.maxDistance === true) {
					distance = $distanceInput.val() || '';
				}
			}

			// The address needs to be determined for the directions link
			var r = new this.reverseGoogleGeocode(this);
			var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
			r.geocode({'latLng': latlng}, function (data) {
				if (data !== null) {
					originAddress = addressInput = data.address;
					olat = mappingObj.lat = position.coords.latitude;
					olng = mappingObj.lng = position.coords.longitude;
					mappingObj.origin = originAddress;
					mappingObj.distance = distance;
					_this.mapping(mappingObj);

					// Fill in the search box.
					if (typeof originAddress !== 'undefined') {
						$('#' + _this.settings.addressID).val(originAddress);
					}
				} else {
					// Unable to geocode
					_this.notify(_this.settings.addressErrorAlert);
				}
			});
		}