TODO: Candidate util method
328344
private static Raster getRaster(final RenderedImage image) {
        return image instanceof BufferedImage
               ? ((BufferedImage) image).getRaster()
               : image.getNumXTiles() == 1 && image.getNumYTiles() == 1
                 ? image.getTile(0, 0)
                 : image.getData();
    }
1313282
private boolean isSimilarSignature(Method possiblyMatchingMethod, String desiredMethodName, Class<?>[] desiredParamTypes) {
        return possiblyMatchingMethod.getName().equals(desiredMethodName) && match(possiblyMatchingMethod.getParameterTypes(), desiredParamTypes);
    }
222676
@Override
  public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
    if (!HAS_MUST_BE_CLOSED_ANNOTATION.matches(tree, state)) {
      return NO_MATCH;
    }
    if (CONSTRUCTOR.matches(tree, state)) {
      return NO_MATCH;
    }
    return matchNewClassOrMethodInvocation(tree, state);
  }
243681
public static int[] candidateMatches(Class<?>[][] signatures, boolean[] varArgs, Class<?>[] argTypes) {
        return candidateMatches(signatures, varArgs, new JavaSignatureComparator(argTypes));
    }
551910
private static Method resolveAmbiguousMethod(Set<Method> candidates,
            Class<?>[] paramTypes) {
        // Identify which parameter isn't an exact match
        Method m = candidates.iterator().next();

        int nonMatchIndex = 0;
        Class<?> nonMatchClass = null;

        for (int i = 0; i < paramTypes.length; i++) {
            if (m.getParameterTypes()[i] != paramTypes[i]) {
                nonMatchIndex = i;
                nonMatchClass = paramTypes[i];
                break;
            }
        }

        if (nonMatchClass == null) {
            // Null will always be ambiguous
            return null;
        }

        for (Method c : candidates) {
           if (c.getParameterTypes()[nonMatchIndex] ==
                   paramTypes[nonMatchIndex]) {
               // Methods have different non-matching parameters
               // Result is ambiguous
               return null;
           }
        }

        // Can't be null
        Class<?> superClass = nonMatchClass.getSuperclass();
        while (superClass != null) {
            for (Method c : candidates) {
                if (c.getParameterTypes()[nonMatchIndex].equals(superClass)) {
                    // Found a match
                    return c;
                }
            }
            superClass = superClass.getSuperclass();
        }

        // Treat instances of Number as a special case
        Method match = null;
        if (Number.class.isAssignableFrom(nonMatchClass)) {
            for (Method c : candidates) {
                Class<?> candidateType = c.getParameterTypes()[nonMatchIndex];
                if (Number.class.isAssignableFrom(candidateType) ||
                        candidateType.isPrimitive()) {
                    if (match == null) {
                        match = c;
                    } else {
                        // Match still ambiguous
                        match = null;
                        break;
                    }
                }
            }
        }

        return match;
    }
457276
public SelectionBuilder where(String selection, String... selectionArgs) {
        if (TextUtils.isEmpty(selection)) {
            if (selectionArgs != null && selectionArgs.length > 0) {
                throw new IllegalArgumentException(
                        "Valid selection required when including arguments=");
            }

            // Shortcut when clause is empty
            return this;
        }

        if (mSelection.length() > 0) {
            mSelection.append(" AND ");
        }

        mSelection.append("(").append(selection).append(")");
        if (selectionArgs != null) {
            Collections.addAll(mSelectionArgs, selectionArgs);
        }

        return this;
    }
773512
public static Method[] candidateMethods(Class<?> clazz, String name, Object[] args) {
        return candidateMethods(collectMethods(clazz, name), args);
    }
576572
Optional<ExecutableElement> findSetterMethodFor(Element field) {
        String name = field.getSimpleName().toString();
        if (field.asType().getKind() == TypeKind.BOOLEAN) {
            if (name.length() > 2 && Character.isUpperCase(name.charAt(2))) {
                name = name.replaceFirst("^(is)(.+)", "$2");
            }
        }
        String setterName = setterNameFor(name);
        // FIXME refine this to discover one of possible overloaded methods with correct signature (i.e. single arg of field type)
        TypeElement typeElement = classElementFor(field);
        if (typeElement == null) {
            return Optional.empty();
        }

        List<? extends Element> elements = typeElement.getEnclosedElements();
        List<ExecutableElement> methods = ElementFilter.methodsIn(elements);
        return methods.stream()
            .filter(method -> {
                String methodName = method.getSimpleName().toString();
                if (setterName.equals(methodName)) {
                    Set<Modifier> modifiers = method.getModifiers();
                    return
                        // it's not static
                        !modifiers.contains(STATIC)
                            // it's either public or package visibility
                            && modifiers.contains(PUBLIC)
                            || !(modifiers.contains(PRIVATE) || modifiers.contains(PROTECTED));
                }
                return false;
            })
            .findFirst();
    }
