Select the best path based on origin attribute.

    IGP is preferred over EGP; EGP is preferred over Incomplete.
    If both paths have same origin, we return None.
183690
def _cmp_by_origin(path1, path2):
    
    def get_origin_pref(origin):
        if origin.value == BGP_ATTR_ORIGIN_IGP:
            return 3
        elif origin.value == BGP_ATTR_ORIGIN_EGP:
            return 2
        elif origin.value == BGP_ATTR_ORIGIN_INCOMPLETE:
            return 1
        else:
            LOG.error('Invalid origin value encountered %s.', origin)
            return 0

    origin1 = path1.get_pattr(BGP_ATTR_TYPE_ORIGIN)
    origin2 = path2.get_pattr(BGP_ATTR_TYPE_ORIGIN)
    assert origin1 is not None and origin2 is not None

    # If both paths have same origins
    if origin1.value == origin2.value:
        return None

    # Translate origin values to preference.
    origin1 = get_origin_pref(origin1)
    origin2 = get_origin_pref(origin2)
    # Return preferred path.
    if origin1 == origin2:
        return None
    elif origin1 > origin2:
        return path1
    return path2
291218
def traverse_path_for_valid_application_paths(self, top_path):
        
        self.put_path(Path(top_path))
        for p in self._walk(top_path):
            self.put_path(p)
521973
def find_path(self, start, end, grid):
        
        start.g = 0
        start.f = 0
        return super(AStarFinder, self).find_path(start, end, grid)
358399
function(originOrUrl) {
    if (originOrUrl == null || originOrUrl === "") {
      return null;
    }
    originOrUrl = originOrUrl.replace(/^\s+|\s+$/g, "");
    if (originOrUrl === "") {
      return null;
    }
    var protocolIndex = originOrUrl.indexOf("//");
    originOrUrl = protocolIndex === -1 ? originOrUrl : originOrUrl.slice(protocolIndex + 2);
    var pathIndex = originOrUrl.indexOf("/");
    originOrUrl = pathIndex === -1 ? originOrUrl : protocolIndex === -1 || pathIndex === 0 ? null : originOrUrl.slice(0, pathIndex);
    if (originOrUrl && originOrUrl.slice(-4).toLowerCase() === ".swf") {
      return null;
    }
    return originOrUrl || null;
  }
529468
def find_best_match(path, prefixes):
    """"""
    path_parts = path.split('.')
    for p in prefixes:
        if len(p) <= len(path_parts) and p == path_parts[:len(p)]:
            return '.'.join(p), '.'.join(path_parts[len(p):])
    return '', path
934064
private static InetAddress chooseAddress(String preferred) throws UnknownHostException {
        Set<InetAddress> addresses = getAddresses();
        if (preferred != null && !preferred.isEmpty()) {
            //Favor preferred address if exists
            try {
                InetAddress preferredAddress = InetAddress.getByName(preferred);
                if (addresses != null && addresses.contains(preferredAddress)) {
                    LOG.info("preferred address is " + preferredAddress.getHostAddress() + " for host " + preferredAddress.getHostName());
                    return preferredAddress;
                }
            } catch (UnknownHostException e) {
                //noop
            }
            for (InetAddress address : addresses) {
                if (preferred.equals(address.getHostName())) {
                    return address;
                }
            }
            StringBuffer hostNameBuffer = new StringBuffer();
            for (InetAddress address : addresses) {
                if (hostNameBuffer.length() > 0) {
                    hostNameBuffer.append(", ");
                }
                hostNameBuffer.append(address.getHostName() + "/" + address.getHostAddress());
            }
            LOG.warn("Could not find network address for preferred '" + preferred + "' when the addresses were: " + hostNameBuffer);
        }
        if (addresses.contains(InetAddress.getLocalHost())) {
            //Then if local host address is not bound to a loop-back interface, use it.
            return InetAddress.getLocalHost();
        } else if (addresses != null && !addresses.isEmpty()) {
            //else return the first available addrress
            return addresses.toArray(new InetAddress[addresses.size()])[0];
        } else {
            //else we are forcedt to use the localhost address.
            return InetAddress.getLocalHost();
        }
    }
