/** Faz as validações solicitadas no manual de integração */ public String isValid() { if (getTpAmb() == null || getTpAmb().length() != 1) { return "Tipo de Ambiente inválido"; } if (getcUF() == null || getcUF().length() != 2) { return "Código da UF inválido"; } if (getAno() == null || getAno().length() != 2) { return "O Ano de inutilização é inválido"; } if (getCNPJ() == null || getCNPJ().length() != 14) { return "CNPJ inválido"; } if (getMod() == null || getMod().length() != 2 || !TextUtil.isNumber(getMod())) { return "Modelo da NF inválido"; } if (getSerie() == null || getSerie().length() < 1 || getSerie().length() > 3 || !TextUtil.isNumber(getSerie())) { return "Série da NF inválida"; } if (getnNFIni() == null || getnNFIni().length() < 1 || getnNFIni().length() > 9 || !NumberUtils.isNumber(getnNFIni())) { return "Número Inicial da NF para inutilização é inválido"; } if (getnNFFin() == null || getnNFFin().length() < 1 || getnNFFin().length() > 9 || !NumberUtils.isNumber(getnNFFin())) { return "Número Final da NF para inutilização é inválido"; } if (getxJust() == null || getxJust().length() < 15) { return "Justificativa deve ser maior que 15 caracteres"; } if (Integer.parseInt(getnNFIni()) > Integer.parseInt(getnNFFin())) { return "Número Final da NF não pode ser menor que Número Inicial da NF"; } setID(); return null; } // isValid
@RequestMapping(value = "/find.html") public ModelAndView find(@RequestParam(value = "q", required = false) String q) { ModelAndView mav = new ModelAndView(); mav.addObject("operation", "find"); if (StringUtils.isEmpty(q)) { mav.setViewName("find"); return mav; } try { if (NumberUtils.isNumber(q) && StringUtils.length(q) == 7) { return show(Integer.valueOf(q)); } else { long startTs = System.currentTimeMillis(); List<TConcept> concepts = nodeService.findConcepts(q); mav.addObject("concepts", concepts); long endTs = System.currentTimeMillis(); mav.addObject("q", q); mav.addObject("elapsed", new Long(endTs - startTs)); } } catch (Exception e) { mav.addObject("error", e.getMessage()); } mav.setViewName("find"); return mav; }
@Override public boolean validate() { if (NumberUtils.isNumber(_textf.getText())) { return true; } return false; }
/** * 对字符串进行混淆,字符串必须是有效整数数字 * * @param id * @return */ public static String chaos(String id) { if (StringUtils.isEmpty(id)) { return StringUtils.EMPTY; } else if (!NumberUtils.isNumber(id)) { return StringUtils.EMPTY; } return chaos(Long.valueOf(id)); }
/** * Returns the value as a {@link Double} value. The returned value will be <code>0</code> or * <code>1</code> if the {@link #value} is a boolean value. If {@link #value} can not be converted * into a number, a {@link NumberFormatException} is thrown. * * @return {@link #value} as {@link Double} */ public double getValueAsDouble() { if (NumberUtils.isNumber(value)) { return NumberUtils.createDouble(value); } if (isBooleanValue(value)) { return BooleanUtils.toBoolean(value) ? 1 : 0; } throw new NumberFormatException(); }
private static Object initializeStringValue(final String value) { if (value == null) { throw new IllegalArgumentException("The left hand side value cannot be null"); } if (NumberUtils.isNumber(value)) { return Integer.valueOf(value); } return value; }
/** * 新增或更新用户月度活跃时长统计,返回执行结果 * * @param uidList 月度活跃uid分页清单 * @param millisList 对应用户在线时长list * @param monthStr 统计月度,yyyyMM * @return 执行结果 */ public boolean batchAddOrUpdateMAUStats( List<String> uidList, List<String> millisList, String monthStr) { if (uidList == null || millisList == null || uidList.isEmpty() || millisList.isEmpty()) { return false; } if (uidList.size() != millisList.size()) { return false; } int listSize = uidList.size(); boolean result = false; Connection conn = null; PreparedStatement ps = null; String sql = "INSERT INTO `ssyh_main`.`mau_stats`" + "(`month_str`,`uid`,`stay_seconds`,`stay_minutes`,`stay_hours`) VALUES(?,?,?,?,?) " + "ON DUPLICATE KEY UPDATE `stay_seconds` = ?,`stay_minutes`=?,`stay_hours`=?;"; try { conn = DBUtil.getConnection(); // 关闭事务自动提交 conn.setAutoCommit(false); ps = conn.prepareStatement(sql); for (int i = 0; i < listSize; i++) { String uid = uidList.get(i); String millisStr = millisList.get(i); long stayMillis = NumberUtils.isNumber(millisStr) ? Long.parseLong(millisStr) : 0L; MAUStatsBean bean = new MAUStatsBean(monthStr, uid, stayMillis); // insert参数 ps.setString(1, bean.getMonthStr()); ps.setString(2, bean.getUid()); ps.setInt(3, bean.getStaySeconds()); ps.setInt(4, bean.getStayMinutes()); ps.setDouble(5, bean.getStayHours()); // update参数 ps.setInt(6, bean.getStaySeconds()); ps.setInt(7, bean.getStayMinutes()); ps.setDouble(8, bean.getStayHours()); ps.addBatch(); } ps.executeBatch(); // 关闭事务自动提交 conn.setAutoCommit(true); result = true; } catch (SQLException e) { result = false; logger.error("addOrUpdateMAUStats exception:" + e.getMessage(), e); } finally { DBUtil.close(null, ps, conn); } return result; }
/* (non-Javadoc) * @see org.springframework.web.servlet.mvc.AbstractController#handleRequestInternal(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ @Override protected ModelAndView handleRequestInternal( HttpServletRequest request, HttpServletResponse response) throws Exception { String query = request.getParameter("query"); if (StringUtils.isBlank(query)) { return new ModelAndView(getSearchView()); } String p = request.getParameter("p"); int currentPage = 1; if (NumberUtils.isNumber(p)) { currentPage = Integer.parseInt(p); } if (currentPage < 1) { currentPage = 1; } CompassSearchCommand searchCommand = new CompassSearchCommand(); searchCommand.setPage(new Integer(currentPage - 1)); searchCommand.setQuery(query); ModelAndView mv = new ModelAndView(); mv.addObject("query", query); mv.addObject("p", currentPage); List<String> errors = new ArrayList<String>(); try { CompassSearchResults searchResults = searchHelper.search(searchCommand); List<CompassHitWapper> hits = new ArrayList<CompassHitWapper>(); for (int i = 0; i < searchResults.getHits().length; i++) { CompassHitWapper hit = new CompassHitWapper(searchResults.getHits()[i]); hits.add(hit); } CompassSearchResultsWrapper results = new CompassSearchResultsWrapper(searchResults); results.setHits(hits); mv.addObject(getSearchResultsName(), results); } catch (SearchEngineQueryParseException ex) { errors.add(TextUtil.escapeHTML(ex.getMessage())); mv.addObject("errors", errors); } catch (Exception ex) { errors.add(TextUtil.escapeHTML(ex.getMessage())); mv.addObject("errors", errors); } mv.setViewName(getSearchResultsView()); return mv; }
// really an update public boolean saveSetting(Account account, String key, String value) throws ControllerException { // check if a search boost setting. hack: expecting that search boosts will only use numeric // values TODO if (NumberUtils.isNumber(value)) { try { SearchBoostField boostField = SearchBoostField.valueOf(key.toUpperCase()); if (boostField != null) { key = "BOOST_" + boostField.name(); } } catch (Exception e) { Logger.debug(e.getMessage()); } } try { return dao.saveOrUpdatePreference(account, key, value) != null; } catch (DAOException e) { throw new ControllerException(e); } }
/** * 修复地区名称为地区代码 (comInterview) * * @param page */ public void fixComInterviewJobLocationToCode(Page<ComInterview> page) { if (page == null || CollectionUtils.isEmpty(page.getItems())) { return; } for (ComInterview comInterview : page.getItems()) { if (StringUtils.isNotBlank(comInterview.getJobLocation())) { List<Integer> jobLocationList = Lists.newArrayList(); String[] jobLocationArr = comInterview.getJobLocation().split(","); for (String location : jobLocationArr) { Integer code = OptionMap.getCityCodeByAddr(location); if (code != null && code > 0 && !NumberUtils.isNumber(location)) { jobLocationList.add(code); } } if (CollectionUtils.isNotEmpty(jobLocationList)) { comInterview.setJobLocation(StringUtils.join(jobLocationList, ",")); } } } }
/** Ensures that all fields are set. */ private void dialogChanged() { if (projectProviders == null) { setEnabled(false); updateStatus(Messages.error_new_project_metadata_not_found); return; } providerDescription.setText( projectProviders.get(providerName.getSelectionIndex()).getDescription()); if (isDemo()) { if (!this.providerName.getText().equals(projectProviders.get(0).getDisplayName())) { this.providerName.setText(projectProviders.get(0).getDisplayName()); // AS/400 setEnabled(false); updateStatus(null); } return; } else { setEnabled(true); } if (hostName.getText().length() == 0) { updateStatus(Messages.error_host_name_not_specified); return; } if (hostPort.getText().length() == 0) { updateStatus(Messages.errror_host_port_not_specified); return; } if (!NumberUtils.isNumber(hostPort.getText())) { updateStatus(Messages.error_port_not_numeric); return; } if (codePage.getText().length() == 0) { updateStatus(Messages.error_code_page_not_specified); return; } this.updateStatus(null); }
/** * {@inheritDoc} * * @see * org.kuali.kra.common.specialreview.service.SpecialReviewService#addProtocolFundingSourceForSpecialReview(java.lang.String, * java.lang.String, java.lang.String, java.lang.String, java.lang.String) */ public void addProtocolFundingSourceForSpecialReview( String protocolNumber, String fundingSourceNumber, String fundingSourceTypeCode, String fundingSourceName, String fundingSourceTitle) { Protocol protocol = getProtocolFinderDao().findCurrentProtocolByNumber(protocolNumber); if (protocol != null && StringUtils.isNotBlank(fundingSourceNumber) && NumberUtils.isNumber(fundingSourceTypeCode)) { ProtocolFundingSource protocolFundingSource = new ProtocolFundingSource(); protocolFundingSource.setProtocolNumber(protocolNumber); protocolFundingSource.setFundingSourceNumber(fundingSourceNumber); protocolFundingSource.setFundingSourceTypeCode(fundingSourceTypeCode); protocolFundingSource.setFundingSourceName(fundingSourceName); protocolFundingSource.setFundingSourceTitle(fundingSourceTitle); protocol.getProtocolFundingSources().add(protocolFundingSource); getBusinessObjectService().save(protocol); } }
public static boolean isNumber(List<String> args, int index) { return NumberUtils.isNumber(args.get(index)); }
/** * Determines the CSV parser setup from the first few lines. Also parses the next few lines, * tossing out comments and blank lines. * * <p>If the separator is GUESS_SEP, then it is guessed by looking at tokenization and column * count of the first few lines. * * <p>If ncols is -1, then it is guessed similarly to the separator. * * <p>singleQuotes is honored in all cases (and not guessed). */ static ParseSetup guessSetup( byte[] bits, byte sep, int ncols, boolean singleQuotes, int checkHeader, String[] columnNames, byte[] columnTypes, String[][] naStrings) { String[] lines = getFirstLines(bits); if (lines.length == 0) throw new H2OParseSetupException("No data!"); // Guess the separator, columns, & header String[] labels; final String[][] data = new String[lines.length][]; if (lines.length == 1) { // Ummm??? Only 1 line? if (sep == GUESS_SEP) { if (lines[0].split(",").length > 2) sep = (byte) ','; else if (lines[0].split(" ").length > 2) sep = ' '; else { // one item, guess type data[0] = new String[] {lines[0]}; byte[] ctypes = new byte[1]; String[][] domains = new String[1][]; if (NumberUtils.isNumber(data[0][0])) { ctypes[0] = Vec.T_NUM; } else { // non-numeric ValueString str = new ValueString(data[0][0]); if (ParseTime.isTime(str)) ctypes[0] = Vec.T_TIME; else if (ParseUUID.isUUID(str)) ctypes[0] = Vec.T_UUID; else { // give up and guess enum ctypes[0] = Vec.T_ENUM; domains[0] = new String[] {data[0][0]}; } } // FIXME should set warning message and let fall through return new ParseSetup( ParserType.CSV, GUESS_SEP, singleQuotes, checkHeader, 1, null, ctypes, domains, naStrings, data, FileVec.DFLT_CHUNK_SIZE); } } data[0] = determineTokens(lines[0], sep, singleQuotes); ncols = (ncols > 0) ? ncols : data[0].length; if (checkHeader == GUESS_HEADER) { if (ParseSetup.allStrings(data[0])) { labels = data[0]; checkHeader = HAS_HEADER; } else { labels = null; checkHeader = NO_HEADER; } } else if (checkHeader == HAS_HEADER) labels = data[0]; else labels = null; } else { // 2 or more lines // First guess the field separator by counting occurrences in first few lines if (sep == GUESS_SEP) { // first guess the separator sep = guessSeparator(lines[0], lines[1], singleQuotes); if (sep == GUESS_SEP && lines.length > 2) { sep = guessSeparator(lines[1], lines[2], singleQuotes); if (sep == GUESS_SEP) sep = guessSeparator(lines[0], lines[2], singleQuotes); } if (sep == GUESS_SEP) sep = (byte) ' '; // Bail out, go for space } // Tokenize the first few lines using the separator for (int i = 0; i < lines.length; ++i) data[i] = determineTokens(lines[i], sep, singleQuotes); // guess columns from tokenization ncols = guessNcols(columnNames, data); // Asked to check for a header, so see if 1st line looks header-ish if (checkHeader == HAS_HEADER || (checkHeader == GUESS_HEADER && ParseSetup.hasHeader(data[0], data[1]))) { checkHeader = HAS_HEADER; labels = data[0]; } else { checkHeader = NO_HEADER; labels = columnNames; } // See if compatible headers if (columnNames != null && labels != null) { if (labels.length != columnNames.length) throw new H2OParseSetupException( "Already have " + columnNames.length + " column labels, but found " + labels.length + " in this file"); else { for (int i = 0; i < labels.length; ++i) if (!labels[i].equalsIgnoreCase(columnNames[i])) { throw new H2OParseSetupException( "Column " + (i + 1) + " label '" + labels[i] + "' does not match '" + columnNames[i] + "'"); } labels = columnNames; // Keep prior case & count in any case } } } // Assemble the setup understood so far ParseSetup resSetup = new ParseSetup( ParserType.CSV, sep, singleQuotes, checkHeader, ncols, labels, null, null /*domains*/, naStrings, data); // now guess the types if (columnTypes == null || ncols != columnTypes.length) { InputStream is = new ByteArrayInputStream(bits); CsvParser p = new CsvParser(resSetup, null); PreviewParseWriter dout = new PreviewParseWriter(resSetup._number_columns); try { p.streamParse(is, dout); resSetup._column_previews = dout; } catch (Throwable e) { throw new RuntimeException(e); } } else { // If user sets column type as unknown/bad, guess numeric. for (int i = 0; i < columnTypes.length; i++) if (columnTypes[i] == Vec.T_BAD) columnTypes[i] = Vec.T_NUM; resSetup._column_types = columnTypes; resSetup._na_strings = null; } // Return the final setup return resSetup; }
@Override public boolean performOk() { String txtResultType = comboRDBResultType.getText(); String txtSelectLimit = textSelectLimit.getText(); String txtResultPage = textResultPage.getText(); String txtQueryTimtout = textQueryTimeout.getText(); String txtOraclePlan = textOraclePlan.getText(); String txtRDBNumberColumnIsComman = comboRDBNumberComma.getText(); String txtFontInfo = lblUserFont.getText(); String txtCommitCount = textCommitCount.getText(); String txtShownInTheColumn = textShowInTheColumn.getText(); if (!NumberUtils.isNumber(txtSelectLimit)) { MessageDialog.openError( getShell(), "Confirm", Messages.get().DefaultPreferencePage_0 + Messages.get().RDBPreferencePage_0); // $NON-NLS-1$ textSelectLimit.setFocus(); return false; } if (!NumberUtils.isNumber(txtResultPage)) { MessageDialog.openError( getShell(), "Confirm", Messages.get().DefaultPreferencePage_other_labelText_1 + Messages.get().RDBPreferencePage_0); // $NON-NLS-1$ textResultPage.setFocus(); return false; } if (!NumberUtils.isNumber(txtQueryTimtout)) { MessageDialog.openError( getShell(), "Confirm", "Query timeout is " + Messages.get().RDBPreferencePage_0); textQueryTimeout.setFocus(); return false; } if (!NumberUtils.isNumber(txtCommitCount)) { MessageDialog.openError( getShell(), "Confirm", "Commit count is " + Messages.get().RDBPreferencePage_0); textCommitCount.setFocus(); return false; } if ("".equals(txtOraclePlan)) { // $NON-NLS-1$ MessageDialog.openError( getShell(), "Confirm", Messages.get().RDBPreferencePage_3); // $NON-NLS-1$ return false; } if (!NumberUtils.isNumber(txtShownInTheColumn)) { MessageDialog.openError(getShell(), "Confirm", Messages.get().RDBPreferencePage_0); textShowInTheColumn.setFocus(); return false; } // 테이블에 저장 try { TadpoleSystem_UserInfoData.updateRDBUserInfoData( txtSelectLimit, txtResultPage, txtQueryTimtout, txtOraclePlan, txtRDBNumberColumnIsComman, txtFontInfo, txtCommitCount, txtShownInTheColumn, txtResultType); // session 데이터를 수정한다. SessionManager.setUserInfo(PreferenceDefine.RDB_RESULT_TYPE, txtResultType); SessionManager.setUserInfo(PreferenceDefine.SELECT_LIMIT_COUNT, txtSelectLimit); SessionManager.setUserInfo(PreferenceDefine.SELECT_RESULT_PAGE_PREFERENCE, txtResultPage); SessionManager.setUserInfo(PreferenceDefine.SELECT_QUERY_TIMEOUT, txtQueryTimtout); SessionManager.setUserInfo(PreferenceDefine.ORACLE_PLAN_TABLE, txtOraclePlan); SessionManager.setUserInfo( PreferenceDefine.RDB_RESULT_NUMBER_IS_COMMA, txtRDBNumberColumnIsComman); SessionManager.setUserInfo(PreferenceDefine.RDB_RESULT_FONT, txtFontInfo); SessionManager.setUserInfo(PreferenceDefine.RDB_COMMIT_COUNT, txtCommitCount); SessionManager.setUserInfo( PreferenceDefine.RDB_CHARACTER_SHOW_IN_THE_COLUMN, txtShownInTheColumn); } catch (Exception e) { logger.error("RDBPreference saveing", e); MessageDialog.openError( getShell(), "Confirm", Messages.get().RDBPreferencePage_5 + e.getMessage()); // $NON-NLS-1$ return false; } return super.performOk(); }
private void doMain() throws SAXParseException, IOException { Normalizer normalizer = null; if (useTokenizer) { normalizer = Normalizer.getInstance(); } PrintWriter reversedWordsWriter = analysisPlacesOut != null ? new PrintWriter(new File(analysisPlacesOut, "reversedWords.txt")) : new PrintWriter(System.out); BufferedReader bufferedReader = new BufferedReader(new FileReader(placesIn)); int lineCount = 0; while (bufferedReader.ready()) { String nextLine = bufferedReader.readLine(); nextLine = nextLine.trim().toLowerCase(); if (nextLine.length() == 0) continue; lineCount++; if (lineCount % 5000 == 0) System.out.println("indexing line " + lineCount); placesCountCC.add(nextLine); totalPlacesCount++; String[] placeList = nextLine.split(SPLIT_REGEX); for (String place : placeList) { place = place.trim(); if (place.length() == 0) continue; if (NumberUtils.isNumber(place)) { numbersCountCC.add(place); totalNumbersCount++; } else { wordsCountCC.add(place); totalWordsCount++; } } int lastCommaIndx = nextLine.lastIndexOf(","); String lastWord = nextLine.substring(lastCommaIndx + 1).trim(); if (lastWord.length() > 0) { endingsOfPlacesCC.add(lastWord); endingsOfPlacesTotalCount++; } if (lineCount % REVERSE_EVERY_N == 0) { StringBuilder reversedWord = new StringBuilder(nextLine); reversedWordsWriter.println(reversedWord.reverse()); } if ((useTokenizer) && (lineCount % TOKENIZE_EVERY_N == 0)) { List<List<String>> levels = normalizer.tokenize(nextLine); for (List<String> levelWords : levels) { tokenizerPlacesCountCC.addAll(levelWords); totalTokenizerPlacesCount += levelWords.size(); } } } System.out.println("total number of lines in files " + lineCount); System.out.println("Indexed a total of " + totalPlacesCount + " places."); System.out.println("Found a total of " + getPlacesCountCC().size() + " unique places."); getPlacesCountCC() .writeSorted( false, 1, analysisPlacesOut != null ? new PrintWriter(new File(analysisPlacesOut, "placesCount.txt")) : new PrintWriter(System.out)); System.out.println("Indexed a total of " + totalWordsCount + " words."); System.out.println("Found a total of " + getWordsCountCC().size() + " unique words."); getWordsCountCC() .writeSorted( false, 1, analysisPlacesOut != null ? new PrintWriter(new File(analysisPlacesOut, "wordsCount.txt")) : new PrintWriter(System.out)); System.out.println("Indexed a total of " + totalNumbersCount + " numbers."); System.out.println("Found a total of " + getNumbersCountCC().size() + " unique numbers."); getNumbersCountCC() .writeSorted( false, 1, analysisPlacesOut != null ? new PrintWriter(new File(analysisPlacesOut, "numbersCount.txt")) : new PrintWriter(System.out)); System.out.println("Indexed a total of " + endingsOfPlacesTotalCount + " endings."); System.out.println("Found a total of " + getEndingsOfPlacesCC().size() + " unique endings."); getEndingsOfPlacesCC() .writeSorted( false, 1, analysisPlacesOut != null ? new PrintWriter(new File(analysisPlacesOut, "endingsCount.txt")) : new PrintWriter(System.out)); if (useTokenizer) { System.out.println("Indexed a total of " + totalTokenizerPlacesCount + " normalized words."); System.out.println( "Found a total of " + getTokenizerPlacesCountCC().size() + " normalized words."); getTokenizerPlacesCountCC() .writeSorted( false, 1, analysisPlacesOut != null ? new PrintWriter(new File(analysisPlacesOut, "normalizedWordsCount.txt")) : new PrintWriter(System.out)); } }
@RequestMapping(value = "/map.html") public ModelAndView map( @RequestParam(value = "q1", required = false) String q1, @RequestParam(value = "q2", required = false) String q2, @RequestParam(value = "q3", required = false) String q3, @RequestParam(value = "if", required = false, defaultValue = UimaUtils.MIMETYPE_STRING) String inputFormat, @RequestParam(value = "of", required = true, defaultValue = "html") String outputFormat, @RequestParam(value = "ofs", required = false, defaultValue = "pretty") String outputFormatStyle, @RequestParam(value = "sgf", required = false) String[] styGroupFilter, @RequestParam(value = "scf", required = false) String[] styCodeFilter) { ModelAndView mav = new ModelAndView(); mav.addObject("operation", "map"); // validate parameters (at least one of o, q, u or t must // be supplied, otherwise show the input form mav.addObject("q1", StringUtils.isEmpty(q1) ? "" : q1); mav.addObject("q2", StringUtils.isEmpty(q2) ? "" : q2); mav.addObject("q3", StringUtils.isEmpty(q3) ? "" : q3); String q = StringUtils.isNotEmpty(q1) ? q1 : StringUtils.isNotEmpty(q2) ? q2 : StringUtils.isNotEmpty(q3) ? q3 : null; if (StringUtils.isEmpty(q)) { setViewName(mav, outputFormat, outputFormatStyle); return mav; } try { if (NumberUtils.isNumber(q) && StringUtils.length(q) == 7) { return show(Integer.valueOf(q)); } else { // show list of concepts String text = q; if ((q.startsWith("http://") && UimaUtils.MIMETYPE_HTML.equals(inputFormat))) { URL u = new URL(q); BufferedReader br = new BufferedReader(new InputStreamReader(u.openStream())); StringBuilder tbuf = new StringBuilder(); String line = null; while ((line = br.readLine()) != null) { tbuf.append(line).append("\n"); } br.close(); text = tbuf.toString(); } List<ConceptAnnotation> annotations = new ArrayList<ConceptAnnotation>(); long startTs = System.currentTimeMillis(); JCas jcas = UimaUtils.runAE(conceptMappingAE, text, inputFormat, null); FSIndex fsindex = jcas.getAnnotationIndex(ConceptAnnotation.type); for (Iterator<ConceptAnnotation> it = fsindex.iterator(); it.hasNext(); ) { ConceptAnnotation annotation = it.next(); annotations.add(annotation); } CollectionUtils.filter(annotations, new StyGroupPredicate(styGroupFilter)); CollectionUtils.filter(annotations, new StyCodePredicate(styCodeFilter)); annotations = filterSubsumedConcepts(q, annotations); if (annotations.size() == 0) { mav.addObject("error", "No concepts found"); } else { mav.addObject("text", text); mav.addObject("annotations", annotations); long endTs = System.currentTimeMillis(); mav.addObject("elapsed", new Long(endTs - startTs)); } setViewName(mav, outputFormat, outputFormatStyle); } } catch (Exception e) { mav.addObject("error", e.getMessage()); setViewName(mav, outputFormat, outputFormatStyle); } return mav; }
/** * Checks if the value of this object is a boolean or numeric value. * * @return <code>true</code> if the value is a boolean or number, otherwise <code>false</code> */ public boolean isBooleanOrNumeric() { return isBooleanValue(value) || NumberUtils.isNumber(value); }
// For example, here is a line from the 5kb chr1 MAPQGE30 raw observed contact matrix // (GM12878_combined/5kb_resolution_intrachromosomal/chr1/MAPQGE30/chr1_5kb.RAWobserved): // 40000000 40100000 59.0 // To normalize this entry using the KR normalization vector, one would divide 59.0 by the 8001st // line ((40000000/5000)+1=8001) and the 8021st line ((40100000/5000)+1=8021) // of GM12878_combined/5kb_resolution_intrachromosomal/chr1/MAPQGE30/chr1_5kb.KRnorm. The 8001st // line of the KR norm file is 1.2988778370674694; // The 8021st line of the KR norm file is 1.6080499717941548. So the corresponding KR normalized // entry for the entry above is 59.0/(1.2988778370674694*1.6080499717941548) // or 28.24776973966101. // If the KR normalization vector file is empty or all NaNs, then the KR algorithm didn’t converge // on that particular matrix (likely due to sparsity of the matrix). private static void processNormalizedInterContactInformation( String fileToRead, String baseName, String normMethod, String chrSmaller, String chrLarger, ArrayList<DesiredChrContact> contactsToCheck, String resolution, double minValue, TextFile outWriter) throws IOException { // ReadIn normalization chr1 TextFile inputNormChr1 = new TextFile( baseName + "\\chr" + chrSmaller + "_" + resolution + "." + normMethod, TextFile.R); ArrayList<String> normFactorSmallerChr = inputNormChr1.readAsArrayList(); inputNormChr1.close(); // System.out.println("Done reading norm factor 1"); // ReadIn normalization chr2 TextFile inputNormChr2 = new TextFile( baseName + "\\chr" + chrLarger + "_" + resolution + "." + normMethod, TextFile.R); ArrayList<String> normFactorLargerChr = inputNormChr2.readAsArrayList(); inputNormChr2.close(); // System.out.println("Done reading norm factor 2"); if (!Gpio.exists(fileToRead + ".sorted")) { umcg.genetica.io.chrContacts.SortInterChrContacts.readNonSortedWriteSorted( fileToRead, fileToRead + ".sorted"); } int numberToBeMatched = 0; LineIterator it = FileUtils.lineIterator(new File(fileToRead + ".sorted"), "UTF-8"); try { while (it.hasNext()) { String[] parts = StringUtils.split(it.nextLine(), '\t'); int posChr1 = org.apache.commons.lang.math.NumberUtils.createInteger(parts[0]); int posChr2 = org.apache.commons.lang.math.NumberUtils.createInteger(parts[1]); while (numberToBeMatched < contactsToCheck.size()) { if (posChr1 < contactsToCheck.get(numberToBeMatched).getChrLocationSmaller()) { break; } else if (posChr1 == contactsToCheck.get(numberToBeMatched).getChrLocationSmaller()) { if (posChr2 < contactsToCheck.get(numberToBeMatched).getChrLocationLarger()) { break; } if (posChr2 == contactsToCheck.get(numberToBeMatched).getChrLocationLarger()) { if (((posChr1 / getNumericResolution(resolution)) + 1) > normFactorSmallerChr.size()) { System.out.println(baseName); System.out.println("Smaller"); System.out.println((posChr1 / getNumericResolution(resolution) + 1)); System.out.println(normFactorSmallerChr.size()); System.exit(-1); } if (((posChr2 / getNumericResolution(resolution)) + 1) > normFactorLargerChr.size()) { System.out.println(baseName); System.out.println("Larger"); System.out.println((posChr2 / getNumericResolution(resolution)) + 1); System.out.println(normFactorLargerChr.size()); System.exit(-1); } String factor1Base = normFactorSmallerChr.get((posChr1 / getNumericResolution(resolution)) + 1); String factor2Base = normFactorLargerChr.get((posChr2 / getNumericResolution(resolution)) + 1); double factor1 = 1.0; double factor2 = 1.0; if (NumberUtils.isNumber(factor1Base) && NumberUtils.isNumber(factor2Base)) { factor1 = Double.parseDouble(factor1Base); factor2 = Double.parseDouble(factor2Base); } else if (NumberUtils.isNumber(factor1Base)) { factor1 = Double.parseDouble(factor1Base); System.out.println("Error in files."); System.out.println("Base 2 is reset to 1"); } else if (NumberUtils.isNumber(factor2Base)) { factor2 = Double.parseDouble(factor2Base); System.out.println("Error in files."); System.out.println("Base 1 is reset to 1"); } double contact = org.apache.commons.lang.math.NumberUtils.createDouble(parts[2]) / (factor1 * factor2); if (contact >= minValue) { outWriter.writeln( contactsToCheck.get(numberToBeMatched).getSnpName() + "\t" + contactsToCheck.get(numberToBeMatched).getProbeName() + "\t" + posChr1 + "\t" + posChr2 + "\tContact\t" + contact + "\t" + org.apache.commons.lang.math.NumberUtils.createDouble(parts[2])); numberToBeMatched++; } else { outWriter.writeln( contactsToCheck.get(numberToBeMatched).getSnpName() + "\t" + contactsToCheck.get(numberToBeMatched).getProbeName() + "\t" + posChr1 + "\t" + posChr2 + "\t-\t-\t-"); numberToBeMatched++; } } else if (posChr2 > contactsToCheck.get(numberToBeMatched).getChrLocationLarger()) { outWriter.writeln( contactsToCheck.get(numberToBeMatched).getSnpName() + "\t" + contactsToCheck.get(numberToBeMatched).getProbeName() + "\t" + posChr1 + "\t" + posChr2 + "\t-\t-\t-"); numberToBeMatched++; } } else if (posChr1 > contactsToCheck.get(numberToBeMatched).getChrLocationSmaller()) { outWriter.writeln( contactsToCheck.get(numberToBeMatched).getSnpName() + "\t" + contactsToCheck.get(numberToBeMatched).getProbeName() + "\t" + posChr1 + "\t" + posChr2 + "\t-\t-\t-"); numberToBeMatched++; } } } } finally { LineIterator.closeQuietly(it); } }
/** * @param requestVO * @return */ @Transactional(propagation = Propagation.REQUIRED) public int saveFindings(FindingsRequestVO requestVO) { Project project = getEntityManager().find(Project.class, Long.parseLong(requestVO.getProjectId())); // FINDINGS List<Finding> findingsList = new ArrayList<Finding>(); for (FindingsVO findingsVO : CollectionUtil.safe(requestVO.getFindingsList())) { Finding findings = null; if (DataValidator.isNotEmpty(findingsVO.getFindingsCategoryId()) || DataValidator.isNotEmpty(findingsVO.getFindingsText())) { if (!DataValidator.isNewRecord(findingsVO.getFindingsId())) { findings = getEntityManager().find(Finding.class, Long.parseLong(findingsVO.getFindingsId())); } else { findings = new Finding(); if (findingsVO.getFindingsCategoryId() != null) { if (NumberUtils.isNumber(findingsVO.getFindingsCategoryId())) { findings.setFindingsCategory( getEntityManager() .find( FindingsCategory.class, Long.parseLong(findingsVO.getFindingsCategoryId()))); } else { FindingsCategory findingsCategory = new FindingsCategory(); findingsCategory.setFindingsCategoryDesc(findingsVO.getFindingsCategoryId()); findingsCategory.setFindingsCategoryName(findingsVO.getFindingsCategoryId()); getEntityManager().persist(findingsCategory); findings.setFindingsCategory(findingsCategory); } } findings.setFindingsText( (findingsVO.getFindingsText() == null) ? RoadmapConstants.EMPTY_STRING : findingsVO.getFindingsText().replace("&", "&")); findings.setProject(project); getEntityManager().persist(findings); } findings.setFindingsText( (findingsVO.getFindingsText() == null) ? RoadmapConstants.EMPTY_STRING : findingsVO.getFindingsText().replace("&", "&")); findings.setImportance(findingsVO.getImportance()); if (!DataValidator.isNewRecord(findingsVO.getFindingsCategoryId()) && NumberUtils.isNumber(findingsVO.getFindingsCategoryId())) { FindingsCategory findingsCategory = getEntityManager() .find(FindingsCategory.class, Long.parseLong(findingsVO.getFindingsCategoryId())); findings.setFindingsCategory(findingsCategory); } findingsList.add(findings); } } // OPPORTUNITY List<Opportunity> opportunityList = new ArrayList<Opportunity>(); for (OpportunityVO opportunityVO : CollectionUtil.safe(requestVO.getOpportunityList())) { Opportunity opportunity = null; if (DataValidator.isNotEmpty(opportunityVO.getOpportunityCategoryId()) || DataValidator.isNotEmpty(opportunityVO.getOpportunityText())) { if (!DataValidator.isNewRecord(opportunityVO.getOpportunityId())) { opportunity = getEntityManager() .find(Opportunity.class, Long.parseLong(opportunityVO.getOpportunityId())); } else { opportunity = new Opportunity(); if (opportunityVO.getOpportunityCategoryId() != null) { if (NumberUtils.isNumber(opportunityVO.getOpportunityCategoryId()) && isValidId(opportunityVO.getOpportunityCategoryId())) { opportunity.setOpportunityCategory( getEntityManager() .find( OpportunityCategory.class, Long.parseLong(opportunityVO.getOpportunityCategoryId()))); } else { OpportunityCategory opportunityCategory = new OpportunityCategory(); opportunityCategory.setOpportunityCategoryDesc( opportunityVO.getOpportunityCategoryId()); opportunityCategory.setOpportunityCategoryName( opportunityVO.getOpportunityCategoryId()); getEntityManager().persist(opportunityCategory); getEntityManager().flush(); opportunity.setOpportunityCategory(opportunityCategory); } } opportunity.setOpportunityText(opportunityVO.getOpportunityText()); opportunity.setProject(project); getEntityManager().persist(opportunity); } opportunity.setOpportunityText(opportunityVO.getOpportunityText()); if (!DataValidator.isNewRecord(opportunityVO.getOpportunityCategoryId()) && NumberUtils.isNumber(opportunityVO.getOpportunityCategoryId()) && isValidId(opportunityVO.getOpportunityCategoryId())) { OpportunityCategory opportunityCategory = getEntityManager() .find( OpportunityCategory.class, Long.parseLong(opportunityVO.getOpportunityCategoryId())); opportunity.setOpportunityCategory(opportunityCategory); } opportunityList.add(opportunity); } } List<Finding> projectFindingsListForRemoval = (List<Finding>) CollectionUtils.removeAll(CollectionUtil.safe(project.getFindings()), findingsList); for (Finding findingForRemoval : projectFindingsListForRemoval) { getEntityManager().remove(findingForRemoval); getEntityManager().flush(); project.removeFinding(findingForRemoval); } List<Opportunity> projectOpportunityListForRemoval = (List<Opportunity>) CollectionUtils.removeAll( CollectionUtil.safe(project.getOpportunities()), opportunityList); for (Opportunity opportunityForRemoval : projectOpportunityListForRemoval) { getEntityManager().remove(opportunityForRemoval); getEntityManager().flush(); project.removeOpportunity(opportunityForRemoval); } return RoadmapConstants.SAVE_SUCCESS; }
private static boolean validNumber(String numberStr) { return numberStr != null && NumberUtils.isNumber(numberStr); }
public CParser(String sql, String outputFileName, int speed, int delay) { CSQL csql = new CSQL(); csql.parser(sql); if (!csql.getTable().equals("arduino")) { System.err.println("Unknown table: " + csql.getTable()); System.exit(0); } int digitalPins[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; int analogPins[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; String columns[] = { "din1", "din2", "din3", "din4", "din5", "din6", "din7", "din8", "din9", "din10", "din11", "din12", "din13", "din14", "din15", "din16", "din17", "din18", "din19", "din20", "ain1", "ain2", "ain3", "ain4", "ain5", "ain6", "ain7", "ain8", "ain9", "ain10", "ain11", "ain12", "ain13", "ain14", "ain15", "ain16", "ain17", "ain18", "ain19", "ain20" }; for (String field : csql.getFields()) { // カラム名が存在するか確認する if (!Arrays.asList(columns).contains(field)) { System.err.println("Unknown column: " + field); System.exit(0); } int pinIndex = Integer.valueOf(field.substring(3)); if (field.startsWith("din")) { digitalPins[pinIndex] = 1; } else { analogPins[pinIndex] = 1; } } for (Expression expression : csql.getConditions()) { // WHERE句のカラム名が存在するか確認する String left = ""; String right = ""; if (expression instanceof EqualsTo) { left = ((EqualsTo) expression).getLeftExpression().toString(); right = ((EqualsTo) expression).getRightExpression().toString(); } else if (expression instanceof GreaterThan) { left = ((GreaterThan) expression).getLeftExpression().toString(); right = ((GreaterThan) expression).getRightExpression().toString(); } else if (expression instanceof GreaterThanEquals) { left = ((GreaterThanEquals) expression).getLeftExpression().toString(); right = ((GreaterThanEquals) expression).getRightExpression().toString(); } else if (expression instanceof MinorThan) { left = ((MinorThan) expression).getLeftExpression().toString(); right = ((MinorThan) expression).getRightExpression().toString(); } else if (expression instanceof MinorThanEquals) { left = ((MinorThanEquals) expression).getLeftExpression().toString(); right = ((MinorThanEquals) expression).getRightExpression().toString(); } else if (expression instanceof NotEqualsTo) { left = ((NotEqualsTo) expression).getLeftExpression().toString(); right = ((NotEqualsTo) expression).getRightExpression().toString(); } if (!Arrays.asList(columns).contains(left)) { System.err.println("Unknown column: " + left); System.exit(0); } int pinIndex = Integer.valueOf(left.substring(3)); if (left.startsWith("din")) { digitalPins[pinIndex] = 1; } else { analogPins[pinIndex] = 1; } if (!NumberUtils.isNumber(right)) { System.err.println("missing value for " + right); System.exit(0); } } StringBuffer condition = new StringBuffer(" "); for (String token : csql.getWhere().split(" ")) { // WHERE句のSQL文法をC言語文法に書き換える if (token.equals("=")) { condition.append("== "); } else if (token.equals("AND")) { condition.append("&& "); } else if (token.equals("OR")) { condition.append("|| "); } else { condition.append(token + " "); } } try { File file = new File(outputFileName); PrintWriter printWriter = new PrintWriter(new BufferedWriter(new FileWriter(file))); // setup printWriter.println("void setup() {"); printWriter.println(String.format(" Serial.begin(%d);", speed)); for (int i = 0; i < digitalPins.length; i++) { if (digitalPins[i] == 1) printWriter.println(String.format(" pinMode(%d, INPUT);", i)); } printWriter.println("}"); printWriter.println(""); // loop printWriter.println("void loop() {"); for (int i = 0; i < digitalPins.length; i++) { if (digitalPins[i] == 1) printWriter.println(String.format(" int din%d = digitalRead(%d);", i, i)); } for (int i = 0; i < analogPins.length; i++) { if (analogPins[i] == 1) printWriter.println(String.format(" int ain%d = analogRead(%d);", i, i)); } // if printWriter.println(String.format(" if(%s) {", condition.toString())); printWriter.println(" Serial.print(\"[ \");"); for (String field : csql.getFields()) { printWriter.println(String.format(" Serial.print(%s);", field)); printWriter.println(" Serial.print(\" \");"); } printWriter.println(" Serial.print(\"]\");"); printWriter.println(" }"); printWriter.println(String.format(" delay(%d);", delay)); printWriter.println("}"); printWriter.close(); } catch (IOException e) { e.printStackTrace(); } }