拿到目标类型

@param candidate 原始类
@return 目标类型
558226
public static Class<?> getTargetClass(Object candidate) {
        return (isCglibProxyClass(candidate.getClass()) ? candidate.getClass().getSuperclass() : candidate.getClass());
    }
1266984
private final String getUnambiguousCompletions(final List<?> candidates) {
        if (candidates == null || candidates.isEmpty()) {
            return null;
        }

        // convert to an array for speed
        String[] strings = candidates.toArray(new String[candidates.size()]);

        String first = strings[0];
        StringBuilder candidate = new StringBuilder();

        for (int i = 0, count = first.length(); i < count; i++) {
            if (startsWith(first.substring(0, i + 1), strings)) {
                candidate.append(first.charAt(i));
            } else {
                break;
            }
        }

        return candidate.toString();
    }
1278089
public File getAndMakeDirectory(final String param) {
    final File f = get(param, new StringToFile(),
        new AlwaysValid<File>(), "existing or creatable directory");

    if (f.exists()) {
      if (f.isDirectory()) {
        return f.getAbsoluteFile();
      } else {
        throw new ParameterValidationException(fullString(param), f
            .getAbsolutePath().toString(),
            new ValidationException("Not an existing or creatable directory"));
      }
    } else {
      f.getAbsoluteFile().mkdirs();
      return f.getAbsoluteFile();
    }
  }
773512
public static Method[] candidateMethods(Class<?> clazz, String name, Object[] args) {
        return candidateMethods(collectMethods(clazz, name), args);
    }
899759
private boolean isGroupMember(final String filter, final File candidate) {
    final String fileName = candidate.getName();
    final int lastDot = fileName.lastIndexOf('.');
    if (lastDot >= 0 && lastDot < fileName.length() - 1) {
      final String extension = ";" + fileName.substring(lastDot + 1).toLowerCase() + ";";
      final String semiFilter = ";" + filter + ";";
      return semiFilter.contains(extension);
    }
    return false;
  }
41572
public void loadFromResource(String resource, Candidate.CandidateType type) throws IOException {
      InputStream candidatesConfig = classloader.getResourceAsStream(resource);
      if(candidatesConfig == null) {
         throw new IOException("Resource '" + resource + "' not found");
      }
      try {
         loadFrom(candidatesConfig, type);
      }
      finally {
         candidatesConfig.close();
      }
   }
539399
public static <E> List<E> refineCandidates(final List<E> candidates, final Predicate<? super E> predicate) {
        if (candidates.size() == 1) {
            return candidates;
        }
        List<E> newCandidates = CollectionUtils.filter(candidates, predicate);
        if (newCandidates.isEmpty()) {
            return candidates;
        }
        return newCandidates;
    }
519994
@Override
	public void complete(final LineReader reader, final ParsedLine line, final List<Candidate> candidates) {
		String buffer = line.line().substring(0, line.cursor());
		String[] parts = getLineParts(buffer);
		int len = parts.length;

		// コード補完する引数の番号を特定。
		int startArgNo = getStartArgNo(line);

		// 対象引数が-1、または開始引数にlenが満たない場合は該当なしなのでコード補完しない
		if (!accept(startArgNo, buffer, len)) {
			return;
		}

		String key = null;

		boolean isBlank = buffer.endsWith(" ");
		if (len == startArgNo && isBlank) {
			key = null;
		} else if (len == startArgNo + 1 && !isBlank) {
			key = parts[len - 1];
		} else {
			return;
		}

		final String keyword = key;

		Stream.of(SqlKeyword.values()).filter(k -> k.match(keyword))
				.forEach(k -> candidates.add(new Candidate(k.toString().toLowerCase())));
	}
1297510
public void registerCandidate(Class<?> candidateClass, String description, Candidate.CandidateType type) {
      Candidate candidate = new Candidate(candidateClass, description, type);
      int index = candidates.indexOf(candidate);
      if(index >= 0) {
         Candidate existingCandidate = candidates.get(index);
         if(!description.equals(existingCandidate.getDescription())) {
            throw new IllegalStateException("Two different descriptions for candidate " + candidateClass.getName());
         }
         existingCandidate.getTypes().add(type);
      }
      else {
         candidates.add(candidate);
      }
   }
