auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public List<Block> execute(ContentMacroParameters parameters, String content, MacroTransformationContext context) throws MacroExecutionException { try { List<Block> blocks = getSyntaxParser(parameters.getSyntax()).parse(new StringReader(content)).getChildren(); if (blocks.size() == 1) { blocks.get(0).setParameter(MetaData.SYNTAX, parameters.getSyntax().toIdString()); return blocks; } else { MetaDataBlock metaDataBlock = new MetaDataBlock(blocks, MetaData.SYNTAX, parameters.getSyntax().toIdString()); return Collections.singletonList(metaDataBlock); } } catch (ParseException e) { throw new MacroExecutionException( String.format("Failed to parse macro content in syntax [%s]", parameters.getSyntax()), e); } }

Target:
public List<Block> execute(ContentMacroParameters parameters, String content, MacroTransformationContext context) throws MacroExecutionException { try { List<Block> blocks = getSyntaxParser(parameters.getSyntax()).parse(new StringReader(content)).getChildren(); MetaDataBlock metaDataBlock = new MetaDataBlock(blocks, MetaData.SYNTAX, parameters.getSyntax().toIdString()); return Collections.singletonList(metaDataBlock); } catch (ParseException e) { throw new MacroExecutionException( String.format("Failed to parse macro content in syntax [%s]", parameters.getSyntax()), e); } }
Source:
public void changePassword(User u, String pw) throws APIException { changePassword(u, "test", pw); }

Target:
public void changePassword(User u, String pw) throws APIException { OpenmrsUtil.validatePassword(u.getUsername(), pw, u.getSystemId()); dao.changePassword(u, pw); }
Source:
private void validateTree() { try { String[] uniqueNames = preferences.node("/os").childrenNames(); for (String uniqueName : Arrays.asList(uniqueNames)) { Preferences node = getKeyNode(uniqueName, "derivedFrom", null); String id = getKeyNode(uniqueName, "id", null).get("value", "0"); if (node != null) { String derivedFrom = node.get("value", null); if (derivedFrom != null && !idToUnameLookup.containsValue(derivedFrom)) { idToUnameLookup.remove(Integer.valueOf(id)); preferences.node("/os/" + uniqueName).removeNode(); log.warn("Illegal parent for os '{}'", uniqueName); } } } } catch (BackingStoreException e) { log.warn("Failed to validate Os Repository due to {}", e); log.debug("Exception", e); throw new RuntimeException("Failed to validate Os Repository due to " + e); } }

Target:
private void validateTree() { try { String[] uniqueNames = preferences.node("/os").childrenNames(); for (String uniqueName : Arrays.asList(uniqueNames)) { Preferences node = getKeyNode(uniqueName, "derivedFrom", null); String id = getKeyNode(uniqueName, "id", null).get("value", "0"); if (node != null) { String derivedFrom = node.get("value", null); if (derivedFrom != null && !idToUnameLookup.containsValue(derivedFrom)) { idToUnameLookup.remove(Integer.valueOf(id)); preferences.node("/os/" + uniqueName).removeNode(); log.warn("Illegal parent for os '{}'", uniqueName); } } } } catch (BackingStoreException e) { log.warn("Failed to validate Os Repository due to {}", e.getMessage()); log.debug("Exception", e); throw new RuntimeException("Failed to validate Os Repository due to " + e); } }
Source:
private BasicDBObject getUserInfo(final DBObject cursor, final boolean loginAsDefault, final boolean loginAsInstructor) throws LoginException { final BasicDBObject result = new BasicDBObject(); final boolean defaultAccountIsInstructor = (Boolean) cursor.get(IS_DEFAULT_INSTRUCTOR); result.append(DatabaseClient.IS_INSTRUCTOR, (loginAsDefault && defaultAccountIsInstructor) || (!loginAsDefault && loginAsInstructor)); if ((loginAsDefault && defaultAccountIsInstructor) || (!loginAsDefault && loginAsInstructor)) { result.append(DatabaseClient.CLIENT_ID, cursor.get(INSTRUCTOR_CLIENT_ID)); result.append(DatabaseClient.SERVER_ID, cursor.get(INSTRUCTOR_ID)); } else if ((loginAsDefault && !defaultAccountIsInstructor) || (!loginAsDefault && !loginAsInstructor)) { result.append(DatabaseClient.CLIENT_ID, cursor.get(STUDENT_CLIENT_ID)); result.append(DatabaseClient.SERVER_ID, cursor.get(STUDENT_ID)); } else { throw new LoginException(LoginServerWebSocketHandler.PERMISSION_ERROR_MESSAGE); } return result; }

Target:
private BasicDBObject getUserInfo(final DBObject cursor, final boolean loginAsDefault, final boolean loginAsInstructor) throws LoginException { final BasicDBObject result = new BasicDBObject(); final boolean defaultAccountIsInstructor = (Boolean) cursor.get(IS_DEFAULT_INSTRUCTOR); final boolean isDefaultInstructor = loginAsDefault && defaultAccountIsInstructor; final boolean isNonDefaultInstructor = !loginAsDefault && loginAsInstructor; final boolean isDefaultStudent = loginAsDefault && !defaultAccountIsInstructor; final boolean isNonDefaultStudent = !loginAsDefault && !loginAsInstructor; result.append(DatabaseClient.IS_INSTRUCTOR, isDefaultInstructor || isNonDefaultInstructor); if (isDefaultInstructor || isNonDefaultInstructor) { result.append(DatabaseClient.CLIENT_ID, cursor.get(INSTRUCTOR_CLIENT_ID)); result.append(DatabaseClient.SERVER_ID, cursor.get(INSTRUCTOR_ID)); } else if (isDefaultStudent || isNonDefaultStudent) { result.append(DatabaseClient.CLIENT_ID, cursor.get(STUDENT_CLIENT_ID)); result.append(DatabaseClient.SERVER_ID, cursor.get(STUDENT_ID)); } else { throw new LoginException(LoginServerWebSocketHandler.PERMISSION_ERROR_MESSAGE); } return result; }
Source:
public Map<String, String> getErrors() { return response.getErrors(); }

Target:
public Map<String, String> getErrors() { Map<String, String> errors = new HashMap<String, String>(); for (ViewResponse.Row<String, Revision> row : response.getRows()) { if(row.getError() != null) { errors.put(row.getKey(), row.getError()); } } return errors; }
Source:
public void testNestedCast() { assertQuery("select cast(varchar_value as varchar(3)) || ' sfd' from (values ('9898.122')) t(varchar_value)"); assertQuery("select cast(cast(varchar_value as varchar(3)) as varchar(5)) from (values ('9898.122')) t(varchar_value)"); }

