List of usage examples for java.lang Double isInfinite
public static boolean isInfinite(double v)
From source file:org.eclipse.dataset.DoubleDataset.java
@Override public boolean containsInvalidNumbers() { IndexIterator iter = getIterator(); // REAL_ONLY while (iter.hasNext()) { // REAL_ONLY double x = data[iter.index]; // PRIM_TYPE // REAL_ONLY if (Double.isNaN(x) || Double.isInfinite(x)) // CLASS_TYPE // REAL_ONLY return true; // REAL_ONLY } // REAL_ONLY return false; }
From source file:de.clusteval.serverclient.BackendClient.java
@Override public void run() { boolean checkForRunStatus = false; boolean checkForOptRunStatus = false; try {/* w w w.j a v a 2 s .co m*/ if (params.hasOption("performRun")) { this.performRun(params.getOptionValue("performRun")); } if (params.hasOption("resumeRun")) { this.resumeRun(params.getOptionValue("resumeRun")); } if (params.hasOption("terminateRun")) { this.terminateRun(params.getOptionValue("terminateRun")); } if (params.hasOption("getRuns")) { System.out.println("Runs: " + this.getRuns()); } if (params.hasOption("getRunResumes")) { System.out.println("RunResumes: " + this.getRunResumes()); } if (params.hasOption("getQueue")) { System.out.println("Queue: " + this.getQueue()); } if (params.hasOption("getActiveThreads")) { Map<String, Triple<String, Integer, Long>> activeThreads = this.server.getActiveThreads(); if (activeThreads.isEmpty()) System.out.println("No active threads"); else { System.out.println("Active threads:"); System.out.format("%10s%20s%50s%30s%40s%10s%20s\n", "Thread #", "Thread", "Run", "ProgramConfig", "DataConfig", "Iteration", "Running time"); List<String> threadNames = new ArrayList<String>(activeThreads.keySet()); Collections.sort(threadNames); int i = 1; for (String t : threadNames) { Triple<String, Integer, Long> value = activeThreads.get(t); String[] split1 = value.getFirst().split(": "); String[] split2 = split1[1].split(","); switch (value.getSecond()) { case -1: System.out.format("%10d%20s%50s%30s%40s%10s%20s\n", i++, t, split1[0], split2[0], split2[1], "isoMDS", Formatter.formatMsToDuration( System.currentTimeMillis() - value.getThird(), false)); break; case -2: System.out.format("%10d%20s%50s%30s%40s%10s%20s\n", i++, t, split1[0], split2[0], split2[1], "PCA", Formatter.formatMsToDuration( System.currentTimeMillis() - value.getThird(), false)); break; default: System.out.format("%10d%20s%50s%30s%40s%10d%20s\n", i++, t, split1[0], split2[0], split2[1], value.getSecond(), Formatter.formatMsToDuration( System.currentTimeMillis() - value.getThird(), false)); } } } } if (params.hasOption("getRunResults")) { Map<Pair<String, String>, Map<String, Double>> result = this .getRunResults(params.getOptionValue("getRunResults")); boolean first = true; for (Pair<String, String> p : result.keySet()) { if (first) { for (String m : result.get(p).keySet()) { System.out.format("%-30s", ""); System.out.print("\t" + m); } System.out.println(); } System.out.format("%-30s", "(" + p.getFirst() + "," + p.getSecond() + ")"); for (String m : result.get(p).keySet()) { System.out.println("\t" + result.get(p).get(m)); } first = false; } } if (params.hasOption("getDataSets")) { System.out.println("DataSets: " + this.getDataSets()); } if (params.hasOption("getPrograms")) { System.out.println("Programs: " + this.getPrograms()); } if (params.hasOption("getRunStatus")) { checkForRunStatus = true; } if (params.hasOption("getOptRunStatus")) { checkForOptRunStatus = true; } if (params.hasOption("shutdown")) { this.shutdownFramework(); } if (params.hasOption("generateDataSet")) { String generatorName = params.getOptionValue("generateDataSet"); CommandLineParser parser = new PosixParser(); Options options = getOptionsForDataSetGenerator(generatorName); try { parser.parse(options, this.args); this.server.generateDataSet(generatorName, this.args); } catch (ParseException e1) { try { reader.println(); HelpFormatter formatter = new HelpFormatter(); formatter.setOptionComparator(new MyOptionComparator()); formatter.printHelp("generateDataSet " + generatorName, options, true); reader.println(); } catch (IOException e) { e.printStackTrace(); } } } if (params.hasOption("randomizeDataConfig")) { String randomizerName = params.getOptionValue("randomizeDataConfig"); CommandLineParser parser = new PosixParser(); Options options = getOptionsForDataRandomizer(randomizerName); try { parser.parse(options, this.args); this.server.randomizeDataConfig(randomizerName, this.args); } catch (ParseException e1) { try { reader.println(); HelpFormatter formatter = new HelpFormatter(); formatter.setOptionComparator(new MyOptionComparator()); formatter.printHelp("randomizeDataConfig " + randomizerName, options, true); reader.println(); } catch (IOException e) { e.printStackTrace(); } } } if (checkForRunStatus) { try { String runName = params.getOptionValue("getRunStatus"); Map<String, Pair<RUN_STATUS, Float>> status = null; if ((status = this.getMyRunStatus()) != null && status.size() > 0) { RUN_STATUS newStatus; Float percent; if (!status.containsKey(runName)) { log.info("No run with name " + runName + " running."); return; } newStatus = status.get(runName).getFirst(); percent = status.get(runName).getSecond(); System.out.println(); System.out.print("\r" + newStatus + " " + percent + "%"); } System.out.println(); } catch (ConnectException e2) { this.log.warn("The server terminated the connection..."); } catch (RemoteException e2) { e2.printStackTrace(); } } if (checkForOptRunStatus) { try { String runName = params.getOptionValue("getOptRunStatus"); // runId -> // ((Status,%),(ProgramConfig,DataConfig)->(QualityMeasure->(ParameterSet->Quality))) Map<String, Pair<Pair<RUN_STATUS, Float>, Map<Pair<String, String>, Map<String, Pair<Map<String, String>, String>>>>> optStatus = null; if ((optStatus = this.getMyOptimizationRunStatus()) != null && optStatus.size() > 0) { RUN_STATUS newStatus; Float percent; if (!optStatus.containsKey(runName)) { log.info("No run with name " + runName + " running."); return; } newStatus = optStatus.get(runName).getFirst().getFirst(); percent = optStatus.get(runName).getFirst().getSecond(); System.out.println(); System.out.println("\r Status:\t" + newStatus + " " + percent + "%"); Map<Pair<String, String>, Map<String, Pair<Map<String, String>, String>>> qualities = optStatus .get(runName).getSecond(); // print the quality measures; just take them from the // first pair of programConfig and dataConfig (runnable) String[] qualityMeasures = qualities.values().iterator().next().keySet() .toArray(new String[0]); Arrays.sort(qualityMeasures); int pos = 0; while (true) { boolean foundMeasure = false; for (String measure : qualityMeasures) { if (pos < measure.length()) { System.out.printf("\t%s", measure.charAt(pos)); foundMeasure = true; } else System.out.print("\t"); } System.out.println(); if (!foundMeasure) break; pos++; } // 06.06.2014: added sets to keep order when printing // the results Set<String> programConfigs = new HashSet<String>(); Set<String> dataConfigs = new HashSet<String>(); for (Pair<String, String> pcDcPair : qualities.keySet()) { programConfigs.add(pcDcPair.getFirst()); dataConfigs.add(pcDcPair.getSecond()); } for (String programConfig : programConfigs) { System.out.printf("%s:\n", programConfig); for (String dataConfig : dataConfigs) { System.out.printf("-- %s:\n", dataConfig); Pair<String, String> pcDcPair = Pair.getPair(programConfig, dataConfig); Map<String, Pair<Map<String, String>, String>> qualitiesPcDc = qualities .get(pcDcPair); for (String measure : qualityMeasures) { if (!qualitiesPcDc.containsKey(measure)) { System.out.print("\t"); continue; } String quality = qualitiesPcDc.get(measure).getSecond(); if (quality.equals("NT")) System.out.print("\tNT"); else { double qualityDouble = Double.valueOf(quality); if (Double.isInfinite(qualityDouble)) System.out.printf("\t%s%s", qualityDouble < 0 ? "-" : "", "Inf"); else System.out.printf("\t%.4f", qualityDouble); } } System.out.println(); } } } System.out.println(); } catch (ConnectException e2) { this.log.warn("The server terminated the connection..."); } catch (RemoteException e2) { e2.printStackTrace(); } } } catch (RemoteException e) { e.printStackTrace(); } }
From source file:com.analog.lyric.dimple.solvers.core.parameterizedMessages.MultivariateNormalParameters.java
private final boolean isInfiniteIdentity(double[][] m) { for (int i = 0; i < m.length; i++) { if (!Double.isInfinite(m[i][i])) return false; }/* w ww . ja v a 2 s . c om*/ return true; }
From source file:org.ojai.json.impl.JsonDocumentBuilder.java
private boolean isWholeNumberInLongRange(double value) { return (value == Math.floor(value)) && !Double.isInfinite(value) && (value >= Long.MIN_VALUE && value <= Long.MAX_VALUE); }
From source file:org.ohmage.request.survey.SurveyResponseReadRequest.java
/** * Builds the output depending on the state of this request and whatever * output format the requester selected. *//*from ww w.j a v a 2 s. c om*/ @Override public void respond(HttpServletRequest httpRequest, HttpServletResponse httpResponse) { LOGGER.info("Responding to the survey response read request."); if (isFailed()) { super.respond(httpRequest, httpResponse, (JSONObject) null); return; } // Create a writer for the HTTP response object. Writer writer = null; try { writer = new BufferedWriter(new OutputStreamWriter(getOutputStream(httpRequest, httpResponse))); } catch (IOException e) { LOGGER.error("Unable to write response message. Aborting.", e); return; } // Sets the HTTP headers to disable caching. expireResponse(httpResponse); String resultString = ""; if (!isFailed()) { try { boolean allColumns = columns.equals(URN_SPECIAL_ALL_LIST); // TODO: I am fairly confident that these two branches can be // merged further and subsequently cleaned up, but I don't have // the time to tackle it right now. if (OutputFormat.JSON_ROWS.equals(outputFormat)) { httpResponse.setContentType("application/json"); JSONObject result = new JSONObject(); result.put(JSON_KEY_RESULT, RESULT_SUCCESS); List<String> uniqueSurveyIds = new LinkedList<String>(); List<String> uniquePromptIds = new LinkedList<String>(); JSONArray results = new JSONArray(); for (SurveyResponse surveyResponse : getSurveyResponses()) { uniqueSurveyIds.add(surveyResponse.getSurvey().getId()); uniquePromptIds.addAll(surveyResponse.getPromptIds()); JSONObject currResult; currResult = surveyResponse.toJson(allColumns || columns.contains(ColumnKey.USER_ID), allColumns || false, allColumns || columns.contains(ColumnKey.CONTEXT_CLIENT), allColumns || columns.contains(ColumnKey.SURVEY_PRIVACY_STATE), allColumns || columns.contains(ColumnKey.CONTEXT_EPOCH_MILLIS), allColumns || columns.contains(ColumnKey.CONTEXT_TIMEZONE), allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_STATUS), false, allColumns || columns.contains(ColumnKey.SURVEY_ID), allColumns || columns.contains(ColumnKey.SURVEY_TITLE), allColumns || columns.contains(ColumnKey.SURVEY_DESCRIPTION), allColumns || columns.contains(ColumnKey.CONTEXT_LAUNCH_CONTEXT_SHORT), allColumns || columns.contains(ColumnKey.CONTEXT_LAUNCH_CONTEXT_LONG), allColumns || columns.contains(ColumnKey.PROMPT_RESPONSE), false, (((returnId == null) ? false : returnId) || allColumns || columns.contains(ColumnKey.SURVEY_RESPONSE_ID)), ((collapse != null) && collapse)); if (allColumns || columns.contains(ColumnKey.CONTEXT_DATE)) { currResult.put("date", DateTimeUtils.getIso8601DateString(surveyResponse.getDate(), false)); } if (allColumns || columns.contains(ColumnKey.CONTEXT_TIMESTAMP)) { currResult.put("timestamp", DateTimeUtils.getIso8601DateString(surveyResponse.getDate(), true)); } if (allColumns || columns.contains(ColumnKey.CONTEXT_UTC_TIMESTAMP)) { Calendar tmpCalendar = Calendar.getInstance(surveyResponse.getTimezone().toTimeZone()); tmpCalendar.setTimeInMillis(surveyResponse.getTime()); currResult.put("utc_timestamp", DateTimeUtils.getIso8601DateString( new DateTime(surveyResponse.getTime(), DateTimeZone.UTC), true)); } if (allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_ACCURACY)) { Location location = surveyResponse.getLocation(); if (location == null) { currResult.put(Location.LocationColumnKey.ACCURACY.toString(false), JSONObject.NULL); } else { double accuracy = location.getAccuracy(); if (Double.isInfinite(accuracy) || Double.isNaN(accuracy)) { currResult.put(Location.LocationColumnKey.ACCURACY.toString(false), JSONObject.NULL); } else { currResult.put(Location.LocationColumnKey.ACCURACY.toString(false), accuracy); } } } if (allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_LATITUDE)) { Location location = surveyResponse.getLocation(); if (location == null) { currResult.put(Location.LocationColumnKey.LATITUDE.toString(false), JSONObject.NULL); } else { double latitude = location.getLatitude(); if (Double.isInfinite(latitude) || Double.isNaN(latitude)) { currResult.put(Location.LocationColumnKey.LATITUDE.toString(false), JSONObject.NULL); } else { currResult.put(Location.LocationColumnKey.LATITUDE.toString(false), latitude); } } } if (allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_LONGITUDE)) { Location location = surveyResponse.getLocation(); if (location == null) { currResult.put(Location.LocationColumnKey.LONGITUDE.toString(false), JSONObject.NULL); } else { double longitude = location.getLongitude(); if (Double.isInfinite(longitude) || Double.isNaN(longitude)) { currResult.put(Location.LocationColumnKey.LONGITUDE.toString(false), JSONObject.NULL); } else { currResult.put(Location.LocationColumnKey.LONGITUDE.toString(false), longitude); } } } if (allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_PROVIDER)) { Location location = surveyResponse.getLocation(); if (location == null) { currResult.put(Location.LocationColumnKey.PROVIDER.toString(false), JSONObject.NULL); } else { currResult.put(Location.LocationColumnKey.PROVIDER.toString(false), location.getProvider()); } } if (allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_TIMESTAMP)) { Location location = surveyResponse.getLocation(); if (location == null) { currResult.put("location_timestamp", JSONObject.NULL); } else { currResult.put("location_timestamp", location.getTime()); } } if (allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_TIMESTAMP)) { Location location = surveyResponse.getLocation(); if (location == null) { currResult.put("location_timezone", JSONObject.NULL); } else { currResult.put("location_timezone", location.getTimeZone().getID()); } } results.put(currResult); } result.put(JSON_KEY_DATA, results); // Metadata if ((suppressMetadata == null) || (!suppressMetadata)) { JSONObject metadata = new JSONObject(); metadata.put(JSON_KEY_NUM_SURVEYS, uniqueSurveyIds.size()); metadata.put(JSON_KEY_NUM_PROMPTS, uniquePromptIds.size()); Collection<String> columnsResult = new HashSet<String>(columns.size()); // If it contains the special 'all' value, add them // all. if (columns.contains(URN_SPECIAL_ALL)) { ColumnKey[] values = SurveyResponse.ColumnKey.values(); for (int i = 0; i < values.length; i++) { columnsResult.add(values[i].toString()); } } // Otherwise, add cycle through them else { for (ColumnKey columnKey : columns) { columnsResult.add(columnKey.toString()); } } // Check if prompt responses were requested, and, if // so, add them to the list of columns. if (columns.contains(SurveyResponse.ColumnKey.PROMPT_RESPONSE) || columns.contains(URN_SPECIAL_ALL)) { for (String promptId : uniquePromptIds) { columnsResult.add(ColumnKey.URN_PROMPT_ID_PREFIX + promptId); } } // Add it to the metadata result. metadata.put(JSON_KEY_ITEMS, columnsResult); // Add the total count to the metadata. metadata.put(JSON_KEY_TOTAL_NUM_RESULTS, getSurveyResponseCount()); result.put(JSON_KEY_METADATA, metadata); } if ((prettyPrint != null) && prettyPrint) { resultString = result.toString(4); } else { resultString = result.toString(); } } else if (OutputFormat.JSON_COLUMNS.equals(outputFormat) || OutputFormat.CSV.equals(outputFormat)) { JSONArray usernames = new JSONArray(); JSONArray clients = new JSONArray(); JSONArray privacyStates = new JSONArray(); JSONArray dates = new JSONArray(); JSONArray timestamps = new JSONArray(); JSONArray utcTimestamps = new JSONArray(); JSONArray epochMillisTimestamps = new JSONArray(); JSONArray timezones = new JSONArray(); JSONArray locationStatuses = new JSONArray(); JSONArray locationLongitude = new JSONArray(); JSONArray locationLatitude = new JSONArray(); JSONArray locationTimestamp = new JSONArray(); JSONArray locationTimeZone = new JSONArray(); JSONArray locationAccuracy = new JSONArray(); JSONArray locationProvider = new JSONArray(); JSONArray surveyIds = new JSONArray(); JSONArray surveyTitles = new JSONArray(); JSONArray surveyDescriptions = new JSONArray(); JSONArray launchContexts = new JSONArray(); JSONArray surveyResponseIds = new JSONArray(); JSONArray counts = new JSONArray(); Map<String, JSONObject> prompts = new HashMap<String, JSONObject>(); // If the user requested to know information about prompt // responses, populate the prompt contexts with the // information about each of the prompts that were // requested. if (allColumns || columns.contains(ColumnKey.PROMPT_RESPONSE)) { // If the user-supplied list of survey IDs is present, if (getSurveyIds() != null) { Map<String, Survey> campaignSurveys = getCampaign().getSurveys(); // If the user asked for all surveys for this // campaign, then populate the prompt information // with all of the data about all of the prompts in // all of the surveys in this campaign. if (getSurveyIds().equals(URN_SPECIAL_ALL_LIST)) { for (Survey currSurvey : campaignSurveys.values()) { populatePrompts(currSurvey.getSurveyItems(), prompts); } } // Otherwise, populate the prompt information only // with the data about the requested surveys. else { for (String surveyId : this.getSurveyIds()) { populatePrompts(campaignSurveys.get(surveyId).getSurveyItems(), prompts); } } } // If the user-supplied list of prompt IDs is present, else if (getPromptIds() != null) { // If the user asked for all prompts for this // campaign, then populate the prompt information // with all of the data about all of the prompts in // this campaign. if (getPromptIds().equals(URN_SPECIAL_ALL_LIST)) { for (Survey currSurvey : getCampaign().getSurveys().values()) { populatePrompts(currSurvey.getSurveyItems(), prompts); } } // Otherwise, populate the prompt information with // the data about only the requested prompts. else { int currNumPrompts = 0; Map<Integer, SurveyItem> tempPromptMap = new HashMap<Integer, SurveyItem>( getPromptIds().size()); for (String promptId : getPromptIds()) { try { tempPromptMap.put(currNumPrompts, getCampaign().getPrompt( getCampaign().getSurveyIdForPromptId(promptId), promptId)); } catch (DomainException e) { LOGGER.error( "A prompt ID that should have already been validated, appears to no longer exist.", e); setFailed(); super.respond(httpRequest, httpResponse, (JSONObject) null); } currNumPrompts++; } populatePrompts(tempPromptMap, prompts); } } } // Process each of the survey responses and keep track of // the number of prompt responses. int numSurveyResponses = getSurveyResponses().size(); int numPromptResponses = 0; for (SurveyResponse surveyResponse : getSurveyResponses()) { try { numPromptResponses += processResponses(allColumns, surveyResponse, surveyResponse.getResponses(), prompts, usernames, clients, privacyStates, dates, timestamps, utcTimestamps, epochMillisTimestamps, timezones, locationStatuses, locationLongitude, locationLatitude, locationTimestamp, locationTimeZone, locationAccuracy, locationProvider, surveyIds, surveyTitles, surveyDescriptions, launchContexts, surveyResponseIds, counts); } catch (DomainException e) { LOGGER.error("There was a problem aggregating the responses.", e); setFailed(); super.respond(httpRequest, httpResponse, (JSONObject) null); } } // Add all of the applicable output stuff. JSONObject result = new JSONObject(); JSONArray keysOrdered = new JSONArray(); // For each of the requested columns, add their respective // data to the result in a specific order per Hongsuda's // request. if (allColumns || columns.contains(ColumnKey.SURVEY_ID)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, surveyIds); result.put(ColumnKey.SURVEY_ID.toString(), values); keysOrdered.put(ColumnKey.SURVEY_ID.toString()); } if (allColumns || columns.contains(ColumnKey.SURVEY_TITLE)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, surveyTitles); result.put(ColumnKey.SURVEY_TITLE.toString(), values); keysOrdered.put(ColumnKey.SURVEY_TITLE.toString()); } if (allColumns || columns.contains(ColumnKey.SURVEY_DESCRIPTION)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, surveyDescriptions); result.put(ColumnKey.SURVEY_DESCRIPTION.toString(), values); keysOrdered.put(ColumnKey.SURVEY_DESCRIPTION.toString()); } if (allColumns || columns.contains(ColumnKey.USER_ID)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, usernames); result.put(ColumnKey.USER_ID.toString(), values); keysOrdered.put(ColumnKey.USER_ID.toString()); } if (allColumns || columns.contains(ColumnKey.CONTEXT_CLIENT)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, clients); result.put(ColumnKey.CONTEXT_CLIENT.toString(), values); keysOrdered.put(ColumnKey.CONTEXT_CLIENT.toString()); } if (allColumns || columns.contains(ColumnKey.CONTEXT_UTC_TIMESTAMP)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, utcTimestamps); result.put(ColumnKey.CONTEXT_UTC_TIMESTAMP.toString(), values); keysOrdered.put(ColumnKey.CONTEXT_UTC_TIMESTAMP.toString()); } if (allColumns || columns.contains(ColumnKey.CONTEXT_EPOCH_MILLIS)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, epochMillisTimestamps); result.put(ColumnKey.CONTEXT_EPOCH_MILLIS.toString(), values); keysOrdered.put(ColumnKey.CONTEXT_EPOCH_MILLIS.toString()); } if (allColumns || columns.contains(ColumnKey.CONTEXT_DATE)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, timestamps); result.put(ColumnKey.CONTEXT_DATE.toString(), values); keysOrdered.put(ColumnKey.CONTEXT_DATE.toString()); } if (allColumns || columns.contains(ColumnKey.CONTEXT_TIMESTAMP)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, timestamps); result.put(ColumnKey.CONTEXT_TIMESTAMP.toString(), values); keysOrdered.put(ColumnKey.CONTEXT_TIMESTAMP.toString()); } if (allColumns || columns.contains(ColumnKey.CONTEXT_TIMEZONE)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, timezones); result.put(ColumnKey.CONTEXT_TIMEZONE.toString(), values); keysOrdered.put(ColumnKey.CONTEXT_TIMEZONE.toString()); } if (allColumns || columns.contains(ColumnKey.PROMPT_RESPONSE)) { List<String> unorderedList = new LinkedList<String>(); for (String promptId : prompts.keySet()) { result.put(SurveyResponse.ColumnKey.URN_PROMPT_ID_PREFIX + promptId, prompts.get(promptId)); unorderedList.add(SurveyResponse.ColumnKey.URN_PROMPT_ID_PREFIX + promptId); } Collections.sort(unorderedList); for (String columnId : unorderedList) { keysOrdered.put(columnId); } } if (allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_STATUS)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, locationStatuses); result.put(ColumnKey.CONTEXT_LOCATION_STATUS.toString(), values); keysOrdered.put(ColumnKey.CONTEXT_LOCATION_STATUS.toString()); } if (allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_LATITUDE)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, locationLatitude); result.put(ColumnKey.CONTEXT_LOCATION_LATITUDE.toString(), values); keysOrdered.put(ColumnKey.CONTEXT_LOCATION_LATITUDE.toString()); } if (allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_LONGITUDE)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, locationLongitude); result.put(ColumnKey.CONTEXT_LOCATION_LONGITUDE.toString(), values); keysOrdered.put(ColumnKey.CONTEXT_LOCATION_LONGITUDE.toString()); } if (allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_PROVIDER)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, locationProvider); result.put(ColumnKey.CONTEXT_LOCATION_PROVIDER.toString(), values); keysOrdered.put(ColumnKey.CONTEXT_LOCATION_PROVIDER.toString()); } if (allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_TIMESTAMP)) { JSONObject timeValues = new JSONObject(); timeValues.put(JSON_KEY_VALUES, locationTimestamp); result.put(ColumnKey.CONTEXT_LOCATION_TIMESTAMP.toString(), timeValues); keysOrdered.put(ColumnKey.CONTEXT_LOCATION_TIMESTAMP.toString()); } if (allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_TIMEZONE)) { JSONObject timeZoneValues = new JSONObject(); timeZoneValues.put(JSON_KEY_VALUES, locationTimeZone); result.put(ColumnKey.CONTEXT_LOCATION_TIMEZONE.toString(), timeZoneValues); keysOrdered.put(ColumnKey.CONTEXT_LOCATION_TIMEZONE.toString()); } if (allColumns || columns.contains(ColumnKey.CONTEXT_LOCATION_ACCURACY)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, locationAccuracy); result.put(ColumnKey.CONTEXT_LOCATION_ACCURACY.toString(), values); keysOrdered.put(ColumnKey.CONTEXT_LOCATION_ACCURACY.toString()); } if (allColumns || columns.contains(ColumnKey.SURVEY_PRIVACY_STATE)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, privacyStates); result.put(ColumnKey.SURVEY_PRIVACY_STATE.toString(), values); keysOrdered.put(ColumnKey.SURVEY_PRIVACY_STATE.toString()); } if (allColumns || columns.contains(ColumnKey.CONTEXT_LAUNCH_CONTEXT_LONG)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, launchContexts); result.put(ColumnKey.CONTEXT_LAUNCH_CONTEXT_LONG.toString(), values); keysOrdered.put(ColumnKey.CONTEXT_LAUNCH_CONTEXT_LONG.toString()); } if (columns.contains(ColumnKey.CONTEXT_LAUNCH_CONTEXT_SHORT)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, launchContexts); result.put(ColumnKey.CONTEXT_LAUNCH_CONTEXT_SHORT.toString(), values); keysOrdered.put(ColumnKey.CONTEXT_LAUNCH_CONTEXT_SHORT.toString()); } if (allColumns || columns.contains(ColumnKey.SURVEY_RESPONSE_ID)) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, surveyResponseIds); result.put(ColumnKey.SURVEY_RESPONSE_ID.toString(), values); keysOrdered.put(ColumnKey.SURVEY_RESPONSE_ID.toString()); } if ((collapse != null) && collapse) { JSONObject values = new JSONObject(); values.put(JSON_KEY_VALUES, counts); result.put("urn:ohmage:context:count", values); keysOrdered.put("urn:ohmage:context:count"); } // If metadata is not suppressed, create it. JSONObject metadata = null; if ((suppressMetadata == null) || (!suppressMetadata)) { metadata = new JSONObject(); metadata.put(InputKeys.CAMPAIGN_URN, getCampaignId()); metadata.put(JSON_KEY_NUM_SURVEYS, getSurveyResponses().size()); metadata.put(JSON_KEY_NUM_PROMPTS, numPromptResponses); // Add the total count to the metadata. metadata.put(JSON_KEY_TOTAL_NUM_RESULTS, getSurveyResponseCount()); } if (OutputFormat.JSON_COLUMNS.equals(outputFormat)) { httpResponse.setContentType("application/json"); JSONObject resultJson = new JSONObject(); resultJson.put(JSON_KEY_RESULT, RESULT_SUCCESS); int numHeaders = keysOrdered.length(); for (int i = 0; i < numHeaders; i++) { String header = keysOrdered.getString(i); if (header.endsWith(":value") || header.endsWith(":key")) { result.remove(header); keysOrdered.remove(i); i--; numHeaders--; } else if (header.endsWith(":label")) { String prunedHeader = header.substring(0, header.length() - 6); result.put(prunedHeader, result.get(header)); result.remove(header); keysOrdered.put(i, prunedHeader); } } if ((suppressMetadata == null) || (!suppressMetadata)) { JSONArray itemsJson = new JSONArray(); Iterator<?> keys = result.keys(); while (keys.hasNext()) { itemsJson.put(keys.next()); } metadata.put("items", itemsJson); resultJson.put(JSON_KEY_METADATA, metadata); } resultJson.put(JSON_KEY_DATA, result); if ((prettyPrint != null) && prettyPrint) { resultString = resultJson.toString(4); } else { resultString = resultJson.toString(); } } // For CSV output, else if (OutputFormat.CSV.equals(outputFormat)) { // Mark it as an attachment. httpResponse.setContentType("text/csv"); httpResponse.setHeader("Content-Disposition", "attachment; filename=" + getCampaign().getName() + ".csv"); StringBuilder resultBuilder = new StringBuilder(); // If the metadata is not suppressed, add it to the // output builder. if ((suppressMetadata == null) || (!suppressMetadata)) { metadata.put(JSON_KEY_RESULT, RESULT_SUCCESS); resultBuilder.append("## begin metadata\n"); resultBuilder.append('#').append(metadata.toString().replace(',', ';')).append('\n'); resultBuilder.append("## end metadata\n"); // Add the prompt contexts to the output builder if // prompts were desired. if (allColumns || columns.contains(ColumnKey.PROMPT_RESPONSE)) { resultBuilder.append("## begin prompt contexts\n"); for (String promptId : prompts.keySet()) { JSONObject promptJson = new JSONObject(); // Use the already-generated JSON from each of // the prompts. promptJson.put(promptId, prompts.get(promptId).get(JSON_KEY_CONTEXT)); resultBuilder.append('#').append(promptJson.toString()).append('\n'); } resultBuilder.append("## end prompt contexts\n"); } // Begin the data section of the CSV. resultBuilder.append("## begin data\n"); } // Get the number of keys. int keyLength = keysOrdered.length(); // Create a comma-separated list of the header names. for (int i = 0; i < keyLength; i++) { String header = keysOrdered.getString(i); if (header.startsWith("urn:ohmage:")) { header = header.substring(11); if (header.startsWith("prompt:id:")) { header = header.substring(10); } } resultBuilder.append(header); if ((i + 1) != keyLength) { resultBuilder.append(','); } } resultBuilder.append('\n'); // For each of the responses, for (int i = 0; i < numSurveyResponses; i++) { for (int j = 0; j < keyLength; j++) { Object currResult = result.getJSONObject(keysOrdered.getString(j)) .getJSONArray(JSON_KEY_VALUES).get(i); if (JSONObject.NULL.equals(currResult)) { resultBuilder.append(""); } else { resultBuilder.append("\"" + currResult.toString().replace("\"", "\"\"") + "\""); } if ((j + 1) != keyLength) { resultBuilder.append(','); } } resultBuilder.append('\n'); } if ((suppressMetadata == null) || (!suppressMetadata)) { resultBuilder.append("## end data"); } resultString = resultBuilder.toString(); } } } catch (JSONException e) { LOGGER.error(e.toString(), e); setFailed(); } catch (IllegalStateException e) { LOGGER.error(e.toString(), e); setFailed(); } catch (DomainException e) { LOGGER.error(e.toString(), e); setFailed(); } } if (isFailed()) { httpResponse.setContentType("application/json"); resultString = this.getFailureMessage(); } try { writer.write(resultString); } catch (ClientAbortException e) { LOGGER.info("The client hung up unexpectedly.", e); } catch (IOException e) { LOGGER.warn("Unable to write response message. Aborting.", e); } // Close it. try { writer.close(); } catch (ClientAbortException e) { LOGGER.info("The client hung up unexpectedly.", e); } catch (IOException e) { LOGGER.warn("Unable to close the writer.", e); } }
From source file:musite.ui.MusiteResultPanel.java
private void setResult() { PredictionModel model = selectedModel(); maxScore = result.getMaxPredictionScore(model); minScore = result.getMinPredictionScore(model); SpecificityEstimator est = model.getSpecEstimator(); if (est != null) { double spec1 = est.threshold(1.0); double spec0 = est.threshold(0.0); if (maxScore < spec1) { maxScore = spec1;//from w w w . j a va 2 s .c o m } if (minScore > spec0) { minScore = spec0; } threshold = result.getThreshold(model); if (Double.isInfinite(threshold)) { //specificity = 0.95; threshold = est.threshold(0.95); } else { specificity = est.specificity(threshold); } } else { this.threshold = (maxScore + minScore) / 2; } result.setThreshold(model, threshold); double eps = (maxScore - minScore) / maxTick; // one more tic each side maxScore += eps; minScore -= eps; // set ui ignoreSlideChangeEvent = true; setSliderTitleModel(); String textSpec; if (est == null) { textSpec = "N/A"; specificityTextField.setEditable(false); } else { textSpec = String.format("%.2f", specificity * 100); } specificityTextField.setText(textSpec); scoreCutoffTextField.setText(String.format("%.2f", threshold)); setSliderLabels(); setMapScoreColor(); specificitySlider.setValue((int) Math.round(maxTick * (threshold - minScore) / (maxScore - minScore))); ignoreSlideChangeEvent = false; }
From source file:net.pms.util.Rational.java
/** * Returns a {@link Rational} whose value is {@code (this + value)}. * * @param value the value to be added to this {@link Rational}. * @return The addition result./*from w w w . j ava 2 s .c o m*/ */ @Nonnull public Rational add(double value) { if (isNaN() || Double.isNaN(value)) { return NaN; } if (value == 0d) { return this; } if (isInfinite()) { if (Double.isInfinite(value) && signum() != Math.signum(value)) { return NaN; // Infinity minus infinity } return this; } return add(valueOf(value)); }
From source file:org.eclipse.january.dataset.Stats.java
/** * @param a dataset//from w ww . j av a2 s . c o m * @param dtype * @param ignoreInvalids see {@link IDataset#max(boolean...)} * @return typed product of all items in dataset * @since 2.0 */ public static Object typedProduct(final Dataset a, final int dtype, final boolean... ignoreInvalids) { final boolean ignoreNaNs; final boolean ignoreInfs; if (a.hasFloatingPointElements()) { ignoreNaNs = ignoreInvalids != null && ignoreInvalids.length > 0 ? ignoreInvalids[0] : false; ignoreInfs = ignoreInvalids != null && ignoreInvalids.length > 1 ? ignoreInvalids[1] : ignoreNaNs; } else { ignoreNaNs = false; ignoreInfs = false; } if (a.isComplex()) { IndexIterator it = a.getIterator(); double rv = 1, iv = 0; while (it.hasNext()) { final double r1 = a.getElementDoubleAbs(it.index); final double i1 = a.getElementDoubleAbs(it.index + 1); if (ignoreNaNs && (Double.isNaN(r1) || Double.isNaN(i1))) { continue; } if (ignoreInfs && (Double.isInfinite(r1) || Double.isInfinite(i1))) { continue; } final double tv = r1 * rv - i1 * iv; iv = r1 * iv + i1 * rv; rv = tv; if (Double.isNaN(rv) && Double.isNaN(iv)) { break; } } return new Complex(rv, iv); } IndexIterator it = a.getIterator(); final int is; final long[] lresults; final double[] dresults; switch (dtype) { case Dataset.BOOL: case Dataset.INT8: case Dataset.INT16: case Dataset.INT32: case Dataset.INT64: long lresult = 1; while (it.hasNext()) { lresult *= a.getElementLongAbs(it.index); } return new Long(lresult); case Dataset.ARRAYINT8: case Dataset.ARRAYINT16: case Dataset.ARRAYINT32: case Dataset.ARRAYINT64: lresult = 1; is = a.getElementsPerItem(); lresults = new long[is]; for (int j = 0; j < is; j++) { lresults[j] = 1; } while (it.hasNext()) { for (int j = 0; j < is; j++) lresults[j] *= a.getElementLongAbs(it.index + j); } return lresults; case Dataset.FLOAT32: case Dataset.FLOAT64: double dresult = 1.; while (it.hasNext()) { final double x = a.getElementDoubleAbs(it.index); if (ignoreNaNs && Double.isNaN(x)) { continue; } if (ignoreInfs && Double.isInfinite(x)) { continue; } dresult *= x; if (Double.isNaN(dresult)) { break; } } return Double.valueOf(dresult); case Dataset.ARRAYFLOAT32: case Dataset.ARRAYFLOAT64: is = a.getElementsPerItem(); double[] vals = new double[is]; dresults = new double[is]; for (int j = 0; j < is; j++) { dresults[j] = 1.; } while (it.hasNext()) { boolean okay = true; for (int j = 0; j < is; j++) { final double val = a.getElementDoubleAbs(it.index + j); if (ignoreNaNs && Double.isNaN(val)) { okay = false; break; } if (ignoreInfs && Double.isInfinite(val)) { okay = false; break; } vals[j] = val; } if (okay) { for (int j = 0; j < is; j++) { double val = vals[j]; dresults[j] *= val; } } } return dresults; } return null; }
From source file:org.gwaspi.reports.GenericReportGenerator.java
public static XYDataset getSampleHetzygDataset(SampleQAHetzygPlotZoom sampleQAHetzygPlotZoom, OperationKey operationKey) throws IOException { XYDataset resultXYDataset;// ww w. j a v a2 s . c o m QASamplesOperationDataSet qaSamplesOpDS = (QASamplesOperationDataSet) OperationManager .generateOperationDataSet(operationKey); OperationMetadata rdOPMetadata = getOperationService().getOperationMetadata(operationKey); Map<Integer, SampleKey> samples = qaSamplesOpDS.getSamplesKeysSource().getIndicesMap(); List<Double> hetzyRatios = (List) qaSamplesOpDS.getHetzyRatios(-1, -1); List<Double> missingRatios = (List) qaSamplesOpDS.getMissingRatios(-1, -1); //<editor-fold defaultstate="expanded" desc="BUILD XYDataset"> XYSeries dataSeries = new XYSeries(""); int count = 0; Map<String, SampleKey> samplesLabeler = new LinkedHashMap<String, SampleKey>(); for (SampleKey tmpSampleKey : samples.values()) { double tmpHetzyVal = hetzyRatios.get(count); double tmpMissratVal = missingRatios.get(count); if (Double.isNaN(tmpHetzyVal) || Double.isInfinite(tmpHetzyVal)) { tmpHetzyVal = 0; } if (Double.isNaN(tmpMissratVal) || Double.isInfinite(tmpMissratVal)) { tmpMissratVal = 0; } dataSeries.add(tmpHetzyVal, tmpMissratVal); samplesLabeler.put(count + "_" + tmpMissratVal + "_" + tmpHetzyVal, tmpSampleKey); count++; } sampleQAHetzygPlotZoom.setLabelerMap(samplesLabeler); dataSeries.setDescription(rdOPMetadata.getDescription()); resultXYDataset = new XYSeriesCollection(dataSeries); //</editor-fold> return resultXYDataset; }
From source file:org.eclipse.dataset.AbstractCompoundDataset.java
/** * Calculate minimum and maximum for a dataset *///from w w w. j a v a 2s .co m protected void calculateHash() { IndexIterator iter = getIterator(); double hash = 0; while (iter.hasNext()) { for (int j = 0; j < isize; j++) { final double val = getElementDoubleAbs(iter.index + j); if (Double.isInfinite(val) || Double.isNaN(val)) { hash = (hash * 19) % Integer.MAX_VALUE; } else { hash = (hash * 19 + val) % Integer.MAX_VALUE; } } } int ihash = ((int) hash) * 19 + getDtype() * 17 + getElementsPerItem(); setStoredValue(STORE_SHAPELESS_HASH, ihash); }