363236
@SuppressWarnings("PMD.AssignmentInOperand")
    public Optional<String> pathRemainder(URI resource) {
        int matchRes = matches(resource);
        if (matchRes < 0) {
            return Optional.empty();
        }
        int segments = matchRes + 1;
        StringBuilder suffix = new StringBuilder();
        int[] count = { 0 };
        PathSpliterator.stream(resource.getPath()).forEach(seg -> {
            if (count[0]++ >= segments) {
                if (count[0] > segments + 1) {
                    suffix.append('/');
                }
                suffix.append(seg);
            }
        });
        return Optional.of(suffix.toString());
    }
664667
public static URI createFolderURI(File file) {
		URI uri = URI.createFileURI(file.getAbsolutePath());
		return toFolderURI(uri);
	}
681882
private FileHandlerResult processDir(final File dir) {
        // CHECKSTYLE:ON

        final FileHandlerResult dirResult = handler.handleFile(dir);
        if (dirResult == FileHandlerResult.STOP) {
            return FileHandlerResult.STOP;
        }
        if (dirResult == FileHandlerResult.SKIP_ALL) {
            return FileHandlerResult.CONTINUE;
        }

        final File[] files = dir.listFiles();
        if (files != null) {
            final List<File> sortedFiles = asList(files);
            for (int i = 0; i < sortedFiles.size(); i++) {
                final File file = sortedFiles.get(i);
                FileHandlerResult result = FileHandlerResult.CONTINUE;
                if (file.isDirectory() && (dirResult != FileHandlerResult.SKIP_SUBDIRS)) {
                    result = processDir(file);
                } else if (file.isFile() && (dirResult != FileHandlerResult.SKIP_FILES)) {
                    result = handler.handleFile(file);
                }
                if (result == FileHandlerResult.STOP) {
                    return FileHandlerResult.STOP;
                }
                if (result == FileHandlerResult.SKIP_ALL) {
                    return FileHandlerResult.CONTINUE;
                }
            }
        }

        return FileHandlerResult.CONTINUE;

    }