14662
def same_origin(url1, url2):
    ''' 
    '''
    p1, p2 = urlparse(url1), urlparse(url2)
    try:
        o1 = (p1.scheme, p1.hostname, p1.port or PROTOCOL_TO_PORT[p1.scheme])
        o2 = (p2.scheme, p2.hostname, p2.port or PROTOCOL_TO_PORT[p2.scheme])
        return o1 == o2
    except (ValueError, KeyError):
        return False
942406
def _get_bgp_route_attr(self, destination, vrf, next_hop, ip_version=4):
        

        CMD_SHIBNV = 'show ip bgp neighbors vrf {vrf} | include "is {neigh}"'

        search_re_dict = {
            "aspath": {
                "re": r"AS-Path: ([\d\(\)]([\d\(\) ])*)",
                "group": 1,
                "default": "",
            },
            "bgpnh": {
                "re": r"[^|\\n][ ]{4}(" + IP_ADDR_REGEX + r")",
                "group": 1,
                "default": "",
            },
            "bgpfrom": {
                "re": r"from (" + IP_ADDR_REGEX + r")",
                "group": 1,
                "default": "",
            },
            "bgpcomm": {
                "re": r"  Community: ([\w\d\-\: ]+)",
                "group": 1,
                "default": "",
            },
            "bgplp": {"re": r"localpref (\d+)", "group": 1, "default": ""},
            # external, internal, redist
            "bgpie": {"re": r"^: (\w+),", "group": 1, "default": ""},
            "vrfimp": {
                "re": r"Imported from [\S]+ \(VRF (\S+)\)",
                "group": 1,
                "default": "",
            },
        }

        bgp_attr = {}
        # get BGP AS number
        outbgp = self._send_command('show bgp process | include "BGP Protocol Tag"')
        matchbgpattr = RE_BGP_PROTO_TAG.match(outbgp)
        if not matchbgpattr:
            return bgp_attr
        bgpas = matchbgpattr.group(1)
        if ip_version == 4:
            bgpcmd = "show ip bgp vrf {vrf} {destination}".format(
                vrf=vrf, destination=destination
            )
            outbgp = self._send_command(bgpcmd)
            outbgpsec = outbgp.split("Path type")

            # this should not happen (zero BGP paths)...
            if len(outbgpsec) == 1:
                return bgp_attr

            # process all bgp paths
            for bgppath in outbgpsec[1:]:
                if "is best path" not in bgppath:
                    # only best path is added to protocol attributes
                    continue
                # find BGP attributes
                for key in search_re_dict:
                    matchre = re.search(search_re_dict[key]["re"], bgppath)
                    if matchre:
                        groupnr = int(search_re_dict[key]["group"])
                        search_re_dict[key]["result"] = matchre.group(groupnr)
                    else:
                        search_re_dict[key]["result"] = search_re_dict[key]["default"]
                bgpnh = search_re_dict["bgpnh"]["result"]

                # if route is not leaked next hops have to match
                if (
                    not (search_re_dict["bgpie"]["result"] in ["redist", "local"])
                ) and (bgpnh != next_hop):
                    # this is not the right route
                    continue
                # find remote AS nr. of this neighbor
                bgpcmd = CMD_SHIBNV.format(vrf=vrf, neigh=bgpnh)
                outbgpnei = self._send_command(bgpcmd)
                matchbgpras = RE_BGP_REMOTE_AS.search(outbgpnei)
                if matchbgpras:
                    bgpras = matchbgpras.group(1)
                else:
                    # next-hop is not known in this vrf, route leaked from
                    #  other vrf or from vpnv4 table?
                    # get remote AS nr. from as-path if it is ebgp neighbor
                    # if locally sourced remote AS if undefined
                    bgpie = search_re_dict["bgpie"]["result"]
                    if bgpie == "external":
                        bgpras = bgpie.split(" ")[0].replace("(", "")
                    elif bgpie == "internal":
                        bgpras = bgpas
                    else:  # redist, local
                        bgpras = ""
                # community
                bothcomm = []
                extcomm = []
                stdcomm = search_re_dict["bgpcomm"]["result"].split()
                commsplit = bgppath.split("Extcommunity:")
                if len(commsplit) == 2:
                    for line in commsplit[1].split("\n")[1:]:
                        #          RT:65004:22
                        matchcommun = RE_BGP_COMMUN.match(line)
                        if matchcommun:
                            extcomm.append(matchcommun.group(1))
                        else:
                            # we've reached end of the extended community section
                            break
                bothcomm = stdcomm + extcomm
                bgp_attr = {
                    "as_path": search_re_dict["aspath"]["result"].strip(),
                    "remote_address": search_re_dict["bgpfrom"]["result"],
                    "local_preference": int(search_re_dict["bgplp"]["result"]),
                    "communities": bothcomm,
                    "local_as": helpers.as_number(bgpas),
                }
                if bgpras:
                    bgp_attr["remote_as"] = helpers.as_number(bgpras)
                else:
                    bgp_attr["remote_as"] = 0  # 0? , locally sourced
        return bgp_attr