Target:
public void testNestedCast() { assertQuery("select cast(varchar_value as varchar(3)) || ' sfd' from (values ('9898.122')) t(varchar_value)", "VALUES '989 sfd'"); assertQuery("select cast(cast(varchar_value as varchar(3)) as varchar(5)) from (values ('9898.122')) t(varchar_value)", "VALUES '989'"); }
Source:
private List<Rule> getRules(Term term) { List<Rule> rules = new ArrayList<>(); if (K.get_indexing_stats){ IndexingStatistics.getRulesForTermStopWatch.reset(); IndexingStatistics.getRulesForTermStopWatch.start(); } if (K.do_indexing) { rules.addAll(pathIndex.getRulesForTerm(term)); } else { rules.addAll(basicIndex.getRules(term)); } if (K.get_indexing_stats){ IndexingStatistics.rulesSelectedAtEachStep.add(rules.size()); long elapsed = IndexingStatistics.getRulesForTermStopWatch.stop().elapsed(TimeUnit.MICROSECONDS); IndexingStatistics.timesForRuleSelection.add(elapsed); } return rules; }

Target:
private List<Rule> getRules(Term term) { List<Rule> rules = new ArrayList<>(); if (K.get_indexing_stats){ IndexingStatistics.getRulesForTermStopWatch.reset(); IndexingStatistics.getRulesForTermStopWatch.start(); } rules.addAll(ruleIndex.getRules(term)); if (K.get_indexing_stats){ IndexingStatistics.rulesSelectedAtEachStep.add(rules.size()); long elapsed = IndexingStatistics.getRulesForTermStopWatch.stop().elapsed(TimeUnit.MICROSECONDS); IndexingStatistics.timesForRuleSelection.add(elapsed); } return rules; }
Source:
public void applicationStarted(ComponentContext context) { boolean started = TransactionHelper.isTransactionActive(); if (started || TransactionHelper.startTransaction()) { boolean completedAbruptly = true; try { doApplicationStarted(); completedAbruptly = false; } finally { if (completedAbruptly) { TransactionHelper.setTransactionRollbackOnly(); } if (started) { TransactionHelper.commitOrRollbackTransaction(); } } } else { doApplicationStarted(); } }

Target:
public void applicationStarted(ComponentContext context) { boolean txWasStartedOutsideComponent = TransactionHelper.isTransactionActiveOrMarkedRollback(); if (txWasStartedOutsideComponent || TransactionHelper.startTransaction()) { boolean completedAbruptly = true; try { doApplicationStarted(); completedAbruptly = false; } finally { if (completedAbruptly) { TransactionHelper.setTransactionRollbackOnly(); } if (!txWasStartedOutsideComponent) { TransactionHelper.commitOrRollbackTransaction(); } } } else { doApplicationStarted(); } }
Source:
public void cleanupLiveInstanceOwners() { String name = this.getShortClassName(); for (String cluster : _liveInstanceOwners.keySet()) { Map<String, HelixZkClient> clientMap = _liveInstanceOwners.get(cluster); for (HelixZkClient client : clientMap.values()) { client.close(); } clientMap.clear(); } _liveInstanceOwners.clear(); boolean status = TestHelper.afterClassCheck(name); if (!status) { System.out.println("---------- Test Class " + name + " thread leakage detected! ---------------"); } }

Target:
public void cleanupLiveInstanceOwners() throws InterruptedException { String testClassName = this.getShortClassName(); System.out.println("AfterClass: " + testClassName + " called."); for (String cluster : _liveInstanceOwners.keySet()) { Map<String, HelixZkClient> clientMap = _liveInstanceOwners.get(cluster); for (HelixZkClient client : clientMap.values()) { client.close(); } clientMap.clear(); } _liveInstanceOwners.clear(); boolean status = false; try { status = ThreadLeakageChecker.afterClassCheck(testClassName); } catch (Exception e) { LOG.error("ThreadLeakageChecker exception:", e); } if (!status) { System.out.println("---------- Test Class " + testClassName + " thread leakage detected! ---------------"); } }
Source:
private void refreshAlias(String alias) { try { updateAlias(alias, this.spawnDataStore.getChild(ALIAS_PATH, alias)); } catch (ExecutionException e) { log.warn("Failed to refresh alias: {}", alias, e); } catch (Exception e) { log.error("",e); } }

Target:
private void refreshAlias(String alias) { try { updateAlias(alias, this.spawnDataStore.getChild(ALIAS_PATH, alias)); } catch (ExecutionException e) { log.error("Failed to refresh alias: {}", alias, e); } catch (Exception e) { log.error("Unexpected error while refreshing alias {}", alias, e); } }
Source:
public void testVcfSorted(final boolean disableSort) { final File liftOutputFile = new File(OUTPUT_DATA_PATH, "lift-delete-me.vcf"); final File rejectOutputFile = new File(OUTPUT_DATA_PATH, "reject-delete-me.vcf"); final File input = new File(TEST_DATA_PATH, "testLiftoverBiallelicIndels.vcf"); liftOutputFile.deleteOnExit(); rejectOutputFile.deleteOnExit(); final String[] args = new String[]{ "INPUT=" + input.getAbsolutePath(), "OUTPUT=" + liftOutputFile.getAbsolutePath(), "REJECT=" + rejectOutputFile.getAbsolutePath(), "CHAIN=" + CHAIN_FILE, "REFERENCE_SEQUENCE=" + REFERENCE_FILE, "CREATE_INDEX=" + (!disableSort), "DISABLE_SORT=" + disableSort }; Assert.assertEquals(runPicardCommandLine(args), 0); try (final VCFFileReader liftReader = new VCFFileReader(liftOutputFile, !disableSort)) { } }

Target:
public void testVcfSorted(final boolean disableSort) { final File liftOutputFile = new File(OUTPUT_DATA_PATH, "lift-delete-me.vcf"); final File rejectOutputFile = new File(OUTPUT_DATA_PATH, "reject-delete-me.vcf"); final File input = new File(TEST_DATA_PATH, "testLiftoverBiallelicIndels.vcf"); liftOutputFile.deleteOnExit(); rejectOutputFile.deleteOnExit(); final String[] args = new String[]{ "INPUT=" + input.getAbsolutePath(), "OUTPUT=" + liftOutputFile.getAbsolutePath(), "REJECT=" + rejectOutputFile.getAbsolutePath(), "CHAIN=" + CHAIN_FILE, "REFERENCE_SEQUENCE=" + REFERENCE_FILE, "CREATE_INDEX=" + (!disableSort), "DISABLE_SORT=" + disableSort }; Assert.assertEquals(runPicardCommandLine(args), 0); try (final VCFFileReader liftReader = new VCFFileReader(liftOutputFile, !disableSort)) { try (final CloseableIterator<VariantContext> iter = liftReader.iterator()) { Assert.assertEquals(iter.stream().count(), 5L); } } }
Source:
private void processLevels(Properties properties) { for (Map.Entry<Object, Object> entry : properties.entrySet()) { String loggerName = entry.getKey().toString(); Level level = Level.parse(entry.getValue().toString()); java.util.logging.Logger.getLogger(loggerName).setLevel(level.toJulLevel()); } }