41662
private Result getCandidateInfo(String candidateId){

        StatsStorage ss = knownSessionIDs.get(currentSessionID);
        if(ss == null){
            log.debug("getModelLastUpdateTimes(): Session ID is unknown: {}", currentSessionID);
            return ok();
        }

        GlobalConfigPersistable gcp = (GlobalConfigPersistable)ss.getStaticInfo(currentSessionID, ARBITER_UI_TYPE_ID, GlobalConfigPersistable.GLOBAL_WORKER_ID);;
        OptimizationConfiguration oc = gcp.getOptimizationConfiguration();

        Persistable p = ss.getLatestUpdate(currentSessionID, ARBITER_UI_TYPE_ID, candidateId);
        if(p == null){
            String title = "No results found for model " + candidateId + ".";
            ComponentText ct = new ComponentText.Builder(title,STYLE_TEXT_SZ12).build();
            return ok(asJson(ct)).as(JSON);
        }

        ModelInfoPersistable mip = (ModelInfoPersistable)p;

        //First: static info
        // Hyperparameter configuration/settings
        // Number of parameters
        // Maybe memory info in the future?

        //Second: dynamic info
        //Runtime
        // Performance stats (total minibatches, total time,
        // Score vs. time

        List<Component> components = new ArrayList<>();

        //First table: mix of static + dynamic in a table
        long runtimeDurationMs = mip.getLastUpdateTime() - mip.getTimeStamp();
        double avgMinibatchesPerSec = mip.getTotalNumUpdates() / (runtimeDurationMs/1000.0);
        String avgMinibatchesPerSecStr = DECIMAL_FORMAT_2DP.format(avgMinibatchesPerSec);
        String runtimeStr = UIUtils.formatDuration(runtimeDurationMs);

        if(mip.getStatus() == CandidateStatus.Failed){
            runtimeStr = "";
            avgMinibatchesPerSecStr = "";
        }

        String[][] table = new String[][]{
                {"Model Index", String.valueOf(mip.getModelIdx())},
                {"Status", mip.getStatus().toString()},
                {"Model Score", mip.getScore() == null ? "" : String.valueOf(mip.getScore())},
                {"Created", TIME_FORMATTER.print(mip.getTimeStamp())},
                {"Runtime", runtimeStr},
                {"Total Number of Model Updates", String.valueOf(mip.getTotalNumUpdates())},
                {"Average # Updates / Sec", avgMinibatchesPerSecStr},
                {"Number of Parameters", String.valueOf(mip.getNumParameters())},
                {"Number of Layers", String.valueOf(mip.getNumLayers())}
        };

        ComponentTable cTable = new ComponentTable.Builder(STYLE_TABLE)
                .content(table)
                .header("Model Information", "")
                .build();
        components.add(cTable);


        //Second: parameter space values, in multiple tables
        double[] paramSpaceValues = mip.getParamSpaceValues();
        if(paramSpaceValues != null){
            BaseNetworkSpace bns = (BaseNetworkSpace)oc.getCandidateGenerator().getParameterSpace();
            Map<String,ParameterSpace> m = bns.getNestedSpaces();

            String[][] hSpaceTable = new String[m.size()][3];
            int i=0;
            for(Map.Entry<String,ParameterSpace> e : m.entrySet()){
                hSpaceTable[i][0] = e.getKey();
                Object currCandidateValue = e.getValue().getValue(paramSpaceValues);
                hSpaceTable[i][1] = ObjectUtils.valueToString(currCandidateValue);
                hSpaceTable[i][2] = e.getValue().toString();
                i++;
            }

            String[] hSpaceTableHeader = new String[]{"Hyperparameter", "Model Value", "Hyperparameter Space"};

            ComponentTable ct2 = new ComponentTable.Builder(STYLE_TABLE3_25_25_50)
                    .content(hSpaceTable)
                    .header(hSpaceTableHeader)
                    .build();


            String title = "Global Network Configuration";
            components.add(DIV_SPACER_20PX);
            components.add(new ComponentText.Builder(title, STYLE_TEXT_SZ12).build());
            components.add(ct2);

            List<BaseNetworkSpace.LayerConf> layerConfs = bns.getLayerSpaces();

            for(BaseNetworkSpace.LayerConf l : layerConfs){
                LayerSpace<?> ls = l.getLayerSpace();
                Map<String,ParameterSpace> lpsm = ls.getNestedSpaces();

                String[][] t = new String[lpsm.size()][3];
                i=0;
                for(Map.Entry<String,ParameterSpace> e : lpsm.entrySet()){
                    t[i][0] = e.getKey();
                    Object currCandidateValue = e.getValue().getValue(paramSpaceValues);
                    t[i][1] = ObjectUtils.valueToString(currCandidateValue);
                    t[i][2] = e.getValue().toString();
                    i++;
                }

                ComponentTable ct3 = new ComponentTable.Builder(STYLE_TABLE3_25_25_50)
                        .content(t)
                        .header(hSpaceTableHeader)
                        .build();

                title = "Layer Space: " + ls.getClass().getSimpleName() + ", Name: " + l.getLayerName();

                components.add(DIV_SPACER_20PX);
                components.add(new ComponentText.Builder(title, STYLE_TEXT_SZ12).build());
                components.add(ct3);
            }
        }


        //Third: Score vs. time chart
        int[] iters = mip.getIter();
        float[] scores = mip.getScoreVsIter();

        if(iters != null) {
            double[] si = new double[iters.length];
            double[] scoresD = new double[iters.length];

            double minScore = Double.MAX_VALUE;
            double maxScore = -Double.MAX_VALUE;
            for( int i=0; i<iters.length; i++ ){
                si[i] = iters[i];
                scoresD[i] = scores[i];
                minScore = Math.min(minScore, scoresD[i]);
                maxScore = Math.max(maxScore, scoresD[i]);
            }

            double[] chartMinMax = UIUtils.graphNiceRange(maxScore, minScore, 5);

            ChartLine cl = new ChartLine.Builder("Model Score vs. Iteration", STYLE_CHART_800_400)
                    .addSeries("Score", si, scoresD )
                    .setYMin(chartMinMax[0])
                    .setYMax(chartMinMax[1])
                    .build();

            components.add(DIV_SPACER_60PX);
            components.add(cl);
        }


        //Post full network configuration JSON, if available:
        String modelJson = mip.getModelConfigJson();
        if(modelJson != null){
            components.add(DIV_SPACER_60PX);
            components.add(new ComponentDiv(STYLE_DIV_WIDTH_100_PC, new ComponentText("Model Configuration", STYLE_TEXT_SZ12)));
            ComponentText jsonText = new ComponentText(modelJson, STYLE_TEXT_SZ10_WHITESPACE_PRE);
            ComponentDiv cd = new ComponentDiv(STYLE_DIV_WIDTH_100_PC, jsonText);
            components.add(cd);
        }


        //Post exception stack trace, if necessary:
        if( mip.getExceptionStackTrace() != null ){
            components.add(DIV_SPACER_60PX);
            components.add(new ComponentDiv(STYLE_DIV_WIDTH_100_PC, new ComponentText("Model Exception - Stack Trace", STYLE_TEXT_SZ12)));
            ComponentText exText = new ComponentText(mip.getExceptionStackTrace(), STYLE_TEXT_SZ10_WHITESPACE_PRE);
            ComponentDiv cd = new ComponentDiv(STYLE_DIV_WIDTH_100_PC, exText);
            components.add(cd);
        }

        ComponentDiv cd = new ComponentDiv(STYLE_DIV_WIDTH_100_PC, components);

        return ok(asJson(cd)).as(JSON);
    }
