List of usage examples for java.text NumberFormat getPercentInstance
public static final NumberFormat getPercentInstance()
From source file:org.apache.rya.indexing.smarturi.duplication.conf.DuplicateDataConfig.java
private static Tolerance parseTolerance(final String key, final XMLConfiguration xmlConfig) throws ConfigurationException { final String type = xmlConfig.getString(key + ".type", null); final ToleranceType toleranceType = ToleranceType.getToleranceTypeByName(type); Double doubleValue = null;//w w w . java 2s. c om if (toleranceType != null) { switch (toleranceType) { case PERCENTAGE: final String value = xmlConfig.getString(key + ".value", null); if (value != null && value.contains("%")) { try { final Number number = NumberFormat.getPercentInstance().parse(value); doubleValue = number.doubleValue(); } catch (final ParseException e) { throw new ConfigurationException(e); } } else { doubleValue = xmlConfig.getDouble(key + ".value", null); } if (doubleValue != null) { if (doubleValue < 0) { throw new ConfigurationException("The " + toleranceType + " tolerance type for \"" + key + "\" must be a positive value. Found this value: " + doubleValue); } if (doubleValue > 1) { throw new ConfigurationException("The " + toleranceType + " tolerance type for \"" + key + "\" can NOT be greater than 100%. Found this value: " + doubleValue); } } break; case DIFFERENCE: doubleValue = xmlConfig.getDouble(key + ".value", null); if (doubleValue != null && doubleValue < 0) { throw new ConfigurationException("The " + toleranceType + " tolerance type for \"" + key + "\" must be a positive value. Found this value: " + doubleValue); } break; default: throw new ConfigurationException( "Unknown Tolerance Type specified in config for <" + type + ">: " + toleranceType); } if (doubleValue != null) { return new Tolerance(doubleValue, toleranceType); } } return null; }
From source file:edu.ucla.stat.SOCR.chart.demo.PieChartDemo4.java
protected JFreeChart createChart(PieDataset dataset) { // create the chart... JFreeChart chart = ChartFactory.createPieChart(chartTitle, // chart title dataset, // dataset !legendPanelOn, // include legend true, false);//w ww . ja v a 2 s . com // set the background color for the chart... chart.setBackgroundPaint(new Color(222, 222, 255)); PiePlot plot = (PiePlot) chart.getPlot(); plot.setBackgroundPaint(Color.white); plot.setCircular(true); for (int i = 0; i < pulloutFlag.length; i++) { //System.out.println("\""+pulloutFlag[i]+"\""); if (isPullout(i)) { Comparable key = dataset.getKey(i); plot.setExplodePercent(key, 0.30); } } plot.setLabelGenerator(new StandardPieSectionLabelGenerator("{0} = {2}", NumberFormat.getNumberInstance(), NumberFormat.getPercentInstance())); plot.setNoDataMessage("No data available"); if (rotateOn) { Rotator rotator = new Rotator(plot); rotator.start(); } setCategorySummary(dataset); return chart; }
From source file:org.pau.assetmanager.viewmodel.chart.PrepareChart.java
public static void prepareJFreeBarChartForStocks(JFreeChart jfchart, CategoryDataset categoryModel) { CategoryPlot categoryPlot = ((CategoryPlot) jfchart.getPlot()); categoryPlot.getRangeAxis().resizeRange(1.2); categoryPlot.setBackgroundPaint(Color.WHITE); categoryPlot.setDomainGridlinePaint(Color.WHITE); categoryPlot.setRangeMinorGridlinePaint(Color.WHITE); categoryPlot.setRangeGridlinePaint(Color.BLACK); BarRenderer renderer = (BarRenderer) categoryPlot.getRenderer(); renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator()); renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator("{2} {1} ", NumberFomatter.PERCENTAGE_FORMATTER, NumberFormat.getPercentInstance())); renderer.setBaseItemLabelsVisible(true); renderer.setBaseItemLabelFont(new Font("Serif", Font.PLAIN, 12)); renderer.setItemLabelAnchorOffset(15); renderer.setDrawBarOutline(false);// w w w . j a va2 s. c o m renderer.setShadowVisible(false); renderer.setItemMargin(.1); renderer.setBarPainter(new StandardBarPainter()); }
From source file:org.zilverline.core.Result.java
/** * DOCUMENT ME!/* w ww. j a va 2 s . c o m*/ * * @param theScore float sets the score, and set scoreString to the String representation of the score as a percentage, e.g. * 13%. */ public final void setScore(final float theScore) { score = theScore; NumberFormat percentFormatter = NumberFormat.getPercentInstance(); scoreString = percentFormatter.format(theScore); }
From source file:org.prom5.framework.log.filter.LogEventLogFilterEnh.java
/** * Returns a Panel for the setting of parameters. When a LogFilter can be * added to a list in the framework. This panel is shown, and parameters can * be set. When the dialog is closed, a new instance of a LogFilter is * created by the framework by calling the <code>getNewLogFilter</code> method * of the dialog.//w ww . j a va 2s .c o m * * @param summary A LogSummary to be used for setting parameters. * @return JPanel */ public LogFilterParameterDialog getParameterDialog(LogSummary summary) { return new LogFilterParameterDialog(summary, LogEventLogFilterEnh.this) { LogEventCheckBoxEnh[] checks; JSpinner percTaskSpinner; JSpinner percPiSpinner; JComboBox choiceBox; /** * Keep the statistics for all the tasks */ SummaryStatistics taskStatistics = null; /** * Keep the statistics for the occurrence of tasks in process instances */ SummaryStatistics piStatistics = null; public LogFilter getNewLogFilter() { LogEvents e = new LogEvents(); for (int i = 0; i < checks.length; i++) { if (checks[i].isSelected()) { e.add(checks[i].getLogEvent()); } } return new LogEventLogFilterEnh(e, getDoubleValueFromSpinner(percTaskSpinner.getValue()), getDoubleValueFromSpinner(percPiSpinner.getValue()), choiceBox.getSelectedItem().toString()); } protected JPanel getPanel() { // add message to the test log for this plugin Message.add("<EnhEvtLogFilter>", Message.TEST); // statistics taskStatistics = SummaryStatistics.newInstance(); piStatistics = SummaryStatistics.newInstance(); // Set up an percentformatter NumberFormat percentFormatter = NumberFormat.getPercentInstance(); percentFormatter.setMinimumFractionDigits(2); percentFormatter.setMaximumFractionDigits(2); // Instantiate the spinners percTaskSpinner = new JSpinner(new SpinnerNumberModel(5.0, 0.0, 100.0, 1.0)); percPiSpinner = new JSpinner(new SpinnerNumberModel(5.0, 0.0, 100.0, 1.0)); // generate the buttons that are needed JButton jButtonCalculate = new JButton("Calculate"); JButton jButtonInvert = new JButton("Invert selection"); // set up a choicebox to indicate whether the relationship between the two // percentages is AND or OR. percTaskSpinner.setValue(new Double(percentageTask)); percPiSpinner.setValue(new Double(percentagePI)); choiceBox = new JComboBox(); choiceBox.addItem("AND"); choiceBox.addItem("OR"); choiceBox.setSelectedItem(selectedItemComboBox); // Some values that are needed for the sequel. int size = summary.getLogEvents().size(); // For the new log reader sumATEs should be calculated in another way int sumATEs = 0; if (summary instanceof ExtendedLogSummary) { sumATEs = summary.getNumberOfAuditTrailEntries(); } else if (summary instanceof LightweightLogSummary) { HashSet<ProcessInstance> pis = new HashSet<ProcessInstance>(); Iterator logEvents = summary.getLogEvents().iterator(); while (logEvents.hasNext()) { LogEvent evt = (LogEvent) logEvents.next(); pis.addAll(summary.getInstancesForEvent(evt)); } Iterator pis2 = pis.iterator(); while (pis2.hasNext()) { ProcessInstance pi = (ProcessInstance) pis2.next(); int simPis = MethodsForWorkflowLogDataStructures.getNumberSimilarProcessInstances(pi); int numberATEs = pi.getAuditTrailEntryList().size(); sumATEs += simPis * numberATEs; pi.isEmpty(); } } else { } // calculate the number of process Instances, taking into account // the number of similar instances int sumPIs = 0; if (summary instanceof LightweightLogSummary) { sumPIs = calculateSumPIs(summary); } checks = new LogEventCheckBoxEnh[size]; // create panels and labels JPanel global = new JPanel(new BorderLayout()); JPanel sub2 = new JPanel(new BorderLayout()); sub2.setBackground(Color.white); JLabel labelPercTask = new JLabel("percentage task"); JLabel labelPercPI = new JLabel("percentage PI"); // create panel sub1 to put the checkboxes on JPanel sub1 = new JPanel(new SpringLayout()); sub1.setBackground(Color.lightGray); // Get percentage of task in the log and percentage of in how many // different PIs it appears. Iterator it = summary.getLogEvents().iterator(); int i = 0; while (it.hasNext()) { LogEvent evt = (LogEvent) it.next(); double percent = 0.0; if (summary instanceof ExtendedLogSummary) { percent = ((double) evt.getOccurrenceCount() / (double) sumATEs); } else if (summary instanceof LightweightLogSummary) { Set instances = summary.getInstancesForEvent(evt); // getFrequencyTasks(evt, instances) percent = (double) getFrequencyTasks(evt, instances) / (double) sumATEs; } else { } //String percString = percentFormatter.format(percent); LogEventCheckBoxEnh check = new LogEventCheckBoxEnh(evt); check.setPercentageTask(percent * 100); // add percentage to the statistics for the tasks taskStatistics.addValue(percent); // Get percentage of in how many different PIs a task appears, // taking into account whether the new or old logreader is used if (summary instanceof LightweightLogSummary) { Set<ProcessInstance> pis = summary.getInstancesForEvent(evt); int numberInstancesTask = 0; Iterator it2 = pis.iterator(); while (it2.hasNext()) { ProcessInstance pi = (ProcessInstance) it2.next(); numberInstancesTask += MethodsForWorkflowLogDataStructures .getNumberSimilarProcessInstances(pi); } double fPI = (double) numberInstancesTask / (double) sumPIs; check.setPercentagePI(fPI * 100); // add percentage to the statistics for the PIs piStatistics.addValue(fPI); } else if (summary instanceof ExtendedLogSummary) { double percPIcheck = getPercentagePI(evt); check.setPercentagePI(percPIcheck); piStatistics.addValue(percPIcheck / 100); } else { // raise exception, unknown logreader } // add to the checks array checks[i++] = check; } // fill sub1 with statistics information sub1.add(new JLabel(" Statistics ( #tasks = " + taskStatistics.getN() + " )")); sub1.add(new JLabel(" ")); sub1.add(new JLabel(" ")); sub1.add(new JLabel(" Arithmetic Mean ")); sub1.add(new JLabel(percentFormatter.format(taskStatistics.getMean()))); sub1.add(new JLabel(percentFormatter.format(piStatistics.getMean()))); sub1.add(new JLabel(" Geometric Mean ")); sub1.add(new JLabel(percentFormatter.format(taskStatistics.getGeometricMean()))); sub1.add(new JLabel(percentFormatter.format(piStatistics.getGeometricMean()))); sub1.add(new JLabel(" Standard Deviation ")); sub1.add(new JLabel(percentFormatter.format(taskStatistics.getStandardDeviation()))); sub1.add(new JLabel(percentFormatter.format(piStatistics.getStandardDeviation()))); sub1.add(new JLabel(" Min ")); sub1.add(new JLabel(percentFormatter.format(taskStatistics.getMin()))); sub1.add(new JLabel(percentFormatter.format(piStatistics.getMin()))); sub1.add(new JLabel(" Max ")); sub1.add(new JLabel(percentFormatter.format(taskStatistics.getMax()))); sub1.add(new JLabel(percentFormatter.format(piStatistics.getMax()))); sub1.add(new JLabel(" ------------------ ")); sub1.add(new JLabel(" --------------- ")); sub1.add(new JLabel(" --------------- ")); sub1.add(new JLabel(" Tasks ")); sub1.add(new JLabel(" percentage task ")); sub1.add(new JLabel(" percentage PI ")); // generate messages for the test case for this plugin Message.add("number tasks: " + taskStatistics.getN(), Message.TEST); Message.add("<percentage task>", Message.TEST); Message.add("arithmetic mean: " + taskStatistics.getMean(), Message.TEST); Message.add("geometric mean: " + taskStatistics.getGeometricMean(), Message.TEST); Message.add("standard deviation: " + taskStatistics.getStandardDeviation(), Message.TEST); Message.add("min: " + taskStatistics.getMin(), Message.TEST); Message.add("max: " + taskStatistics.getMax(), Message.TEST); Message.add("<percentage task/>", Message.TEST); Message.add("<percentage PI>", Message.TEST); Message.add("arithmetic mean: " + piStatistics.getMean(), Message.TEST); Message.add("geometric mean: " + piStatistics.getGeometricMean(), Message.TEST); Message.add("standard deviation: " + piStatistics.getStandardDeviation(), Message.TEST); Message.add("min: " + piStatistics.getMin(), Message.TEST); Message.add("max: " + piStatistics.getMax(), Message.TEST); Message.add("<percentage PI/>", Message.TEST); // add the checkboxes to the GUI. Arrays.sort(checks); for (i = 0; i < checks.length; i++) { sub1.add(checks[i]); if ((eventsToKeep != null) && (!eventsToKeep.contains(checks[i].getLogEvent()))) { checks[i].setSelected(false); } // put the percentages on the GUI sub1.add(new JLabel(percentFormatter.format(checks[i].getPercentageTask() / 100))); sub1.add(new JLabel(percentFormatter.format(checks[i].getPercentagePI() / 100))); } // SpringUtilities util = new SpringUtilities(); util.makeCompactGrid(sub1, checks.length + 8, 3, 3, 3, 8, 3); // put the contents on the respective panels global.add(sub2, java.awt.BorderLayout.CENTER); global.add(sub1, java.awt.BorderLayout.SOUTH); // JPanel sub21 = new JPanel(new SpringLayout()); //sub21.setLayout(new BoxLayout(sub21, BoxLayout.PAGE_AXIS)); sub2.setBackground(Color.red); JPanel textPanel = new JPanel(new BorderLayout()); textPanel.setBackground(Color.yellow); JPanel sub221 = new JPanel(new FlowLayout()); sub221.setBackground(Color.yellow); JPanel sub222 = new JPanel(new FlowLayout()); sub222.setBackground(Color.yellow); // two different panels to be places on sub21 //JPanel sub21First = new JPanel(); //sub21First.setLayout(new BoxLayout(sub21First, BoxLayout.LINE_AXIS)); //sub21First.setMaximumSize(new Dimension(1000, 25)); //sub21First.add(Box.createHorizontalGlue()); //sub21First.add(labelPercTask); //sub21First.add(percTaskSpinner, null); //percTaskSpinner.setMaximumSize(new Dimension(10, 20)); //sub21First.add(jButtonCalculate); //jButtonCalculate.setMaximumSize(new Dimension(10, 20)); //sub21First.add(labelPercPI); //sub21First.add(percPiSpinner, null); //percPiSpinner.setMaximumSize(new Dimension(10, 20)); //sub21First.add(choiceBox); //choiceBox.setMaximumSize(new Dimension(10, 20)); //sub21First.add(Box.createHorizontalGlue()); //JPanel sub21Second = new JPanel(); //sub21Second.setLayout(new BoxLayout(sub21Second, BoxLayout.LINE_AXIS)); //sub21Second.setMaximumSize(new Dimension(1000, 25)); //sub21Second.add(Box.createHorizontalGlue()); //sub21Second.add(jButtonInvert); //sub21Second.add(Box.createHorizontalGlue()); // //sub21.add(sub21First); //sub21.add(sub21Second); sub21.add(labelPercTask); sub21.add(percTaskSpinner, null); sub21.add(jButtonCalculate); sub21.add(labelPercPI); sub21.add(percPiSpinner, null); sub21.add(choiceBox); // add the invert button sub21.add(new JLabel(" ")); sub21.add(new JLabel(" ")); sub21.add(jButtonInvert); sub21.add(new JLabel(" ")); sub21.add(new JLabel(" ")); sub21.add(new JLabel(" ")); sub21.setMaximumSize(sub21.getPreferredSize()); sub2.add(sub21, java.awt.BorderLayout.CENTER); sub2.add(textPanel, java.awt.BorderLayout.SOUTH); textPanel.add(new JLabel( "The Calculate button needs to be clicked to calculate which tasks need to be selected!!!"), java.awt.BorderLayout.CENTER); textPanel.add( new JLabel("Clicking the OK button only accepts, but nothing is again calculated!!!!"), java.awt.BorderLayout.SOUTH); util.makeCompactGrid(sub21, 2, 6, 3, 3, 8, 3); // // specify button action for the button ButtonPreview jButtonCalculate.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // The preview button is clicked buttonClicked(); // end for } }); // specify button action for the button Invert jButtonInvert.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { invertButtonClicked(); } }); return global; } /** * When the preview button is clicked */ public void buttonClicked() { for (int k = 0; k < checks.length; k++) { boolean firstCheck = false; boolean secondCheck = false; LogEventCheckBoxEnh c = checks[k]; // check for the task in c whether its percentage is higher than // perc firstCheck = checkTask(c, percTaskSpinner.getValue()); // Also check whether the task occurs in more than percTr // percent of the traces secondCheck = checkPI(c, percPiSpinner.getValue()); // Check whether for choiceBox OR or AND is selected boolean logicalResult = true; if (((String) choiceBox.getSelectedItem()).equals("AND")) { logicalResult = firstCheck && secondCheck; } else if (((String) choiceBox.getSelectedItem()).equals("OR")) { logicalResult = firstCheck || secondCheck; } // set the checkbox selected or not if (logicalResult == true) { c.setSelected(true); } else { c.setSelected(false); } } // add messages to the test log for this case int numberCheckedBoxes = 0; for (int i = 0; i < checks.length; i++) { if (checks[i].isSelected()) { numberCheckedBoxes++; } } Message.add("number of selected tasks: " + numberCheckedBoxes, Message.TEST); Message.add("<EnhEvtLogFilter/>", Message.TEST); } /** * */ public void invertButtonClicked() { for (int i = 0; i < checks.length; i++) { checks[i].setSelected(!checks[i].isSelected()); } } /** * Checks whether the task in c occurs with a lower percentage in the log * than the percentage given by percTask. * @param c LogEventCheckBoxEnh the checkbox that contains the task. * @param percTask Object the percentage * @return boolean True if the percentage of which the task in c occurs * in the log is greater or equal than percTaks, false otherwise. */ private boolean checkTask(LogEventCheckBoxEnh c, Object percTask) { boolean returnBoolean = false; double percT = 0.0; percT = getDoubleValueFromSpinner(percTask); // check whether its percentage is higher than percT if (c.getPercentageTask() >= percT) { returnBoolean = true; } else { returnBoolean = false; } return returnBoolean; } /** * Checks whether the task in c occurs with a lower percentage in different * process instances than the percentage given by percTrace. * @param c LogEventCheckBoxEnh the checkbox that contains the task. * @param percTrace Object the percentage. * @return boolean True, if the percentage of which the task in different * process instances occurs in the log is greater or equal than percTrace, * false otherwise. */ private boolean checkPI(LogEventCheckBoxEnh c, Object percPIobj) { boolean returnBoolean = false; double percPI = 0.0; percPI = getDoubleValueFromSpinner(percPIobj); // check whether its percentage is higher than percPI if (c.getPercentagePI() >= percPI) { returnBoolean = true; } else { returnBoolean = false; } return returnBoolean; } /** * Get the percentage of that this task occurs in different PIs * @param evt LogEvent the logEvent in which the task can be found * @return double the percentage of which this task in the log occurs */ private double getPercentagePI(LogEvent evt) { double returnPercent = 0.0; HashMap mapping = ((ExtendedLogSummary) summary).getMappingAtesToNumberPIs(); int numberPI = summary.getNumberOfProcessInstances(); // Get the frequency of PI in which the task occurs Object value = null; Iterator it = mapping.keySet().iterator(); while (it.hasNext()) { Object keyObj = it.next(); String key = (String) keyObj; if (key.equals( evt.getModelElementName().trim() + " " + "(" + evt.getEventType().trim() + ")")) { value = mapping.get(keyObj); break; } } if (value != null) { // calculate frequency returnPercent = (((Integer) value).doubleValue() / new Double(numberPI).doubleValue()) * 100; } return returnPercent; } private int getFrequencyTasks(LogEvent evt, Set instances) { int returnFrequency = 0; Iterator instIterator = instances.iterator(); while (instIterator.hasNext()) { ProcessInstance pi = (ProcessInstance) instIterator.next(); Iterator ates = pi.getAuditTrailEntryList().iterator(); while (ates.hasNext()) { AuditTrailEntry ate = (AuditTrailEntry) ates.next(); if (ate.getElement().trim().equals(evt.getModelElementName().trim()) && ate.getType().equals(evt.getEventType())) { returnFrequency += MethodsForWorkflowLogDataStructures .getNumberSimilarProcessInstances(pi); } } } return returnFrequency; } /** * Gets the double value of an object, provided that value is a * Double or Long object * @param value Object * @return double the double value */ private double getDoubleValueFromSpinner(Object value) { double returnDouble = 0.0; if (value instanceof Long) { returnDouble = (((Long) value).doubleValue()); } else if (value instanceof Double) { returnDouble = (((Double) value).doubleValue()); } return returnDouble; } /** * Returns the number of process instances, taking into account the * number of similar instances * @param summary LogSummary the log summary * @return int the number of process instances */ private int calculateSumPIs(LogSummary summary) { int returnSum = 0; HashSet pis = new HashSet<ProcessInstance>(); Iterator it = summary.getLogEvents().iterator(); while (it.hasNext()) { LogEvent evt = (LogEvent) it.next(); pis.addAll(summary.getInstancesForEvent(evt)); } // for each process instance in pis, get the number of similar instances Iterator it2 = pis.iterator(); while (it2.hasNext()) { ProcessInstance pi = (ProcessInstance) it2.next(); returnSum += MethodsForWorkflowLogDataStructures.getNumberSimilarProcessInstances(pi); } return returnSum; } protected boolean getAllParametersSet() { // calculate values //buttonClicked(); return true; } }; }
From source file:API.JSONPractice.java
private void getMatch() throws Exception { Integer[] apIds = { 1026, 1052, 1056, 1058, 3001, 3003, 3020, 3023, 3025, 3027, 3040, 3041, 3050, 3057, 3060, 3089, 3092, 3098, 3100, 3108, 3113, 3115, 3116, 3124, 3135, 3136, 3145, 3146, 3151, 3152, 3157, 3165, 3174, 3191, 3285, 3303, 3504, 3708, 3716, 3720, 3724 }; List<Integer> apIdsList = Arrays.asList(apIds); Files.walk(Paths.get("C:\\AP_ITEMS\\")).forEach(filePath -> { if (Files.isRegularFile(filePath)) { try (FileReader fileReader = new FileReader(filePath.toString())) { File file = new File(filePath.toString()); String fileName = file.getName(); String region = fileName.replace(".json", "").toLowerCase(); JSONParser jsonParser = new JSONParser(); JSONArray matchId = (JSONArray) jsonParser.parse(fileReader); for (int i = 0; i < jsonFileSize; i++) { url = "https://" + region + ".api.pvp.net/api/lol/" + region + "/v2.2/match/" + matchId.get(i) + "?api_key=" + api_key; System.out.println(url); File jsonFile = new File("C:\\Riot_API\\" + region + "\\" + matchId.get(i) + ".json"); if (!jsonFile.exists()) { FileWriter fileWriter = new FileWriter(jsonFile); BufferedWriter bw = new BufferedWriter(fileWriter); URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); do { // optional default is GET con.setRequestMethod("GET"); int responseCode = con.getResponseCode(); System.out.println("\nSending 'GET' request to URL : " + url); System.out.println("Response Code : " + responseCode); if (responseCode == 500 || responseCode == 503) { tryAgain = true; } else { tryAgain = false; }/* w w w . j a va 2s .co m*/ } while (tryAgain); StringBuffer response = new StringBuffer(); try (BufferedReader in = new BufferedReader( new InputStreamReader(con.getInputStream()))) { String inputLine; while ((inputLine = in.readLine()) != null) { response.append(inputLine); } // do try in.close(); } catch (IOException e) { e.printStackTrace(); } JSONObject jsonObject = new JSONObject(response.toString()); for (int n = 0; n < numberOfParticipants; n++) { JSONObject stats = jsonObject.getJSONArray("participants").getJSONObject(n) .getJSONObject("stats"); JSONObject object = new JSONObject(); JSONArray arr = new JSONArray(); // String test = jsonObject.getJSONArray("participants").getJSONObject(i).getJSONObject("timeline").getString("lane"); for (int count = 0; count < itemSlots; count++) { if (stats.getInt("item" + count) != 0) { arr.add(stats.getInt("item" + count)); itemList.add(stats.getInt("item" + count)); } } object.put("participant" + (n + 1), arr); bw.write(object.toString()); } bw.flush(); bw.close(); } /* for (int itemId : itemList) { if (apIdsList.contains(itemId)) { fullApList.add(itemId); } } */ // Sleep count came from request limit of 500 request per 10 minute. // Therefore, 1.2 sec per request is allowed. Thread.sleep(1200); } NumberFormat defaultFormat = NumberFormat.getPercentInstance(); defaultFormat.setMinimumFractionDigits(1); /* for (int value : apIdsList) { double occurrences = Collections.frequency(fullApList, value); System.out.println(defaultFormat.format(occurrences / itemList.size())); } */ } catch (Exception e) { e.printStackTrace(); } } }); // } catch (FileNotFoundException | IOException | ParseException e) }
From source file:com.android.contacts.vcard.NotificationImportExportListener.java
/** * Constructs a {@link Notification} showing the current status of import/export. * Users can cancel the process with the Notification. * * @param context/* ww w .j ava 2 s.com*/ * @param type import/export * @param description Content of the Notification. * @param tickerText * @param jobId * @param displayName Name to be shown to the Notification (e.g. "finished importing XXXX"). * Typycally a file name. * @param totalCount The number of vCard entries to be imported. Used to show progress bar. * -1 lets the system show the progress bar with "indeterminate" state. * @param currentCount The index of current vCard. Used to show progress bar. */ /* package */ static Notification constructProgressNotification(Context context, int type, String description, String tickerText, int jobId, String displayName, int totalCount, int currentCount) { // Note: We cannot use extra values here (like setIntExtra()), as PendingIntent doesn't // preserve them across multiple Notifications. PendingIntent preserves the first extras // (when flag is not set), or update them when PendingIntent#getActivity() is called // (See PendingIntent#FLAG_UPDATE_CURRENT). In either case, we cannot preserve extras as we // expect (for each vCard import/export request). // // We use query parameter in Uri instead. // Scheme and Authority is arbitorary, assuming CancelActivity never refers them. final Intent intent = new Intent(context, CancelActivity.class); final Uri uri = (new Uri.Builder()).scheme("invalidscheme").authority("invalidauthority") .appendQueryParameter(CancelActivity.JOB_ID, String.valueOf(jobId)) .appendQueryParameter(CancelActivity.DISPLAY_NAME, displayName) .appendQueryParameter(CancelActivity.TYPE, String.valueOf(type)).build(); intent.setData(uri); final NotificationCompat.Builder builder = new NotificationCompat.Builder(context); builder.setOngoing(true).setChannelId(ContactsNotificationChannelsUtil.DEFAULT_CHANNEL) .setOnlyAlertOnce(true).setProgress(totalCount, currentCount, totalCount == -1) .setTicker(tickerText).setContentTitle(description) .setColor(context.getResources().getColor(R.color.dialtacts_theme_color)) .setSmallIcon(type == VCardService.TYPE_IMPORT ? android.R.drawable.stat_sys_download : android.R.drawable.stat_sys_upload) .setContentIntent(PendingIntent.getActivity(context, 0, intent, 0)); if (totalCount > 0) { String percentage = NumberFormat.getPercentInstance().format((double) currentCount / totalCount); builder.setContentText(percentage); } return builder.build(); }
From source file:org.processmining.framework.log.filter.LogEventLogFilterEnh.java
/** * Returns a Panel for the setting of parameters. When a LogFilter can be * added to a list in the framework. This panel is shown, and parameters can * be set. When the dialog is closed, a new instance of a LogFilter is * created by the framework by calling the <code>getNewLogFilter</code> * method of the dialog.//from w w w . java 2s .c o m * * @param summary * A LogSummary to be used for setting parameters. * @return JPanel */ public LogFilterParameterDialog getParameterDialog(LogSummary summary) { return new LogFilterParameterDialog(summary, LogEventLogFilterEnh.this) { LogEventCheckBoxEnh[] checks; JSpinner percTaskSpinner; JSpinner percPiSpinner; JComboBox choiceBox; /** * Keep the statistics for all the tasks */ SummaryStatistics taskStatistics = null; /** * Keep the statistics for the occurrence of tasks in process * instances */ SummaryStatistics piStatistics = null; public LogFilter getNewLogFilter() { LogEvents e = new LogEvents(); for (int i = 0; i < checks.length; i++) { if (checks[i].isSelected()) { e.add(checks[i].getLogEvent()); } } return new LogEventLogFilterEnh(e, getDoubleValueFromSpinner(percTaskSpinner.getValue()), getDoubleValueFromSpinner(percPiSpinner.getValue()), choiceBox.getSelectedItem().toString()); } protected JPanel getPanel() { // add message to the test log for this plugin Message.add("<EnhEvtLogFilter>", Message.TEST); // statistics taskStatistics = SummaryStatistics.newInstance(); piStatistics = SummaryStatistics.newInstance(); // Set up an percentformatter NumberFormat percentFormatter = NumberFormat.getPercentInstance(); percentFormatter.setMinimumFractionDigits(2); percentFormatter.setMaximumFractionDigits(2); // Instantiate the spinners percTaskSpinner = new JSpinner(new SpinnerNumberModel(5.0, 0.0, 100.0, 1.0)); percPiSpinner = new JSpinner(new SpinnerNumberModel(5.0, 0.0, 100.0, 1.0)); // generate the buttons that are needed JButton jButtonCalculate = new JButton("Calculate"); JButton jButtonInvert = new JButton("Invert selection"); // set up a choicebox to indicate whether the relationship // between the two // percentages is AND or OR. percTaskSpinner.setValue(new Double(percentageTask)); percPiSpinner.setValue(new Double(percentagePI)); choiceBox = new JComboBox(); choiceBox.addItem("AND"); choiceBox.addItem("OR"); choiceBox.setSelectedItem(selectedItemComboBox); // Some values that are needed for the sequel. int size = summary.getLogEvents().size(); // For the new log reader sumATEs should be calculated in // another way int sumATEs = 0; if (summary instanceof ExtendedLogSummary) { sumATEs = summary.getNumberOfAuditTrailEntries(); } else if (summary instanceof LightweightLogSummary) { HashSet<ProcessInstance> pis = new HashSet<ProcessInstance>(); Iterator logEvents = summary.getLogEvents().iterator(); while (logEvents.hasNext()) { LogEvent evt = (LogEvent) logEvents.next(); pis.addAll(summary.getInstancesForEvent(evt)); } Iterator pis2 = pis.iterator(); while (pis2.hasNext()) { ProcessInstance pi = (ProcessInstance) pis2.next(); int simPis = MethodsForWorkflowLogDataStructures.getNumberSimilarProcessInstances(pi); int numberATEs = pi.getAuditTrailEntryList().size(); sumATEs += simPis * numberATEs; pi.isEmpty(); } } else { } // calculate the number of process Instances, taking into // account // the number of similar instances int sumPIs = 0; if (summary instanceof LightweightLogSummary) { sumPIs = calculateSumPIs(summary); } checks = new LogEventCheckBoxEnh[size]; // create panels and labels JPanel global = new JPanel(new BorderLayout()); JPanel sub2 = new JPanel(new BorderLayout()); sub2.setBackground(Color.white); JLabel labelPercTask = new JLabel("percentage task"); JLabel labelPercPI = new JLabel("percentage PI"); // create panel sub1 to put the checkboxes on JPanel sub1 = new JPanel(new SpringLayout()); sub1.setBackground(Color.lightGray); // Get percentage of task in the log and percentage of in how // many // different PIs it appears. Iterator it = summary.getLogEvents().iterator(); int i = 0; while (it.hasNext()) { LogEvent evt = (LogEvent) it.next(); double percent = 0.0; if (summary instanceof ExtendedLogSummary) { percent = ((double) evt.getOccurrenceCount() / (double) sumATEs); } else if (summary instanceof LightweightLogSummary) { Set instances = summary.getInstancesForEvent(evt); // getFrequencyTasks(evt, instances) percent = (double) getFrequencyTasks(evt, instances) / (double) sumATEs; } else { } // String percString = percentFormatter.format(percent); LogEventCheckBoxEnh check = new LogEventCheckBoxEnh(evt); check.setPercentageTask(percent * 100); // add percentage to the statistics for the tasks taskStatistics.addValue(percent); // Get percentage of in how many different PIs a task // appears, // taking into account whether the new or old logreader is // used if (summary instanceof LightweightLogSummary) { Set<ProcessInstance> pis = summary.getInstancesForEvent(evt); int numberInstancesTask = 0; Iterator it2 = pis.iterator(); while (it2.hasNext()) { ProcessInstance pi = (ProcessInstance) it2.next(); numberInstancesTask += MethodsForWorkflowLogDataStructures .getNumberSimilarProcessInstances(pi); } double fPI = (double) numberInstancesTask / (double) sumPIs; check.setPercentagePI(fPI * 100); // add percentage to the statistics for the PIs piStatistics.addValue(fPI); } else if (summary instanceof ExtendedLogSummary) { double percPIcheck = getPercentagePI(evt); check.setPercentagePI(percPIcheck); piStatistics.addValue(percPIcheck / 100); } else { // raise exception, unknown logreader } // add to the checks array checks[i++] = check; } // fill sub1 with statistics information sub1.add(new JLabel(" Statistics ( #tasks = " + taskStatistics.getN() + " )")); sub1.add(new JLabel(" ")); sub1.add(new JLabel(" ")); sub1.add(new JLabel(" Arithmetic Mean ")); sub1.add(new JLabel(percentFormatter.format(taskStatistics.getMean()))); sub1.add(new JLabel(percentFormatter.format(piStatistics.getMean()))); sub1.add(new JLabel(" Geometric Mean ")); sub1.add(new JLabel(percentFormatter.format(taskStatistics.getGeometricMean()))); sub1.add(new JLabel(percentFormatter.format(piStatistics.getGeometricMean()))); sub1.add(new JLabel(" Standard Deviation ")); sub1.add(new JLabel(percentFormatter.format(taskStatistics.getStandardDeviation()))); sub1.add(new JLabel(percentFormatter.format(piStatistics.getStandardDeviation()))); sub1.add(new JLabel(" Min ")); sub1.add(new JLabel(percentFormatter.format(taskStatistics.getMin()))); sub1.add(new JLabel(percentFormatter.format(piStatistics.getMin()))); sub1.add(new JLabel(" Max ")); sub1.add(new JLabel(percentFormatter.format(taskStatistics.getMax()))); sub1.add(new JLabel(percentFormatter.format(piStatistics.getMax()))); sub1.add(new JLabel(" ------------------ ")); sub1.add(new JLabel(" --------------- ")); sub1.add(new JLabel(" --------------- ")); sub1.add(new JLabel(" Tasks ")); sub1.add(new JLabel(" percentage task ")); sub1.add(new JLabel(" percentage PI ")); // generate messages for the test case for this plugin Message.add("number tasks: " + taskStatistics.getN(), Message.TEST); Message.add("<percentage task>", Message.TEST); Message.add("arithmetic mean: " + taskStatistics.getMean(), Message.TEST); Message.add("geometric mean: " + taskStatistics.getGeometricMean(), Message.TEST); Message.add("standard deviation: " + taskStatistics.getStandardDeviation(), Message.TEST); Message.add("min: " + taskStatistics.getMin(), Message.TEST); Message.add("max: " + taskStatistics.getMax(), Message.TEST); Message.add("<percentage task/>", Message.TEST); Message.add("<percentage PI>", Message.TEST); Message.add("arithmetic mean: " + piStatistics.getMean(), Message.TEST); Message.add("geometric mean: " + piStatistics.getGeometricMean(), Message.TEST); Message.add("standard deviation: " + piStatistics.getStandardDeviation(), Message.TEST); Message.add("min: " + piStatistics.getMin(), Message.TEST); Message.add("max: " + piStatistics.getMax(), Message.TEST); Message.add("<percentage PI/>", Message.TEST); // add the checkboxes to the GUI. Arrays.sort(checks); for (i = 0; i < checks.length; i++) { sub1.add(checks[i]); if ((eventsToKeep != null) && (!eventsToKeep.contains(checks[i].getLogEvent()))) { checks[i].setSelected(false); } // put the percentages on the GUI sub1.add(new JLabel(percentFormatter.format(checks[i].getPercentageTask() / 100))); sub1.add(new JLabel(percentFormatter.format(checks[i].getPercentagePI() / 100))); } // SpringUtilities util = new SpringUtilities(); util.makeCompactGrid(sub1, checks.length + 8, 3, 3, 3, 8, 3); // put the contents on the respective panels global.add(sub2, java.awt.BorderLayout.CENTER); global.add(sub1, java.awt.BorderLayout.SOUTH); // JPanel sub21 = new JPanel(new SpringLayout()); // sub21.setLayout(new BoxLayout(sub21, BoxLayout.PAGE_AXIS)); sub2.setBackground(Color.red); JPanel textPanel = new JPanel(new BorderLayout()); textPanel.setBackground(Color.yellow); JPanel sub221 = new JPanel(new FlowLayout()); sub221.setBackground(Color.yellow); JPanel sub222 = new JPanel(new FlowLayout()); sub222.setBackground(Color.yellow); // two different panels to be places on sub21 // JPanel sub21First = new JPanel(); // sub21First.setLayout(new BoxLayout(sub21First, // BoxLayout.LINE_AXIS)); // sub21First.setMaximumSize(new Dimension(1000, 25)); // sub21First.add(Box.createHorizontalGlue()); // sub21First.add(labelPercTask); // sub21First.add(percTaskSpinner, null); // percTaskSpinner.setMaximumSize(new Dimension(10, 20)); // sub21First.add(jButtonCalculate); // jButtonCalculate.setMaximumSize(new Dimension(10, 20)); // sub21First.add(labelPercPI); // sub21First.add(percPiSpinner, null); // percPiSpinner.setMaximumSize(new Dimension(10, 20)); // sub21First.add(choiceBox); // choiceBox.setMaximumSize(new Dimension(10, 20)); // sub21First.add(Box.createHorizontalGlue()); // JPanel sub21Second = new JPanel(); // sub21Second.setLayout(new BoxLayout(sub21Second, // BoxLayout.LINE_AXIS)); // sub21Second.setMaximumSize(new Dimension(1000, 25)); // sub21Second.add(Box.createHorizontalGlue()); // sub21Second.add(jButtonInvert); // sub21Second.add(Box.createHorizontalGlue()); // // sub21.add(sub21First); // sub21.add(sub21Second); sub21.add(labelPercTask); sub21.add(percTaskSpinner, null); sub21.add(jButtonCalculate); sub21.add(labelPercPI); sub21.add(percPiSpinner, null); sub21.add(choiceBox); // add the invert button sub21.add(new JLabel(" ")); sub21.add(new JLabel(" ")); sub21.add(jButtonInvert); sub21.add(new JLabel(" ")); sub21.add(new JLabel(" ")); sub21.add(new JLabel(" ")); sub21.setMaximumSize(sub21.getPreferredSize()); sub2.add(sub21, java.awt.BorderLayout.CENTER); sub2.add(textPanel, java.awt.BorderLayout.SOUTH); textPanel.add(new JLabel( "The Calculate button needs to be clicked to calculate which tasks need to be selected!!!"), java.awt.BorderLayout.CENTER); textPanel.add( new JLabel("Clicking the OK button only accepts, but nothing is again calculated!!!!"), java.awt.BorderLayout.SOUTH); util.makeCompactGrid(sub21, 2, 6, 3, 3, 8, 3); // // specify button action for the button ButtonPreview jButtonCalculate.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // The preview button is clicked buttonClicked(); // end for } }); // specify button action for the button Invert jButtonInvert.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { invertButtonClicked(); } }); return global; } /** * When the preview button is clicked */ public void buttonClicked() { for (int k = 0; k < checks.length; k++) { boolean firstCheck = false; boolean secondCheck = false; LogEventCheckBoxEnh c = checks[k]; // check for the task in c whether its percentage is higher // than // perc firstCheck = checkTask(c, percTaskSpinner.getValue()); // Also check whether the task occurs in more than percTr // percent of the traces secondCheck = checkPI(c, percPiSpinner.getValue()); // Check whether for choiceBox OR or AND is selected boolean logicalResult = true; if (((String) choiceBox.getSelectedItem()).equals("AND")) { logicalResult = firstCheck && secondCheck; } else if (((String) choiceBox.getSelectedItem()).equals("OR")) { logicalResult = firstCheck || secondCheck; } // set the checkbox selected or not if (logicalResult == true) { c.setSelected(true); } else { c.setSelected(false); } } // add messages to the test log for this case int numberCheckedBoxes = 0; for (int i = 0; i < checks.length; i++) { if (checks[i].isSelected()) { numberCheckedBoxes++; } } Message.add("number of selected tasks: " + numberCheckedBoxes, Message.TEST); Message.add("<EnhEvtLogFilter/>", Message.TEST); } /** * */ public void invertButtonClicked() { for (int i = 0; i < checks.length; i++) { checks[i].setSelected(!checks[i].isSelected()); } } /** * Checks whether the task in c occurs with a lower percentage in * the log than the percentage given by percTask. * * @param c * LogEventCheckBoxEnh the checkbox that contains the * task. * @param percTask * Object the percentage * @return boolean True if the percentage of which the task in c * occurs in the log is greater or equal than percTaks, * false otherwise. */ private boolean checkTask(LogEventCheckBoxEnh c, Object percTask) { boolean returnBoolean = false; double percT = 0.0; percT = getDoubleValueFromSpinner(percTask); // check whether its percentage is higher than percT if (c.getPercentageTask() >= percT) { returnBoolean = true; } else { returnBoolean = false; } return returnBoolean; } /** * Checks whether the task in c occurs with a lower percentage in * different process instances than the percentage given by * percTrace. * * @param c * LogEventCheckBoxEnh the checkbox that contains the * task. * @param percTrace * Object the percentage. * @return boolean True, if the percentage of which the task in * different process instances occurs in the log is greater * or equal than percTrace, false otherwise. */ private boolean checkPI(LogEventCheckBoxEnh c, Object percPIobj) { boolean returnBoolean = false; double percPI = 0.0; percPI = getDoubleValueFromSpinner(percPIobj); // check whether its percentage is higher than percPI if (c.getPercentagePI() >= percPI) { returnBoolean = true; } else { returnBoolean = false; } return returnBoolean; } /** * Get the percentage of that this task occurs in different PIs * * @param evt * LogEvent the logEvent in which the task can be found * @return double the percentage of which this task in the log * occurs */ private double getPercentagePI(LogEvent evt) { double returnPercent = 0.0; HashMap mapping = ((ExtendedLogSummary) summary).getMappingAtesToNumberPIs(); int numberPI = summary.getNumberOfProcessInstances(); // Get the frequency of PI in which the task occurs Object value = null; Iterator it = mapping.keySet().iterator(); while (it.hasNext()) { Object keyObj = it.next(); String key = (String) keyObj; if (key.equals( evt.getModelElementName().trim() + " " + "(" + evt.getEventType().trim() + ")")) { value = mapping.get(keyObj); break; } } if (value != null) { // calculate frequency returnPercent = (((Integer) value).doubleValue() / new Double(numberPI).doubleValue()) * 100; } return returnPercent; } private int getFrequencyTasks(LogEvent evt, Set instances) { int returnFrequency = 0; Iterator instIterator = instances.iterator(); while (instIterator.hasNext()) { ProcessInstance pi = (ProcessInstance) instIterator.next(); Iterator ates = pi.getAuditTrailEntryList().iterator(); while (ates.hasNext()) { AuditTrailEntry ate = (AuditTrailEntry) ates.next(); if (ate.getElement().trim().equals(evt.getModelElementName().trim()) && ate.getType().equals(evt.getEventType())) { returnFrequency += MethodsForWorkflowLogDataStructures .getNumberSimilarProcessInstances(pi); } } } return returnFrequency; } /** * Gets the double value of an object, provided that value is a * Double or Long object * * @param value * Object * @return double the double value */ private double getDoubleValueFromSpinner(Object value) { double returnDouble = 0.0; if (value instanceof Long) { returnDouble = (((Long) value).doubleValue()); } else if (value instanceof Double) { returnDouble = (((Double) value).doubleValue()); } return returnDouble; } /** * Returns the number of process instances, taking into account the * number of similar instances * * @param summary * LogSummary the log summary * @return int the number of process instances */ private int calculateSumPIs(LogSummary summary) { int returnSum = 0; HashSet pis = new HashSet<ProcessInstance>(); Iterator it = summary.getLogEvents().iterator(); while (it.hasNext()) { LogEvent evt = (LogEvent) it.next(); pis.addAll(summary.getInstancesForEvent(evt)); } // for each process instance in pis, get the number of similar // instances Iterator it2 = pis.iterator(); while (it2.hasNext()) { ProcessInstance pi = (ProcessInstance) it2.next(); returnSum += MethodsForWorkflowLogDataStructures.getNumberSimilarProcessInstances(pi); } return returnSum; } protected boolean getAllParametersSet() { // calculate values // buttonClicked(); return true; } }; }
From source file:org.hyperic.hq.plugin.system.ProcessData.java
public String getFormattedMemPerc() { if (_memPerc == Sigar.FIELD_NOTIMPL) { return NA; }/*from w ww . j ava 2 s. c om*/ NumberFormat percentFormat = NumberFormat.getPercentInstance(); percentFormat.setMaximumFractionDigits(1); percentFormat.setMinimumFractionDigits(1); return percentFormat.format(_memPerc); }
From source file:com.android.contacts.common.vcard.NotificationImportExportListener.java
/** * Constructs a {@link Notification} showing the current status of import/export. * Users can cancel the process with the Notification. * * @param context/*from w w w. j a va2s . com*/ * @param type import/export * @param description Content of the Notification. * @param tickerText * @param jobId * @param displayName Name to be shown to the Notification (e.g. "finished importing XXXX"). * Typycally a file name. * @param totalCount The number of vCard entries to be imported. Used to show progress bar. * -1 lets the system show the progress bar with "indeterminate" state. * @param currentCount The index of current vCard. Used to show progress bar. */ /* package */ static Notification constructProgressNotification(Context context, int type, String description, String tickerText, int jobId, String displayName, int totalCount, int currentCount) { // Note: We cannot use extra values here (like setIntExtra()), as PendingIntent doesn't // preserve them across multiple Notifications. PendingIntent preserves the first extras // (when flag is not set), or update them when PendingIntent#getActivity() is called // (See PendingIntent#FLAG_UPDATE_CURRENT). In either case, we cannot preserve extras as we // expect (for each vCard import/export request). // // We use query parameter in Uri instead. // Scheme and Authority is arbitorary, assuming CancelActivity never refers them. final Intent intent = new Intent(context, CancelActivity.class); final Uri uri = (new Uri.Builder()).scheme("invalidscheme").authority("invalidauthority") .appendQueryParameter(CancelActivity.JOB_ID, String.valueOf(jobId)) .appendQueryParameter(CancelActivity.DISPLAY_NAME, displayName) .appendQueryParameter(CancelActivity.TYPE, String.valueOf(type)).build(); intent.setData(uri); final NotificationCompat.Builder builder = new NotificationCompat.Builder(context); builder.setOngoing(true).setProgress(totalCount, currentCount, totalCount == -1).setTicker(tickerText) .setContentTitle(description) .setColor(context.getResources().getColor(R.color.dialtacts_theme_color)) .setSmallIcon(type == VCardService.TYPE_IMPORT ? android.R.drawable.stat_sys_download : android.R.drawable.stat_sys_upload) .setContentIntent(PendingIntent.getActivity(context, 0, intent, 0)); if (totalCount > 0) { String percentage = NumberFormat.getPercentInstance().format((double) currentCount / totalCount); builder.setContentText(percentage); } return builder.getNotification(); }