Find the shortest conversion path between the from and to units. Currently
we just look for path with the lowest precision, falling back to the
shortest path (fewest number of conversions to get from A to B).
349411
protected List<UnitFactor> getPath(Unit from, Unit to) {
    if (from == to) {
      return list(new UnitFactor(Rational.ONE, to));
    }

    // Find all paths between the two units.
    List<List<UnitFactor>> paths = getPaths(from, to, new HashSet<>());
    if (paths.isEmpty()) {
      return Collections.emptyList();
    }

    // Sort and return the path with the smallest precision. If two paths
    // have equal precision return the shorter path.
    paths.sort((a, b) -> {
      int cmp = Integer.compare(precisionSum(a), precisionSum(b));
      if (cmp == 0) {
        return Integer.compare(a.size(), b.size());
      }
      return cmp;
    });
    return paths.get(0);
  }
348641
def _getDirection(coord1, coord2):
    
    x1, y1 = coord1
    x2, y2 = coord2

    if x1 == x2 and y1 == y2:
        return None # two coordinates are the same.
    elif x1 == x2 and y1 > y2:
        return UP
    elif x1 == x2 and y1 < y2:
        return DOWN
    elif x1 > x2 and y1 == y2:
        return LEFT
    elif x1 < x2 and y1 == y2:
        return RIGHT

    slope = float(y2 - y1) / float(x2 - x1)

    # Figure out which quadrant the line is going in, and then
    # determine the closest direction by calculating the slope
    if x2 > x1 and y2 < y1: # up right quadrant
        if slope > -0.4142:
            return RIGHT # slope is between 0 and 22.5 degrees
        elif slope < -2.4142:
            return UP # slope is between 67.5 and 90 degrees
        else:
            return UPRIGHT # slope is between 22.5 and 67.5 degrees
    elif x2 > x1 and y2 > y1: # down right quadrant
        if slope > 2.4142:
            return DOWN
        elif slope < 0.4142:
            return RIGHT
        else:
            return DOWNRIGHT
    elif x2 < x1 and y2 < y1: # up left quadrant
        if slope < 0.4142:
            return LEFT
        elif slope > 2.4142:
            return UP
        else:
            return UPLEFT
    elif x2 < x1 and y2 > y1: # down left quadrant
        if slope < -2.4142:
            return DOWN
        elif slope > -0.4142:
            return LEFT
        else:
            return DOWNLEFT
229356
def find_base_path(paths)
      return nil if paths.length <= 1
      paths.sort!
      first = paths.first.split('/')
      last  = paths.last.split('/')
      i = 0
      while first[i] == last[i] && i <= first.length
        i += 1
      end
      res = first.slice(0, i).join('/')
      res.empty? ? nil : res
    end
340909
def point_to_line(point, segment_start, segment_end):
    
    # TODO: Needs unittests.

    segment_vec = segment_end - segment_start
    # t is distance along line
    t = -(segment_start - point).dot(segment_vec) / (
          segment_vec.length_squared())

    closest_point = segment_start + scale_v3(segment_vec, t)
    return point - closest_point
547532
function (_choice, _choicesLength) {
    _choice = Math.abs(_choice);

    if (_choicesLength === 2) {
      return _choice
        ? _choice > 1
          ? 1
          : 0
        : 1
    }

    return _choice ? Math.min(_choice, 2) : 0
  }
245895
public static Path subPath(Path path, int fromIndex, int toIndex) {
		if (null == path) {
			return null;
		}
		final int len = path.getNameCount();

		if (fromIndex < 0) {
			fromIndex = len + fromIndex;
			if (fromIndex < 0) {
				fromIndex = 0;
			}
		} else if (fromIndex > len) {
			fromIndex = len;
		}

		if (toIndex < 0) {
			toIndex = len + toIndex;
			if (toIndex < 0) {
				toIndex = len;
			}
		} else if (toIndex > len) {
			toIndex = len;
		}

		if (toIndex < fromIndex) {
			int tmp = fromIndex;
			fromIndex = toIndex;
			toIndex = tmp;
		}

		if (fromIndex == toIndex) {
			return null;
		}
		return path.subpath(fromIndex, toIndex);
	}
200203
def convert(self, destination_units, *, convert_variables=False):
        
        if self.units is None and (destination_units is None or destination_units == "None"):
            return
        if not wt_units.is_valid_conversion(self.units, destination_units):
            valid = wt_units.get_valid_conversions(self.units)
            raise wt_exceptions.UnitsError(valid, destination_units)
        if convert_variables:
            for v in self.variables:
                v.convert(destination_units)
        self.units = destination_units
1015757
def midpoint(self):
        
        minpoint = self.leftedge

        if self.leftop is gt:
            minpoint += 1
    
        maxpoint = self.rightedge

        if self.rightop is lt:
            maxpoint -= 1

        if minpoint is None:
            return maxpoint
            
        elif maxpoint is None:
            return minpoint
            
        else:
            return (minpoint + maxpoint) / 2