1036931
@NonNull
    @Override
    public Uri toUri(@NonNull final File file) {
        return FileProvider
                .getUriForFile(getContext(),
                        getContext().getApplicationContext().getPackageName() + ".provider",
                        file);
    }
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;
	}
89471
private static File getUserDirectory(final String prefix, final String suffix, final File parent) {
        final String dirname = formatDirName(prefix, suffix);
        return new File(parent, dirname);
    }
885084
private static List<Word> selectBest(List<List<Word>> candidateWords){
        if(LOGGER.isDebugEnabled()) {
            LOGGER.debug("开始从多个识别结果中选择一个最佳的结果:{}", candidateWords);
        }
        Map<List<Word>, Integer> map = new ConcurrentHashMap<>();
        AtomicInteger i = new AtomicInteger();
        candidateWords.stream().forEach(candidateWord -> {
            if(LOGGER.isDebugEnabled()) {
                LOGGER.debug(i.incrementAndGet() + "、开始处理：" + candidateWord);
            }
            //词性标注
            PartOfSpeechTagging.process(candidateWord);
            //根据词性标注的结果进行评分
            StringBuilder seq = new StringBuilder();
            candidateWord.forEach(word -> seq.append(word.getPartOfSpeech().getPos().charAt(0)).append(" "));
            String seqStr = seq.toString();
            AtomicInteger score = new AtomicInteger();
            if(LOGGER.isDebugEnabled()) {
                LOGGER.debug("词序列：{} 的词性序列：{}", candidateWord, seqStr);
            }
            POS_SEQ.keySet().stream().forEach(pos_seq -> {
                if (seqStr.contains(pos_seq)) {
                    int sc = POS_SEQ.get(pos_seq);
                    if(LOGGER.isDebugEnabled()) {
                        LOGGER.debug(pos_seq + "词序增加分值：" + sc);
                    }
                    score.addAndGet(sc);
                }
            });
            score.addAndGet(-candidateWord.size());
            if(LOGGER.isDebugEnabled()) {
                LOGGER.debug("长度的负值也作为分值：" + (-candidateWord.size()));
                LOGGER.debug("评分结果：" + score.get());
            }
            map.put(candidateWord, score.get());
        });
        //选择分值最高的
        List<Word> result = map.entrySet().stream().sorted((a,b)->b.getValue().compareTo(a.getValue())).map(e->e.getKey()).collect(Collectors.toList()).get(0);
        if(LOGGER.isDebugEnabled()){
            LOGGER.debug("选择结果："+result);
        }
        return result;
    }