/////////////////////////////////////////////////////////////////
// These are some helpers for accounting in functional tests.
/////////////////////////////////////////////////////////////////
// NumRoutes will report the number of registered routes.
554246
func (s *Server) NumRoutes() int {
	s.mu.Lock()
	nr := len(s.routes)
	s.mu.Unlock()
	return nr
}
1331569
function getRouteParams(route, params) {
  const routeParams = {}

  if (!route.path)
    return routeParams

  const paramNames = getParamNames(route.path)

  for (const p in params) {
    if (
      Object.prototype.hasOwnProperty.call(params, p) &&
      paramNames.indexOf(p) !== -1
    ) {
      routeParams[p] = params[p]
    }
  }

  return routeParams
}
737384
function _buildRoute(route) {

  let newRoute = route;

  // Normalize the route string
  newRoute = (newRoute.indexOf('/') === 0) ? newRoute.slice(1, newRoute.length) : newRoute;
  newRoute = '/' + newRoute;

  // Prepend the root if the user defined one
  newRoute = (Nasa.__config__['root']) ? Nasa.__config__['root'] + newRoute : newRoute;

  return newRoute;
}
605773
function compareUrlRoute(currentURL, currentRoute) {
                var regex = /\{(.*)\}/i;
                var arraySize = currentRoute.length,
                    testValue = false;
                for (var i = 0; i < arraySize; i++) {
                    var dynamic = regex.exec(currentRoute[i]);
                    if (dynamic) {
                        document.routeParams[dynamic[1]] = currentURL[i];
                    } else {
                        if (currentRoute[i] === currentURL[i]) {
                            testValue = true;
                        }
                    }
                }

                return testValue;
            }