964797
function convertDistance (distance) {
  let cleaned, converted;

  // clean up to ensure node-units will be able to convert it
  // for instance: "3 258,55 Ft" => "3258.55 ft"
  cleaned = distance
    .replace(/[-\s]/g, '')
    .replace(/,/g, '.')
    .toLowerCase()
    .replace(/([0-9])([a-z])/, '$1 $2');

  try {
    converted = units.convert(cleaned + ' to m');
  }
  catch (e) {
    throw new BadRequestError(`unable to parse distance value "${distance}"`);
  }

  return converted;
}
567028
def path(cls, name, type_=Type.String, description=None, default=None,
             minimum=None, maximum=None, enum=None, **options):
        
        if minimum is not None and maximum is not None and minimum > maximum:
            raise ValueError("Minimum must be less than or equal to the maximum.")
        return cls(name, In.Path, type_, None, description,
                   default=default, minimum=minimum, maximum=maximum,
                   enum=enum, required=True, **options)
920550
def _find_short_paths(self, paths):
        
        # Split each path to parts.
        # E.g. '/home/aoik' to ['', 'home', 'aoik']
        path_parts_s = [path.split(os.path.sep) for path in paths]

        # Root node
        root_node = {}

        # Sort these path parts by length, with the longest being the first.
        #
        # Longer paths appear first so that their extra parts are discarded
        # when a shorter path is found at 5TQ8L.
        #
        # Then for each path's parts.
        for parts in sorted(path_parts_s, key=len, reverse=True):
            # Start from the root node
            node = root_node

            # For each part of the path
            for part in parts:
                # Create node of the path
                node = node.setdefault(part, {})

            # 5TQ8L
            # Clear the last path part's node's child nodes.
            #
            # This aims to keep only the shortest path that needs be watched.
            #
            node.clear()

        # Short paths
        short_path_s = set()

        # Collect leaf paths
        self._collect_leaf_paths(
            node=root_node,
            path_parts=(),
            leaf_paths=short_path_s,
        )

        # Return short paths
        return short_path_s
442479
def nearestPoint(self, pos):
        
        # lookup subpaths
        for x, y, path in self._subpaths:
            if path.contains(pos):
                return (x, y)
        
        return (None, None)
1325017
def get_path(self, i):
        """"""
        index = (i - 1) // 2
        reverse = (i - 1) % 2
        path = self.paths[index]
        if reverse:
            return path.reversed()
        else:
            return path
792009
def distance_to(self, *args):
        """"""
        if not len(args) > 0:
            raise ValueError("at least one parameter must be given")

        x = args[0]
        if len(args) > 1:
            unit = args[1]
        else:
            unit = "px"
        u = {"px": (1.,1.), "in": (1.,72.), "cm": (2.54, 72.),
             "mm": (25.4, 72.)}
        f = u[unit][0] / u[unit][1]
        if type(x) is Point:
            return abs(self - x) * f

# from here on, x is a rectangle
# as a safeguard, make a finite copy of it
        r = Rect(x.top_left, x.top_left)
        r = r | x.bottom_right
        if self in r:
            return 0.0
        if self.x > r.x1:
            if self.y >= r.y1:
                return self.distance_to(r.bottom_right, unit)
            elif self.y <= r.y0:
                return self.distance_to(r.top_right, unit)
            else:
                return (self.x - r.x1) * f
        elif r.x0 <= self.x <= r.x1:
            if self.y >= r.y1:
                return (self.y - r.y1) * f
            else:
                return (r.y0 - self.y) * f
        else:
            if self.y >= r.y1:
                return self.distance_to(r.bottom_left, unit)
            elif self.y <= r.y0:
                return self.distance_to(r.top_left, unit)
            else:
                return (r.x0 - self.x) * f
382372
synchronized Weight getMinimumStart() {
        if (calcMinStart == null) {
            // Find the shortest distance from a start to time zero.
            Weight result = WeightFactory.NEG_INFINITY;
            if (shortestDistancesFromTimeZeroDestination == null) {
                shortestDistancesFromTimeZeroDestination = BellmanFord.calcShortestDistances(timeZero, directedGraph,
                        BellmanFord.Mode.DESTINATION);

                if (shortestDistancesFromTimeZeroDestination == null) {
                    throw new IllegalStateException("Negative cycle detected!");
                }
            }
            for (int i = 0, n = intervals.size(); i < n; i++) {
                Object start = intervals.get(i).getStart();
                result = Weight.max(result,
                        (Weight) shortestDistancesFromTimeZeroDestination.get(start));
            }
            calcMinStart = result.invertSign();
        }

        return calcMinStart;
    }
1108552
def distance(line, point):
    
    x0, y0, x1, y1 = line
    try:
        p1, p2 = point
    except ValueError:
        # line is given instead of point
        p1, p2 = middle(point)
    n1 = ascent(line)
    n2 = -1
    n0 = y0 - n1 * x0
    return abs(n1 * p1 + n2 * p2 + n0) / (n1 ** 2 + n2 ** 2) ** 0.5
986784
def edges_to_path(edges):
    
    if not edges:
        return None

    G = edges_to_graph(edges)
    path = nx.topological_sort(G)
    return path