1276087
private RenditionMetadata getExactMatchRendition(final Set<RenditionMetadata> candidates, MediaArgs mediaArgs) {
    // check for fixed width and/or height request
    if (mediaArgs.getFixedWidth() > 0 || mediaArgs.getFixedHeight() > 0) {
      for (RenditionMetadata candidate : candidates) {
        if (candidate.matches(mediaArgs.getFixedWidth(), mediaArgs.getFixedHeight())) {
          return candidate;
        }
      }
    }

    // otherwise check for media format restriction
    else if (mediaArgs.getMediaFormats() != null && mediaArgs.getMediaFormats().length > 0) {
      return visitMediaFormats(mediaArgs, new MediaFormatVisitor<RenditionMetadata>() {
        @Override
        public RenditionMetadata visit(MediaFormat mediaFormat) {
          for (RenditionMetadata candidate : candidates) {
            if (candidate.matches((int)mediaFormat.getEffectiveMinWidth(),
                (int)mediaFormat.getEffectiveMinHeight(),
                (int)mediaFormat.getEffectiveMaxWidth(),
                (int)mediaFormat.getEffectiveMaxHeight(),
                mediaFormat.getRatio())) {
              candidate.setMediaFormat(mediaFormat);
              return candidate;
            }
          }
          return null;
        }
      });
    }

    // no restriction - return original or first rendition
    else {
      return getOriginalOrFirstRendition(candidates);
    }

    // none found
    return null;
  }
814528
@Override
    public Object evaluate(TaskRequest req, TaskResponse res) {

        String rslt = null;

        Element e = (Element) element.evaluate(req, res);
        if (e.getName().equals("group")) {
            // This is a group name, we need to look up the key...
            try {

                Class[] types = new Class[] {IPerson.class, IPortletDefinition.class};

                for (Class c : types) {
                    EntityIdentifier[] eis =
                            GroupService.searchForGroups(
                                    e.getText(), IGroupConstants.SearchMethod.DISCRETE, c);
                    switch (eis.length) {
                        case 1:
                            // This is good -- what we hope for...
                            rslt = GroupService.findGroup(eis[0].getKey()).getKey();
                            break;
                        case 0:
                            // This is ok -- try the next type...
                            continue;
                        default:
                            String msg2 = "Ambiguous group name:  " + e.getText();
                            throw new RuntimeException(msg2);
                    }
                }

                // We better have a match by now...
                if (rslt == null) {
                    String msg = "No group with the specified name was found:  " + e.getText();
                    throw new RuntimeException(msg);
                }

            } catch (Throwable t) {
                String msg = "Error looking up the specified group:  " + e.getText();
                throw new RuntimeException(msg, t);
            }
        } else if (e.getName().equals("literal")) {
            rslt = e.getText();
        } else {
            String msg = "Unsupported element type:  " + e.getName();
            throw new RuntimeException(msg);
        }

        return rslt;
    }
572972
private static boolean hasMethod(JavaClass c, Method candidateMethod) {
		String name = candidateMethod.getName();
		String sig = candidateMethod.getSignature();

		for (Method method : c.getMethods()) {
			if (!method.isStatic() && method.getName().equals(name) && method.getSignature().equals(sig)) {
				return true;
			}
		}

		return false;
	}
1040785
private static int querySingleInteger(Connection connection, String sql,
			String[] args, boolean allowEmptyResults) {

		int result = 0;

		Object value = querySingleResult(connection, sql, args, 0,
				GeoPackageDataType.MEDIUMINT);
		if (value != null) {
			result = ((Number) value).intValue();
		} else if (!allowEmptyResults) {
			throw new GeoPackageException(
					"Failed to query for single result. SQL: " + sql);
		}

		return result;
	}
977198
Mappings matchRoot(IAtom root) {
        checkCompatibleAPI(root);
        IAtomContainer mol = root.getContainer();
        if (query.getAtomCount() > 0 && ((IQueryAtom) query.getAtom(0)).matches(root)) {
            DfState local = new DfState(state);
            local.setRoot(root);
            return filter(new Mappings(query, mol, local), query, mol);
        } else {
            return new Mappings(query, mol, Collections.<int[]>emptySet());
        }
    }
849009
private Optional<SoyType> soyTypeForProtoOrEnum(Class<?> type, Method method) {
    // Message isn't supported because we can't get a descriptor from it.
    if (type == Message.class) {
      reporter.invalidReturnType(Message.class, method);
      return Optional.absent();
    }
    Optional<String> fullName = nameFromDescriptor(type);
    if (!fullName.isPresent()) {
      reporter.incompatibleReturnType(type, method);
      return Optional.absent();
    }
    SoyType returnType = registry.getType(fullName.get());
    if (returnType == null) {
      reporter.incompatibleReturnType(type, method);
      return Optional.absent();
    }
    return Optional.of(returnType);
  }
498340
function parameterize(candidate) {
		candidate.param = candidate.param.map(function(param) {
			var value;

			if ('value' in param) {
				value = param.value;
			}
			else if ('reference' in param) {
				value = candidate.param.reduce(function(p, c) {
					return c !== param && !p && param.reference === c.name && 'value' in c ? c.value : p;
				}, null);
			}

			return value;
		});

		return candidate;
	}