Target:
private void processLevels(Properties properties) { for (Map.Entry<Object, Object> entry : properties.entrySet()) { String loggerName = entry.getKey().toString(); Level level = Level.valueOf(entry.getValue().toString().toUpperCase(Locale.US)); setLevel(loggerName, level); } }
Source:
public Builder trustStore(File file) { if (file == null) { return this; } if (!file.exists()) { throw new IllegalArgumentException("Truststore file does not exist: " + file); } this.trustStoreSource = Files.asByteSource(file); return this; }

Target:
public Builder trustStore(File file) { if (file == null || !file.exists()) { throw new IllegalArgumentException("A file with the truststore must be provided."); } this.trustStoreSource = Files.asByteSource(file); return this; }
Source:
protected EntityRecordWithColumns toRecord(E entity) { final EntityRecord entityRecord = entityConverter().convert(entity); final Map<String, Column.MemoizedValue<?>> storageFields = Columns.from(entity); final EntityRecordWithColumns envelope = EntityRecordWithColumns.of(entityRecord, storageFields); return envelope; }

Target:
protected EntityRecordWithColumns toRecord(E entity) { final EntityRecord entityRecord = entityConverter().convert(entity); checkNotNull(entityRecord); final EntityRecordWithColumns recordWithColumns = EntityRecordWithColumns.create(entityRecord, entity); return recordWithColumns; }
Source:
public static void main(final String[] args) { System.exit(new MarkDuplicatesWithMateCigar().instanceMain(args)); }

Target:
public static void main(final String[] args) { new MarkDuplicatesWithMateCigar().instanceMainWithExit(args); }
Source:
public Set<String> getTags(WebrequestData webrequest){ Set<String> tags = new HashSet<>(); assert webrequest.getUriHost()!=null: webrequest; assert webrequest.getHttpStatus() != null: webrequest; assert webrequest.getUserAgent() != null: webrequest; if(Webrequest.SUCCESS_HTTP_STATUSES.contains(webrequest.getHttpStatus()) ) { for (Tagger t : this.chain) { Set<String> newTags = t.getTags(webrequest, tags); tags.addAll(newTags); } } return tags; }

Target:
public Set<String> getTags(WebrequestData webrequest){ Set<String> tags = new HashSet<>(); assert webrequest.getUriHost()!=null: webrequest; assert webrequest.getHttpStatus() != null: webrequest; assert webrequest.getUserAgent() != null: webrequest; if(Webrequest.SUCCESS_HTTP_STATUSES.contains(webrequest.getHttpStatus()) ) { List<Integer> stages = new ArrayList(this.chain.keySet()); Collections.sort(stages); for (Integer stage : stages) { List<Tagger> stageChain = this.chain.get(stage); for (Tagger t : stageChain) { Set<String> newTags = t.getTags(webrequest, tags); tags.addAll(newTags); } } } return tags; }
Source:
public void retireIdentifierSource_shouldRetireAnIdentifierSourceFromTheSystem() throws Exception { IdentifierSource s = iss.getIdentifierSource(1); Assert.assertFalse(iss.getIdentifierSource(1).isRetired()); iss.retireIdentifierSource(s, "testing"); Assert.assertTrue(iss.getIdentifierSource(1).isRetired()); }

Target:
public void retireIdentifierSource_shouldRetireAnIdentifierSourceFromTheSystem() throws Exception { IdentifierSource identifierSource = identifierSourceService.getIdentifierSource(2); Assert.assertFalse(identifierSourceService.getIdentifierSource(2).isRetired()); identifierSourceService.retireIdentifierSource(identifierSource, "testing"); Assert.assertTrue(identifierSourceService.getIdentifierSource(2).isRetired()); }
Source:
public final void literal(final String name, final String value) { final String value_new = Normalizer.normalize(value, Form.NFD); if (idnControlSubField == true){ if (compareIdFromRecord(value)) idnControlSubField = false; } builder.append(SUB_DELIMITER); builder.append(name); builder.append(value_new); }

Target:
public void literal(final String name, final String value) { if (name.length()!=1){ throw new FormatException(name); } if (!entityOpen){ throw new FormatException(name); } final String valueNew = Normalizer.normalize(value, Form.NFD); if (idnControlSubField){ if (!this.id.equals(value)) { throw new MissingIdException(value); } idnControlSubField = false; } builder.append(SUB_DELIMITER); builder.append(name); builder.append(valueNew); }
Source:
public static String formatSince(String value, TimeZone timezone) { try { Date date = parse(value); DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.FULL); if(timezone != null) { formatter.setTimeZone(timezone); } return formatter.format(date); } catch (ParseException e) { System.out.println(e); } return value; }

Target:
public static String formatSince(String value, TimeZone timezone) { try { Date date = parse(value); DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.FULL); if(timezone != null) { formatter.setTimeZone(timezone); } return formatter.format(date); } catch (ParseException e) { OpenShiftCommonUIActivator.getDefault().getLogger().logWarning("Unable to parse format duration value: " + value, e); } return value; }
Source:
public void shouldGenerateCorrectUpdateSQL(){ Student s = new Student(); s.set("first_name", "Jim"); s.set("last_name", "Cary"); s.set("dob", new java.sql.Date(getDate(1965, 12, 1).getTime())); s.set("id", 1); String updateSQL = s.toUpdate(); System.out.println(updateSQL); the(updateSQL).shouldBeEqual("UPDATE students SET dob = DATE '1965-12-01', first_name = 'Jim', id = 1, last_name = 'Cary' WHERE id = 1"); }