388422
function(request, params, route) {
        var uRe         = params.url.split(/\//)
            , uRo       = route.split(/\//)
            , maxLen    = uRo.length
            , score     = 0
            , r         = {}
            , i         = 0;

        //attaching routing description for this request
        request.routing = params; // can be retried in controller with: req.routing

        if (uRe.length === uRo.length) {
            for (; i<maxLen; ++i) {
                if (uRe[i] === uRo[i]) {
                    ++score
                } else if (score == i && hasParams(uRo[i]) && fitsWithRequirements(request, uRo[i], uRe[i], params)) {
                    ++score
                }
            }
        }

        r.past = (score === maxLen) ? true : false;
        r.request = request;

        return r
    }
116485
function ParamRoutePath(routePath) {
        this.routePath = routePath;
        this.terminal = true;
        this._assertValidPath(routePath);
        this._parsePathString(routePath);
        this.specificity = this._calculateSpecificity();
        this.hash = this._calculateHash();
        var lastSegment = this._segments[this._segments.length - 1];
        this.terminal = !(lastSegment instanceof ContinuationPathSegment);
    }
225410
function(controller, appRoutes) {
    if (!appRoutes){ return; }

    var routeNames = _.keys(appRoutes).reverse(); // Backbone requires reverted order of routes

    _.each(routeNames, function(route) {
      this._addAppRoute(controller, route, appRoutes[route]);
    }, this);
  }
590629
protected void diagnoseNumPaths(Vector paths, int numPathsEliminated,  
                                  int numUniquePathsEliminated) 
  {
		if (numPathsEliminated > 0)
		{ 
		  if(paths == m_paths)
		  {
		    System.err.println("Eliminated " + numPathsEliminated + " total paths!");
		    System.err.println(
		      "Consolodated " + numUniquePathsEliminated + " redundent paths!");
		  }
		  else
		  {
		    System.err.println("Eliminated " + numPathsEliminated + " total global paths!");
		    System.err.println(
		      "Consolodated " + numUniquePathsEliminated + " redundent global paths!");
		  }
		}  
  }
124894
function findRouteName(routeToTest) {
    if (!window.Backbone) {
        throw new Error('Dependency: Backbone is missing.');
    }
    let handlers = window.Backbone.history.handlers;
    //console.log('handlers', )
    let h = find(handlers, function (handler) {
        return handler.route.test(routeToTest);
    });
    if (h !== undefined) {
        return h.route.toString();
    }
    return some(handlers, function (handler) {
        if (handler.route.test(routeToTest)) {
            return handler.route.toString();
        }
    });
}
858736
function tally(pathname, offenses) {
    var count = offenses.length,
        plural = count > 1 ? 'errors' : 'error';

    function perOffense(o) {
        if (!errors[pathname]) {
            errors[pathname] = [];
        }

        if (o) {
            errors[pathname].push({
                line: o.line,
                col: o.character,
                msg: o.reason,
                evidence: o.evidence || ''
            });
        }
    }

    log.error([count, plural, 'in', pathname].join(' '));
    offenses.forEach(perOffense);
}
590436
public function math()
  {
    $url = parse_url($_SERVER['REQUEST_URI'])['path'];

      // If request method page GET
      if ($_SERVER['REQUEST_METHOD'] == 'GET') {

        // Parse route only GET
        foreach ($this->routerCollection->getGetRoutes() as $route) {

          // Replace params route and trim (/)
          $pattern = preg_replace("/\{(.*?)\}/", "(?P<$1>[\w-]+)", $route->route);
          $pattern = "#^". trim($pattern, '/') ."$#";
          preg_match($pattern, trim($url, '/'), $matches);

          // If Route finded
          if ($matches) {
            $this->handler = $route->handler;
            $this->route = $route->route;
            $this->routeMethod =  $route->method;
            $this->params[] = $matches;
          }
        }
      }
      // If request method page POST
      if ($_SERVER['REQUEST_METHOD'] == 'POST') {

        // Parse route only POST
        foreach ($this->routerCollection->getPostRoutes() as $route) {

          // Replace params route and trim (/)
          $pattern = preg_replace("/\{(.*?)\}/", "(?P<$1>[\w-]+)", $route->route);
          $pattern = "#^". trim($pattern, '/') ."$#";
          preg_match($pattern, trim($url, '/'), $matches);

          // If Route finded
          if ($matches) {
            $this->handler = $route->handler;
            $this->route = $route->route;
            $this->routeMethod =  $route->method;
            $this->params[] = $matches;
          }
        }
      }

      return $this;
    }
594962
def _calculate_num_queries(self):
        
        request_totals = self._totals("request")
        response_totals = self._totals("response")

        return request_totals[2] + response_totals[2]
1016622
function checkMethods(spec) {
  assert(spec.method, 'missing route methods');

  if (typeof spec.method === 'string') {
    spec.method = spec.method.split(' ');
  }

  if (!Array.isArray(spec.method)) {
    throw new TypeError('route methods must be an array or string');
  }

  if (spec.method.length === 0) {
    throw new Error('missing route method');
  }

  spec.method.forEach((method, i) => {
    assert(typeof method === 'string', 'route method must be a string');
    spec.method[i] = method.toLowerCase();
  });
}
191196
public List<Path> calcPaths(GHRequest request, GHResponse ghRsp) {
        if (ghStorage == null || !fullyLoaded)
            throw new IllegalStateException("Do a successful call to load or importOrLoad before routing");

        if (ghStorage.isClosed())
            throw new IllegalStateException("You need to create a new GraphHopper instance as it is already closed");

        // default handling
        String vehicle = request.getVehicle();
        if (vehicle.isEmpty()) {
            vehicle = getDefaultVehicle().toString();
            request.setVehicle(vehicle);
        }

        Lock readLock = readWriteLock.readLock();
        readLock.lock();
        try {
            if (!encodingManager.hasEncoder(vehicle))
                throw new IllegalArgumentException("Vehicle not supported: " + vehicle + ". Supported are: " + encodingManager.toString());

            HintsMap hints = request.getHints();
            String tModeStr = hints.get("traversal_mode", traversalMode.toString());
            TraversalMode tMode = TraversalMode.fromString(tModeStr);
            if (hints.has(Routing.EDGE_BASED))
                tMode = hints.getBool(Routing.EDGE_BASED, false) ? TraversalMode.EDGE_BASED_2DIR : TraversalMode.NODE_BASED;

            FlagEncoder encoder = encodingManager.getEncoder(vehicle);

            boolean disableCH = hints.getBool(CH.DISABLE, false);
            if (!chFactoryDecorator.isDisablingAllowed() && disableCH)
                throw new IllegalArgumentException("Disabling CH not allowed on the server-side");

            boolean disableLM = hints.getBool(Landmark.DISABLE, false);
            if (!lmFactoryDecorator.isDisablingAllowed() && disableLM)
                throw new IllegalArgumentException("Disabling LM not allowed on the server-side");

            String algoStr = request.getAlgorithm();
            if (algoStr.isEmpty())
                algoStr = chFactoryDecorator.isEnabled() && !disableCH ? DIJKSTRA_BI : ASTAR_BI;

            List<GHPoint> points = request.getPoints();
            // TODO Maybe we should think about a isRequestValid method that checks all that stuff that we could do to fail fast
            // For example see #734
            checkIfPointsAreInBounds(points);

            RoutingTemplate routingTemplate;
            if (ROUND_TRIP.equalsIgnoreCase(algoStr))
                routingTemplate = new RoundTripRoutingTemplate(request, ghRsp, locationIndex, encodingManager, maxRoundTripRetries);
            else if (ALT_ROUTE.equalsIgnoreCase(algoStr))
                routingTemplate = new AlternativeRoutingTemplate(request, ghRsp, locationIndex, encodingManager);
            else
                routingTemplate = new ViaRoutingTemplate(request, ghRsp, locationIndex, encodingManager);

            List<Path> altPaths = null;
            int maxRetries = routingTemplate.getMaxRetries();
            Locale locale = request.getLocale();
            Translation tr = trMap.getWithFallBack(locale);
            for (int i = 0; i < maxRetries; i++) {
                StopWatch sw = new StopWatch().start();
                List<QueryResult> qResults = routingTemplate.lookup(points, encoder);
                ghRsp.addDebugInfo("idLookup:" + sw.stop().getSeconds() + "s");
                if (ghRsp.hasErrors())
                    return Collections.emptyList();

                RoutingAlgorithmFactory tmpAlgoFactory = getAlgorithmFactory(hints);
                Weighting weighting;
                QueryGraph queryGraph;

                if (chFactoryDecorator.isEnabled() && !disableCH) {
                    boolean forceCHHeading = hints.getBool(CH.FORCE_HEADING, false);
                    if (!forceCHHeading && request.hasFavoredHeading(0))
                        throw new IllegalArgumentException("Heading is not (fully) supported for CHGraph. See issue #483");

                    // if LM is enabled we have the LMFactory with the CH algo!
                    RoutingAlgorithmFactory chAlgoFactory = tmpAlgoFactory;
                    if (tmpAlgoFactory instanceof LMAlgoFactoryDecorator.LMRAFactory)
                        chAlgoFactory = ((LMAlgoFactoryDecorator.LMRAFactory) tmpAlgoFactory).getDefaultAlgoFactory();

                    if (chAlgoFactory instanceof PrepareContractionHierarchies)
                        weighting = ((PrepareContractionHierarchies) chAlgoFactory).getWeighting();
                    else
                        throw new IllegalStateException("Although CH was enabled a non-CH algorithm factory was returned " + tmpAlgoFactory);

                    queryGraph = new QueryGraph(ghStorage.getGraph(CHGraph.class, weighting));
                    queryGraph.lookup(qResults);
                } else {
                    checkNonChMaxWaypointDistance(points);
                    queryGraph = new QueryGraph(ghStorage);
                    queryGraph.lookup(qResults);
                    weighting = createWeighting(hints, encoder, queryGraph);
                }
                ghRsp.addDebugInfo("tmode:" + tMode.toString());

                int maxVisitedNodesForRequest = hints.getInt(Routing.MAX_VISITED_NODES, maxVisitedNodes);
                if (maxVisitedNodesForRequest > maxVisitedNodes)
                    throw new IllegalArgumentException("The max_visited_nodes parameter has to be below or equal to:" + maxVisitedNodes);

                weighting = createTurnWeighting(queryGraph, weighting, tMode);

                AlgorithmOptions algoOpts = AlgorithmOptions.start().
                        algorithm(algoStr).traversalMode(tMode).weighting(weighting).
                        maxVisitedNodes(maxVisitedNodesForRequest).
                        hints(hints).
                        build();

                // do the actual route calculation !
                altPaths = routingTemplate.calcPaths(queryGraph, tmpAlgoFactory, algoOpts);

                boolean tmpEnableInstructions = hints.getBool(Routing.INSTRUCTIONS, getEncodingManager().isEnableInstructions());
                boolean tmpCalcPoints = hints.getBool(Routing.CALC_POINTS, calcPoints);
                double wayPointMaxDistance = hints.getDouble(Routing.WAY_POINT_MAX_DISTANCE, 1d);

                DouglasPeucker peucker = new DouglasPeucker().setMaxDistance(wayPointMaxDistance);
                PathMerger pathMerger = new PathMerger().
                        setCalcPoints(tmpCalcPoints).
                        setDouglasPeucker(peucker).
                        setEnableInstructions(tmpEnableInstructions).
                        setPathDetailsBuilders(pathBuilderFactory, request.getPathDetails()).
                        setSimplifyResponse(simplifyResponse && wayPointMaxDistance > 0);

                if (request.hasFavoredHeading(0))
                    pathMerger.setFavoredHeading(request.getFavoredHeading(0));

                if (routingTemplate.isReady(pathMerger, tr))
                    break;
            }

            return altPaths;

        } catch (IllegalArgumentException ex) {
            ghRsp.addError(ex);
            return Collections.emptyList();
        } finally {
            readLock.unlock();
        }
    }
1313475
private function getRoutesFromIndexActions (&$routes, array &$routeActions, &$requestMethod, array &$requestPathParts) {
        foreach ($routeActions as $routeData) {
            $routePath = $routeData[0];
            $routeAction = $routeData[1];
            $routeParameters = [];
            if (strpos($routePath, self::ROUTE_PARAMETER_PREFIX) !== false || strpos($routePath, self::ROUTE_GENERIC_PATH) !== false) {
                $routePathParts = explode(self::ROUTE_PATH_SEPARATOR, trim($routePath, self::ROUTE_PATH_SEPARATOR));;
                for ($i = 0; $i < sizeof($routePathParts); $i++) {
                    $routePathPart = $routePathParts[$i];
                    if ($routePathPart == self::ROUTE_GENERIC_PATH) {
                        $path = array_slice($requestPathParts, $i);
                        $routeParameters[self::ROUTE_PATH_PARAMETER_NAME] = $path;
                        break;
                    }
                    else if ($routePathPart[0] == self::ROUTE_PARAMETER_PREFIX) {
                        $parameterName = substr($routePathPart, 1);
                        $parameterValue = $requestPathParts[$i];
                        $routeParameters[$parameterName] = $parameterValue;
                    }
                }
            }
            if ($routeAction instanceof RouteGenerator) {
                $route = $routeAction->generateRoute($requestMethod, isset($path)?$path : $requestPathParts);
                if ($route) {
                    $routes[] = $route;
                }
            }
            else {
                $routes[] = new Route($routeAction, $routeParameters);
            }
        }
    }
269412
public void recordRoute(List<Feature> features, int numPoints) throws InterruptedException {
    info("*** RecordRoute");
    final CountDownLatch finishLatch = new CountDownLatch(1);
    StreamObserver<RouteSummary> responseObserver = new StreamObserver<RouteSummary>() {
      @Override
      public void onNext(RouteSummary summary) {
        info("Finished trip with {0} points. Passed {1} features. "
            + "Travelled {2} meters. It took {3} seconds.", summary.getPointCount(),
            summary.getFeatureCount(), summary.getDistance(), summary.getElapsedTime());
        if (testHelper != null) {
          testHelper.onMessage(summary);
        }
      }

      @Override
      public void onError(Throwable t) {
        warning("RecordRoute Failed: {0}", Status.fromThrowable(t));
        if (testHelper != null) {
          testHelper.onRpcError(t);
        }
        finishLatch.countDown();
      }

      @Override
      public void onCompleted() {
        info("Finished RecordRoute");
        finishLatch.countDown();
      }
    };

    StreamObserver<Point> requestObserver = asyncStub.recordRoute(responseObserver);
    try {
      // Send numPoints points randomly selected from the features list.
      for (int i = 0; i < numPoints; ++i) {
        int index = random.nextInt(features.size());
        Point point = features.get(index).getLocation();
        info("Visiting point {0}, {1}", RouteGuideUtil.getLatitude(point),
            RouteGuideUtil.getLongitude(point));
        requestObserver.onNext(point);
        // Sleep for a bit before sending the next one.
        Thread.sleep(random.nextInt(1000) + 500);
        if (finishLatch.getCount() == 0) {
          // RPC completed or errored before we finished sending.
          // Sending further requests won't error, but they will just be thrown away.
          return;
        }
      }
    } catch (RuntimeException e) {
      // Cancel RPC
      requestObserver.onError(e);
      throw e;
    }
    // Mark the end of requests
    requestObserver.onCompleted();

    // Receiving happens asynchronously
    if (!finishLatch.await(1, TimeUnit.MINUTES)) {
      warning("recordRoute can not finish within 1 minutes");
    }
  }
380742
function (fragment, callback) {

            var routeExecutionStack = [];

            for (var i = 0; i < this.$routers.length; i++) {
                routeExecutionStack = routeExecutionStack.concat(this.$routers[i].generateRoutingStack(fragment));
            }

            if (routeExecutionStack.length === 0) {
                this.routeNotFound(fragment, callback);
            } else {
                flow()
                    .seqEach(routeExecutionStack, function(routingFunction, cb){
                        routingFunction(cb);
                    })
                    .exec(callback);
            }
        }