1331903
public static MatchResult doMatch(final String requestURI, final String httpMethod) {
        MatchResult ret;
        final int segs = StringUtils.countMatches(requestURI, "/");
        ContextHandlerMeta contextHandlerMeta;
        String concreteKey = httpMethod + "." + requestURI;
        switch (segs) {
            case 1:
                contextHandlerMeta = ONE_SEG_CONCRETE_CTX_HANDLER_METAS.get(concreteKey);
                if (null != contextHandlerMeta) {
                    return new MatchResult(contextHandlerMeta, requestURI, httpMethod, requestURI);
                }

                switch (httpMethod) {
                    case "GET":
                        return route(requestURI, httpMethod, ONE_SEG_GET_VAR_CTX_HANDLER_METAS);
                    case "POST":
                        return route(requestURI, httpMethod, ONE_SEG_POST_VAR_CTX_HANDLER_METAS);
                    case "PUT":
                        return route(requestURI, httpMethod, ONE_SEG_PUT_VAR_CTX_HANDLER_METAS);
                    case "DELETE":
                        return route(requestURI, httpMethod, ONE_SEG_DELETE_VAR_CTX_HANDLER_METAS);
                    default:
                        return route(requestURI, httpMethod, ONE_SEG_OTHER_METHOD_VAR_CTX_HANDLER_METAS);
                }
            case 2:
                contextHandlerMeta = TWO_SEG_CONCRETE_CTX_HANDLER_METAS.get(concreteKey);
                if (null != contextHandlerMeta) {
                    return new MatchResult(contextHandlerMeta, requestURI, httpMethod, requestURI);
                }

                switch (httpMethod) {
                    case "GET":
                        return route(requestURI, httpMethod, TWO_SEG_GET_VAR_CTX_HANDLER_METAS);
                    case "POST":
                        return route(requestURI, httpMethod, TWO_SEG_POST_VAR_CTX_HANDLER_METAS);
                    case "PUT":
                        return route(requestURI, httpMethod, TWO_SEG_PUT_VAR_CTX_HANDLER_METAS);
                    case "DELETE":
                        return route(requestURI, httpMethod, TWO_SEG_DELETE_VAR_CTX_HANDLER_METAS);
                    default:
                        return route(requestURI, httpMethod, TWO_SEG_OTHER_METHOD_VAR_CTX_HANDLER_METAS);
                }
            case 3:
                contextHandlerMeta = THREE_SEG_CONCRETE_CTX_HANDLER_METAS.get(concreteKey);
                if (null != contextHandlerMeta) {
                    return new MatchResult(contextHandlerMeta, requestURI, httpMethod, requestURI);
                }

                switch (httpMethod) {
                    case "GET":
                        return route(requestURI, httpMethod, THREE_SEG_GET_VAR_CTX_HANDLER_METAS);
                    case "POST":
                        return route(requestURI, httpMethod, THREE_SEG_POST_VAR_CTX_HANDLER_METAS);
                    case "PUT":
                        return route(requestURI, httpMethod, THREE_SEG_PUT_VAR_CTX_HANDLER_METAS);
                    case "DELETE":
                        return route(requestURI, httpMethod, THREE_SEG_DELETE_VAR_CTX_HANDLER_METAS);
                    default:
                        return route(requestURI, httpMethod, THREE_SEG_OTHER_METHOD_VAR_CTX_HANDLER_METAS);
                }
            default:
                contextHandlerMeta = FOUR_MORE_SEG_CONCRETE_CTX_HANDLER_METAS.get(concreteKey);
                if (null != contextHandlerMeta) {
                    return new MatchResult(contextHandlerMeta, requestURI, httpMethod, requestURI);
                }

                switch (httpMethod) {
                    case "GET":
                        return route(requestURI, httpMethod, FOUR_MORE_SEG_GET_VAR_CTX_HANDLER_METAS);
                    case "POST":
                        return route(requestURI, httpMethod, FOUR_MORE_SEG_POST_VAR_CTX_HANDLER_METAS);
                    case "PUT":
                        return route(requestURI, httpMethod, FOUR_MORE_SEG_PUT_VAR_CTX_HANDLER_METAS);
                    case "DELETE":
                        return route(requestURI, httpMethod, FOUR_MORE_SEG_DELETE_VAR_CTX_HANDLER_METAS);
                    default:
                        return route(requestURI, httpMethod, FOUR_MORE_SEG_OTHER_METHOD_VAR_CTX_HANDLER_METAS);
                }
        }
    }
1314487
@Override
    public <I> MatchResult<I> matchResult(I item) {
        StringDescription mismatch = new StringDescription();
        if (matches(item, mismatch)) {
            return new MatchResultSuccess<>(item, this);
        } else {
            return new MatchResultMismatch<>(item, this, mismatch.toString());
        }
    }