Target:
public void shouldGenerateCorrectUpdateSQL() { deleteAndPopulateTable("students"); Student s = new Student(); s.set("first_name", "Jim"); s.set("last_name", "Cary"); s.set("dob", new java.sql.Date(getDate(1965, 12, 1).getTime())); s.set("id", 1); s.saveIt(); s = Student.findById(1); s.set("first_name", "Drew"); s.saveIt(); String updateSQL = s.toUpdate(); Base.exec(updateSQL); s = Student.findById(1); the(s.get("first_name")).shouldBeEqual("Drew"); System.out.println(updateSQL); }
Source:
public void configure() throws Exception { server.addEventListener(mbeans()); server.addConnector(plainConnector()); server.addConnector(sslConnector()); HandlerCollection handlers = new HandlerCollection(); handlers.addHandler(welcomeFileHandler()); createWebAppContext(); addResourceHandler(handlers, webAppContext); handlers.addHandler(webAppContext); JettyCustomErrorPageHandler errorHandler = new JettyCustomErrorPageHandler(); webAppContext.setErrorHandler(errorHandler); server.addBean(errorHandler); server.setHandler(handlers); performCustomConfiguration(); server.setStopAtShutdown(true); SessionManager sessionManager = webAppContext.getSessionHandler().getSessionManager(); sessionManager.setMaxInactiveInterval(systemEnvironment.sessionTimeoutInSeconds()); }

Target:
public void configure() throws Exception { server.addEventListener(mbeans()); server.addConnector(plainConnector()); server.addConnector(sslConnector()); HandlerCollection handlers = new HandlerCollection(); handlers.addHandler(welcomeFileHandler()); createWebAppContext(); addResourceHandler(handlers, webAppContext); handlers.addHandler(webAppContext); JettyCustomErrorPageHandler errorHandler = new JettyCustomErrorPageHandler(); webAppContext.setErrorHandler(errorHandler); server.addBean(errorHandler); server.setHandler(handlers); performCustomConfiguration(); server.setStopAtShutdown(true); }
Source:
public static Module module() { return new CacheModule() { @Override protected void configure() { cache(ID_CACHE, Project.NameKey.class, new TypeLiteral<List<Change>>() {}) .maximumWeight(1024) .expireAfterWrite(120, TimeUnit.MINUTES) .loader(Loader.class); } }; }

Target:
public static Module module() { return new CacheModule() { @Override protected void configure() { cache(ID_CACHE, Project.NameKey.class, new TypeLiteral<List<Change>>() {}) .maximumWeight(1024) .loader(Loader.class); } }; }
Source:
public void shouldReturn400IfNoApiKeyParam() { Response response = envTarget("verify") .request() .get(); assertEquals(HttpStatusCode.BAD_REQUEST_400, response.getStatus()); }

Target:
public void shouldReturn400IfNoApiKeyParam() { Response response = envTarget("_verify") .request() .post(null); assertEquals(HttpStatusCode.BAD_REQUEST_400, response.getStatus()); }
Source:
public String serializeSlots(Iterable<Slot> slots, String delimiter) { List<String> slotStrings = new ArrayList<>(); for (Slot slot : slots) { String constraintString = delimiter + slot.serialize(this); slotStrings.add(constraintString); } Collections.sort(slotStrings); StringBuilder sb = new StringBuilder(); for (String string : slotStrings) { sb.append(string); } return sb.toString(); }

Target:
public String serializeSlots(Iterable<Slot> slots, String delimiter) { List<String> slotStrings = new ArrayList<>(); for (Slot slot : slots) { slotStrings.add(slot.serialize(this).toString()); } Collections.sort(slotStrings); StringBuilder sb = new StringBuilder(); boolean first = true; for (String string : slotStrings) { String slotString = first ? "" : delimiter; slotString += string; sb.append(slotString); first = false; } return sb.toString(); }
Source:
private void parseLevelDBCacheStore(XMLExtendedStreamReader reader, LevelDBCacheStoreConfigurationBuilder builder) throws XMLStreamException { for (int i = 0; i < reader.getAttributeCount(); i++) { ParseUtils.requireNoNamespaceAttribute(reader, i); String value = StringPropertyReplacer.replaceProperties(reader .getAttributeValue(i)); Attribute attribute = Attribute.forName(reader .getAttributeLocalName(i)); switch (attribute) { case LOCATION: { builder.location(value); break; } case EXPIRED_LOCATION: { builder.expiredLocation(value); break; } case CLEAR_THRESHOLD: { builder.clearThreshold(Integer.valueOf(value)); break; } case EXPIRY_QUEUE_SIZE: { builder.expiryQueueSize(Integer.valueOf(value)); } case BLOCK_SIZE: { builder.blockSize(Integer.valueOf(value)); break; } case CACHE_SIZE: { builder.cacheSize(Long.valueOf(value)); break; } case COMPRESSION_TYPE: { builder.compressionType(CompressionType.valueOf(value)); break; } default: { Parser52.parseCommonStoreAttributes(reader, i, builder); } } } }