669669
def isabspath(self):
        """"""
        return (self.scheme is None and self.authority is None and
                self.path.startswith(self.SLASH))
1024349
def compare_root_path(path_cost1, path_cost2, bridge_id1, bridge_id2,
                          port_id1, port_id2):
        
        result = Stp._cmp_value(path_cost1, path_cost2)
        if not result:
            result = Stp._cmp_value(bridge_id1, bridge_id2)
            if not result:
                result = Stp._cmp_value(port_id1, port_id2)
        return result
221612
def get_basedir(path):
  
  return path[:path.index(os.sep)] if os.sep in path else path
429475
def _select_source_arch(self, source, source64):
        
        src = ""
        if self.meta.arch == "x86_64":
            if source64:
                src = source64
            else:
                src = source
            if self.meta.skip_unst in self.answer and source64 in self.unst:
                src = source
        else:
            if source:
                src = source
            if self.meta.skip_unst in self.answer and source in self.unst:
                src = source64
        return src
890337
function getorigPath(filePath, base) {
    var extName = path.extname(filePath);
    var pt = path.resolve(base, filePath);
    if (!extName) pt += '.js';
    return pt;
}
372779
def best(self):
        '''
        
        '''

        if len(self.choices) < 1:
            print('slots: No trials run so far.')
            return None
        else:
            return np.argmax(self.wins/(self.pulls+0.1))
1084490
@Nullable
    public CorsPolicy getPolicy(String origin, PathMappingContext pathMappingContext) {
        requireNonNull(origin, "origin");
        if (isAnyOriginSupported()) {
            return Iterables.getFirst(policies, null);
        }
        final String lowerCaseOrigin = Ascii.toLowerCase(origin);
        final boolean isNullOrigin = CorsService.NULL_ORIGIN.equals(lowerCaseOrigin);
        for (final CorsPolicy policy : policies) {
            if (isNullOrigin && policy.isNullOriginAllowed() &&
                isPathMatched(policy, pathMappingContext)) {
                return policy;
            } else if (!isNullOrigin && policy.origins().contains(lowerCaseOrigin) &&
                       isPathMatched(policy, pathMappingContext)) {
                return policy;
            }
        }
        return null;
    }
481279
private void setAcceptedLocalCandidate(TransportCandidate bestLocalCandidate) {
        for (int i = 0; i < resolver.getCandidateCount(); i++) {
            // TODO FIX The EQUAL Sentence
            if (resolver.getCandidate(i).getIp().equals(bestLocalCandidate.getIp())
                    && resolver.getCandidate(i).getPort() == bestLocalCandidate.getPort()) {
                acceptedLocalCandidate = resolver.getCandidate(i);
                return;
            }
        }
        LOGGER.fine("BEST: ip=" + bestLocalCandidate.getIp() + " port=" + bestLocalCandidate.getPort() + " has not been offered.");
        // throw new XMPPException("Local transport candidate has not be offered.");
    }
63434
def fast_relpath_optional(path, start):
  
  if len(start) == 0:
    # Empty prefix.
    return path

  # Determine where the matchable prefix ends.
  pref_end = len(start) - 1 if start[-1] == '/' else len(start)
  if pref_end > len(path):
    # The prefix is too long to match.
    return None
  elif path[:pref_end] == start[:pref_end] and (len(path) == pref_end or path[pref_end] == '/'):
    # The prefix matches, and the entries are either identical, or the suffix indicates that
    # the prefix is a directory.
    return path[pref_end+1:]