List of usage examples for java.util HashMap containsKey
public boolean containsKey(Object key)
From source file:com.iss.android.wearable.datalayer.MainActivity.java
private void showCurrentAppState() { if (SensorsDataService.itself == null) { return;/*from w w w . j av a 2s. c o m*/ } // get measured states HashMap<String, Boolean> recordedActivities = SensorsDataService.getRecordedActivities(); ImageButton morningHR = (ImageButton) findViewById(R.id.morningHR); ImageButton trainingHR = (ImageButton) findViewById(R.id.trainingHR); ImageButton startCooldown = (ImageButton) findViewById(R.id.startCooldown); ImageButton continueCooldown = (ImageButton) findViewById(R.id.continueCooldown); ImageButton eveningHR = (ImageButton) findViewById(R.id.eveningHR); morningHR.setBackgroundColor(recordedActivities.containsKey("MorningHR") ? Color.GREEN : Color.GRAY); trainingHR.setBackgroundColor(recordedActivities.containsKey("TrainingHR") ? Color.GREEN : Color.GRAY); startCooldown.setBackgroundColor(recordedActivities.containsKey("Cooldown") ? Color.GREEN : Color.GRAY); continueCooldown.setBackgroundColor(recordedActivities.containsKey("Recovery") ? Color.GREEN : Color.GRAY); eveningHR.setBackgroundColor(recordedActivities.containsKey("EveningHR") ? Color.GREEN : Color.GRAY); int inProgressColor = Color.argb(255, 255, 165, 0); if (SensorsDataService.itself.currentState.equals("Cooldown")) { startCooldown.setBackgroundColor(inProgressColor); } if (SensorsDataService.itself.currentState.equals("TrainingHR")) { trainingHR.setBackgroundColor(inProgressColor); } if (SensorsDataService.itself.currentState.equals("Recovery")) { continueCooldown.setBackgroundColor(inProgressColor); } if (SensorsDataService.itself.currentState.equals("MorningHR")) { morningHR.setBackgroundColor(inProgressColor); } if (SensorsDataService.itself.currentState.equals("EveningHR")) { eveningHR.setBackgroundColor(inProgressColor); } }
From source file:de.gfz_potsdam.datasync.Datasync.java
private void addContainerMembers(String parentdir, Container parent, ArrayList<VersionableResource> children) throws Exception { if (parent == null || children == null) return;/*from ww w . j a va2 s .c om*/ HashMap<String, VersionableResource> ids = new HashMap<String, VersionableResource>(); for (VersionableResource child : children) { ids.put(child.getObjid(), child); } //do not add twice if (parent.getStructMap() != null) { for (MemberRef m : parent.getStructMap()) { if (ids.containsKey(m.getObjid())) ids.remove(m.getObjid()); } } if (ids.isEmpty()) return; DateTime r = srv.containerAddMembers(parent, ids.values()); File dir = new File(directory + File.separator + parentdir); App.db.storeMapping(parentdir, parent.getObjid(), dir.lastModified(), r, SyncDB.DIRECTORY); log.log(Level.INFO, "added members : {0}", new Object[] { dir.getAbsoluteFile() }); }
From source file:ca.mcgill.cs.creco.logic.ScoredAttribute.java
private void setStringStats(ArrayList<TypedValue> pValues) { HashMap<String, Double> stringCounts = new HashMap<String, Double>(); ArrayList<TypedValue> dictionary = new ArrayList<TypedValue>(); double count; double totalCount = 0; for (TypedValue tv : pValues) { if (tv.isString()) { totalCount += 1;// w ww . j a va2 s . c o m if (stringCounts.containsKey(tv.getString())) { count = stringCounts.get(tv.getString()); } else { count = 0; } stringCounts.put(tv.getString(), count + 1); } } double entropy = 0; double maxCount = 0; String mode = ""; for (String key : stringCounts.keySet()) { dictionary.add(new TypedValue(key)); if (stringCounts.get(key) > maxCount) { mode = key; maxCount = stringCounts.get(key); } double probKey = stringCounts.get(key) / totalCount; entropy = entropy - probKey * (Math.log(probKey)); } aStringValues = dictionary; aDefaultValue = new TypedValue(mode); if (!Double.isNaN(entropy)) { aEntropy = entropy; } else { aEntropy = 0; } // Compute Correlation and rankings aLabelMeanScores = new HashMap<String, Double>(); NominalCorrelator nominalCorrelator = new NominalCorrelator(aCategory); ArrayList<Map.Entry<String, Double>> entryList = new ArrayList<Map.Entry<String, Double>>(); entryList.addAll(nominalCorrelator.getLabelMeanScores(aAttributeID).entrySet()); sortEntries(entryList); int rank = 1; for (Map.Entry<String, Double> entry : entryList) { aLabelMeanScores.put(entry.getKey(), entry.getValue()); aStringValueRank.put(entry.getKey(), rank); rank++; } aCorrelation = nominalCorrelator.computeAttributeWeight(aAttributeID); }
From source file:com.krawler.spring.documents.documentDAOImpl.java
@Override public KwlReturnObject saveDocOwners(HashMap<String, Object> requestParams) throws Exception { List ll = new ArrayList(); try {//from w ww .j a v a 2 s . c o m String docid = ""; if (requestParams.containsKey("docid") && requestParams.get("docid") != null) { docid = requestParams.get("docid").toString(); } String owners = ""; if (requestParams.containsKey("owners") && requestParams.get("owners") != null) { owners = requestParams.get("owners").toString(); } String mainowner = ""; if (requestParams.containsKey("mainOwner") && requestParams.get("mainOwner") != null) { mainowner = requestParams.get("mainOwner").toString(); } String hql = "delete from DocOwners c where c.document.docid = ? "; executeUpdate(hql, docid); DocOwners docOwnersObj = new DocOwners(); docOwnersObj.setDocument((Docs) get(Docs.class, docid)); docOwnersObj.setUsersByUserid((User) get(User.class, mainowner)); docOwnersObj.setMainOwner(true); save(docOwnersObj); if (!StringUtil.isNullOrEmpty(owners) && !owners.equalsIgnoreCase("undefined")) { String[] ownerIds = owners.split(","); for (int i = 0; i < ownerIds.length; i++) { docOwnersObj = new DocOwners(); docOwnersObj.setDocument((Docs) get(Docs.class, docid)); docOwnersObj.setUsersByUserid((User) get(User.class, ownerIds[i])); docOwnersObj.setMainOwner(false); save(docOwnersObj); } } ll.add(docOwnersObj); } catch (Exception e) { logger.warn(e.getMessage(), e); throw ServiceException.FAILURE("crmOpportunityDAOImpl.saveOppOwners", e); } return new KwlReturnObject(true, KWLErrorMsgs.S01, "", ll, 1); }
From source file:de.intranda.goobi.plugins.utils.ModsUtils.java
/** * //from ww w . j a v a 2 s . c om * @param pres * @param dsLogical * @param dsPhysical * @param eleMods * @param mappingFile * @throws IOException * @throws JDOMException */ @SuppressWarnings("unchecked") public static void parseModsSection(CSICOAIImport plugin, DocStruct dsLogical, DocStruct dsAnchor, DocStruct dsPhysical, Element eleMods, int volumeNo, String pieceDesignation) throws JDOMException, IOException { fillPersonRoleMap(); String mappingFileName = CSICOAIImport.MODS_MAPPING_FILE; Prefs prefs = plugin.getPrefs(); String suffix = plugin.getCurrentSuffix(); boolean writeAllMetadataToAnchor = false; if (dsAnchor != null && dsAnchor.getType().getName().contentEquals("MultiVolumeWork")) { writeAllMetadataToAnchor = true; } File mappingFile = new File(mappingFileName); File seriesInfoFile = new File(TEMP_DIRECTORY, seriesInfoFilename); if (seriesInfoFile.isFile()) { logger.debug("Reading data from " + seriesInfoFile.getName()); Object obj = readFile(seriesInfoFile); if (obj instanceof HashMap<?, ?>) { seriesInfo = (HashMap<String, String>) obj; } } Document doc = new Document(); Element eleNewMods = (Element) eleMods.clone(); doc.setRootElement(eleNewMods); Document mapDoc = new SAXBuilder().build(mappingFile); String seriesTitle = null; String seriesID = null; List<String> publicationYears = new ArrayList<String>(); for (Object obj : mapDoc.getRootElement().getChildren("metadata", null)) { Element eleMetadata = (Element) obj; String mdName = eleMetadata.getChildTextTrim("name", null); if ("location".equals(mdName)) { // write location info int counter = 0; List<Element> eleXpathList = eleMetadata.getChildren("xpath", null); if (eleXpathList == null || eleXpathList.isEmpty()) { continue; } String query = eleXpathList.get(0).getTextTrim(); XPath xpath = XPath.newInstance(query); xpath.addNamespace(NS_MODS); List<Element> eleValueList = xpath.selectNodes(doc); for (Element element : eleValueList) { int locationVolumeNo = getVolumeNumberFromLocation(element); if (locationVolumeNo > 0 && locationVolumeNo != volumeNo) { continue; } String shelfmarkSource = null; String physicalLocation = null; String physicalCollection = null; String localPieceDesignation = null; int localVolumeNo = -1; boolean isCurrentColume = true; Element eleShelfmarkSource = element.getChild("shelfLocator", NS_MODS); if (eleShelfmarkSource != null) { shelfmarkSource = eleShelfmarkSource.getValue(); } Element elePhysLocation = element.getChild("physicalLocation", NS_MODS); if (elePhysLocation != null) { physicalLocation = elePhysLocation.getValue(); } Element eleHoldingSimple = element.getChild("holdingSimple", NS_MODS); if (eleHoldingSimple != null) { Element eleCopyInformation = eleHoldingSimple.getChild("copyInformation", NS_MODS); if (eleCopyInformation != null) { Element elePhysicalCollection = eleCopyInformation.getChild("subLocation", NS_MODS); if (elePhysicalCollection != null) { physicalCollection = elePhysicalCollection.getValue(); } Element elePieceDesignation = eleCopyInformation.getChild("pieceDesignation", NS_MODS); if (elePieceDesignation != null) { localPieceDesignation = elePieceDesignation.getValue(); } Element eleVolumeNo = eleCopyInformation.getChild("VolumeNo", NS_MODS); if (eleVolumeNo == null) { eleVolumeNo = eleCopyInformation.getChild("VolumeLabel", NS_MODS); } if (eleVolumeNo != null) { String volumeString = eleVolumeNo.getValue().replaceAll("\\D", ""); if (volumeString != null && !volumeString.isEmpty()) { localVolumeNo = Integer.valueOf(volumeString); } } } } if (localPieceDesignation == null) { localPieceDesignation = pieceDesignation; } // if (pieceDesignation != null && localPieceDesignation.contentEquals(pieceDesignation)) { // This is either the correct volume or no volume is specified. try { String mdPrefix = ""; if (counter > 0) { mdPrefix = "copy" + volumeNumberFormat.format(counter); } if (shelfmarkSource != null) { MetadataType shelfmarkSourceType = prefs .getMetadataTypeByName(mdPrefix + "shelfmarksource"); Metadata shelfmarkSourceMetadata = new Metadata(shelfmarkSourceType); shelfmarkSourceMetadata.setValue(shelfmarkSource); dsPhysical.addMetadata(shelfmarkSourceMetadata); } if (physicalLocation != null) { MetadataType physicalLocationType = prefs .getMetadataTypeByName(mdPrefix + "physicalLocation"); Metadata physicalLocationMetadata = new Metadata(physicalLocationType); physicalLocationMetadata.setValue(physicalLocation); dsPhysical.addMetadata(physicalLocationMetadata); } if (physicalCollection != null) { MetadataType physicalCollectionType = prefs .getMetadataTypeByName(mdPrefix + "physicalCollection"); Metadata physicalCollectionMetadata = new Metadata(physicalCollectionType); physicalCollectionMetadata.setValue(physicalCollection); dsPhysical.addMetadata(physicalCollectionMetadata); } if (localPieceDesignation != null) { MetadataType pieceDesignationType = prefs .getMetadataTypeByName(mdPrefix + "pieceDesignation"); Metadata pieceDesignationMetadata = new Metadata(pieceDesignationType); pieceDesignationMetadata.setValue(localPieceDesignation); dsPhysical.addMetadata(pieceDesignationMetadata); } if (counter < 10) { counter++; } } catch (MetadataTypeNotAllowedException e) { logger.warn(e.getMessage()); } // } } continue; } MetadataType mdType = prefs.getMetadataTypeByName(mdName); if (mdType != null) { List<Element> eleXpathList = eleMetadata.getChildren("xpath", null); if (mdType.getIsPerson()) { // Persons for (Element eleXpath : eleXpathList) { String query = eleXpath.getTextTrim(); // logger.debug("XPath: " + query); XPath xpath = XPath.newInstance(query); xpath.addNamespace(NS_MODS); // Element eleValue = (Element) xpath.selectSingleNode(doc); List<Element> eleValueList = xpath.selectNodes(doc); if (eleValueList != null) { for (Element eleValue : eleValueList) { String name = ""; String firstName = ""; String lastName = ""; String termsOfAddress = ""; String roleTerm = ""; String typeName = ""; for (Object o : eleValue.getChildren()) { Element eleNamePart = (Element) o; if (eleNamePart.getName().contentEquals("role")) { Element eleRoleTerm = eleNamePart.getChild("roleTerm", null); if (eleRoleTerm != null) { roleTerm = eleRoleTerm.getValue(); } } else { String type = eleNamePart.getAttributeValue("type"); if (type == null || type.isEmpty()) { // no type name = eleNamePart.getValue(); } else if (type.contentEquals("date")) { // do nothing? } else if (type.contentEquals("termsOfAddress")) { termsOfAddress = eleNamePart.getValue(); } else if (type.contentEquals("given")) { firstName = eleNamePart.getValue(); } else if (type.contentEquals("family")) { lastName = eleNamePart.getValue(); } } } // set metadata type to role if (roleTerm != null && !roleTerm.isEmpty()) { roleTerm = roleTerm.replaceAll("\\.", ""); typeName = personRoleMap.get(roleTerm.toLowerCase()); if (typeName == null) { String[] parts = roleTerm.split(" "); if (parts != null && parts.length > 0) { typeName = personRoleMap.get(parts[0].toLowerCase()); } if (typeName == null) { typeName = mdName; } } } else { // with no role specified, assume it is an author typeName = "Author"; } mdType = prefs.getMetadataTypeByName(typeName); if (name.contains(",")) { String[] nameSplit = name.split("[,]"); if (nameSplit.length > 0 && StringUtils.isEmpty(lastName)) { lastName = nameSplit[0].trim(); } if (nameSplit.length > 1 && StringUtils.isEmpty(firstName)) { for (int i = 1; i < nameSplit.length; i++) { firstName += nameSplit[i].trim() + ", "; } firstName = firstName.substring(0, firstName.length() - 2); } } else { lastName = name; } if (StringUtils.isNotEmpty(lastName)) { try { Person person = new Person(mdType); person.setFirstname(firstName); person.setLastname(lastName); person.setRole(mdType.getName()); if (eleMetadata.getAttribute("logical") != null && eleMetadata .getAttributeValue("logical").equalsIgnoreCase("true")) { dsLogical.addPerson(person); if (writeAllMetadataToAnchor) { dsAnchor.addPerson(person); } } } catch (MetadataTypeNotAllowedException e) { logger.warn(e.getMessage()); } } } } } } else { // Regular metadata List<String> values = new ArrayList<String>(); String separator = " "; if (eleMetadata.getAttribute("separator") != null) { separator = eleMetadata.getAttributeValue("separator"); } for (Element eleXpath : eleXpathList) { String query = eleXpath.getTextTrim(); // logger.debug("XPath: " + query); XPath xpath = XPath.newInstance(query); xpath.addNamespace(NS_MODS); List eleValueList = xpath.selectNodes(doc); if (eleValueList != null) { if (mdName.contentEquals("Taxonomy")) { for (Object objValue : eleValueList) { if (objValue instanceof Element) { Element eleValue = (Element) objValue; List<Element> subjectChildren = eleValue.getChildren(); String value = ""; for (Element element : subjectChildren) { if (taxonomyFieldsList.contains(element.getName().toLowerCase())) { List<Element> subElements = element.getChildren(); if (subElements != null && !subElements.isEmpty()) { String subValue = ""; for (Element subElement : subElements) { if (subElement.getValue() != null && !subElement.getValue().trim().isEmpty()) { subValue = subValue + " " + subElement.getValue(); } } value = value + separator + subValue.trim(); } else if (element.getValue() != null && !element.getValue().trim().isEmpty()) { value = value + separator + element.getValue(); } } } if (value.length() > separator.length()) { value = value.substring(separator.length()).trim(); values.add(value); } } } } else { int count = 0; for (Object objValue : eleValueList) { String value = null; if (objValue instanceof Element) { Element eleValue = (Element) objValue; logger.debug("mdType: " + mdType.getName() + "; Value: " + eleValue.getTextTrim()); value = getElementValue(eleValue, ", "); // value = eleValue.getTextTrim(); } else if (objValue instanceof Attribute) { Attribute atrValue = (Attribute) objValue; logger.debug( "mdType: " + mdType.getName() + "; Value: " + atrValue.getValue()); value = atrValue.getValue(); } boolean mergeXPaths = mergeXPaths(eleMetadata); if (value != null && (values.size() <= count || !mergeXPaths)) { values.add(value); } else if (value != null) { value = values.get(count) + separator + value; values.set(count, value); } count++; } } } } for (String value : values) { if (mdType.getName().contentEquals("CurrentNoSorting")) { value = correctCurrentNoSorting(value); } else if (mdType.getName().contentEquals("CurrentNo")) { value = formatVolumeString(value, PREFIX_SERIES); } else if (!writeAllMetadataToAnchor && mdType.getName().contentEquals("TitleDocParallel")) { seriesTitle = value; } // // Add singleDigCollection to series also // if (!writeAllMetadataToAnchor && anchorMetadataList.contains(mdType.getName()) && dsAnchor != null) { // // if (mdType.getName().contentEquals("singleDigCollection") && dsSeries != null) { // try { // if (value.length() > 0) { // Metadata metadata = new Metadata(mdType); // metadata.setValue(value); // logger.debug("Found metadata: " + metadata.getType().getName()); // if (eleMetadata.getAttribute("logical") != null // && eleMetadata.getAttributeValue("logical").equalsIgnoreCase("true")) { // logger.debug("Added metadata \"" + metadata.getValue() + "\" to logical structure"); // dsAnchor.addMetadata(metadata); // } // } // } catch (MetadataTypeNotAllowedException e) { // logger.warn(e.getMessage()); // } // } try { if (value.length() > 0) { Metadata metadata = new Metadata(mdType); metadata.setValue(value); // logger.debug("Found metadata: " + metadata.getType().getName()); if (eleMetadata.getAttribute("logical") != null && eleMetadata.getAttributeValue("logical").equalsIgnoreCase("true")) { // logger.debug("Added metadata \"" + metadata.getValue() + "\" to logical structure"); if (mdName.contentEquals("PublicationStart") || mdName.contentEquals("PublicationEnd")) { publicationYears.add(value); continue; } if (mdName.contentEquals("TitleDocMain")) { if (suffix != null && !suffix.isEmpty() && (plugin.addVolumeNoToTitle || !writeAllMetadataToAnchor)) { if (plugin.useSquareBracketsForVolume) { metadata.setValue(value + " [" + suffix + "]"); } else { metadata.setValue(value + " (" + formatVolumeString(suffix, PREFIX_VOLUME) + ")"); } } try { dsLogical.addMetadata(metadata); seriesTitle = value; } catch (MetadataTypeNotAllowedException e) { logger.warn(e.getMessage()); } } else if (mdName.contentEquals("CatalogIDDigital")) { if (suffix != null && !suffix.isEmpty()) { metadata.setValue(value + "_" + suffix); if (writeAllMetadataToAnchor) { seriesID = value; } } try { dsLogical.addMetadata(metadata); } catch (MetadataTypeNotAllowedException e) { logger.warn(e.getMessage()); } } else { try { dsLogical.addMetadata(metadata); } catch (MetadataTypeNotAllowedException e) { logger.warn(e.getMessage()); } try { if (writeAllMetadataToAnchor && !volumeExclusiveMetadataList .contains(metadata.getType().getName())) { dsAnchor.addMetadata(metadata); } } catch (MetadataTypeNotAllowedException e) { logger.warn(e.getMessage()); } } } if (eleMetadata.getAttribute("physical") != null && eleMetadata.getAttributeValue("physical").equalsIgnoreCase("true")) { // logger.debug("Added metadata \"" + metadata.getValue() + "\" to physical structure"); dsPhysical.addMetadata(metadata); } } } catch (MetadataTypeNotAllowedException e) { logger.warn(e.getMessage()); } } } } else { logger.warn("Metadata '" + mdName + "' is not defined in the ruleset."); } } //construct PublicationYear from Start and Enddate if necessary List<? extends Metadata> mdPublicationList = dsLogical .getAllMetadataByType(prefs.getMetadataTypeByName("PublicationYear")); if ((mdPublicationList == null || mdPublicationList.isEmpty()) && !publicationYears.isEmpty()) { Collections.sort(publicationYears); String value = publicationYears.get(0); if (publicationYears.size() > 1) { value += ("-" + publicationYears.get(publicationYears.size() - 1)); } if (value != null && !value.trim().isEmpty()) { try { Metadata mdPublicationYear = new Metadata(prefs.getMetadataTypeByName("PublicationYear")); mdPublicationYear.setValue(value); try { dsLogical.addMetadata(mdPublicationYear); } catch (MetadataTypeNotAllowedException e) { logger.error(e.getMessage()); } catch (DocStructHasNoTypeException e) { logger.error(e.getMessage()); } if (writeAllMetadataToAnchor) { try { dsAnchor.addMetadata(mdPublicationYear); } catch (MetadataTypeNotAllowedException e) { logger.warn(e.getMessage()); } catch (DocStructHasNoTypeException e) { logger.warn(e.getMessage()); } } } catch (MetadataTypeNotAllowedException e) { logger.error(e.getMessage()); } } } // Code to handle related works, e.g. series, but only if we are not working within a MultiVolume if (!writeAllMetadataToAnchor) { String query = "/mods:mods/mods:relatedItem[@type='series']/mods:titleInfo[@type='uniform']"; XPath xpath = XPath.newInstance(query); xpath.addNamespace(NS_MODS); List<Element> eleValueList = xpath.selectNodes(doc); List<String> values = new ArrayList<String>(); if (eleValueList == null || eleValueList.isEmpty()) { query = "/mods:mods/mods:relatedItem[@type='series']/mods:titleInfo[not(@type)]"; xpath = XPath.newInstance(query); xpath.addNamespace(NS_MODS); eleValueList = xpath.selectNodes(doc); } if (eleValueList != null && !eleValueList.isEmpty()) { for (Element eleValue : eleValueList) { if (eleValue.getText() != null && !eleValue.getText().isEmpty()) { values.add(eleValue.getTextTrim()); } List<Element> eleSubList = eleValue.getChildren(); if (eleSubList != null && !eleSubList.isEmpty()) { for (Element element : eleSubList) { if (element.getName().contentEquals("title")) { if (element.getText() != null && !element.getText().isEmpty()) { values.add(element.getTextTrim()); } } } } } String value = ""; for (String s : values) { if (StringUtils.isNotEmpty(s)) { value += " " + s; } } value = value.trim(); String[] valueParts = value.split("\\s"); seriesTitle = ""; HashMap<String, Boolean> valueMap = new HashMap<String, Boolean>(); for (int i = 0; i < valueParts.length; i++) { if (!valueMap.containsKey(valueParts[i])) { seriesTitle += " " + valueParts[i]; valueMap.put(valueParts[i], true); } } seriesTitle = seriesTitle.trim(); logger.debug("related Series = " + seriesTitle); } } if (dsAnchor != null) { if (seriesID == null) { if (seriesTitle != null) { seriesID = seriesInfo.get(seriesTitle); } if (seriesID == null) { seriesID = "CSIC" + System.currentTimeMillis(); logger.debug("Series not found. creating new one: " + seriesID); } } if (seriesTitle == null) { seriesTitle = seriesID; } // Creating metadata for series try { MetadataType titleType = prefs.getMetadataTypeByName("TitleDocMain"); MetadataType idType = prefs.getMetadataTypeByName("CatalogIDDigital"); Metadata mdTitle; mdTitle = new Metadata(titleType); Metadata mdID = new Metadata(idType); mdTitle.setValue(seriesTitle); mdID.setValue(seriesID); dsAnchor.addMetadata(mdTitle); dsAnchor.addMetadata(mdID); } catch (MetadataTypeNotAllowedException e) { logger.warn(e.getMessage()); } } // Create CurrentNo and CurrentNoSorting if necessary if (dsAnchor != null && suffix != null && !suffix.isEmpty()) { List<? extends Metadata> mdCurrentNoList = dsLogical .getAllMetadataByType(prefs.getMetadataTypeByName("CurrentNo")); if (!writeAllMetadataToAnchor || plugin.writeCurrentNoToMultiVolume) { if ((mdCurrentNoList == null || mdCurrentNoList.isEmpty())) { // No current Number, so we create one try { String value = null; Metadata md = new Metadata(prefs.getMetadataTypeByName("CurrentNo")); if (writeAllMetadataToAnchor) { value = formatVolumeString(suffix, PREFIX_VOLUME); } else { value = formatVolumeString(suffix, PREFIX_SERIES); } md.setValue(value); dsLogical.addMetadata(md); } catch (MetadataTypeNotAllowedException e) { logger.warn(e.toString()); } } } List<? extends Metadata> mdCurrentNoSortList = dsLogical .getAllMetadataByType(prefs.getMetadataTypeByName("CurrentNoSorting")); if (!writeAllMetadataToAnchor || plugin.writeCurrentNoSortingToMultiVolume) { if (mdCurrentNoSortList == null || mdCurrentNoSortList.isEmpty() && !writeAllMetadataToAnchor) { // No current Number, so we create one try { Metadata md = new Metadata(prefs.getMetadataTypeByName("CurrentNoSorting")); String str = suffix; if (str.contains("_")) { str = suffix.split("_")[0]; } if (str.startsWith("V")) { str = str.substring(1); } str = correctCurrentNoSorting(str); md.setValue(str); dsLogical.addMetadata(md); } catch (MetadataTypeNotAllowedException e) { logger.warn(e.toString()); } } } } // write seriesInfo to file if (seriesTitle != null && !seriesTitle.isEmpty()) { seriesInfo.put(seriesTitle, seriesID); if (seriesInfoFile.isFile()) { logger.debug("deleting old seriesInfoFile"); seriesInfoFile.delete(); } writeFile(seriesInfoFile, seriesInfo); } }
From source file:MSUmpire.PSMDataStructure.FragmentSelection.java
public void GeneratePepFragScoreMap() { for (LCMSID IDSummary : FileList) { for (String key : IDSummary.GetPepIonList().keySet()) { if (!PepFragScore.containsKey(key)) { PepFragScore.put(key, new HashMap<String, Float>()); }// w ww.j av a 2 s .co m } for (String key : IDSummary.GetMappedPepIonList().keySet()) { if (!PepFragScore.containsKey(key)) { PepFragScore.put(key, new HashMap<String, Float>()); } } } for (String PepKey : PepFragScore.keySet()) { int IDNo = 0; HashMap<String, Float> fragmentscore = new HashMap<>(); HashMap<String, Integer> fragmentfreq = new HashMap<>(); for (LCMSID IDSummary : FileList) { PepIonID pep = null; if (IDSummary.GetPepIonList().containsKey(PepKey)) { pep = IDSummary.GetPepIonList().get(PepKey); } else if (IDSummary.GetMappedPepIonList().containsKey(PepKey)) { pep = IDSummary.GetMappedPepIonList().get(PepKey); } if (pep != null) { IDNo++; for (FragmentPeak frag : pep.FragmentPeaks) { if (frag.corr > CorrelationThreshold && frag.FragMZ >= MinFragMZ) { if (!fragmentscore.containsKey(frag.GetFragKey())) { fragmentscore.put(frag.GetFragKey(), 0f); fragmentfreq.put(frag.GetFragKey(), 0); } if (scoring == Scoring.Intensity) { fragmentscore.put(frag.GetFragKey(), fragmentscore.get(frag.GetFragKey()) + frag.intensity); } else if (scoring == Scoring.IntensityCorr) { fragmentscore.put(frag.GetFragKey(), fragmentscore.get(frag.GetFragKey()) + frag.corr * frag.intensity); } fragmentfreq.put(frag.GetFragKey(), fragmentfreq.get(frag.GetFragKey()) + 1); if (!FragInt.containsKey(pep.GetKey() + "_" + frag.GetFragKey())) { FragInt.put(pep.GetKey() + "_" + frag.GetFragKey(), new HashMap<String, Float>()); } FragInt.get(pep.GetKey() + "_" + frag.GetFragKey()) .put(FilenameUtils.getBaseName(IDSummary.Filename), frag.intensity); } } } } for (String fragkey : fragmentfreq.keySet()) { if (fragmentfreq.get(fragkey) > IDNo * freqPercent) { PepFragScore.get(PepKey).put(fragkey, fragmentscore.get(fragkey)); } } } }
From source file:com.yahoo.dba.perf.myperf.springmvc.StatusController.java
@Override protected ModelAndView handleRequestImpl(HttpServletRequest req, HttpServletResponse resp) throws Exception { String dbgroup = req.getParameter("group"); if (dbgroup == null || dbgroup.trim().length() == 0) dbgroup = "all"; String dbhost = req.getParameter("host"); java.util.Date now = new java.util.Date(); //the first scan yet to complete long oneinterval = (this.frameworkContext.getMyperfConfig().getScannerIntervalSeconds() + 1) * 1000; boolean withinOneScan = (now.getTime() - this.frameworkContext.getStartTime().getTime()) <= oneinterval; long twointerval = (2 * this.frameworkContext.getMyperfConfig().getScannerIntervalSeconds() + 1) * 1000; ResultList rList = new ResultList(); //if("all".equalsIgnoreCase(dbgroup)) if (dbhost == null || dbhost.isEmpty())//we should have id either as all or a dbgroup {// w w w .j a v a2 s .c o m ColumnDescriptor desc = new ColumnDescriptor(); desc.addColumn("DBGROUP", false, 1); desc.addColumn("HOST", false, 2); desc.addColumn("QUERIES /SEC", true, 3); desc.addColumn("SYS CPU%", true, 4); desc.addColumn("USER CPU%", true, 5); desc.addColumn("IOWAIT%", true, 6); desc.addColumn("LOAD AVG", true, 7); desc.addColumn("REPL LAG", true, 8); desc.addColumn("FREE MEM (MB)", true, 9); desc.addColumn("SLOW QUERY /MIN", true, 10); desc.addColumn("THREADS RUNNING", true, 11); desc.addColumn("THREADS", true, 12); desc.addColumn("CONNECTIONS /SEC", true, 13); desc.addColumn("ABORTED CC /SEC", true, 14); desc.addColumn("DEADLOCKS", false, 15); desc.addColumn("STATUS", false, 16); desc.addColumn("LAST CHECK TIME", false, 17); desc.addColumn("LAST ALERT", false, 18); desc.addColumn("SCAN TIME", true, 19); rList.setColumnDescriptor(desc); java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); sdf.setTimeZone(TimeZone.getTimeZone("UTC")); java.text.DecimalFormat df = new java.text.DecimalFormat("#.###"); for (Map.Entry<String, DBGroupInfo> e : this.frameworkContext.getDbInfoManager().getClusters() .entrySet()) { for (DBInstanceInfo dbinfo : e.getValue().getInstances()) { String dbgroupName = dbinfo.getDbGroupName(); String dbHostName = dbinfo.getHostName(); if (!"all".equals(dbgroup) && !dbgroup.equalsIgnoreCase(dbgroupName)) continue; InstanceStates stateSnaps = this.frameworkContext.getInstanceStatesManager() .getStates(dbinfo.getDbid()); if (stateSnaps == null) continue; //java.util.Date lastConnectTime = this.frameworkContext.getDbInfoManager().getLastAccessDate(dbgroupName, dbHostName); java.util.Date lastConnectTime = stateSnaps.getLastAccessTime(); String dbstatus = "Green"; if (lastConnectTime == null && withinOneScan) dbstatus = "Unknown"; else if (lastConnectTime == null) dbstatus = "Red"; else if (now.getTime() - lastConnectTime.getTime() > twointerval) dbstatus = "Red"; else if (now.getTime() - lastConnectTime.getTime() > oneinterval) dbstatus = "Yellow"; ResultRow row = new ResultRow(); row.setColumnDescriptor(desc); List<String> vals = new ArrayList<String>(); vals.add(dbgroupName); vals.add(dbHostName); StateSnapshot[] snaps = stateSnaps.copySnapshots(); boolean isSnapValid = snaps[0].getTimestamp() >= 0L && snaps[1].getTimestamp() > snaps[0].getTimestamp(); long interval = snaps[1].getTimestamp() - snaps[0].getTimestamp(); if (isSnapValid) { //sys CPU double syscpu = 0.0f; double usercpu = 0.0f; double iowaits = 0.0f; double loadAvg = 0.0f; int activeThreads = 0; if (snaps[0].getQueries() >= 0L && snaps[1].getQueries() >= 0L) { //double val = ((double)(snaps[1].getQueries() - snaps[0].getQueries())*1000)/(double)interval; double val = diffAvgNoNegative(snaps[1].getQueries(), snaps[0].getQueries(), snaps[1].getTimestamp(), snaps[0].getTimestamp(), snaps[1].getUptime(), true, 1000); vals.add(df.format(val)); } else { vals.add("0.00"); } if (snaps[0].getSyscputime() >= 0L && snaps[1].getSyscputime() >= 0L) { double val = ((double) (snaps[1].getSyscputime() - snaps[0].getSyscputime()) * 100) / (double) (snaps[1].getTotalcputime() - snaps[0].getTotalcputime()); vals.add(df.format(val)); syscpu = val; } else { vals.add("0.00"); } if (snaps[0].getUsercputime() >= 0L && snaps[1].getUsercputime() >= 0L) { double val = ((double) (snaps[1].getUsercputime() - snaps[0].getUsercputime()) * 100) / (double) (snaps[1].getTotalcputime() - snaps[0].getTotalcputime()); vals.add(df.format(val)); usercpu = val; } else { vals.add("0.00"); } if (snaps[0].getIotime() >= 0L && snaps[1].getIotime() >= 0L) { double val = ((double) (snaps[1].getIotime() - snaps[0].getIotime()) * 100) / (double) (snaps[1].getTotalcputime() - snaps[0].getTotalcputime()); vals.add(df.format(val)); iowaits = val; } else { vals.add("0.00"); } if (snaps[1].getLoadAverage() >= 0.0f) { vals.add(df.format(snaps[1].getLoadAverage())); loadAvg = snaps[1].getLoadAverage(); } else vals.add("0.00"); vals.add(String.valueOf(snaps[1].getReplLag())); if (snaps[1].getAvailableMem() >= 0L) { long val = snaps[1].getAvailableMem() / 1024; vals.add(String.valueOf(val)); } else vals.add("0.00"); if (snaps[0].getSlowQueryCount() >= 0L && snaps[1].getSlowQueryCount() >= 0L) { double val = diffAvgNoNegative(snaps[1].getSlowQueryCount(), snaps[0].getSlowQueryCount(), snaps[1].getTimestamp(), snaps[0].getTimestamp(), snaps[1].getUptime(), true, 60000); vals.add(df.format(val)); } else vals.add("0.00"); vals.add(String.valueOf(snaps[1].getActiveThreads())); activeThreads = snaps[1].getActiveThreads(); vals.add(String.valueOf(snaps[1].getThreads())); if (snaps[0].getConnections() >= 0L && snaps[1].getConnections() >= 0L) { //double val = ((double)(snaps[1].getConnections() - snaps[0].getConnections())*1000)/(double)interval; double val = diffAvgNoNegative(snaps[1].getConnections(), snaps[0].getConnections(), snaps[1].getTimestamp(), snaps[0].getTimestamp(), snaps[1].getUptime(), true, 1000); vals.add(df.format(val)); } else { vals.add("0.00"); } if (snaps[0].getAbortedConnectsClients() >= 0L && snaps[1].getAbortedConnectsClients() >= 0L) { //double val = ((double)(snaps[1].getAbortedConnectsClients() - snaps[0].getAbortedConnectsClients())*1000)/(double)interval; double val = diffAvgNoNegative(snaps[1].getAbortedConnectsClients(), snaps[0].getAbortedConnectsClients(), snaps[1].getTimestamp(), snaps[0].getTimestamp(), snaps[1].getUptime(), true, 1000); vals.add(df.format(val)); } else { vals.add("0.00"); } if (snaps[0].getDeadlocks() >= 0L && snaps[1].getDeadlocks() >= 0L) { double val = diffAvgNoNegative(snaps[1].getDeadlocks(), snaps[0].getDeadlocks(), snaps[1].getTimestamp(), snaps[0].getTimestamp(), snaps[1].getUptime(), false, 1); vals.add((long) val + "(" + snaps[0].getDeadlocks() + ")"); } else { vals.add(String.valueOf(snaps[1].getDeadlocks())); } //hardcoded threshold now if (iowaits > this.frameworkContext.getAlertSettings().getAlertThreshold(dbinfo, "IO") || (syscpu + usercpu > this.frameworkContext.getAlertSettings() .getAlertThreshold(dbinfo, "CPU")) || loadAvg > this.frameworkContext.getAlertSettings().getAlertThreshold(dbinfo, "LOADAVG") || activeThreads > this.frameworkContext.getAlertSettings() .getAlertThreshold(dbinfo, "THREAD")) if (!"Red".equals(dbstatus)) dbstatus = "Yellow"; } else { vals.add("0.00"); vals.add("0.00"); vals.add("0.00"); vals.add("0.00"); if (snaps[1].getTimestamp() > 0L) vals.add(String.valueOf(snaps[1].getReplLag())); else vals.add("0"); vals.add("0.00"); vals.add("0.00"); vals.add("0"); vals.add("0"); vals.add("0.00"); vals.add("0.00"); vals.add("0.00"); vals.add("0"); } vals.add(dbstatus); if (lastConnectTime != null) vals.add(sdf.format(lastConnectTime)); else vals.add(""); Date altDt = stateSnaps.getLastAlertTime(); if (altDt != null) { String val = stateSnaps.getLastAlertValue(); if (val == null) val = ""; //else if(val.indexOf('.')>0 && val.length()>=val.indexOf('.')+4) // val = val.substring(0, val.indexOf('.')+4); String end_dt = stateSnaps.getLastAlertEndTime() != null ? sdf.format(stateSnaps.getLastAlertEndTime()) : ""; vals.add( sdf.format(altDt) + "-" + end_dt + "/" + stateSnaps.getLastAlertType() + "/" + val); } else vals.add(""); vals.add(String.valueOf(stateSnaps.getLastScanTime())); row.setColumns(vals); rList.addRow(row); } } } else { Date d1 = null; Date d2 = null; Calendar c = Calendar.getInstance(); c.add(Calendar.DATE, -7); //7 days d1 = c.getTime(); d2 = new Date(); java.text.SimpleDateFormat sdf2 = new java.text.SimpleDateFormat("yyyyMMddHHmmss"); sdf2.setTimeZone(TimeZone.getTimeZone("UTC")); String startDate = sdf2.format(d1); String endDate = sdf2.format(d2); try { //TODO validate DB rList = this.frameworkContext.getAutoScanner().getMetricDb().retrieveMetricsStatus( "mysql_globalstatus".toUpperCase(), this.frameworkContext.getDbInfoManager().findDB(dbgroup, dbhost).getDbid(), Long.parseLong(startDate), Long.parseLong(endDate)); HashMap<String, Integer> connectCounter = new HashMap<String, Integer>(24 * 8); HashMap<String, Integer> slowCounter = new HashMap<String, Integer>(24 * 8); if (rList != null && rList.getRows().size() > 0) { for (ResultRow row : rList.getRows()) { String ts = row.getColumns().get(1); String h = ts.substring(0, ts.length()); if (connectCounter.containsKey(h)) connectCounter.put(h, connectCounter.get(h) + 1); else connectCounter.put(h, 1); try { if (slowCounter.containsKey(h)) slowCounter.put(h, connectCounter.get(h) + Integer.parseInt(row.getColumns().get(3))); else slowCounter.put(h, Integer.parseInt(row.getColumns().get(3))); } catch (Exception ex) { } } } } catch (Exception ex) { //logger.log(Level.WARNING, "Failed to retrieve metrics data", ex); } } ModelAndView mv = new ModelAndView(jsonView); String msg = "OK"; mv.addObject("json_result", ResultListUtil.toJSONString(rList, null, 0, msg)); return mv; }
From source file:ec.coevolve.MultiPopCoevolutionaryEvaluatorExtra.java
@Override void loadElites(final EvolutionState state, int whichSubpop) { Subpopulation subpop = state.population.subpops[whichSubpop]; // Update hall of fame if (hallOfFame != null) { int best = 0; Individual[] oldinds = subpop.individuals; for (int x = 1; x < oldinds.length; x++) { if (betterThan(oldinds[x], oldinds[best])) { best = x;//from w w w . ja v a 2 s . co m } } hallOfFame[whichSubpop].add((Individual) subpop.individuals[best].clone()); } int index = 0; // Last champions if (lastChampions > 0) { for (int i = 1; i <= lastChampions && i <= hallOfFame[whichSubpop].size(); i++) { eliteIndividuals[whichSubpop][index++] = (Individual) hallOfFame[whichSubpop] .get(hallOfFame[whichSubpop].size() - i).clone(); } } double randChamps = randomChampions; // Novel champions if (novelChampions > 0) { Individual[] behaviourElite = behaviourElite(state, whichSubpop); for (int i = 0; i < behaviourElite.length; i++) { eliteIndividuals[whichSubpop][index++] = (Individual) behaviourElite[i].clone(); //System.out.println(whichSubpop + "\t" + ((ExpandedFitness) behaviourElite[i].fitness).getFitnessScore()); } randChamps = randomChampions + (novelChampions - behaviourElite.length); } // Random champions if (randChamps > 0) { // Choose random positions ArrayList<Integer> pos = new ArrayList<Integer>(hallOfFame[whichSubpop].size()); for (int i = 0; i < hallOfFame[whichSubpop].size(); i++) { pos.add(i); } Collections.shuffle(pos); for (int i = 0; i < pos.size() && i < randChamps; i++) { eliteIndividuals[whichSubpop][index++] = (Individual) hallOfFame[whichSubpop].get(pos.get(i)) .clone(); } } // NEAT Elite if (neatElite > 0) { NEATGeneticAlgorithm neat = ((NEATSubpop) subpop).getNEAT(); if (!neat.getSpecies().specieList().isEmpty()) { HashMap<Integer, Individual> specieBests = new HashMap<Integer, Individual>( neat.getSpecies().specieList().size() * 2); Chromosome[] genoTypes = neat.population().genoTypes(); for (int i = 0; i < genoTypes.length; i++) { int specie = ((NEATChromosome) genoTypes[i]).getSpecieId(); if (!specieBests.containsKey(specie) || betterThan(subpop.individuals[i], specieBests.get(specie))) { specieBests.put(specie, subpop.individuals[i]); } } Individual[] specBests = new Individual[specieBests.size()]; specieBests.values().toArray(specBests); QuickSort.qsort(specBests, new EliteComparator2()); for (int i = 0; i < specBests.length && i < neatElite; i++) { eliteIndividuals[whichSubpop][index++] = (Individual) specBests[i].clone(); } } } // Fill remaining with the elite of the current pop int toFill = numElite - index; if (toFill == 1) { // Just one to place Individual best = subpop.individuals[0]; for (int x = 1; x < subpop.individuals.length; x++) { if (betterThan(subpop.individuals[x], best)) { best = subpop.individuals[x]; } } eliteIndividuals[whichSubpop][index++] = (Individual) best.clone(); } else if (toFill > 1) { Individual[] orderedPop = Arrays.copyOf(subpop.individuals, subpop.individuals.length); QuickSort.qsort(orderedPop, new EliteComparator2()); // load the top N individuals for (int j = 0; j < toFill; j++) { eliteIndividuals[whichSubpop][index++] = (Individual) orderedPop[j].clone(); } } }
From source file:Data.c_CardDB.java
public boolean isInLegal(c_Deck deck, Legals leg) { boolean isDeckInLegal = true; c_Card card;//from w ww . j av a 2 s. com if (m_expansionDB.doesLegalContainLegals(leg)) { HashMap<Integer, Keyword> list = m_expansionDB.getOtherLegals(leg); for (int mid : deck.getAllCards().keySet()) { card = getCard(mid); HashMap<c_Expansion, Integer> expList = getExpansionList(card.Name); ArrayList<Integer> legalExpansions = m_expansionDB.getLegalExpansions(leg); for (c_Expansion exp : expList.keySet()) { if (!legalExpansions.contains(m_expansionDB.getEID(exp))) { isDeckInLegal = false; expList = null; legalExpansions = null; break; } } int nameHash = card.Name.hashCode(); if (list.containsKey(nameHash)) { if (list.get(nameHash) == Keyword.Banned || deck.getAmountOfCard(mid, c_Deck.WhichHalf.BOTH) > 1) { isDeckInLegal = false; list = null; break; } } } } card = null; return isDeckInLegal; }