Target:
private void parseLevelDBCacheStore(XMLExtendedStreamReader reader, LevelDBCacheStoreConfigurationBuilder builder) throws XMLStreamException { for (int i = 0; i < reader.getAttributeCount(); i++) { ParseUtils.requireNoNamespaceAttribute(reader, i); String value = StringPropertyReplacer.replaceProperties(reader .getAttributeValue(i)); Attribute attribute = Attribute.forName(reader .getAttributeLocalName(i)); switch (attribute) { case LOCATION: { builder.location(value); break; } case EXPIRED_LOCATION: { builder.expiredLocation(value); break; } case CLEAR_THRESHOLD: { builder.clearThreshold(Integer.valueOf(value)); break; } case EXPIRY_QUEUE_SIZE: { builder.expiryQueueSize(Integer.valueOf(value)); } case BLOCK_SIZE: { builder.blockSize(Integer.valueOf(value)); break; } case CACHE_SIZE: { builder.cacheSize(Long.valueOf(value)); break; } case COMPRESSION_TYPE: { builder.compressionType(CompressionType.valueOf(value)); break; } default: { Parser53.parseCommonStoreAttributes(reader, i, builder); } } } if (reader.hasNext() && (reader.nextTag() != XMLStreamConstants.END_ELEMENT)) { ParseUtils.unexpectedElement(reader); } }
Source:
public Map<String, InstanceState> getInstanceState(GoogleComputeInstanceTemplate template, Collection<String> instanceIds) { Map<String, InstanceState> result = new HashMap<String, InstanceState>(); for (String currentId : instanceIds) { Compute compute = credentials.getCompute(); String projectId = credentials.getProjectId(); String zone = getConfigurationValue(GoogleComputeProviderConfigurationProperty.ZONE); String decoratedInstanceName = decorateInstanceName(template, currentId); try { Instance instance = compute.instances().get(projectId, zone, decoratedInstanceName).execute(); InstanceStatus instanceStatus = convertGCEInstanceStatusToDirectorInstanceStatus(instance.getStatus()); result.put(currentId, new SimpleInstanceState(instanceStatus)); } catch (GoogleJsonResponseException e) { if (e.getStatusCode() == 404) { LOG.info("Instance '" + decoratedInstanceName + "' not found."); result.put(currentId, new SimpleInstanceState(InstanceStatus.UNKNOWN)); } else { e.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } } return result; }

Target:
public Map<String, InstanceState> getInstanceState(GoogleComputeInstanceTemplate template, Collection<String> instanceIds) { Map<String, InstanceState> result = new HashMap<String, InstanceState>(); for (String currentId : instanceIds) { Compute compute = credentials.getCompute(); String projectId = credentials.getProjectId(); String zone = getConfigurationValue(GoogleComputeInstanceTemplateConfigurationProperty.ZONE); String decoratedInstanceName = decorateInstanceName(template, currentId); try { Instance instance = compute.instances().get(projectId, zone, decoratedInstanceName).execute(); InstanceStatus instanceStatus = convertGCEInstanceStatusToDirectorInstanceStatus(instance.getStatus()); result.put(currentId, new SimpleInstanceState(instanceStatus)); } catch (GoogleJsonResponseException e) { if (e.getStatusCode() == 404) { LOG.info("Instance '" + decoratedInstanceName + "' not found."); result.put(currentId, new SimpleInstanceState(InstanceStatus.UNKNOWN)); } else { throw new RuntimeException(e); } } catch (IOException e) { throw new RuntimeException(e); } } return result; }
Source:
public static ModuleIdentifier forClosure(String name) { String normalizedName = name; if (normalizedName.startsWith("goog:")) { normalizedName = normalizedName.substring(5); } String namespace = normalizedName; String moduleName = normalizedName; int splitPoint = normalizedName.indexOf(':'); if (splitPoint != -1) { moduleName = normalizedName.substring(0, splitPoint); namespace = normalizedName.substring(Math.min(splitPoint + 1, normalizedName.length() - 1)); } return new ModuleIdentifier(normalizedName, namespace, moduleName); }

Target:
public static ModuleIdentifier forClosure(String name) { String normalizedName = name; if (normalizedName.startsWith("goog:")) { normalizedName = normalizedName.substring("goog:".length()); } String namespace = normalizedName; String moduleName = normalizedName; int splitPoint = normalizedName.indexOf(':'); if (splitPoint != -1) { moduleName = normalizedName.substring(0, splitPoint); namespace = normalizedName.substring(Math.min(splitPoint + 1, normalizedName.length() - 1)); } return new ModuleIdentifier(normalizedName, namespace, moduleName); }
Source:
public String getJsId() { return "popover_" + "overlay_" + element.getMarkupId(); }

Target:
public String getJsId() { return "popover_overlay_" + element.getMarkupId(); }
Source:
public void testCloneWithNewJarUrlString() { RuntimeSettingProvider properties = createPropsWithDriverName("org.talend.Driver1"); JdbcRuntimeInfo jdbcRuntimeInfo = new JdbcRuntimeInfo(properties, "anyRuntimeClassName"); JdbcRuntimeInfo clone = jdbcRuntimeInfo.cloneWithNewJarUrlString("mvn: new/url"); assertTrue(jdbcRuntimeInfo != clone); }

Target:
public void testCloneWithNewJarUrlString() { RuntimeSettingProvider properties = createPropsWithDriverName("org.talend.Driver1"); JdbcRuntimeInfo jdbcRuntimeInfo = new JdbcRuntimeInfo(properties, "anyRuntimeClassName"); JdbcRuntimeInfo clone = jdbcRuntimeInfo.cloneWithNewJarUrlString("mvn: new/url"); assertTrue(jdbcRuntimeInfo != clone); assertNotEquals(jdbcRuntimeInfo, clone); assertEquals(jdbcRuntimeInfo.getDepTxtPath(), clone.getDepTxtPath()); assertEquals(jdbcRuntimeInfo.getRuntimeClassName(), clone.getRuntimeClassName()); assertNotEquals(jdbcRuntimeInfo.getJarUrl(), clone.getJarUrl()); }
Source:
@Override public double estimateRowCount(RelMetadataQuery mq) { double inputRowCount = mq.getRowCount(getInput()); int lim = intFromRex(fetch); int off = intFromRex(offset); if (lim == 0 && off == 0) return inputRowCount; if (lim == 0) return Math.max(0, inputRowCount - off); return Math.min(lim, inputRowCount - off); }

Target:
@Override public double estimateRowCount(RelMetadataQuery mq) { double inputRowCount = mq.getRowCount(getInput()); double lim = fetch != null ? doubleFromRex(fetch, inputRowCount * FETCH_IS_PARAM_FACTOR) : inputRowCount; double off = offset != null ? doubleFromRex(offset, inputRowCount * OFFSET_IS_PARAM_FACTOR) : 0; return Math.min(lim, inputRowCount - off); }
Source:
@Test public void nullCipherName() { try { forJavaName(null); fail("Should have thrown"); } catch (NullPointerException expected) { } catch (IllegalArgumentException expected) { } }

Target:
@Test public void nullCipherName() { try { forJavaName(null); fail("Should have thrown"); } catch (NullPointerException expected) { } }
Source:
public static <T> Collection<T> cloneCollection(Collection<T> source, boolean deepCopy) throws InstantiationException, IllegalAccessException { if (source == null) { return null; } Collection<T> copy; try { copy = source.getClass().newInstance(); } catch (InstantiationException e) { copy = new ArrayList<T>(); } if (deepCopy) { for (T object : source) { T objectCopy = clone(object); copy.add(objectCopy); } } else { copy.addAll(source); } return copy; }

Target:
public static <T> Collection<T> cloneCollection(Collection<T> source, boolean deepCopy) throws InstantiationException, IllegalAccessException { if (source == null) { return null; } Collection<T> copy; try { copy = source.getClass().newInstance(); } catch (InstantiationException e) { if (source instanceof Set) { copy = new HashSet<T>(); } else { copy = new ArrayList<T>(); } } if (deepCopy) { for (T object : source) { T objectCopy = clone(object); copy.add(objectCopy); } } else { copy.addAll(source); } return copy; }
Source:
public URL create() { try { return new URL(urlRepresentation); } catch (MalformedURLException e) { throw new DolphinRuntimeException("Can not create url for '" + urlRepresentation + "'"); } }

Target:
public URL create() { try { return new URL(urlRepresentation); } catch (final MalformedURLException e) { throw new DolphinRuntimeException("Can not create url for '" + urlRepresentation + "'"); } }
Source:
protected void validate() { assertNonNull(transactionManager, "The TransactionManager is a hard requirement and should be provided"); assertNonNull(messageMonitor, "The MessageMonitor is a hard requirement and should be provided"); assertNonNull(rollbackConfiguration, "The RollbackConfiguration is a hard requirement and should be provided"); }

Target:
protected void validate() { }
Source:
protected byte[] encryptString(@NonNull final Key key, @NonNull final String value, @Nullable final EncryptStringHandler handler) throws IOException, GeneralSecurityException { final Cipher cipher = Cipher.getInstance(getEncryptionTransformation()); try (final ByteArrayOutputStream output = new ByteArrayOutputStream()) { if (null != handler) { handler.initialize(cipher, key, output); output.flush(); } try (final CipherOutputStream encrypt = new CipherOutputStream(output, cipher)) { encrypt.write(value.getBytes(UTF8)); } return output.toByteArray(); } catch (Throwable fail) { Log.e(LOG_TAG, fail.getMessage(), fail); throw fail; } }

Target:
protected byte[] encryptString(@NonNull final Key key, @NonNull final String value, @Nullable final EncryptStringHandler handler) throws IOException, GeneralSecurityException { final Cipher cipher = getCachedInstance(); try (final ByteArrayOutputStream output = new ByteArrayOutputStream()) { if (null != handler) { handler.initialize(cipher, key, output); output.flush(); } try (final CipherOutputStream encrypt = new CipherOutputStream(output, cipher)) { encrypt.write(value.getBytes(UTF8)); } return output.toByteArray(); } catch (Throwable fail) { Log.e(LOG_TAG, fail.getMessage(), fail); throw fail; } }
Source:
public void setErrorsVisibility(boolean givenNameError, boolean familyNameError, boolean dayOfBirthError, boolean addressError, boolean countryError, boolean genderError, boolean countryNull, boolean stateError, boolean cityError, boolean postalError) { if (givenNameError) { fnameerror.setVisibility(View.VISIBLE); } else { fnameerror.setVisibility(View.INVISIBLE); } if (familyNameError) { lnameerror.setVisibility(View.VISIBLE); } else { lnameerror.setVisibility(View.INVISIBLE); } if (dayOfBirthError) { doberror.setVisibility(View.VISIBLE); dateTimeFormatter = DateTimeFormat.forPattern(DateUtils.DEFAULT_DATE_FORMAT); String minimumDate = DateTime.now().minusYears( ApplicationConstants.RegisterPatientRequirements.MAX_PATIENT_AGE) .toString(dateTimeFormatter); String maximumDate = DateTime.now().toString(dateTimeFormatter); doberror.setText(getString(R.string.dob_error, minimumDate, maximumDate)); } else { doberror.setVisibility(View.GONE); } if (addressError) { addrerror.setVisibility(View.VISIBLE); } else { addrerror.setVisibility(View.GONE); } if (countryError) { countryerror.setVisibility(View.VISIBLE); } else { countryerror.setVisibility(View.GONE); } if (genderError) { gendererror.setVisibility(View.VISIBLE); } else { gendererror.setVisibility(View.GONE); } if (countryNull) { countrynull.setVisibility(View.VISIBLE); } else { countrynull.setVisibility(View.GONE); } if (stateError) { stateerror.setVisibility(View.VISIBLE); } else { stateerror.setVisibility(View.GONE); } if (cityError) { cityerror.setVisibility(View.VISIBLE); } else { cityerror.setVisibility(View.GONE); } if (postalError) { postalerror.setVisibility(View.VISIBLE); } else { postalerror.setVisibility(View.GONE); } }

Target:
public void setErrorsVisibility(boolean givenNameError, boolean familyNameError, boolean dayOfBirthError, boolean addressError, boolean countryError, boolean genderError, boolean countryNull, boolean stateError, boolean cityError, boolean postalError) { setVisibility(fnameerror, givenNameError); setVisibility(lnameerror, familyNameError); setVisibility(addrerror, addressError); setVisibility(countryerror, countryError); setVisibility(gendererror, genderError); setVisibility(countrynull, countryNull); setVisibility(stateerror, stateError); setVisibility(cityerror, cityError); setVisibility(stateerror, stateError); setVisibility(postalerror, postalError); if (dayOfBirthError) { doberror.setVisibility(View.VISIBLE); dateTimeFormatter = DateTimeFormat.forPattern(DateUtils.DEFAULT_DATE_FORMAT); String minimumDate = DateTime.now().minusYears( ApplicationConstants.RegisterPatientRequirements.MAX_PATIENT_AGE) .toString(dateTimeFormatter); String maximumDate = DateTime.now().toString(dateTimeFormatter); doberror.setText(getString(R.string.dob_error, minimumDate, maximumDate)); } else { doberror.setVisibility(View.GONE); } }
Source:
void multipleRecords() { EntityRecordStorage<StgProjectId, StgProject> storage = storage(); int count = 10; List<StgProjectId> ids = new ArrayList<>(); @SuppressWarnings("rawtypes") Class<? extends EntityState> stateClass = null; for (int i = 0; i < count; i++) { StgProjectId id = newId(); EntityState<StgProjectId> state = newState(id); if (stateClass == null) { stateClass = state.getClass(); } EntityRecord record = EntityRecordStorageTestEnv.newStorageRecord(id, state); storage.write(id, record); ids.add(id); } int bulkCount = count / 2; FieldMask fieldMask = fromFieldNumbers(stateClass, 2); Iterator<EntityRecord> readRecords = storage.readAll(ids.subList(0, bulkCount), fieldMask); List<EntityRecord> readList = newArrayList(readRecords); assertThat(readList).hasSize(bulkCount); for (EntityRecord record : readList) { Message state = unpack(record.getState()); assertMatchesMask(state, fieldMask); } }

Target:
void multipleRecords() { EntityRecordStorage<StgProjectId, StgProject> storage = storage(); int recordCount = 10; ImmutableList<StgProjectId> ids = range(0, recordCount).mapToObj(i -> newId()) .collect(toImmutableList()); @SuppressWarnings("rawtypes") Class<? extends EntityState> stateClass = writeRandomRecords(storage, ids); int halfSize = recordCount / 2; List<StgProjectId> halfOfIds = ids.subList(0, halfSize); FieldMask fieldMask = fromFieldNumbers(stateClass, 2); Iterator<EntityRecord> iterator = storage.readAll(halfOfIds, fieldMask); List<EntityRecord> actualRecords = ImmutableList.copyOf(iterator); assertThat(actualRecords).hasSize(halfSize); for (EntityRecord record : actualRecords) { Message state = unpack(record.getState()); assertMatchesMask(state, fieldMask); } }
Source:
public void onPreAdd(IoFilterChain parent, String name, NextFilter nextFilter) throws SSLException { IoSession session = parent.getSession(); SocketAddress remoteAddress = session.getRemoteAddress(); if(remoteAddress instanceof InetSocketAddress) { log.info("activating TLS SNI support"); session.setAttribute(PEER_ADDRESS, remoteAddress); } super.onPreAdd(parent, name, nextFilter); }

Target:
public void onPreAdd(IoFilterChain parent, String name, NextFilter nextFilter) throws SSLException { if (useSNI) { IoSession session = parent.getSession(); SocketAddress remoteAddress = session.getRemoteAddress(); if (remoteAddress instanceof InetSocketAddress) { log.info("Activating TLS SNI support for peer address: {}", remoteAddress); session.setAttribute(PEER_ADDRESS, remoteAddress); } } super.onPreAdd(parent, name, nextFilter); }
Source:
public void vmTypeChanged(VmType vmType) { if (basedOnCustomInstanceType()) { getModel().getIsSoundcardEnabled().setEntity(vmType == VmType.Desktop && !clusterHasPpcArchitecture()); } getModel().getAllowConsoleReconnect().setEntity(vmType == VmType.Server); getModel().getIoThreadsEnabled().setEntity(vmType == VmType.Server || vmType == VmType.HighPerformance); if (vmType == VmType.HighPerformance) { getModel().getIsHeadlessModeEnabled().setEntity(true); getModel().getIsConsoleDeviceEnabled().setEntity(true); getModel().getUsbPolicy().setSelectedItem(UsbPolicy.DISABLED); getModel().getIsSmartcardEnabled().setEntity(false); getModel().getWatchdogModel().setSelectedItem(null); getModel().getWatchdogAction().setSelectedItem(getModel().getWatchdogAction().getItems().iterator().next()); getModel().getIsRngEnabled().setEntity(true); getModel().getMigrationMode().setItems(Arrays.asList(MigrationSupport.IMPLICITLY_NON_MIGRATABLE, MigrationSupport.PINNED_TO_HOST)); getModel().getMigrationMode().setSelectedItem(MigrationSupport.IMPLICITLY_NON_MIGRATABLE); if (!clusterHasPpcArchitecture()) { getModel().getHostCpu().setEntity(true); } getModel().getMemoryBalloonDeviceEnabled().setEntity(false); if (getModel().getMultiQueues().getIsAvailable()) { getModel().getMultiQueues().setEntity(true); } } else { getModel().getMigrationMode().setItems(Arrays.asList(MigrationSupport.values())); } }

Target:
public void vmTypeChanged(VmType vmType) { if (basedOnCustomInstanceType()) { getModel().getIsSoundcardEnabled().setEntity(vmType == VmType.Desktop && !clusterHasPpcArchitecture()); } getModel().getAllowConsoleReconnect().setEntity(vmType == VmType.Server); getModel().getIoThreadsEnabled().setEntity(vmType == VmType.Server || vmType == VmType.HighPerformance); if (vmType == VmType.HighPerformance) { getModel().getIsHeadlessModeEnabled().setEntity(true); getModel().getIsConsoleDeviceEnabled().setEntity(true); getModel().getUsbPolicy().setSelectedItem(UsbPolicy.DISABLED); getModel().getIsSmartcardEnabled().setEntity(false); getModel().getWatchdogModel().setSelectedItem(null); getModel().getWatchdogAction().setSelectedItem(getModel().getWatchdogAction().getItems().iterator().next()); getModel().getIsRngEnabled().setEntity(true); getModel().getMigrationMode().setItems(Arrays.asList(MigrationSupport.IMPLICITLY_NON_MIGRATABLE, MigrationSupport.PINNED_TO_HOST)); getModel().getMigrationMode().setSelectedItem(MigrationSupport.IMPLICITLY_NON_MIGRATABLE); if (!clusterHasPpcArchitecture()) { getModel().getHostCpu().setEntity(true); } getModel().getMemoryBalloonDeviceEnabled().setEntity(false); } else { getModel().getMigrationMode().setItems(Arrays.asList(MigrationSupport.values())); } }
Source:
private void assertValue(int nodeIndex, Object key, Object expectedValue) { InternalCacheEntry entry = cache(nodeIndex).getAdvancedCache().getDataContainer().get(key); assertEquals(expectedValue, entry != null ? entry.getValue() : null); }

Target:
private void assertValue(int nodeIndex, Object key, Object expectedValue) { assertEquals(expectedValue, cache(nodeIndex).get(key)); }
Source:
public StandardSlackService(String baseUrl, String teamDomain, boolean botUser, String roomId, boolean replyBroadcast, String populatedToken) { this(new StandardSlackServiceBuilder() .withBaseUrl(baseUrl) .withTeamDomain(teamDomain) .withBotUser(botUser) .withRoomId(roomId) .withReplyBroadcast(replyBroadcast) .withPopulatedToken(populatedToken) ); if (populatedToken == null) { throw new IllegalArgumentException("No slack token found, setup a secret text credential and configure it to be used"); } this.populatedToken = populatedToken; }

Target:
public StandardSlackService(String baseUrl, String teamDomain, boolean botUser, String roomId, boolean replyBroadcast, String populatedToken) { this(builder() .withBaseUrl(baseUrl) .withTeamDomain(teamDomain) .withBotUser(botUser) .withRoomId(roomId) .withReplyBroadcast(replyBroadcast) .withPopulatedToken(populatedToken) ); if (populatedToken == null) { throw new IllegalArgumentException("No slack token found, setup a secret text credential and configure it to be used"); } this.populatedToken = populatedToken; }
Source:
public void updated(Dictionary<String, ?> config) throws ConfigurationException { if (config != null) { String refreshIntervalString = (String) config.get("refresh"); if (StringUtils.isNotBlank(refreshIntervalString)) { refreshInterval = Long.parseLong(refreshIntervalString); } String userName = (String) config.get("userName"); if(StringUtils.isNotBlank(userName)) { this.userName = userName; } else { throw new ConfigurationException("userName", "The userName to connect to myStrom must be specified in config file"); } String password = (String) config.get("password"); if(StringUtils.isNotBlank(password)) { this.password = password; } else { throw new ConfigurationException("password", "The password to connect to myStrom must be specified in config file"); } if(this.devMode){ this.mystromClient = new MockMystromClient(); } else { this.mystromClient = new MystromClient(this.userName, this.password, logger); } if(ChangeStateJob.MystromClient == null){ ChangeStateJob.MystromClient = this.mystromClient; } setProperlyConfigured(true); try { this.mystromDiscovery(); } catch (IOException e) { e.printStackTrace(); } } }

Target:
public void updated(Dictionary<String, ?> config) throws ConfigurationException { if (config != null) { String refreshIntervalString = (String) config.get("refresh"); if (StringUtils.isNotBlank(refreshIntervalString)) { refreshInterval = Long.parseLong(refreshIntervalString); } String userName = (String) config.get("userName"); if (StringUtils.isNotBlank(userName)) { this.userName = userName; } else { throw new ConfigurationException("userName", "The userName to connect to myStrom must be specified in config file"); } String password = (String) config.get("password"); if (StringUtils.isNotBlank(password)) { this.password = password; } else { throw new ConfigurationException("password", "The password to connect to myStrom must be specified in config file"); } if (this.devMode) { this.mystromClient = new MockMystromClient(); } else { this.mystromClient = new MystromClient(this.userName, this.password, logger); } if (ChangeStateJob.MystromClient == null) { ChangeStateJob.MystromClient = this.mystromClient; } setProperlyConfigured(true); try { this.mystromDiscovery(); } catch (IOException e) { logger.error("Error doing discovery of your devices", e); } } }
Source:
private List<DiskImage> manualAggregateSnapshots() { DiskImage diskWithSnaps = diskWithSnapshots; diskWithSnaps.getSnapshots().addAll(snapshotsList); return Arrays.asList(diskWithSnapshots, diskWithoutSnapshots, ovfImage, cinderDisk); }

Target:
private List<DiskImage> manualAggregateSnapshots() { diskWithSnapshots.getSnapshots().addAll(snapshotsList); return Arrays.asList(diskWithSnapshots, diskWithoutSnapshots, ovfImage, cinderDisk); }
Source:
public void init() throws Exception { VerifiableProperties vProps = new VerifiableProperties(getNonBlockingRouterProperties()); operationCompleteLatch = new CountDownLatch(1); mockTime = new MockTime(); mockSelectorState = new AtomicReference<MockSelectorState>(MockSelectorState.Good); clusterMap = new MockClusterMap(); serverLayout = new MockServerLayout(clusterMap); setServerResponse(true); router = new NonBlockingRouter(new RouterConfig(vProps), new NonBlockingRouterMetrics(new MetricRegistry()), new MockNetworkClientFactory(vProps, mockSelectorState, MAX_PORTS_PLAIN_TEXT, MAX_PORTS_SSL, CHECKOUT_TIMEOUT_MS, serverLayout, mockTime), new LoggingNotificationSystem(), clusterMap, mockTime); List<PartitionId> mockPartitions = clusterMap.getWritablePartitionIds(); partition = mockPartitions.get(ThreadLocalRandom.current().nextInt(mockPartitions.size())); blobId = new BlobId(partition); blobIdString = blobId.getID(); }

Target:
public void init() throws Exception { VerifiableProperties vProps = new VerifiableProperties(getNonBlockingRouterProperties()); operationCompleteLatch = new CountDownLatch(1); mockTime = new MockTime(); mockSelectorState = new AtomicReference<MockSelectorState>(MockSelectorState.Good); clusterMap = new MockClusterMap(); serverLayout = new MockServerLayout(clusterMap); router = new NonBlockingRouter(new RouterConfig(vProps), new NonBlockingRouterMetrics(new MetricRegistry()), new MockNetworkClientFactory(vProps, mockSelectorState, MAX_PORTS_PLAIN_TEXT, MAX_PORTS_SSL, CHECKOUT_TIMEOUT_MS, serverLayout, mockTime), new LoggingNotificationSystem(), clusterMap, mockTime); List<PartitionId> mockPartitions = clusterMap.getWritablePartitionIds(); partition = mockPartitions.get(ThreadLocalRandom.current().nextInt(mockPartitions.size())); blobId = new BlobId(partition); blobIdString = blobId.getID(); }
Source:
public String getCurrentSignatureForPackage(final String packagename) { try { PackageInfo info = mContext.getPackageManager().getPackageInfo(packagename, PackageManager.GET_SIGNATURES); if (info != null && info.signatures != null && info.signatures.length > 0) { Signature signature = info.signatures[0]; MessageDigest md = MessageDigest.getInstance("SHA"); md.update(signature.toByteArray()); String tag = Base64.encodeToString(md.digest(), Base64.DEFAULT); return tag; } } catch (NameNotFoundException e) { Logger.e(TAG, "Calling App's package does not exist in PackageManager", "", ADALError.APP_PACKAGE_NAME_NOT_FOUND); } catch (NoSuchAlgorithmException e) { Logger.e(TAG, "Digest SHA algorithm does not exists", "", ADALError.DEVICE_NO_SUCH_ALGORITHM); } return null; }

Target:
public String getCurrentSignatureForPackage(final String packagename) { try { PackageInfo info = mContext.getPackageManager().getPackageInfo(packagename, PackageManager.GET_SIGNATURES); if (info != null && info.signatures != null && info.signatures.length > 0) { Signature signature = info.signatures[0]; MessageDigest md = MessageDigest.getInstance("SHA"); md.update(signature.toByteArray()); return Base64.encodeToString(md.digest(), Base64.DEFAULT); } } catch (NameNotFoundException e) { Logger.e(TAG, "Calling App's package does not exist in PackageManager", "", ADALError.APP_PACKAGE_NAME_NOT_FOUND); } catch (NoSuchAlgorithmException e) { Logger.e(TAG, "Digest SHA algorithm does not exists", "", ADALError.DEVICE_NO_SUCH_ALGORITHM); } return null; }
Source:
public void onTrimMemory(int level) { if (level < TRIM_MEMORY_COMPLETE) { return; } Context context = getContext(); if (context == null) { return; } deleteOldTemporaryFiles(context); if (receiverRegistered != null) { context.unregisterReceiver(receiverRegistered); receiverRegistered = null; } }

Target:
public void onTrimMemory(int level) { if (level < TRIM_MEMORY_COMPLETE) { return; } final Context context = getContext(); if (context == null) { return; } new AsyncTask<Void,Void,Void>() { @Override protected Void doInBackground(Void... voids) { deleteOldTemporaryFiles(context); return null; } }.execute(); unregisterFileCleanupReceiver(context); }