List of usage examples for java.lang StringBuilder insert
@Override public StringBuilder insert(int offset, double d)
From source file:org.sakaiproject.reports.logic.impl.ReportsManagerImpl.java
/** * {@inheritDoc}/*from www .java 2s. com*/ */ public String replaceSystemValues(String inString) { UserDirectoryService userDirectoryService = org.sakaiproject.user.cover.UserDirectoryService.getInstance(); Session s = SessionManager.getCurrentSession(); User user = userDirectoryService.getCurrentUser(); String worksiteId = ToolManager.getCurrentPlacement().getContext(); // current site id Site site = getCurrentWorksite(worksiteId); Map map = new HashMap(); map.put("{userid}", Validator.escapeSql(s.getUserId())); //system values are stored in session if report is scheduled through quartz if (s.getAttribute("toolid") == null) { UserDirectoryService dirServ = org.sakaiproject.user.cover.UserDirectoryService.getInstance(); User u = dirServ.getCurrentUser(); map.put("{userdisplayname}", Validator.escapeSql(u.getDisplayName())); map.put("{useremail}", Validator.escapeSql(u.getEmail())); map.put("{userfirstname}", Validator.escapeSql(u.getFirstName())); map.put("{userlastname}", Validator.escapeSql(u.getLastName())); map.put("{worksiteid}", Validator.escapeSql(ToolManager.getCurrentPlacement().getContext())); map.put("{toolid}", Validator.escapeSql(ToolManager.getCurrentPlacement().getId())); } else { map.put("{userdisplayname}", Validator.escapeSql((String) s.getAttribute("userdisplayname"))); map.put("{useremail}", Validator.escapeSql((String) s.getAttribute("useremail"))); map.put("{userfirstname}", Validator.escapeSql((String) s.getAttribute("userfirstname"))); map.put("{userlastname}", Validator.escapeSql((String) s.getAttribute("userlastname"))); map.put("{worksiteid}", Validator.escapeSql((String) s.getAttribute("worksiteid"))); map.put("{toolid}", Validator.escapeSql((String) s.getAttribute("toolid"))); } Iterator iter = map.keySet().iterator(); StringBuilder str = new StringBuilder(inString); // loop through all the parameters and find in query for replacement while (iter.hasNext()) { // get the parameter and associated parameter definition String key = (String) iter.next(); int i = str.indexOf(key); // Loop until no instances exist while (i != -1) { // replace the parameter with the value str.delete(i, i + key.length()); str.insert(i, (String) map.get(key)); // look for a second instance i = str.indexOf(key); } } String string = str.toString(); // create a list of the supported bean objects whose values can be replaced Map beans = new HashMap(); beans.put("{session.attribute.", s); beans.put("{site.property.", site); beans.put("{user.property.", user); string = replaceSystemValues(string, beans); beans = new HashMap(); beans.put("{session.", s); beans.put("{site.", site); beans.put("{user.", user); string = replaceSystemValues(string, beans); return string; }
From source file:com.heliosdecompiler.helios.tasks.DecompileTask.java
@Override public void run() { LoadedFile loadedFile = Helios.getLoadedFile(fileName); byte[] classFile = loadedFile.getAllData().get(className); PreDecompileEvent event = new PreDecompileEvent(transformer, classFile); Events.callEvent(event);// w w w .j av a 2 s . c o m classFile = event.getBytes(); StringBuilder output = new StringBuilder(); if (transformer instanceof Decompiler) { if (((Decompiler) transformer).decompile(loadedFile.getClassNode(className), classFile, output)) { CompilationUnit cu = null; try { cu = JavaParser.parse( new ByteArrayInputStream(output.toString().getBytes(StandardCharsets.UTF_8)), "UTF-8", false); this.compilationUnit = cu; } catch (ParseException | TokenMgrError e) { StringBuilder message = new StringBuilder("/*\n"); Consumer<String> write = msg -> { message.append(" * ").append(msg).append("\n"); }; write.accept("Error: Helios could not parse this file. Hyperlinks will not be inserted"); write.accept("The error has been inserted at the bottom of the output"); if (transformer instanceof CFRDecompiler) { write.accept(""); write.accept("I noticed you are using CFR"); write.accept( "Try nagging the author to output valid Java even if the code is undecompilable"); } message.append(" */\n\n"); output.insert(0, message.toString()); message.setLength(0); message.append("\n/*\n"); StringBuilder exceptionToString = new StringBuilder(); e.printStackTrace(new PrintWriter(new StringBuilderWriter(exceptionToString))); String[] lines = exceptionToString.toString().split("\r*\n"); for (String line : lines) { write.accept(line); } message.append(" */"); output.append(message.toString()); } finally { if (cu != null) { String result = output.toString(); result = result.replaceAll("\r*\n", "\n"); output = new StringBuilder(result); try { handle(cu, output.toString()); } catch (Throwable t) { textArea.links.clear(); StringBuilder message = new StringBuilder("/*\n"); Consumer<String> write = msg -> { message.append(" * ").append(msg).append("\n"); }; write.accept( "Error: Helios could not parse this file. Hyperlinks will not be inserted"); write.accept("The error has been inserted at the bottom of the output"); message.append(" */\n\n"); output.insert(0, message.toString()); message.setLength(0); message.append("\n/*\n"); StringBuilder exceptionToString = new StringBuilder(); t.printStackTrace(new PrintWriter(new StringBuilderWriter(exceptionToString))); String[] lines = exceptionToString.toString().split("\r*\n"); for (String line : lines) { write.accept(line); } message.append(" */"); output.append(message.toString()); t.printStackTrace(); } } } textArea.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_JAVA); textArea.setCodeFoldingEnabled(true); } textArea.setText(output.toString()); if (jumpTo != null) { Events.callEvent(new SearchRequest(jumpTo, false, false, false, true)); } } else if (transformer instanceof Disassembler) { if (((Disassembler) transformer).disassembleClassNode(loadedFile.getClassNode(className), classFile, output)) { textArea.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_JAVA); textArea.setCodeFoldingEnabled(true); } textArea.setText(output.toString()); } }
From source file:com.evolveum.polygon.scim.StandardScimHandlingStrategy.java
@Override public void query(Filter query, StringBuilder queryUriSnippet, String resourceEndPoint, ResultsHandler resultHandler, ScimConnectorConfiguration conf) { LOGGER.info("Processing query"); Boolean isCAVGroupQuery = false; // query is a ContainsAllValues // filter query for the group // endpoint?/*from w ww. j a v a 2 s .c om*/ Boolean valueIsUid = false; ServiceAccessManager accessManager = new ServiceAccessManager(conf); Header authHeader = accessManager.getAuthHeader(); String scimBaseUri = accessManager.getBaseUri(); if (authHeader == null || scimBaseUri.isEmpty()) { throw new ConnectorException( "The data needed for authorization of request to the provider was not found."); } String q; String[] baseUrlParts = scimBaseUri.split("\\."); String providerName = baseUrlParts[1]; if (query != null) { if (query instanceof EqualsFilter) { Attribute filterAttr = ((EqualsFilter) query).getAttribute(); if (filterAttr instanceof Uid) { valueIsUid = true; isCAVGroupQuery = checkFilter(query, resourceEndPoint); if (!isCAVGroupQuery) { q = ((Uid) filterAttr).getUidValue(); } else { q = ((Uid) filterAttr).getUidValue(); resourceEndPoint = "Users"; } } else { isCAVGroupQuery = checkFilter(query, resourceEndPoint); if (!isCAVGroupQuery) { LOGGER.info("Attribute not instance of UID"); q = qIsFilter(query, queryUriSnippet, providerName, resourceEndPoint); } else { q = (String) filterAttr.getValue().get(0); resourceEndPoint = "Users"; } } } else { isCAVGroupQuery = checkFilter(query, resourceEndPoint); if (!isCAVGroupQuery) { q = qIsFilter(query, queryUriSnippet, providerName, resourceEndPoint); } else { Attribute filterAttr = ((AttributeFilter) query).getAttribute(); q = (String) filterAttr.getValue().get(0); resourceEndPoint = "Users"; } } } else { LOGGER.info("No filter was defined, query will return all the resource values"); q = queryUriSnippet.toString(); } HttpClient httpClient = initHttpClient(conf); String uri = new StringBuilder(scimBaseUri).append(SLASH).append(resourceEndPoint).append(SLASH).append(q) .toString(); LOGGER.info("Query url: {0}", uri); HttpGet httpGet = buildHttpGet(uri, authHeader); String responseString = null; try (CloseableHttpResponse response = (CloseableHttpResponse) httpClient.execute(httpGet)) { int statusCode = response.getStatusLine().getStatusCode(); HttpEntity entity = response.getEntity(); if (entity != null) { responseString = EntityUtils.toString(entity); } else { responseString = ""; } LOGGER.info("Status code: {0}", statusCode); if (statusCode == 200) { if (!responseString.isEmpty()) { try { JSONObject jsonObject = new JSONObject(responseString); // LOGGER.info("Json object returned from service provider: {0}", jsonObject.toString(1)); try { if (valueIsUid) { ConnectorObject connectorObject = buildConnectorObject(jsonObject, resourceEndPoint); resultHandler.handle(connectorObject); } else { if (isCAVGroupQuery) { handleCAVGroupQuery(jsonObject, GROUPS, resultHandler, scimBaseUri, authHeader, conf); } else if (jsonObject.has(RESOURCES)) { int amountOfResources = jsonObject.getJSONArray(RESOURCES).length(); int totalResults = 0; int startIndex = 0; int itemsPerPage = 0; if (jsonObject.has(STARTINDEX) && jsonObject.has(TOTALRESULTS) && jsonObject.has(ITEMSPERPAGE)) { totalResults = (int) jsonObject.get(TOTALRESULTS); startIndex = (int) jsonObject.get(STARTINDEX); itemsPerPage = (int) jsonObject.get(ITEMSPERPAGE); } for (int i = 0; i < amountOfResources; i++) { JSONObject minResourceJson = new JSONObject(); minResourceJson = jsonObject.getJSONArray(RESOURCES).getJSONObject(i); if (minResourceJson.has(ID) && minResourceJson.getString(ID) != null) { if (minResourceJson.has(USERNAME)) { ConnectorObject connectorObject = buildConnectorObject( minResourceJson, resourceEndPoint); resultHandler.handle(connectorObject); } else if (!USERS.equals(resourceEndPoint)) { if (minResourceJson.has(DISPLAYNAME)) { ConnectorObject connectorObject = buildConnectorObject( minResourceJson, resourceEndPoint); resultHandler.handle(connectorObject); } } else if (minResourceJson.has(META)) { String resourceUri = minResourceJson.getJSONObject(META) .getString("location").toString(); HttpGet httpGetR = buildHttpGet(resourceUri, authHeader); try (CloseableHttpResponse resourceResponse = (CloseableHttpResponse) httpClient .execute(httpGetR)) { statusCode = resourceResponse.getStatusLine().getStatusCode(); responseString = EntityUtils .toString(resourceResponse.getEntity()); if (statusCode == 200) { JSONObject fullResourcejson = new JSONObject( responseString); // LOGGER.info( // "The {0}. resource // jsonobject which was // returned by the // service // provider: {1}", // i + 1, // fullResourcejson); ConnectorObject connectorObject = buildConnectorObject( fullResourcejson, resourceEndPoint); resultHandler.handle(connectorObject); } else { ErrorHandler.onNoSuccess(responseString, statusCode, resourceUri); } } } } else { LOGGER.error("No uid present in fetched object: {0}", minResourceJson); throw new ConnectorException( "No uid present in fetchet object while processing queuery result"); } } if (resultHandler instanceof SearchResultsHandler) { Boolean allResultsReturned = false; int remainingResult = totalResults - (startIndex - 1) - itemsPerPage; if (remainingResult <= 0) { remainingResult = 0; allResultsReturned = true; } // LOGGER.info("The number of remaining // results: {0}", remainingResult); SearchResult searchResult = new SearchResult(DEFAULT, remainingResult, allResultsReturned); ((SearchResultsHandler) resultHandler).handleResult(searchResult); } } else { LOGGER.error("Resource object not present in provider response to the query"); throw new ConnectorException( "No uid present in fetchet object while processing queuery result"); } } } catch (Exception e) { LOGGER.error( "Builder error. Error while building connId object. The exception message: {0}", e.getLocalizedMessage()); LOGGER.info( "Builder error. Error while building connId object. The excetion message: {0}", e); throw new ConnectorException("Builder error. Error while building connId object.", e); } } catch (JSONException jsonException) { if (q == null) { q = "the full resource representation"; } LOGGER.error( "An exception has occurred while setting the variable \"jsonObject\". Occurrence while processing the http response to the queuey request for: {1}, exception message: {0}", jsonException.getLocalizedMessage(), q); LOGGER.info( "An exception has occurred while setting the variable \"jsonObject\". Occurrence while processing the http response to the queuey request for: {1}, exception message: {0}", jsonException, q); throw new ConnectorException( "An exception has occurred while setting the variable \"jsonObject\".", jsonException); } } else { LOGGER.warn("Service provider response is empty, responce returned on query: {0}", q); } } else if (statusCode == 401) { handleInvalidStatus("while querying for resources. ", responseString, "retrieving an object", statusCode); } else if (valueIsUid) { LOGGER.info("Abouth to throw an exception, the resource: {0} was not found.", q); ErrorHandler.onNoSuccess(responseString, statusCode, uri); StringBuilder errorBuilder = new StringBuilder("The resource with the uid: ").append(q) .append(" was not found."); throw new UnknownUidException(errorBuilder.toString()); } else if (statusCode == 404) { String error = ErrorHandler.onNoSuccess(responseString, statusCode, uri); LOGGER.warn("Resource not found: {0}", error); } else { ErrorHandler.onNoSuccess(responseString, statusCode, uri); } } catch (IOException e) { if (q == null) { q = "the full resource representation"; } StringBuilder errorBuilder = new StringBuilder( "An error occurred while processing the query http response for "); errorBuilder.append(q); if ((e instanceof SocketTimeoutException || e instanceof NoRouteToHostException)) { errorBuilder.insert(0, "The connection timed out while closing the http connection. "); throw new OperationTimeoutException(errorBuilder.toString(), e); } else { LOGGER.error( "An error occurred while processing the queuery http response. Occurrence while processing the http response to the queuey request for: {1}, exception message: {0}", e.getLocalizedMessage(), q); LOGGER.info( "An error occurred while processing the queuery http response. Occurrence while processing the http response to the queuey request for: {1}, exception message: {0}", e, q); throw new ConnectorIOException(errorBuilder.toString(), e); } } }
From source file:de.schildbach.game.chess.ChessRules.java
@Override protected String[] basicFormatGameArray(Game game, Locale locale) { int size = game.getSize(); String[] array = new String[size]; ChessBoardGeometry geometry = (ChessBoardGeometry) getBoardGeometry(); ChessLikePosition position = (ChessLikePosition) game.getInitialPosition().clone(); Board board = position.getBoard();// w w w .j a va 2 s . c o m Board initialBoard = game.getInitialPosition().getBoard(); PieceSet pieceSet = getPieceSet(); StringBuilder notation = new StringBuilder(); for (int index = 0; index < size; index++) { ChessMove move = (ChessMove) game.getMove(index); Coordinate source = move.getSource(); Coordinate target = move.getTarget(); Piece piece = board.getPiece(source); String sourceNotation = source.getNotation(); char sourceFile = sourceNotation.charAt(0); char sourceRank = sourceNotation.charAt(1); notation.setLength(0); if (looksLikeCastlingMove(move, board)) { if (geometry.isKingSide(source, target)) notation.append("O-O"); else notation.append("O-O-O"); } else { Collection<? extends ChessLikeMove> potentialMoves = allowedMoves(position, initialBoard); // narrow by target for (Iterator<? extends ChessLikeMove> iAllowed = potentialMoves.iterator(); iAllowed.hasNext();) { if (!iAllowed.next().getTarget().equals(target)) iAllowed.remove(); } notation.append(target.getNotation()); boolean pawn = piece instanceof Pawn || piece instanceof BerolinaPawn; // narrow by capture boolean capture = looksLikePlainCapture(move, board) || looksLikeEnPassantCapture(move, board); if (capture) { for (Iterator<? extends ChessLikeMove> iAllowed = potentialMoves.iterator(); iAllowed .hasNext();) { if (!looksLikeCapture(iAllowed.next(), board)) iAllowed.remove(); } notation.insert(0, 'x'); if (pawn) { // narrow to source file for (Iterator<? extends ChessLikeMove> iAllowed = potentialMoves.iterator(); iAllowed .hasNext();) { if (!geometry.sameFile(iAllowed.next().getSource(), source)) iAllowed.remove(); } notation.insert(0, sourceFile); } } // narrow by piece for (Iterator<? extends ChessLikeMove> iAllowed = potentialMoves.iterator(); iAllowed.hasNext();) { if (!board.getPiece(iAllowed.next().getSource()).equals(piece)) iAllowed.remove(); } // narrow by promotion for (Iterator<? extends ChessLikeMove> iAllowed = potentialMoves.iterator(); iAllowed.hasNext();) { if (!ObjectUtils.equals(((ChessMove) iAllowed.next()).getPromotionPiece(), move.getPromotionPiece())) iAllowed.remove(); } if (move.getPromotionPiece() != null) notation.append("=" + pieceSet.getCharRepresentation(move.getPromotionPiece(), locale)); if (potentialMoves.size() > 1) { boolean sameRank = false; boolean sameFile = false; for (ChessLikeMove potentialMove : potentialMoves) { Coordinate potentialSource = potentialMove.getSource(); if (!potentialSource.equals(source)) { if (geometry.sameFile(potentialSource, source)) sameFile = true; if (geometry.sameRank(potentialSource, source)) sameRank = true; } } if (sameRank && sameFile) { // narrow to source for (Iterator<? extends ChessLikeMove> iAllowed = potentialMoves.iterator(); iAllowed .hasNext();) { if (!iAllowed.next().getSource().equals(source)) iAllowed.remove(); } notation.insert(0, sourceNotation); } else if (!sameFile) { // narrow to source file for (Iterator<? extends ChessLikeMove> iAllowed = potentialMoves.iterator(); iAllowed .hasNext();) { if (!geometry.sameFile(iAllowed.next().getSource(), source)) iAllowed.remove(); } notation.insert(0, sourceFile); } else { // narrow to source rank for (Iterator<? extends ChessLikeMove> iAllowed = potentialMoves.iterator(); iAllowed .hasNext();) { if (!geometry.sameRank(iAllowed.next().getSource(), source)) iAllowed.remove(); } notation.insert(0, sourceRank); } } // piece character if (!pawn) notation.insert(0, pieceSet.getCharRepresentation(piece.getClass(), locale)); // sanity check if (potentialMoves.size() != 1) throw new IllegalStateException(potentialMoves.toString()); } // execute move List<MicroOperation> ops = disassembleMove(move, position, game.getInitialPosition().getBoard()); doOperations(ops, position); // check CheckState checkState = checkState(position, game.getInitialPosition().getBoard()); if (checkState == CheckState.CHECKMATE) { notation.append("#"); } else if (checkState == CheckState.CHECK) { notation.append("+"); } array[index] = notation.toString(); } return array; }
From source file:com.sciaps.view.SpectrumShotPanel.java
private void doBackgroundRemoval() { final int[] selectedRow = getSelectedRows(); if (selectedRow == null || selectedRow.length == 0) { return;//from w w w .j a va2 s .c om } final double stepSize = baselineSettingPanel_.getStepSize(); final double wlInterval = baselineSettingPanel_.getWaveLengthInterval(); if (stepSize < 0 || wlInterval < 0) { return; } BackgroundTask.runBackgroundTask(new BackgroundTask() { private JDialog mDialog; private JProgressBar mProgress; @Override public void onBefore() { mProgress = new JProgressBar(); mProgress.setIndeterminate(true); mDialog = new JDialog(Constants.MAIN_FRAME); mDialog.setLocationRelativeTo(Constants.MAIN_FRAME); mDialog.setAlwaysOnTop(true); mDialog.setResizable(false); mDialog.setContentPane(mProgress); mDialog.setSize(400, 100); mDialog.setVisible(true); } @Override public void onBackground() { final ArrayList<SpectrumShotItem> tmpList = new ArrayList<SpectrumShotItem>(); final StringBuilder errMsg = new StringBuilder(); for (int rowIndex = 0; rowIndex < selectedRow.length; rowIndex++) { String name = shotListTableModel_.getRow(selectedRow[rowIndex]).getName(); name = name + "R" + stepSize + "_" + wlInterval; if (shotListTableModel_.isNameAlreadyExist(name) == false) { Spectrum spectrum = shotListTableModel_.getRow(selectedRow[rowIndex]).getShot(); RawDataSpectrum rawSpect = doBackgroundRemoval(spectrum); if (rawSpect != null) { SpectrumShotItem shot = new SpectrumShotItem(name); shot.setShot(rawSpect, SpectrumShotItem.BG_REMOVED); tmpList.add(shot); } else { errMsg.append(name).append("\n"); } } else { errMsg.append(name).append("\n"); } } SwingUtilities.invokeLater(new Runnable() { @Override public void run() { for (SpectrumShotItem shot : tmpList) { shotListTableModel_.addRow(0, shot); } if (tmpList.isEmpty() == false) { shotListTableModel_.showSeries(0); } if (errMsg.length() > 0) { errMsg.insert(0, "The following shot(s) already exist, skipped:\n"); showErrorDialog(errMsg.toString()); } } }); } @Override public void onAfter() { mDialog.setVisible(false); } }); }
From source file:com.moviejukebox.MovieJukebox.java
/** * Append the library filename or the date/time to the log filename * * @param logFilename/* w w w .j av a 2 s . c o m*/ */ private static void renameLogFile() { StringBuilder newLogFilename = new StringBuilder(LOG_FILENAME); // Use the base log filename boolean renameFile = Boolean.FALSE; String libraryName = "_Library"; if (PropertiesUtil.getBooleanProperty("mjb.appendLibraryToLogFile", Boolean.FALSE)) { renameFile = Boolean.TRUE; for (final MediaLibraryPath mediaLibrary : mediaLibraryPaths) { if (isValidString(mediaLibrary.getDescription())) { libraryName = "_" + mediaLibrary.getDescription(); libraryName = FileTools.makeSafeFilename(libraryName); break; } } newLogFilename.append(libraryName); } if (PropertiesUtil.getBooleanProperty("mjb.appendDateToLogFile", Boolean.FALSE)) { renameFile = Boolean.TRUE; newLogFilename.append("_") .append(JukeboxStatistics.getTime(JukeboxStatistics.JukeboxTimes.START, "yyyy-MM-dd-kkmmss")); } String logDir = PropertiesUtil.getProperty("mjb.logFileDirectory", ""); if (StringTools.isValidString(logDir)) { renameFile = Boolean.TRUE; // Add the file separator if we need to logDir += logDir.trim().endsWith(File.separator) ? "" : File.separator; newLogFilename.insert(0, logDir); } if (renameFile) { // File (or directory) with old name File oldLogFile = new File(LOG_FILENAME + ".log"); // File with new name File newLogFile = new File(newLogFilename.toString() + ".log"); // Try and create the directory if needed, but don't stop the rename if we can't if (StringTools.isValidString(logDir)) { FileTools.makeDirsForFile(newLogFile); } // First we need to tell Log4J to change the name of the current log file to something else so it unlocks the file System.setProperty("file.name", PropertiesUtil.getProperty("mjb.jukeboxTempDir", "./temp") + File.separator + LOG_FILENAME + ".tmp"); PropertyConfigurator.configure("properties/log4j.properties"); // Rename file (or directory) if (!oldLogFile.renameTo(newLogFile)) { System.err.println("Error renaming log file."); } // Try and rename the ERROR file too. oldLogFile = new File(LOG_FILENAME + ".ERROR.log"); if (oldLogFile.length() > 0) { newLogFile = new File(newLogFilename.toString() + ".ERROR.log"); if (!oldLogFile.renameTo(newLogFile)) { System.err.println("Error renaming ERROR log file."); } } else if (!oldLogFile.delete()) { System.err.println("Error deleting ERROR log file."); } } }
From source file:org.exoplatform.outlook.OutlookServiceImpl.java
/** * Make JCR compatible item name./* w w w . j a v a2 s. co m*/ * * @param name {@link String} * @return {@link String} JCR compatible name of local file */ public static String cleanName(String name) { String str = accentsConverter.transliterate(name.trim()); // the character ? seems to not be changed to d by the transliterate function StringBuilder cleanedStr = new StringBuilder(str.trim()); // delete special character if (cleanedStr.length() == 1) { char c = cleanedStr.charAt(0); if (c == '.' || c == '/' || c == ':' || c == '[' || c == ']' || c == '*' || c == '\'' || c == '"' || c == '|') { // any -> _<NEXNUM OF c> cleanedStr.deleteCharAt(0); cleanedStr.append('_'); cleanedStr.append(Integer.toHexString(c).toUpperCase()); } } else { for (int i = 0; i < cleanedStr.length(); i++) { char c = cleanedStr.charAt(i); if (c == '/' || c == ':' || c == '[' || c == ']' || c == '*' || c == '\'' || c == '"' || c == '|') { cleanedStr.deleteCharAt(i); cleanedStr.insert(i, '_'); } else if (!(Character.isLetterOrDigit(c) || Character.isWhitespace(c) || c == '.' || c == '-' || c == '_')) { cleanedStr.deleteCharAt(i--); } } // XXX finally ensure the name doesn't hava a dot at the end // https://github.com/exo-addons/outlook/issues/5 // https://jira.exoplatform.org/browse/COMMONS-510 int lastCharIndex = cleanedStr.length() - 1; char c = cleanedStr.charAt(lastCharIndex); if (c == '.') { cleanedStr.deleteCharAt(lastCharIndex); } } return cleanedStr.toString().trim(); // finally trim also }
From source file:gdsc.smlm.ij.plugins.TraceMolecules.java
/** * Find the contour that intersects zero on the fractional difference plot. * Find the point on the contour nearest the origin. * //from w ww . j a va 2 s .c o m * @param results */ private boolean findOptimalParameters(List<double[]> results) { // This method only works if there are many results and if the results // cover enough of the search space to go from above zero (i.e. not enough traces) // to below zero (i.e. too many traces) int maxx = tThresholds.length; int maxy = dThresholds.length; // -------- // Find zero crossings using linear interpolation zeroCrossingPoints = new ArrayList<double[]>(); // -------- // Pass across all time points boolean noZeroCrossingAtT0 = false; boolean noZeroCrossingAtTN = false; for (int x = 0; x < maxx; x++) { // Find zero crossings on distance points double[] data = new double[maxy]; for (int y = 0; y < maxy; y++) { int i = y * maxx + x; double[] result = results.get(i); data[y] = result[2]; } double zeroCrossing = findZeroCrossing(data, dThresholds); if (zeroCrossing > 0) zeroCrossingPoints.add(new double[] { tThresholds[x], zeroCrossing }); else if (x == 0) noZeroCrossingAtT0 = true; else if (x == maxx - 1) noZeroCrossingAtTN = true; } // If there were not enough zero crossings then the ranges are wrong if (zeroCrossingPoints.size() < 3) { IJ.log(String.format("Very few zero crossings (%d). Increase the optimisation space", zeroCrossingPoints.size())); return false; } // -------- // Use relative distances to find the zero crossing with the smallest distance from origin // and set this as the optimal parameters // -------- double minD = Double.MAX_VALUE; final double maxTimeThresholdInFrames = timeInFrames(settings.maxTimeThreshold); for (double[] point : zeroCrossingPoints) { double dx = point[0] / maxTimeThresholdInFrames; double dy = point[1] / settings.maxDistanceThreshold; double d = dx * dx + dy * dy; if (d < minD) { minD = d; settings.distanceThreshold = point[1]; settings.timeThreshold = point[0]; } } // -------- // Add more points to make the plotted line look better when showing the plot. // -------- // Pass across all distance points boolean noZeroCrossingAtD0 = false; boolean noZeroCrossingAtDN = false; double[] tThresholdsD = toDouble(tThresholds); for (int y = 0; y < maxy; y++) { // Find zero crossings on time points double[] data = new double[maxx]; for (int x = 0; x < maxx; x++) { int i = y * maxx + x; double[] result = results.get(i); data[x] = result[2]; } double zeroCrossing = findZeroCrossing(data, tThresholdsD); if (zeroCrossing > 0) zeroCrossingPoints.add(new double[] { zeroCrossing, dThresholds[y] }); else if (y == 0) noZeroCrossingAtD0 = true; else if (y == maxy - 1) noZeroCrossingAtDN = true; } sortPoints(); // -------- // Output a message suggesting if the limits should be updated. // -------- StringBuilder sb = new StringBuilder(); boolean reduceTime = false; boolean reduceDistance = false; if (noZeroCrossingAtDN && settings.minTimeThreshold > 1) { sb.append(" * No zero crossing at max distance\n"); reduceTime = true; } if (noZeroCrossingAtTN && settings.minDistanceThreshold > 0) { sb.append(" * No zero crossing at max time\n"); reduceDistance = true; } if (!noZeroCrossingAtD0 && settings.minDistanceThreshold > 0) { sb.append(" * Zero crossing at min distance\n"); reduceDistance = true; } if (!noZeroCrossingAtT0 && settings.minTimeThreshold > 1) { sb.append(" * Zero crossing at min time\n"); reduceTime = true; } if (reduceTime) sb.append(" => Reduce the min time threshold\n"); if (reduceDistance) sb.append(" => Reduce the min distance threshold\n"); if (sb.length() > 0) { sb.insert(0, "\nWarning:\n"); sb.append("\n"); IJ.log(sb.toString()); } // TODO - Fit a function to the zero crossing points. I am not sure what function // is suitable for the asymptotic curve (e.g. 1/x == x^-1), perhaps: // f(x) = a + (bx+c)^n // where // n < 0 // a = Distance asymptote (equivalent to the distance resolution?) // b = Scaling factor // c = Time asymptote //interpolateZeroCrossingPoints(); return true; }
From source file:com.flexive.core.search.genericSQL.GenericSQLDataSelector.java
/** * Builds the source table./*ww w. j a va 2 s . c o m*/ * * @param values the selected values * @return a select statement which builds the source table */ private String buildSourceTable(final SubSelectValues[] values) { // Prepare type filter final String typeFilter = search.getTypeFilter() == null ? "" : " AND " + FILTER_ALIAS + ".TDEF=" + search.getTypeFilter().getId() + " "; final Map<Integer, String> orderByNumbers = new HashMap<Integer, String>(); // order by index --> column select final List<String> columns = new ArrayList<String>(); final boolean noSort = orderByNumbers.isEmpty() && search.getParams().isNoInternalSort(); // create select columns for (String column : INTERNAL_RESULTCOLS) { if ("rownr".equals(column)) { if (supportsCounterAfterOrderBy() || noSort) { columns.add(getCounterStatement(column)); } } else { columns.add(filterProperties(column)); } } columns.add(search.getStorage().concat("t.name", "'[@pk='", filterProperties("id"), "'.'", filterProperties("ver"), "']'") + " AS xpathPref"); // order by starts after the internal selected columns int orderByPos = columns.size() + 1; // create SQL statement final StringBuilder sql = new StringBuilder(); sql.append("select ").append(StringUtils.join(columns, ',')).append(' '); // add order by indices for (SubSelectValues ssv : values) { if (ssv.isSorted()) { for (SubSelectValues.Item item : ssv.getItems()) { if (item.isOrderBy()) { // select item from order by sql.append(",").append(item.getSelect()).append(" AS ").append(item.getAlias()) .append("\n"); // add index for first selected column if (!orderByNumbers.containsKey(ssv.getSortPos())) { orderByNumbers.put(ssv.getSortPos(), orderByPos + " " + (ssv.isSortedAscending() ? "asc" : "desc")); } } else { sql.append(",null AS ").append(item.getAlias()).append('\n'); } orderByPos++; } } } sql.append(("FROM " + search.getCacheTable() + " filter, " + DatabaseConst.TBL_STRUCT_TYPES + " t " + "WHERE search_id=" + search.getSearchId() + " AND " + FILTER_ALIAS + ".tdef=t.id " + typeFilter + " ")); final boolean usePaging = search.getStartIndex() > 0 || search.getFetchRows() < Integer.MAX_VALUE; if (noSort) { if (usePaging) { LOG.warn("Paging is disabled because noInternalSort was specified"); } } else { if (orderByNumbers.size() == 0) { // No order by specified = order by id and version int idCol = supportsCounterAfterOrderBy() ? 2 : 1; orderByNumbers.put(1, idCol + " asc"); orderByNumbers.put(2, (idCol + 1) + " asc"); } sql.append("ORDER BY "); // insert order by columns in the order they were defined in the FxSQL query for (Integer index : new TreeSet<Integer>(orderByNumbers.keySet())) { sql.append(orderByNumbers.get(index)).append(','); } sql.setCharAt(sql.length() - 1, ' '); // replace last separator if (!supportsCounterAfterOrderBy()) { // insert outer SELECT sql.insert(0, "SELECT " + getCounterStatement("rownr") + ", x.* FROM ("); sql.append(") x "); } // Evaluate the order by, then limit the result by the desired range if needed if (usePaging) { return "SELECT * FROM (" + sql + ") tmp " + search.getStorage().getLimitOffsetVar("rownr", false, search.getFetchRows(), search.getStartIndex()); } } return sql.toString(); }